repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
replicatorg/ReplicatorG | src/main/java/replicatorg/drivers/gen3/EEPROMClass.java | 101 |
package replicatorg.drivers.gen3;
interface EEPROMClass {
// public boolean eepromChecked();
}
| gpl-2.0 |
android-plugin/uexGaodeNavi | src/org/zywx/wbpalmstar/plugin/uexgaodenavi/vo/InitOutputVO.java | 958 | /*
* Copyright (c) 2015. The AppCan Open Source Project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.zywx.wbpalmstar.plugin.uexgaodenavi.vo;
import java.io.Serializable;
/**
* Created by ylt on 15/12/8.
*/
public class InitOutputVO implements Serializable {
public boolean result=false;
}
| gpl-2.0 |
identityxx/penrose-studio | src/java/org/safehaus/penrose/studio/directory/dialog/SourceDialog.java | 12414 | /**
* Copyright 2009 Red Hat, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.safehaus.penrose.studio.directory.dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.*;
import org.safehaus.penrose.source.SourceConfig;
import org.safehaus.penrose.directory.EntrySourceConfig;
import org.safehaus.penrose.studio.PenroseImage;
import org.safehaus.penrose.studio.PenroseStudio;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @author Endi S. Dewata
*/
public class SourceDialog extends Dialog {
Shell shell;
Tree sourceTree;
Text aliasText;
Map<String,TreeItem> items = new HashMap<String,TreeItem>();
EntrySourceConfig entrySourceConfig;
Combo searchCombo;
Combo bindCombo;
Combo addCombo;
Combo deleteCombo;
Combo modifyCombo;
Combo modrdnCombo;
Button saveButton;
private boolean saved;
public SourceDialog(Shell parent, int style) {
super(parent, style);
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE);
createControl(shell);
}
public void open () {
Point size = new Point(400, 400);
shell.setSize(size);
Point l = getParent().getLocation();
Point s = getParent().getSize();
shell.setLocation(l.x + (s.x - size.x)/2, l.y + (s.y - size.y)/2);
shell.setText(getText());
shell.setImage(PenroseStudio.getImage(PenroseImage.LOGO));
shell.open();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
}
public Composite createSelectorPage(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
sourceTree = new Tree(composite, SWT.BORDER | SWT.MULTI);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.horizontalSpan = 2;
sourceTree.setLayoutData(gd);
sourceTree.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent event) {
if (sourceTree.getSelectionCount() == 0) return;
TreeItem item = sourceTree.getSelection()[0];
//if (item.getData() != null) {
// SourceConfig sourceConfig = (SourceConfig)item.getData();
// aliasText.setText(sourceConfig.getName());
//}
//aliasText.setEnabled(canEnterAlias());
saveButton.setEnabled(canSave());
}
});
Label aliasLabel = new Label(composite, SWT.NONE);
aliasLabel.setText("Alias:");
aliasText = new Text(composite, SWT.BORDER);
aliasText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
aliasText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent event) {
saveButton.setEnabled(canSave());
}
});
return composite;
}
public Composite createPropertiesPage(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
Label bindLabel = new Label(composite, SWT.NONE);
bindLabel.setText("Bind:");
bindLabel.setLayoutData(new GridData());
bindCombo = new Combo(composite, SWT.BORDER);
bindCombo.add("");
bindCombo.add(EntrySourceConfig.REQUIRED);
bindCombo.add(EntrySourceConfig.REQUISITE);
bindCombo.add(EntrySourceConfig.SUFFICIENT);
bindCombo.add(EntrySourceConfig.IGNORE);
bindCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label requiredLabel = new Label(composite, SWT.NONE);
requiredLabel.setText("Search:");
requiredLabel.setLayoutData(new GridData());
searchCombo = new Combo(composite, SWT.BORDER);
searchCombo.add("");
searchCombo.add(EntrySourceConfig.REQUIRED);
searchCombo.add(EntrySourceConfig.REQUISITE);
searchCombo.add(EntrySourceConfig.SUFFICIENT);
searchCombo.add(EntrySourceConfig.IGNORE);
searchCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
Label addLabel = new Label(composite, SWT.NONE);
addLabel.setText("Add:");
addLabel.setLayoutData(new GridData());
addCombo = new Combo(composite, SWT.BORDER);
addCombo.add("");
addCombo.add(EntrySourceConfig.REQUIRED);
addCombo.add(EntrySourceConfig.IGNORE);
addCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label deleteLabel = new Label(composite, SWT.NONE);
deleteLabel.setText("Delete:");
deleteLabel.setLayoutData(new GridData());
deleteCombo = new Combo(composite, SWT.BORDER);
deleteCombo.add("");
deleteCombo.add(EntrySourceConfig.REQUIRED);
deleteCombo.add(EntrySourceConfig.IGNORE);
deleteCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label modifyLabel = new Label(composite, SWT.NONE);
modifyLabel.setText("Modify:");
modifyLabel.setLayoutData(new GridData());
modifyCombo = new Combo(composite, SWT.BORDER);
modifyCombo.add("");
modifyCombo.add(EntrySourceConfig.REQUIRED);
modifyCombo.add(EntrySourceConfig.IGNORE);
modifyCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label modrdnLabel = new Label(composite, SWT.NONE);
modrdnLabel.setText("Modify RDN:");
modrdnLabel.setLayoutData(new GridData());
modrdnCombo = new Combo(composite, SWT.BORDER);
modrdnCombo.add("");
modrdnCombo.add(EntrySourceConfig.REQUIRED);
modrdnCombo.add(EntrySourceConfig.IGNORE);
modrdnCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
return composite;
}
public void createControl(final Shell parent) {
parent.setLayout(new GridLayout());
TabFolder tabFolder = new TabFolder(parent, SWT.NONE);
tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite selectorPage = createSelectorPage(tabFolder);
selectorPage.setLayoutData(new GridData(GridData.FILL_BOTH));
TabItem selectorTab = new TabItem(tabFolder, SWT.NONE);
selectorTab.setText("Source");
selectorTab.setControl(selectorPage);
Composite propertiesPage = createPropertiesPage(tabFolder);
propertiesPage.setLayoutData(new GridData(GridData.FILL_BOTH));
TabItem propertiesTab = new TabItem(tabFolder, SWT.NONE);
propertiesTab.setText("Properties");
propertiesTab.setControl(propertiesPage);
Composite buttons = new Composite(parent, SWT.NONE);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment = GridData.END;
buttons.setLayoutData(gd);
buttons.setLayout(new RowLayout());
saveButton = new Button(buttons, SWT.PUSH);
saveButton.setText("OK");
saveButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
//if ("".equals(aliasText.getText())) return;
if (sourceTree.getSelectionCount() == 0) return;
TreeItem item = sourceTree.getSelection()[0];
if (item.getData() == null) return;
SourceConfig sourceConfig = (SourceConfig)item.getData();
String alias = aliasText.getText();
entrySourceConfig.setAlias("".equals(alias) ? sourceConfig.getName() : alias);
entrySourceConfig.setSourceName(sourceConfig.getName());
entrySourceConfig.setSearch("".equals(searchCombo.getText()) ? null : searchCombo.getText());
entrySourceConfig.setBind("".equals(bindCombo.getText()) ? null : bindCombo.getText());
entrySourceConfig.setAdd("".equals(addCombo.getText()) ? null : addCombo.getText());
entrySourceConfig.setDelete("".equals(deleteCombo.getText()) ? null : deleteCombo.getText());
entrySourceConfig.setModify("".equals(modifyCombo.getText()) ? null : modifyCombo.getText());
entrySourceConfig.setModrdn("".equals(modrdnCombo.getText()) ? null : modrdnCombo.getText());
saved = true;
shell.close();
}
});
Button cancelButton = new Button(buttons, SWT.PUSH);
cancelButton.setText("Cancel");
cancelButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
shell.close();
}
});
}
public boolean canEnterAlias() {
boolean enabled = false;
if (sourceTree.getSelectionCount() != 0) {
TreeItem item = sourceTree.getSelection()[0];
if (item.getData() != null) {
enabled = true;
}
}
return enabled;
}
public boolean canSave() {
boolean enabled = false;
if (sourceTree.getSelectionCount() != 0) {
//TreeItem item = sourceTree.getSelection()[0];
//if (item.getData() != null && !"".equals(aliasText.getText())) {
enabled = true;
//}
}
return enabled;
}
public void setSourceConfigs(Collection<SourceConfig> sourceConfigs) {
sourceTree.removeAll();
items.clear();
for (SourceConfig sourceConfig : sourceConfigs) {
TreeItem ti = new TreeItem(sourceTree, SWT.NONE);
ti.setText(sourceConfig.getName());
ti.setData(sourceConfig);
ti.setImage(PenroseStudio.getImage(PenroseImage.SOURCE));
items.put(sourceConfig.getName(), ti);
}
}
public boolean isSaved() {
return saved;
}
public void setSaved(boolean saved) {
this.saved = saved;
}
public EntrySourceConfig getSourceConfig() {
return entrySourceConfig;
}
public void setSourceConfig(EntrySourceConfig source) {
this.entrySourceConfig = source;
String sourceName = source.getSourceName();
TreeItem item = items.get(sourceName);
if (item != null) {
sourceTree.setSelection(new TreeItem[] { item });
}
String alias = source.getAlias();
aliasText.setText(alias == null || alias.equals(sourceName) ? "" : source.getAlias());
searchCombo.setText(source.getSearch() == null ? "" : source.getSearch());
bindCombo.setText(source.getBind() == null ? "" : source.getBind());
addCombo.setText(source.getAdd() == null ? "" : source.getAdd());
deleteCombo.setText(source.getDelete() == null ? "" : source.getDelete());
modifyCombo.setText(source.getModify() == null ? "" : source.getModify());
modrdnCombo.setText(source.getModrdn() == null ? "" : source.getModrdn());
//aliasText.setEnabled(canEnterAlias());
saveButton.setEnabled(canSave());
}
}
| gpl-2.0 |
Agnie-Software/3a | code/user-persistence/src/main/java/com/agnie/useradmin/persistance/server/listrequest/PageNSort.java | 1525 | /*******************************************************************************
* Copyright (c) 2014 Agnie Technologies.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Agnie Technologies - initial API and implementation
******************************************************************************/
package com.agnie.useradmin.persistance.server.listrequest;
import java.io.Serializable;
import open.pandurang.gwt.helper.requestfactory.marker.RFProxyMethod;
import open.pandurang.gwt.helper.requestfactory.marker.RFValueProxy;
@RFValueProxy
public class PageNSort implements Serializable {
private static final long serialVersionUID = 1L;
private Page page;
private Sort sort;
public PageNSort() {
}
/**
* @param page
* @param sort
*/
public PageNSort(Page page, Sort sort) {
super();
this.page = page;
this.sort = sort;
}
/**
* @return the page
*/
@RFProxyMethod
public Page getPage() {
return page;
}
/**
* @param page
* the page to set
*/
@RFProxyMethod
public void setPage(Page page) {
this.page = page;
}
/**
* @return the sort
*/
@RFProxyMethod
public Sort getSort() {
return sort;
}
/**
* @param sort
* the sort to set
*/
@RFProxyMethod
public void setSort(Sort sort) {
this.sort = sort;
}
}
| gpl-2.0 |
sjanos/sokoban | src/main/java/com/janos/sokoban/net/package-info.java | 50 | /**
* Package.
*/
package com.janos.sokoban.net; | gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest03614.java | 1859 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest03614")
public class BenchmarkTest03614 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
java.util.Map<String,String[]> map = request.getParameterMap();
String param = "";
if (!map.isEmpty()) {
param = map.get("foo")[0];
}
String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);
java.lang.Math.random();
response.getWriter().println("Weak Randomness Test java.lang.Math.random() executed");
}
}
| gpl-2.0 |
vlabatut/totalboumboum | src/org/totalboumboum/ai/v201314/adapter/path/cost/PixelCostCalculator.java | 5119 | package org.totalboumboum.ai.v201314.adapter.path.cost;
/*
* Total Boum Boum
* Copyright 2008-2014 Vincent Labatut
*
* This file is part of Total Boum Boum.
*
* Total Boum Boum is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* Total Boum Boum is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Total Boum Boum. If not, see <http://www.gnu.org/licenses/>.
*
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.totalboumboum.ai.v201314.adapter.agent.ArtificialIntelligence;
import org.totalboumboum.ai.v201314.adapter.data.AiHero;
import org.totalboumboum.ai.v201314.adapter.data.AiItem;
import org.totalboumboum.ai.v201314.adapter.data.AiTile;
import org.totalboumboum.ai.v201314.adapter.data.AiZone;
import org.totalboumboum.ai.v201314.adapter.path.AiLocation;
import org.totalboumboum.ai.v201314.adapter.path.AiSearchNode;
import org.totalboumboum.ai.v201314.adapter.path.heuristic.NoHeuristicCalculator;
import org.totalboumboum.ai.v201314.adapter.path.heuristic.PixelHeuristicCalculator;
import org.totalboumboum.ai.v201314.adapter.path.successor.BasicSuccessorCalculator;
/**
* Classe étendant la classe abstraite {@link CostCalculator} de la manière à déterminer
* le coût en fonction de la distance en pixels entre deux emplacements.
* <br/>
* La classe est compatible avec :
* <ul>
* <li>Fonction heuristiques :
* <ul>
* <li>{@link NoHeuristicCalculator}</li>
* <li>{@link PixelHeuristicCalculator}</li>
* </ul>
* </li>
* <li>Fonctions successeurs :
* <ul>
* <li>{@link BasicSuccessorCalculator}</li>
* </ul>
* </li>
* </ul>
* <br/>
* Cette classe n'est pas conçue pour traiter les chemins contenant des
* retours en arrière. Voir {@link TimeCostCalculator} pour ça.
*
* @author Vincent Labatut
*
* @deprecated
* Ancienne API d'IA, à ne plus utiliser.
*/
public class PixelCostCalculator extends CostCalculator
{
/**
* Construit une fonction de coût
* utilisant l'agent passée en paramètre
* pour gérer les interruptions.
*
* @param ai
* Agent de référence.
*/
public PixelCostCalculator(ArtificialIntelligence ai)
{ super(ai);
}
/////////////////////////////////////////////////////////////////
// PROCESS /////////////////////////////////////
/////////////////////////////////////////////////////////////////
/**
* Les deux emplacements sont supposés être dans des cases voisines.
* On renvoie la <a href="http://fr.wikipedia.org/wiki/Distance_de_Manhattan">distance de Manhattan</a>
* (exprimée en pixels) qui les sépare.
*
* @param currentNode
* Le noeud contenant l'emplacement de départ.
* @param nextLocation
* L'emplacement d'arrivée (case voisine de la case courante).
* @return
* La distance en pixels entre l'emplacement de départ et celui d'arrivée.
*/
@Override
public double processCost(AiSearchNode currentNode, AiLocation nextLocation)
{ // on calcule simplement la distance en pixels
AiLocation currentLocation = currentNode.getLocation();
AiTile destination = nextLocation.getTile();
AiZone zone = currentLocation.getZone();
double result = zone.getPixelDistance(currentLocation,nextLocation);
// on rajoute le coût supplémentaire si la case contient un adversaire
if(opponentCost>0)
{ List<AiHero> opponents = new ArrayList<AiHero>(zone.getRemainingOpponents());
List<AiHero> heroes = destination.getHeroes();
opponents.retainAll(heroes);
if(!opponents.isEmpty())
result = result + opponentCost;
}
// on rajoute le coût supplémentaire si la case contient un malus
if(malusCost>0)
{ List<AiItem> items = destination.getItems();
Iterator<AiItem> it = items.iterator();
boolean containsMalus = false;
while(it.hasNext() && !containsMalus)
{ AiItem item = it.next();
containsMalus = !item.getType().isBonus();
}
if(containsMalus)
result = result + malusCost;
}
// on rajoute le coût supplémentaire s'il est défini pour la case
if(tileCosts!=null)
{ int row = destination.getRow();
int col = destination.getCol();
result = result + tileCosts[row][col];
}
return result;
}
/**
* Le coût d'un chemin correspond ici à sa distance
* exprimée en pixels.
*
* @param path
* Chemin à traiter.
* @return
* Le coût de ce chemin.
*/
/* @Override
public double processCost(AiPath path)
{ double result = path.getPixelDistance();
return result;
}
*/
}
| gpl-2.0 |
plx9421/JavaRushHomeWork | javarush/test/level38/lesson08/task02/Solution.java | 1002 | package com.javarush.test.level38.lesson08.task02;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;
/* Неверные аннотации
Исправь неверные аннотации. Код должен компилировался без ошибок и предупреждений.
*/
@Target(ElementType.METHOD)
@interface Main {
}
public class Solution {
@Main
public static void main(String[] args) {
Solution solution = new Solution().new SubSolution();
solution.overriddenMethod();
}
public void overriddenMethod() {
}
public class SubSolution extends Solution {
@Override
public void overriddenMethod() {
System.out.println(uncheckedCall());
}
@SuppressWarnings("unchecked")
List uncheckedCall() {
List list = new ArrayList();
list.add("hello");
return list;
}
}
}
| gpl-2.0 |
christianbors/snapshot-plugin | src/main/java/org/ssanalytics/snapshotplugin/io/dbConnection/dao/filter/FriendFilterData.java | 1171 | package org.ssanalytics.snapshotplugin.io.dbConnection.dao.filter;
import java.util.List;
public class FriendFilterData {
private Boolean genderIsMale;
private String relationship;
private List<String> interests;
private Boolean interestSearchOR;
/**
*
* @param genderIsMale True = Male, false = female
* @param relationship
* @param interests A list of interests, can be AND or OR connected (defined
* in param friendSearchOR)
* @param interestSearchOR defines the way the interest search criteria is
* connected (can be OR or AND)
*/
public FriendFilterData(Boolean genderIsMale, String relationship, List<String> interests, Boolean interestSearchOR) {
this.genderIsMale = genderIsMale;
this.relationship = relationship;
this.interests = interests;
}
public Boolean getGender() {
return this.genderIsMale;
}
public String getRelationship() {
return this.relationship;
}
public List<String> getInterests() {
return this.interests;
}
public Boolean getInterestSearchOR() {
return this.interestSearchOR;
}
}
| gpl-2.0 |
s2sprodotti/SDS | SistemaDellaSicurezza/src/com/apconsulting/luna/ejb/RischioCantiere/Rischio_Art_Legge_View.java | 1597 | /** ======================================================================== */
/** */
/** @copyright Copyright (c) 2010-2015, S2S s.r.l. */
/** @license http://www.gnu.org/licenses/gpl-2.0.html GNU Public License v.2 */
/** @version 6.0 */
/** This file is part of SdS - Sistema della Sicurezza . */
/** SdS - Sistema della Sicurezza is free software: you can redistribute it and/or modify */
/** it under the terms of the GNU General Public License as published by */
/** the Free Software Foundation, either version 3 of the License, or */
/** (at your option) any later version. */
/** SdS - Sistema della Sicurezza is distributed in the hope that it will be useful, */
/** but WITHOUT ANY WARRANTY; without even the implied warranty of */
/** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/** GNU General Public License for more details. */
/** You should have received a copy of the GNU General Public License */
/** along with SdS - Sistema della Sicurezza . If not, see <http://www.gnu.org/licenses/gpl-2.0.html> GNU Public License v.2 */
/** */
/** ======================================================================== */
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.apconsulting.luna.ejb.RischioCantiere;
public class Rischio_Art_Legge_View {
public long COD_ARL;
public String NOM_ARL;
public String DES_ARL;
}
| gpl-2.0 |
klaus201192239/schooltime | schooltime/src/coreservlet/getsignupinfo.java | 2494 | package coreservlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.json.JSONObject;
import staticData.StaticString;
import utils.jsonUtil;
import com.dbDao.CreateQueryFromBean;
import com.dbDao.DaoImpl;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCursor;
import bean.TableInfo;
public class getsignupinfo extends HttpServlet {
private static final long serialVersionUID = 1L;
public getsignupinfo() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String activityid=request.getParameter("activityid");
log("hahahaha");
log("~~"+activityid);
int type=0;
String result="error";
TableInfo ta=new TableInfo();
ta.setActivityId(new ObjectId(activityid));
ta.setType(type);
BasicDBObject pro=new BasicDBObject();
pro.put(StaticString.TableInfo_TableInfoColumn, 1);
try {
MongoCursor<Document> cursor= DaoImpl.GetSelectCursor(TableInfo.class, CreateQueryFromBean.EqualObj(ta),pro);
while(cursor.hasNext()){
Document doc=cursor.next();
JSONObject obj=jsonUtil.ParaFromDocument(doc);
result=obj.toString();
}
} catch (Exception e1) {
result="error";
}
log(result);
out.println(result);
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
public void init() throws ServletException {
// Put your code here
}
}
| gpl-2.0 |
git4gecko/jMeasurement | src/de/us/rpi/jMeasurement/bmp085/CalibrationData.java | 370 | package de.us.rpi.jMeasurement.bmp085;
/**
* Calibration data
*
* @author us
*
*/
public class CalibrationData {
public int ac1 = 0;
public int ac2 = 0;
public int ac3 = 0;
public int ac4 = 0;
public int ac5 = 0;
public int ac6 = 0;
public int b1 = 0;
public int b2 = 0;
public int mb = 0;
public int mc = 0;
public int md = 0;
}
| gpl-2.0 |
Nadahar/UniversalMediaServer | src/main/java/net/pms/newgui/LooksFrame.java | 20797 | /*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.newgui;
import com.jgoodies.looks.Options;
import com.jgoodies.looks.plastic.PlasticLookAndFeel;
import com.jgoodies.looks.windows.WindowsLookAndFeel;
import com.sun.jna.Platform;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import java.util.Observable;
import java.util.Observer;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.metal.DefaultMetalTheme;
import javax.swing.plaf.metal.MetalLookAndFeel;
import net.pms.Messages;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.io.WindowsNamedPipe;
import net.pms.newgui.components.CustomJButton;
import net.pms.newgui.update.AutoUpdateDialog;
import net.pms.update.AutoUpdater;
import net.pms.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LooksFrame extends JFrame implements IFrame, Observer {
private static final Logger LOGGER = LoggerFactory.getLogger(LooksFrame.class);
private final AutoUpdater autoUpdater;
private final PmsConfiguration configuration;
public static final String START_SERVICE = "start.service";
private static final long serialVersionUID = 8723727186288427690L;
private Dimension storedWindowSize = new Dimension();
private Dimension storedScreenSize = new Dimension();
protected static final Dimension STANDARD_SIZE = new Dimension(1000, 750);
// https://code.google.com/p/ps3mediaserver/issues/detail?id=949
protected static final Dimension MINIMUM_SIZE = new Dimension(800, 480);
private Dimension screenSize = getToolkit().getScreenSize();
/**
* List of context sensitive help pages URLs. These URLs should be
* relative to the documentation directory and in the same order as the
* tabs. The value <code>null</code> means "don't care", activating the
* tab will not change the help page.
*/
protected static final String[] HELP_PAGES = {
"index.html",
null,
"general_configuration.html",
null,
"navigation_share.html",
"transcoding.html",
null,
null
};
private NavigationShareTab nt;
private StatusTab st;
private TracesTab tt;
private TranscodingTab tr;
private GeneralTab gt;
private HelpTab ht;
private PluginTab pt;
private AbstractButton reload;
private JLabel status;
private static Object lookAndFeelInitializedLock = new Object();
private static boolean lookAndFeelInitialized = false;
private ViewLevel viewLevel = ViewLevel.UNKNOWN;
public ViewLevel getViewLevel() {
return viewLevel;
}
public void setViewLevel(ViewLevel viewLevel) {
if (viewLevel != ViewLevel.UNKNOWN){
this.viewLevel = viewLevel;
tt.applyViewLevel();
}
}
public TracesTab getTt() {
return tt;
}
public NavigationShareTab getNt() {
return nt;
}
public TranscodingTab getTr() {
return tr;
}
public GeneralTab getGt() {
return gt;
}
public PluginTab getPt() {
return pt;
}
public AbstractButton getReload() {
return reload;
}
public static void initializeLookAndFeel() {
synchronized (lookAndFeelInitializedLock) {
if (lookAndFeelInitialized) {
return;
}
LookAndFeel selectedLaf = null;
if (Platform.isWindows()) {
selectedLaf = new WindowsLookAndFeel();
} else if (System.getProperty("nativelook") == null && !Platform.isMac()) {
selectedLaf = new PlasticLookAndFeel();
} else {
try {
String systemClassName = UIManager.getSystemLookAndFeelClassName();
// Workaround for Gnome
try {
String gtkLAF = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
Class.forName(gtkLAF);
if (systemClassName.equals("javax.swing.plaf.metal.MetalLookAndFeel")) {
systemClassName = gtkLAF;
}
} catch (ClassNotFoundException ce) {
LOGGER.error("Error loading GTK look and feel: ", ce);
}
LOGGER.trace("Choosing Java look and feel: " + systemClassName);
UIManager.setLookAndFeel(systemClassName);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e1) {
selectedLaf = new PlasticLookAndFeel();
LOGGER.error("Error while setting native look and feel: ", e1);
}
}
if (selectedLaf instanceof PlasticLookAndFeel) {
PlasticLookAndFeel.setPlasticTheme(PlasticLookAndFeel.createMyDefaultTheme());
PlasticLookAndFeel.setTabStyle(PlasticLookAndFeel.TAB_STYLE_DEFAULT_VALUE);
PlasticLookAndFeel.setHighContrastFocusColorsEnabled(false);
} else if (selectedLaf != null && selectedLaf.getClass() == MetalLookAndFeel.class) {
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
}
// Work around caching in MetalRadioButtonUI
JRadioButton radio = new JRadioButton();
radio.getUI().uninstallUI(radio);
JCheckBox checkBox = new JCheckBox();
checkBox.getUI().uninstallUI(checkBox);
if (selectedLaf != null) {
try {
UIManager.setLookAndFeel(selectedLaf);
} catch (UnsupportedLookAndFeelException e) {
LOGGER.warn("Can't change look and feel", e);
}
}
lookAndFeelInitialized = true;
}
}
/**
* Constructs a <code>DemoFrame</code>, configures the UI,
* and builds the content.
*/
public LooksFrame(AutoUpdater autoUpdater, PmsConfiguration configuration) {
this.autoUpdater = autoUpdater;
this.configuration = configuration;
assert this.configuration != null;
Options.setDefaultIconSize(new Dimension(18, 18));
Options.setUseNarrowButtons(true);
// Set view level, can be omitted if ViewLevel is implemented in configuration
// by setting the view level as variable initialization
if (configuration.isHideAdvancedOptions()) {
viewLevel = ViewLevel.NORMAL;
} else {
viewLevel = ViewLevel.ADVANCED;
}
// Global options
Options.setTabIconsEnabled(true);
UIManager.put(Options.POPUP_DROP_SHADOW_ENABLED_KEY, null);
// Swing Settings
initializeLookAndFeel();
// wait till the look and feel has been initialized before (possibly) displaying the update notification dialog
if (autoUpdater != null) {
autoUpdater.addObserver(this);
autoUpdater.pollServer();
}
// http://propedit.sourceforge.jp/propertieseditor.jnlp
Font sf = null;
// Set an unicode font for testing exotic languages (Japanese)
final String language = configuration.getLanguageTag();
if (language != null && (language.equals("ja") || language.startsWith("zh") || language.equals("ko"))) {
sf = new Font("SansSerif", Font.PLAIN, 12);
}
if (sf != null) {
UIManager.put("Button.font", sf);
UIManager.put("ToggleButton.font", sf);
UIManager.put("RadioButton.font", sf);
UIManager.put("CheckBox.font", sf);
UIManager.put("ColorChooser.font", sf);
UIManager.put("ToggleButton.font", sf);
UIManager.put("ComboBox.font", sf);
UIManager.put("ComboBoxItem.font", sf);
UIManager.put("InternalFrame.titleFont", sf);
UIManager.put("Label.font", sf);
UIManager.put("List.font", sf);
UIManager.put("MenuBar.font", sf);
UIManager.put("Menu.font", sf);
UIManager.put("MenuItem.font", sf);
UIManager.put("RadioButtonMenuItem.font", sf);
UIManager.put("CheckBoxMenuItem.font", sf);
UIManager.put("PopupMenu.font", sf);
UIManager.put("OptionPane.font", sf);
UIManager.put("Panel.font", sf);
UIManager.put("ProgressBar.font", sf);
UIManager.put("ScrollPane.font", sf);
UIManager.put("Viewport", sf);
UIManager.put("TabbedPane.font", sf);
UIManager.put("TableHeader.font", sf);
UIManager.put("TextField.font", sf);
UIManager.put("PasswordFiled.font", sf);
UIManager.put("TextArea.font", sf);
UIManager.put("TextPane.font", sf);
UIManager.put("EditorPane.font", sf);
UIManager.put("TitledBorder.font", sf);
UIManager.put("ToolBar.font", sf);
UIManager.put("ToolTip.font", sf);
UIManager.put("Tree.font", sf);
UIManager.put("Spinner.font", sf);
}
setTitle("Test");
setIconImage(readImageIcon("icon-32.png").getImage());
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JComponent jp = buildContent();
String showScrollbars = System.getProperty("scrollbars", "").toLowerCase();
/**
* Handle scrollbars:
*
* 1) forced scrollbars (-Dscrollbars=true): always display them
* 2) optional scrollbars (-Dscrollbars=optional): display them as needed
* 3) otherwise (default): don't display them
*/
switch (showScrollbars) {
case "true":
setContentPane(
new JScrollPane(
jp,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS
)
);
break;
case "optional":
setContentPane(
new JScrollPane(
jp,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
)
);
break;
default:
setContentPane(jp);
break;
}
String projectName = PropertiesUtil.getProjectProperties().get("project.name");
String projectVersion = PropertiesUtil.getProjectProperties().get("project.version");
String title = projectName + " " + projectVersion;
// If the version contains a "-" (e.g. "1.50.1-SNAPSHOT" or "1.50.1-beta1"), add a warning message
if (projectVersion.indexOf('-') > -1) {
title = title + " - " + Messages.getString("LooksFrame.26");
}
if (PMS.getTraceMode() == 2) {
// Forced trace mode
title = title + " [" + Messages.getString("TracesTab.10").toUpperCase() + "]";
}
setTitle(title);
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
if (screenSize.width < MINIMUM_SIZE.width || screenSize.height < MINIMUM_SIZE.height) {
setMinimumSize(screenSize);
} else {
setMinimumSize(MINIMUM_SIZE);
}
String ss = configuration.getScreenSize();
storedScreenSize.height = Integer.parseInt(ss.substring(ss.indexOf("x") + 1));
storedScreenSize.width = Integer.parseInt(ss.substring(0, ss.indexOf("x")));
String[] windowGeometryValues = configuration.getWindowGeometry().split(",");
int posX = Integer.parseInt(windowGeometryValues[0].substring(windowGeometryValues[0].indexOf("=") + 1));
int posY = Integer.parseInt(windowGeometryValues[1].substring(windowGeometryValues[1].indexOf("=") + 1));
storedWindowSize.width = Integer.parseInt(windowGeometryValues[2].substring(windowGeometryValues[2].indexOf("=") + 1));
storedWindowSize.height = Integer.parseInt(windowGeometryValues[3].substring(windowGeometryValues[3].indexOf("=") + 1));
setSize(storedWindowSize);
boolean screenChanged = false;
if (storedScreenSize.width != screenSize.getWidth() || storedScreenSize.height != screenSize.getHeight()) {
setSize(STANDARD_SIZE);
screenChanged = true;
} else if (configuration.getWindowExtendedState() != NORMAL) {
setExtendedState(configuration.getWindowExtendedState());
} else if (screenSize.width < storedWindowSize.width || screenSize.height < storedWindowSize.height) {
setSize(screenSize);
}
// Customize the colors used in tooltips
UIManager.put("ToolTip.background", new ColorUIResource(PMS.getConfiguration().getToolTipBackgroundColor()));
Border border = BorderFactory.createLineBorder(PMS.getConfiguration().getToolTipBackgroundColor(), 4);
UIManager.put("ToolTip.border", border);
UIManager.put("ToolTip.foreground", new ColorUIResource(PMS.getConfiguration().getToolTipForegroundColor()));
// Display tooltips immediately and for a long time
ToolTipManager.sharedInstance().setInitialDelay(400);
ToolTipManager.sharedInstance().setDismissDelay(60000);
ToolTipManager.sharedInstance().setReshowDelay(400);
setResizable(true);
Dimension paneSize = getSize();
if (posX == -1 && posY == -1 || screenChanged) { // first run of UMS or screen/desktop was changed so set the position to the middle of the screen
setLocation(
((screenSize.width > paneSize.width) ? ((screenSize.width - paneSize.width) / 2) : 0),
((screenSize.height > paneSize.height) ? ((screenSize.height - paneSize.height) / 2) : 0)
);
} else {
setLocation(posX, posY);
}
if (!configuration.isMinimized() && System.getProperty(START_SERVICE) == null) {
setVisible(true);
}
PMS.get().getRegistry().addSystemTray(this);
}
public static ImageIcon readImageIcon(String filename) {
URL url = LooksFrame.class.getResource("/resources/images/" + filename);
return new ImageIcon(url);
}
public JComponent buildContent() {
JPanel panel = new JPanel(new BorderLayout());
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.setRollover(true);
toolBar.add(new JPanel());
reload = createToolBarButton(Messages.getString("LooksFrame.12"), "button-restart.png");
reload.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PMS.get().reset();
}
});
reload.setToolTipText(Messages.getString("LooksFrame.28"));
toolBar.add(reload);
toolBar.addSeparator(new Dimension(20, 1));
AbstractButton quit = createToolBarButton(Messages.getString("LooksFrame.5"), "button-quit.png");
quit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
quit();
}
});
toolBar.add(quit);
if (System.getProperty(START_SERVICE) != null) {
quit.setEnabled(false);
}
toolBar.add(new JPanel());
// Apply the orientation to the toolbar and all components in it
ComponentOrientation orientation = ComponentOrientation.getOrientation(PMS.getLocale());
toolBar.applyComponentOrientation(orientation);
panel.add(toolBar, BorderLayout.NORTH);
panel.add(buildMain(), BorderLayout.CENTER);
status = new JLabel("");
status.setBorder(BorderFactory.createEmptyBorder());
status.setComponentOrientation(orientation);
// Calling applyComponentOrientation() here would be ideal.
// Alas it horribly mutilates the layout of several tabs.
//panel.applyComponentOrientation(orientation);
panel.add(status, BorderLayout.SOUTH);
return panel;
}
public JComponent buildMain() {
final JTabbedPane tabbedPane = new JTabbedPane(SwingConstants.TOP);
tabbedPane.setUI(new CustomTabbedPaneUI());
st = new StatusTab(configuration);
tt = new TracesTab(configuration, this);
gt = new GeneralTab(configuration, this);
pt = new PluginTab(configuration, this);
nt = new NavigationShareTab(configuration, this);
tr = new TranscodingTab(configuration, this);
ht = new HelpTab();
tabbedPane.addTab(Messages.getString("LooksFrame.18"), st.build());
tabbedPane.addTab(Messages.getString("LooksFrame.19"), tt.build());
tabbedPane.addTab(Messages.getString("LooksFrame.20"), gt.build());
tabbedPane.addTab(Messages.getString("LooksFrame.27"), pt.build());
tabbedPane.addTab(Messages.getString("LooksFrame.22"), nt.build());
tabbedPane.addTab(Messages.getString("LooksFrame.21"), tr.build());
tabbedPane.addTab(Messages.getString("LooksFrame.24"), new HelpTab().build());
tabbedPane.addTab(Messages.getString("LooksFrame.25"), new AboutTab().build());
tabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
int selectedIndex = tabbedPane.getSelectedIndex();
if (HELP_PAGES[selectedIndex] != null) {
PMS.setHelpPage(HELP_PAGES[selectedIndex]);
// Update the contents of the help tab itself
ht.updateContents();
}
}
});
tabbedPane.setBorder(new EmptyBorder(5, 5, 5, 5));
/*
* Set the orientation of the tabbedPane.
* Note: Do not use applyComponentOrientation() here because it
* messes with the layout of several tabs.
*/
ComponentOrientation orientation = ComponentOrientation.getOrientation(PMS.getLocale());
tabbedPane.setComponentOrientation(orientation);
return tabbedPane;
}
protected AbstractButton createToolBarButton(String text, String iconName) {
CustomJButton button = new CustomJButton(text, readImageIcon(iconName));
button.setFocusable(false);
button.setBorderPainted(false);
return button;
}
protected AbstractButton createToolBarButton(String text, String iconName, String toolTipText) {
CustomJButton button = new CustomJButton(text, readImageIcon(iconName));
button.setToolTipText(toolTipText);
button.setFocusable(false);
button.setBorderPainted(false);
return button;
}
public void quit() {
WindowsNamedPipe.setLoop(false);
String windowGeometry = getBounds().toString();
try {
if (getExtendedState() != NORMAL) {
configuration.setWindowExtendedState(getExtendedState());
} else {
configuration.setWindowExtendedState(NORMAL);
configuration.setWindowGeometry(windowGeometry.substring(windowGeometry.indexOf("[") + 1, windowGeometry.indexOf("]")));
}
configuration.setScreenSize((int) screenSize.getWidth() + "x" + (int) screenSize.getHeight());
} catch (Exception e) {
LOGGER.warn("Failed to save window geometry and size: {}", e.getMessage());
LOGGER.debug("", e);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
LOGGER.error("Interrupted during shutdown: {}", e);
}
System.exit(0);
}
@Override
public void append(final String msg) {
tt.append(msg);
}
@Override
public void setReadValue(long v, String msg) {
st.setReadValue(v, msg);
}
@Override
public void setStatusCode(int code, String msg, String icon) {
st.getJl().setText(msg);
try {
st.getImagePanel().set(ImageIO.read(LooksFrame.class.getResourceAsStream("/resources/images/" + icon)));
} catch (IOException e) {
LOGGER.error(null, e);
}
}
@Override
public void updateBuffer() {
st.updateCurrentBitrate();
}
/**
* This method is being called when a configuration change requiring
* a restart of the HTTP server has been done by the user. It should notify the user
* to restart the server.<br>
* Currently the icon as well as the tool tip text of the restart button is being
* changed.<br>
* The actions requiring a server restart are defined by {@link PmsConfiguration#NEED_RELOAD_FLAGS}
*
* @param bool true if the server has to be restarted, false otherwise
*/
@Override
public void setReloadable(boolean bool) {
if (bool) {
reload.setIcon(readImageIcon("button-restart-required.png"));
reload.setToolTipText(Messages.getString("LooksFrame.13"));
} else {
reload.setIcon(readImageIcon("button-restart.png"));
reload.setToolTipText(Messages.getString("LooksFrame.28"));
}
}
@Override
public void addEngines() {
tr.addEngines();
}
// Fired on AutoUpdater state changes
@Override
public void update(Observable o, Object arg) {
if (configuration.isAutoUpdate()) {
checkForUpdates(true);
}
}
/**
* Start the process of checking for updates.
*
* @param isStartup whether this is being called via startup or button
*/
public void checkForUpdates(boolean isStartup) {
if (autoUpdater != null) {
try {
AutoUpdateDialog.showIfNecessary(this, autoUpdater, isStartup);
} catch (NoClassDefFoundError ncdfe) {
LOGGER.error("Error displaying AutoUpdateDialog", ncdfe);
}
}
}
@Override
public void setStatusLine(String line) {
if (line == null || "".equals(line)) {
line = "";
status.setBorder(BorderFactory.createEmptyBorder());
} else {
status.setBorder(BorderFactory.createEmptyBorder(0, 9, 8, 0));
}
status.setText(line);
}
@Override
public void addRenderer(RendererConfiguration renderer) {
st.addRenderer(renderer);
}
@Override
public void updateRenderer(RendererConfiguration renderer) {
StatusTab.updateRenderer(renderer);
}
@Override
public void serverReady() {
st.updateMemoryUsage();
gt.addRenderers();
pt.addPlugins();
}
@Override
public void setScanLibraryEnabled(boolean flag) {
getNt().setScanLibraryEnabled(flag);
}
public String getLog() {
return getTt().getList().getText();
}
}
| gpl-2.0 |
sigmaroot/FlatMe | src/de/sigmaroot/plugins/FlatMe.java | 6855 | package de.sigmaroot.plugins;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import com.earth2me.essentials.IEssentials;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class FlatMe extends JavaPlugin implements Listener {
public CommandHandler commandHandler;
public Configurator configurator;
public PlayerMap flatMePlayers;
public FileConfiguration config;
public WorldGuardHandler worldGuardHandler;
public IEssentials essAPI;
public WorldGuardPlugin wgAPI;
public final String PLUGIN_TITLE = "FlatMe";
public final String PLUGIN_VERSION = "2.2";
public boolean config_autoUpdate;
public int config_daysPerPlot;
public int config_extendCost;
public int config_levelHeight;
public int config_maxBlocksPerTick;
public int config_maxResultsPerPage;
public int config_plotSize;
public int config_plotsPerUser;
public int config_portDelay;
public int config_radius;
public String config_world;
public int config_jumpInterval;
private boolean areRegistered = false;
@Override
public void onEnable() {
// Use default config if no config exists
// Create reference to loaded configuration
saveDefaultConfig();
config = getConfig();
this.getLogger().info("Configuration and its defaults loaded.");
loadConfigValues();
// Create configurator for alternative configurations
configurator = new Configurator(this, config.getString("language", "en"));
// Configurator: Localization
configurator.loadLocalizationFile();
String args_0[] = { configurator.getLocalization(), configurator.resolveLocalizedString("%language%", null) };
this.getLogger().info(configurator.resolveLocalizedString("%localizationLoaded%", args_0));
// Create command handler
commandHandler = new CommandHandler(this);
// EXTERNAL: Essentials
essAPI = (IEssentials) Bukkit.getServer().getPluginManager().getPlugin("Essentials");
// EXTERNAL: WorldGuard
wgAPI = (WorldGuardPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldGuard");
// TRY HOOK
this.getServer().getPluginManager().registerEvents(new OurServerListener(), this);
if (essAPI.isEnabled() && wgAPI.isEnabled()) {
activateHooks();
}
// Create empty player map for queues
flatMePlayers = new PlayerMap(this);
// Configurator: Plots
configurator.loadPlotFile();
int plotCount = configurator.loadAllPlots();
String args_1[] = { "plots.yml", String.format("%d", plotCount) };
this.getLogger().info(configurator.resolveLocalizedString("%plotsLoaded%", args_1));
// Finished
if (!areRegistered) {
getServer().getPluginManager().registerEvents(this, this);
areRegistered = true;
}
this.getLogger().info(configurator.resolveLocalizedString("%pluginLoaded%", null));
}
@Override
public void onDisable() {
flatMePlayers.stopAllQueues();
configurator.saveAllPlots();
configurator.backupPlotFile();
// Finished
this.getLogger().info(configurator.resolveLocalizedString("%pluginUnloaded%", null));
}
@Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("flatme")) {
if (args.length == 0) {
sender.sendMessage(configurator.resolveLocalizedString("%noCommand%", null));
sender.sendMessage(commandHandler.returnCorrectUsage("help"));
} else {
commandHandler.handleCommand(sender, args);
}
}
return true;
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
flatMePlayers.add(player.getUniqueId());
flatMePlayers.getPlayer(player.getUniqueId()).checkForPlayer();
flatMePlayers.getPlayer(player.getUniqueId()).checkForPlots();
flatMePlayers.getPlayer(player.getUniqueId()).getQueue().setSilence(!player.hasPermission("flatme.admin"));
}
@Override
public void saveDefaultConfig() {
File customConfigFile = null;
customConfigFile = new File(this.getDataFolder(), "config.yml");
if (!customConfigFile.exists()) {
this.getLogger().warning("Configuration file config.yml doesn't exist. Using default configuration.");
this.saveResource("config.yml", false);
}
}
public void loadConfigValues() {
config_autoUpdate = config.getBoolean("autoUpdate", true);
config_daysPerPlot = config.getInt("daysPerPlot", 60);
config_extendCost = config.getInt("extendCost", 1000);
config_levelHeight = config.getInt("levelHeight", 3);
config_maxBlocksPerTick = config.getInt("maxBlocksPerTick", 1000);
config_maxResultsPerPage = config.getInt("maxResultsPerPage", 5);
config_plotSize = config.getInt("plotSize", 50);
config_plotsPerUser = config.getInt("plotsPerUser", 1);
config_portDelay = config.getInt("portDelay", 3);
config_radius = config.getInt("radius", 3);
config_world = config.getString("world", "world");
config_jumpInterval = config_plotSize + 7;
}
public void reloadConfiguration() {
onDisable();
flatMePlayers.clear();
config = null;
configurator = null;
commandHandler = null;
worldGuardHandler = null;
essAPI = null;
wgAPI = null;
this.reloadConfig();
onEnable();
}
private class OurServerListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
public void onPluginEnable(PluginEnableEvent event) {
Plugin p = event.getPlugin();
String name = p.getDescription().getName();
if (name.equals("WorldGuard") || name.equals("Essentials")) {
if (wgAPI.isEnabled() && essAPI.isEnabled())
activateHooks();
}
}
}
private void activateHooks() {
// HOOK: Essentials
essAPI = (IEssentials) Bukkit.getServer().getPluginManager().getPlugin("Essentials");
this.getLogger().info(configurator.resolveLocalizedString("%hookedIntoEssentials%", null));
// HOOKL: WorldGuard
wgAPI = (WorldGuardPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldGuard");
this.getLogger().info(configurator.resolveLocalizedString("%hookedIntoWorldGuard%", null));
if (worldGuardHandler == null) {
worldGuardHandler = new WorldGuardHandler(this, wgAPI);
if (config_autoUpdate) {
this.getLogger().info(configurator.resolveLocalizedString("%autoUpdateTriggered%", null));
Bukkit.getServer().getScheduler().runTaskLater(this, new Runnable() {
public void run() {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "flatme update");
}
}, 1200L);
}
}
}
public int getConfig_levelHeight() {
return config_levelHeight;
}
}
| gpl-2.0 |
autermann/SOS | core/api/src/main/java/org/n52/sos/exception/swes/InvalidRequestException.java | 1927 | /*
* Copyright (C) 2012-2018 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* License version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*/
package org.n52.sos.exception.swes;
import static org.n52.janmayen.http.HTTPStatus.BAD_REQUEST;
import org.n52.shetland.ogc.swes.exception.SwesExceptionCode;
/**
* @author <a href="mailto:c.autermann@52north.org">Christian Autermann</a>
* @author <a href="mailto:e.h.juerrens@52north.org">Eike Hinderk
* Jürrens</a>
*
* @since 4.0.0
*/
public class InvalidRequestException extends CodedSwesException {
private static final long serialVersionUID = 716704289288231167L;
public InvalidRequestException() {
super(SwesExceptionCode.InvalidRequest);
setStatus(BAD_REQUEST);
}
}
| gpl-2.0 |
52North/SOS | converter/eprtr/src/main/java/org/n52/sos/converter/EprtrConverter.java | 33539 | /*
* Copyright (C) 2012-2022 52°North Spatial Information Research GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* License version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*/
package org.n52.sos.converter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import org.apache.xmlbeans.XmlObject;
import org.n52.faroe.annotation.Setting;
import org.n52.iceland.convert.RequestResponseModifier;
import org.n52.iceland.convert.RequestResponseModifierFacilitator;
import org.n52.iceland.convert.RequestResponseModifierKey;
import org.n52.shetland.ogc.gml.AbstractFeature;
import org.n52.shetland.ogc.gml.ReferenceType;
import org.n52.shetland.ogc.gml.time.Time;
import org.n52.shetland.ogc.gml.time.TimeInstant;
import org.n52.shetland.ogc.gml.time.TimePeriod;
import org.n52.shetland.ogc.om.NamedValue;
import org.n52.shetland.ogc.om.ObservationMergeIndicator;
import org.n52.shetland.ogc.om.ObservationStream;
import org.n52.shetland.ogc.om.OmConstants;
import org.n52.shetland.ogc.om.OmObservableProperty;
import org.n52.shetland.ogc.om.OmObservation;
import org.n52.shetland.ogc.om.OmObservationConstellation;
import org.n52.shetland.ogc.om.ParameterHolder;
import org.n52.shetland.ogc.om.SingleObservationValue;
import org.n52.shetland.ogc.om.features.FeatureCollection;
import org.n52.shetland.ogc.om.features.samplingFeatures.AbstractSamplingFeature;
import org.n52.shetland.ogc.om.values.BooleanValue;
import org.n52.shetland.ogc.om.values.SweDataArrayValue;
import org.n52.shetland.ogc.ows.exception.NoApplicableCodeException;
import org.n52.shetland.ogc.ows.exception.OwsExceptionReport;
import org.n52.shetland.ogc.ows.service.OwsServiceRequest;
import org.n52.shetland.ogc.ows.service.OwsServiceResponse;
import org.n52.shetland.ogc.sos.Sos2Constants;
import org.n52.shetland.ogc.sos.request.GetFeatureOfInterestRequest;
import org.n52.shetland.ogc.sos.request.GetObservationRequest;
import org.n52.shetland.ogc.sos.response.AbstractStreaming;
import org.n52.shetland.ogc.sos.response.GetFeatureOfInterestResponse;
import org.n52.shetland.ogc.sos.response.GetObservationResponse;
import org.n52.shetland.ogc.swe.SweAbstractDataComponent;
import org.n52.shetland.ogc.swe.SweDataArray;
import org.n52.shetland.ogc.swe.SweDataRecord;
import org.n52.shetland.ogc.swe.SweField;
import org.n52.shetland.ogc.swe.encoding.SweTextEncoding;
import org.n52.shetland.ogc.swe.simpleType.SweBoolean;
import org.n52.shetland.ogc.swe.simpleType.SweQuantity;
import org.n52.shetland.ogc.swe.simpleType.SweText;
import org.n52.shetland.ogc.swe.simpleType.SweTime;
import org.n52.shetland.util.CollectionHelper;
import org.n52.shetland.util.JavaHelper;
import org.n52.svalbard.decode.Decoder;
import org.n52.svalbard.decode.DecoderKey;
import org.n52.svalbard.decode.DecoderRepository;
import org.n52.svalbard.decode.XmlNamespaceDecoderKey;
import org.n52.svalbard.decode.exception.DecodingException;
import org.n52.svalbard.decode.exception.NoDecoderForKeyException;
import org.w3c.dom.Node;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
public class EprtrConverter implements RequestResponseModifier {
public static final String MERGE_FOR_EPRTR = "misc.merge.eprtr";
private static final String POLLUTANTS = "pollutants";
private static final String METHOD_USED = "MethodUsed";
private static final String REMARK_TEXT = "RemarkText";
private static final String AIR = "AIR";
private static final String YEAR = "Year";
private static final String POLLUTANT_CODE = "PollutantCode";
private static final String TOTAL_QUANTITY = "TotalQuantity";
private static final String QUANTITY = "Quantity";
private static final String WASTE_HANDLER_PARTY = "WasteHandlerParty";
private static final String WASTE_TYPE_CODE = "WasteTypeCode";
private static final String WASTE_TREATMENT_CODE = "WasteTreatmentCode";
private static final String NAME = "Name";
private static final String ADDRESS = "Address";
private static final String SITE_ADDRESS = "SiteAddress";
private static final String STRET_NAME = "StreetName";
private static final String BUILDING_NUMBER = "BuildingNumber";
private static final String CITY_NAME = "CityName";
private static final String POSTCODE_CODE = "PostcodeCode";
private static final String COUNTRY_ID = "CountryID";
private static final String CONFIDENTIAL_INDICATOR = "ConfidentialIndicator";
private static final String METHOD_BASIS_CODE = "MethodBasisCode";
private static final String ACCIDENTIAL_QUANTITY = "AccidentialQuantity";
private static final String MEDIUM_CODE = "MediumCode";
private static final String CONFIDENTIAL_CODE = "ConfidentialCode";
private static final String POLLUTANT_RELEASE = "PollutantRelease";
private static final String POLLUTANT_TRANSFER = "PollutantTransfer";
private static final String WASTE_TRANSFER = "WasteTransfer";
private static final Set<RequestResponseModifierKey> REQUEST_RESPONSE_MODIFIER_KEYS = getKey();
private static final ObservationMergeIndicator INDICATOR =
new ObservationMergeIndicator().setFeatureOfInterest(true).setProcedure(true);
private DecoderRepository decoderRepository;
private boolean mergeForEprtr;
private static Set<RequestResponseModifierKey> getKey() {
Set<RequestResponseModifierKey> keys = Sets.newHashSet();
keys.add(new RequestResponseModifierKey(Sos2Constants.SOS, Sos2Constants.SERVICEVERSION,
new GetObservationRequest(), new GetObservationResponse()));
keys.add(new RequestResponseModifierKey(Sos2Constants.SOS, Sos2Constants.SERVICEVERSION,
new GetFeatureOfInterestRequest(), new GetFeatureOfInterestResponse()));
return keys;
}
@Setting(MERGE_FOR_EPRTR)
public void setMergeForEprtr(boolean mergeForEprtr) {
this.mergeForEprtr = mergeForEprtr;
}
public DecoderRepository getDecoderRepository() {
return decoderRepository;
}
@Inject
public void setDecoderRepository(DecoderRepository decoderRepository) {
this.decoderRepository = decoderRepository;
}
@Override
public Set<RequestResponseModifierKey> getKeys() {
return Collections.unmodifiableSet(REQUEST_RESPONSE_MODIFIER_KEYS);
}
@Override
public RequestResponseModifierFacilitator getFacilitator() {
return new RequestResponseModifierFacilitator().setMerger(true).setSplitter(false);
}
@Override
public OwsServiceRequest modifyRequest(OwsServiceRequest request) throws OwsExceptionReport {
return request;
}
@Override
public OwsServiceResponse modifyResponse(OwsServiceRequest request, OwsServiceResponse response)
throws OwsExceptionReport {
if (response instanceof GetObservationResponse) {
if (mergeForEprtr()) {
return mergeObservations((GetObservationResponse) response);
} else {
return checkGetObservationFeatures((GetObservationResponse) response);
}
}
if (response instanceof GetFeatureOfInterestResponse && mergeForEprtr()) {
return checkFeatures((GetFeatureOfInterestResponse) response);
}
return response;
}
private OwsServiceResponse mergeObservations(GetObservationResponse response) throws OwsExceptionReport {
response.setObservationCollection(
ObservationStream.of(mergeObservations(mergeStreamingData(response.getObservationCollection()))));
checkObservationFeatures(response.getObservationCollection());
return response;
}
private List<OmObservation> mergeObservations(List<OmObservation> observations) throws OwsExceptionReport {
if (CollectionHelper.isNotEmpty(observations)) {
final List<OmObservation> mergedObservations = new LinkedList<OmObservation>();
int obsIdCounter = 1;
for (final OmObservation sosObservation : observations) {
if (checkForProcedure(sosObservation)) {
if (mergedObservations.isEmpty()) {
if (!sosObservation.isSetGmlID()) {
sosObservation.setObservationID(Integer.toString(obsIdCounter++));
}
mergedObservations.add(convertObservation(sosObservation));
} else {
boolean combined = false;
for (final OmObservation combinedSosObs : mergedObservations) {
if (checkForMerge(combinedSosObs, sosObservation, INDICATOR)) {
mergeValues(combinedSosObs, convertObservation(sosObservation));
combined = true;
break;
}
}
if (!combined) {
mergedObservations.add(convertObservation(sosObservation));
}
}
}
}
return mergedObservations;
}
return Lists.newArrayList(observations);
}
private OwsServiceResponse checkGetObservationFeatures(GetObservationResponse response)
throws NoSuchElementException, OwsExceptionReport {
response.setObservationCollection(
ObservationStream.of(checkObservationFeatures(response.getObservationCollection())));
return response;
}
private List<OmObservation> checkObservationFeatures(ObservationStream observationStream)
throws NoSuchElementException, OwsExceptionReport {
List<OmObservation> processed = new LinkedList<>();
while (observationStream != null && observationStream.hasNext()) {
OmObservation omObservation = observationStream.next();
checkFeature(omObservation.getObservationConstellation().getFeatureOfInterest());
processed.add(omObservation);
}
return processed;
}
private OwsServiceResponse checkFeatures(GetFeatureOfInterestResponse response) {
AbstractFeature abstractFeature = response.getAbstractFeature();
if (abstractFeature instanceof FeatureCollection) {
for (AbstractFeature feature : ((FeatureCollection) abstractFeature).getMembers().values()) {
checkFeature(feature);
}
} else {
checkFeature(abstractFeature);
}
return response;
}
private void checkFeature(AbstractFeature abstractFeature) {
if (abstractFeature instanceof AbstractSamplingFeature) {
AbstractSamplingFeature asf = (AbstractSamplingFeature) abstractFeature;
if (asf.isSetParameter() && isPrtr(asf.getParameters())
&& !containsConfidentialIndicator(asf.getParameters())) {
NamedValue<Boolean> confidentialIndicator = new NamedValue<>();
confidentialIndicator.setName(new ReferenceType(CONFIDENTIAL_INDICATOR));
if (containsConfidentialCode(asf.getParameters())) {
confidentialIndicator.setValue(new BooleanValue(true));
} else {
confidentialIndicator.setValue(new BooleanValue(false));
}
asf.addParameter(confidentialIndicator);
}
}
}
private boolean isPrtr(List<NamedValue<?>> parameters) {
for (NamedValue<?> namedValue : parameters) {
if (namedValue.getName().getHref().equalsIgnoreCase(METHOD_BASIS_CODE)
|| namedValue.getName().getHref().equalsIgnoreCase(ACCIDENTIAL_QUANTITY)
|| namedValue.getName().getHref().equalsIgnoreCase(MEDIUM_CODE)) {
return true;
}
}
return false;
}
private boolean containsConfidentialCode(List<NamedValue<?>> parameters) {
for (NamedValue<?> namedValue : parameters) {
if (namedValue.getName().getHref().equalsIgnoreCase(CONFIDENTIAL_CODE)) {
return true;
}
}
return false;
}
private boolean containsConfidentialIndicator(List<NamedValue<?>> parameters) {
for (NamedValue<?> namedValue : parameters) {
if (namedValue.getName().getHref().equalsIgnoreCase(CONFIDENTIAL_INDICATOR)) {
return true;
}
}
return false;
}
private List<OmObservation> mergeStreamingData(ObservationStream observationStream) throws OwsExceptionReport {
List<OmObservation> processed = new LinkedList<>();
while (observationStream.hasNext()) {
OmObservation observation = observationStream.next();
if (observation.getValue() instanceof AbstractStreaming) {
ObservationStream valueStream = ((AbstractStreaming) observation.getValue()).merge(INDICATOR);
while (valueStream.hasNext()) {
processed.add(valueStream.next());
}
} else {
processed.add(observation);
}
}
return processed;
}
private boolean checkForProcedure(OmObservation sosObservation) {
return POLLUTANT_RELEASE.equals(sosObservation.getObservationConstellation().getProcedureIdentifier())
|| POLLUTANT_TRANSFER.equals(sosObservation.getObservationConstellation().getProcedureIdentifier())
|| WASTE_TRANSFER.equals(sosObservation.getObservationConstellation().getProcedureIdentifier());
}
private boolean checkForProcedure(OmObservation observation, OmObservation observationToAdd) {
return observation.getObservationConstellation().getProcedure()
.equals(observationToAdd.getObservationConstellation().getProcedure());
}
private OmObservation convertObservation(OmObservation sosObservation) throws OwsExceptionReport {
if (POLLUTANT_RELEASE.equals(sosObservation.getObservationConstellation().getProcedureIdentifier())) {
SweDataArrayValue value = new SweDataArrayValue();
value.setValue(getPollutantReleaseArray(sosObservation.getValue().getValue().getUnit()));
value.addBlock(createPollutantReleaseBlock(sosObservation));
SingleObservationValue<SweDataArray> singleObservationValue = new SingleObservationValue<>(value);
singleObservationValue.setPhenomenonTime(sosObservation.getPhenomenonTime());
sosObservation.setValue(singleObservationValue);
OmObservationConstellation obsConst = sosObservation.getObservationConstellation().copy();
obsConst.setObservationType(OmConstants.OBS_TYPE_SWE_ARRAY_OBSERVATION);
obsConst.setObservableProperty(new OmObservableProperty(POLLUTANTS));
sosObservation.setObservationConstellation(obsConst);
} else if (POLLUTANT_TRANSFER.equals(sosObservation.getObservationConstellation().getProcedureIdentifier())) {
SweDataArrayValue value = new SweDataArrayValue();
value.setValue(getPollutantTransferArray(sosObservation.getValue().getValue().getUnit()));
value.addBlock(createPollutantTransferBlock(sosObservation));
SingleObservationValue<SweDataArray> singleObservationValue = new SingleObservationValue<>(value);
singleObservationValue.setPhenomenonTime(sosObservation.getPhenomenonTime());
sosObservation.setValue(singleObservationValue);
OmObservationConstellation obsConst = sosObservation.getObservationConstellation().copy();
obsConst.setObservationType(OmConstants.OBS_TYPE_SWE_ARRAY_OBSERVATION);
obsConst.setObservableProperty(new OmObservableProperty(POLLUTANTS));
sosObservation.setObservationConstellation(obsConst);
} else if (WASTE_TRANSFER.equals(sosObservation.getObservationConstellation().getProcedureIdentifier())) {
SweDataArrayValue value = new SweDataArrayValue();
value.setValue(getWasteTransferArray(sosObservation.getValue().getValue().getUnit()));
value.addBlock(createWasteTransferBlock(sosObservation));
SingleObservationValue<SweDataArray> singleObservationValue = new SingleObservationValue<>(value);
singleObservationValue.setPhenomenonTime(sosObservation.getPhenomenonTime());
sosObservation.setValue(singleObservationValue);
OmObservationConstellation obsConst = sosObservation.getObservationConstellation().copy();
obsConst.setObservationType(OmConstants.OBS_TYPE_SWE_ARRAY_OBSERVATION);
obsConst.setObservableProperty(new OmObservableProperty(POLLUTANTS));
sosObservation.setObservationConstellation(obsConst);
}
return sosObservation;
}
private List<String> createPollutantReleaseBlock(OmObservation sosObservation) {
List<String> values = new LinkedList<>();
values.add(getYear(sosObservation.getPhenomenonTime()));
// MediumCode
values.add(getMediumCode(sosObservation.getObservationConstellation()));
// PollutantCode
values.add(sosObservation.getObservationConstellation().getObservablePropertyIdentifier());
values.add(getParameter(sosObservation.getParameterHolder(), METHOD_BASIS_CODE));
values.add(getParameter(sosObservation.getParameterHolder(), METHOD_USED));
values.add(JavaHelper.asString(sosObservation.getValue().getValue().getValue()));
values.add(getParameter(sosObservation.getParameterHolder(), ACCIDENTIAL_QUANTITY));
String confidentialCode = getParameter(sosObservation.getParameterHolder(), CONFIDENTIAL_CODE);
values.add(getConfidentialIndicator(confidentialCode, sosObservation.getParameterHolder()));
values.add(confidentialCode);
values.add(getParameter(sosObservation.getParameterHolder(), REMARK_TEXT));
return values;
}
private String getMediumCode(OmObservationConstellation observationConstellation) {
if (observationConstellation.isSetOfferings()) {
Optional<String> offering = observationConstellation.getOfferings().stream().findFirst();
return offering.isPresent() ? offering.get() : AIR;
}
return AIR;
}
private SweDataArray getPollutantReleaseArray(String unit) {
SweDataRecord record = new SweDataRecord();
record.addName(POLLUTANTS);
record.addField(
new SweField(YEAR, new SweTime().setUom(OmConstants.PHEN_UOM_ISO8601).setDefinition(YEAR)));
record.addField(new SweField(MEDIUM_CODE, new SweText().setDefinition(MEDIUM_CODE)));
record.addField(new SweField(POLLUTANT_CODE, new SweText().setDefinition(POLLUTANT_CODE)));
record.addField(new SweField(METHOD_BASIS_CODE, new SweText().setDefinition(METHOD_BASIS_CODE)));
record.addField(new SweField(METHOD_USED, new SweText().setDefinition(METHOD_USED)));
record.addField(new SweField(TOTAL_QUANTITY, new SweQuantity().setUom(unit).setDefinition(TOTAL_QUANTITY)));
record.addField(new SweField(ACCIDENTIAL_QUANTITY,
new SweQuantity().setUom(unit).setDefinition(ACCIDENTIAL_QUANTITY)));
record.addField(
new SweField(CONFIDENTIAL_INDICATOR, new SweBoolean().setDefinition(CONFIDENTIAL_INDICATOR)));
record.addField(new SweField(CONFIDENTIAL_CODE, new SweText().setDefinition(CONFIDENTIAL_CODE)));
record.addField(new SweField(REMARK_TEXT, new SweText().setDefinition(REMARK_TEXT)));
SweDataArray array = new SweDataArray();
array.setElementType(record);
array.setEncoding(getEncoding());
return array;
}
private List<String> createPollutantTransferBlock(OmObservation sosObservation) {
List<String> values = new LinkedList<>();
values.add(getYear(sosObservation.getPhenomenonTime()));
values.add(sosObservation.getObservationConstellation().getObservablePropertyIdentifier());
values.add(getParameter(sosObservation.getParameterHolder(), METHOD_BASIS_CODE));
values.add(getParameter(sosObservation.getParameterHolder(), METHOD_USED));
values.add(JavaHelper.asString(sosObservation.getValue().getValue().getValue()));
String confidentialCode = getParameter(sosObservation.getParameterHolder(), CONFIDENTIAL_CODE);
values.add(getConfidentialIndicator(confidentialCode, sosObservation.getParameterHolder()));
values.add(confidentialCode);
values.add(getParameter(sosObservation.getParameterHolder(), REMARK_TEXT));
return values;
}
private SweDataArray getPollutantTransferArray(String unit) {
SweDataRecord record = new SweDataRecord();
record.addName(POLLUTANTS);
record.addField(
new SweField(YEAR, new SweTime().setUom(OmConstants.PHEN_UOM_ISO8601).setDefinition(YEAR)));
record.addField(new SweField(POLLUTANT_CODE, new SweText().setDefinition(POLLUTANT_CODE)));
record.addField(new SweField(METHOD_BASIS_CODE, new SweText().setDefinition(METHOD_BASIS_CODE)));
record.addField(new SweField(METHOD_USED, new SweText().setDefinition(METHOD_USED)));
record.addField(new SweField(QUANTITY, new SweQuantity().setUom(unit).setDefinition(QUANTITY)));
record.addField(
new SweField(CONFIDENTIAL_INDICATOR, new SweBoolean().setDefinition(CONFIDENTIAL_INDICATOR)));
record.addField(new SweField(CONFIDENTIAL_CODE, new SweText().setDefinition(CONFIDENTIAL_CODE)));
record.addField(new SweField(REMARK_TEXT, new SweText().setDefinition(REMARK_TEXT)));
SweDataArray array = new SweDataArray();
array.setElementType(record);
array.setEncoding(getEncoding());
return array;
}
private List<String> createWasteTransferBlock(OmObservation sosObservation) throws OwsExceptionReport {
List<String> values = new LinkedList<>();
values.add(getYear(sosObservation.getPhenomenonTime()));
values.add(sosObservation.getObservationConstellation().getObservablePropertyIdentifier());
values.add(getWasteTreatmentCode(sosObservation.getObservationConstellation().getOfferings()));
values.add(JavaHelper.asString(sosObservation.getValue().getValue().getValue()));
values.add(getParameter(sosObservation.getParameterHolder(), METHOD_BASIS_CODE));
values.add(getParameter(sosObservation.getParameterHolder(), METHOD_USED));
String confidentialCode = getParameter(sosObservation.getParameterHolder(), CONFIDENTIAL_CODE);
values.add(getConfidentialIndicator(confidentialCode, sosObservation.getParameterHolder()));
values.add(confidentialCode);
values.add(getParameter(sosObservation.getParameterHolder(), REMARK_TEXT));
values.add(getWasteHandlerPartyParameter(sosObservation.getParameterHolder(), WASTE_HANDLER_PARTY));
return values;
}
private String getConfidentialIndicator(String confidentialCode, ParameterHolder parameterHolder) {
String confidentialIndicator = getParameter(parameterHolder, CONFIDENTIAL_INDICATOR);
return confidentialIndicator != null && !confidentialIndicator.isEmpty() ? confidentialIndicator
: confidentialCode != null && !confidentialCode.isEmpty() ? "true" : "false";
}
private SweDataArray getWasteTransferArray(String unit) {
SweDataRecord record = new SweDataRecord();
record.addName(POLLUTANTS);
record.addField(
new SweField(YEAR, new SweTime().setUom(OmConstants.PHEN_UOM_ISO8601).setDefinition(YEAR)));
record.addField(new SweField(WASTE_TYPE_CODE, new SweText().setDefinition(WASTE_TYPE_CODE)));
record.addField(new SweField(WASTE_TREATMENT_CODE, new SweText().setDefinition(WASTE_TREATMENT_CODE)));
record.addField(new SweField(QUANTITY, new SweQuantity().setUom(unit).setDefinition(QUANTITY)));
record.addField(new SweField(METHOD_BASIS_CODE, new SweText().setDefinition(METHOD_BASIS_CODE)));
record.addField(new SweField(METHOD_USED, new SweText().setDefinition(METHOD_USED)));
record.addField(
new SweField(CONFIDENTIAL_INDICATOR, new SweBoolean().setDefinition(CONFIDENTIAL_INDICATOR)));
record.addField(new SweField(CONFIDENTIAL_CODE, new SweText().setDefinition(CONFIDENTIAL_CODE)));
record.addField(new SweField(REMARK_TEXT, new SweText().setDefinition(REMARK_TEXT)));
record.addField(new SweField(WASTE_HANDLER_PARTY, createWasteHandlerPary()));
SweDataArray array = new SweDataArray();
array.setElementType(record);
array.setEncoding(getEncoding());
return array;
}
private String getWasteTreatmentCode(Set<String> offerings) {
for (String offering : offerings) {
if (offering.length() == 1) {
return offering;
}
}
return "";
}
private SweAbstractDataComponent createWasteHandlerPary() {
SweDataRecord record = new SweDataRecord();
record.setDefinition(WASTE_HANDLER_PARTY);
record.addField(new SweField(NAME, new SweText().setDefinition(NAME)));
record.addField(new SweField(ADDRESS, createAddressRecord(ADDRESS)));
record.addField(new SweField(SITE_ADDRESS, createAddressRecord(SITE_ADDRESS)));
return record;
}
private SweAbstractDataComponent createAddressRecord(String definition) {
SweDataRecord record = new SweDataRecord();
record.setDefinition(definition);
record.addField(new SweField(STRET_NAME, new SweText().setDefinition(STRET_NAME)));
record.addField(new SweField(BUILDING_NUMBER, new SweText().setDefinition(BUILDING_NUMBER)));
record.addField(new SweField(CITY_NAME, new SweText().setDefinition(CITY_NAME)));
record.addField(new SweField(POSTCODE_CODE, new SweText().setDefinition(POSTCODE_CODE)));
record.addField(new SweField(COUNTRY_ID, new SweText().setDefinition(COUNTRY_ID)));
return record;
}
private String getYear(Time phenomenonTime) {
if (phenomenonTime instanceof TimePeriod) {
return Integer.toString(((TimePeriod) phenomenonTime).getEnd().getYear());
}
return Integer.toString(((TimeInstant) phenomenonTime).getValue().getYear());
}
private String getParameter(ParameterHolder holder, String name) {
Object parameterObject = getParameterObject(holder, name);
return parameterObject != null ? parameterObject.toString() : "";
}
private Object getParameterObject(ParameterHolder holder, String name) {
for (NamedValue<?> namedValue : holder.getParameter()) {
if (name.equals(namedValue.getName().getHref())) {
holder.removeParameter(namedValue);
if (namedValue.getValue().isSetValue()) {
return namedValue.getValue().getValue();
}
}
}
return null;
}
private String getWasteHandlerPartyParameter(ParameterHolder parameterHolder, String name)
throws OwsExceptionReport {
Object parameterObject = getParameterObject(parameterHolder, name);
if (parameterObject != null && parameterObject instanceof XmlObject) {
try {
Object xml = decodeXmlObject((XmlObject) parameterObject);
if (xml instanceof SweDataRecord) {
List<String> values = getValuesFromRecord((SweDataRecord) xml);
if (!values.isEmpty()) {
return Joiner.on(",").join(values);
}
}
} catch (DecodingException e) {
throw new NoApplicableCodeException().causedBy(e);
}
}
return ",,,,,,,,,,";
}
private List<String> getValuesFromRecord(SweDataRecord record) {
List<String> values = new LinkedList<>();
if (record.isSetFields()) {
for (SweField field : record.getFields()) {
if (field.getElement() instanceof SweText) {
values.add(((SweText) field.getElement()).getValue());
} else if (field.getElement() instanceof SweDataRecord) {
values.addAll(getValuesFromRecord((SweDataRecord) field.getElement()));
}
}
}
return values;
}
private SweTextEncoding getEncoding() {
SweTextEncoding encoding = new SweTextEncoding();
encoding.setBlockSeparator("#");
encoding.setTokenSeparator(",");
return encoding;
}
private void mergeValues(OmObservation combinedSosObs, OmObservation sosObservation) {
SweDataArray combinedValue = (SweDataArray) combinedSosObs.getValue().getValue().getValue();
SweDataArray value = (SweDataArray) sosObservation.getValue().getValue().getValue();
if (value.isSetValues()) {
combinedValue.addAll(value.getValues());
if (combinedSosObs.getPhenomenonTime() instanceof TimePeriod) {
((TimePeriod) combinedSosObs.getPhenomenonTime()).extendToContain(sosObservation.getPhenomenonTime());
}
}
}
protected boolean checkForMerge(OmObservation observation, OmObservation observationToAdd,
ObservationMergeIndicator observationMergeIndicator) {
boolean merge = true;
if (observation.isSetAdditionalMergeIndicator() && observationToAdd.isSetAdditionalMergeIndicator()) {
merge = observation.getAdditionalMergeIndicator().equals(observationToAdd.getAdditionalMergeIndicator());
} else if ((observation.isSetAdditionalMergeIndicator() && !observationToAdd.isSetAdditionalMergeIndicator())
|| (!observation.isSetAdditionalMergeIndicator()
&& observationToAdd.isSetAdditionalMergeIndicator())) {
merge = false;
}
if (observationMergeIndicator.isProcedure()) {
merge = merge && checkForProcedure(observation, observationToAdd);
}
if (observationMergeIndicator.isFeatureOfInterest()) {
merge = merge && checkForFeatureOfInterest(observation, observationToAdd);
}
return merge;
}
private boolean checkForFeatureOfInterest(OmObservation observation, OmObservation observationToAdd) {
return observation.getObservationConstellation().getFeatureOfInterest()
.equals(observationToAdd.getObservationConstellation().getFeatureOfInterest());
}
private boolean mergeForEprtr() {
return mergeForEprtr;
}
private <T> T decodeXmlObject(XmlObject xbObject) throws DecodingException {
DecoderKey key = getDecoderKey(xbObject);
Decoder<T, XmlObject> decoder = getDecoderRepository().getDecoder(key);
if (decoder == null) {
DecoderKey schemaTypeKey =
new XmlNamespaceDecoderKey(xbObject.schemaType().getName().getNamespaceURI(), xbObject.getClass());
decoder = getDecoderRepository().getDecoder(schemaTypeKey);
}
if (decoder == null) {
throw new NoDecoderForKeyException(key);
}
return decoder.decode(xbObject);
}
private DecoderKey getDecoderKey(XmlObject doc) {
Node domNode = doc.getDomNode();
String namespaceURI = domNode.getNamespaceURI();
if (namespaceURI == null && domNode.getFirstChild() != null) {
namespaceURI = domNode.getFirstChild().getNamespaceURI();
}
/*
* if document starts with a comment, get next sibling (and ignore
* initial comment)
*/
if (namespaceURI == null && domNode.getFirstChild() != null
&& domNode.getFirstChild().getNextSibling() != null) {
namespaceURI = domNode.getFirstChild().getNextSibling().getNamespaceURI();
}
return new XmlNamespaceDecoderKey(namespaceURI, doc.getClass());
}
}
| gpl-2.0 |
hjgode/android-stuff | BarcodeExample/src/com/intermec/barcodeexample/SymbologyActivity.java | 11418 | package com.intermec.barcodeexample;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class SymbologyActivity extends Activity{
com.intermec.aidc.BarcodeReader bcr;
SymbologyAdapter dataAdapter = null;
//number of symbologies for enabling and disabling
private static final int SYMBOLOGY_SIZE = 40;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_symbology);
//set lock the orientation
//otherwise, the onDestory will trigger
//when orientation changes
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//get BarcodeReader instance
bcr = MainActivity.getBarcodeObject();
if(bcr != null)
{
//Generate list View from ArrayList
displaySymbologyListView();
}
}
ListView listView;
int selctedPos;
SymbologyItems selectedItem;
private void displaySymbologyListView()
{
//Array list of symbologies
ArrayList<SymbologyItems> symbologyList = new ArrayList<SymbologyItems>();
for (int i = 1; i<= SYMBOLOGY_SIZE; i++)
{
ArrayList<Object> itemList = getSymbologyStatus(i);
SymbologyItems symbItem = new SymbologyItems(i, (String)itemList.get(0), (Boolean)itemList.get(1));
symbologyList.add(symbItem);
}
//create an ArrayAdaptar from the String Array
dataAdapter = new SymbologyAdapter(this, R.layout.symbology_info, symbologyList);
listView = (ListView) findViewById(R.id.listViewSymbology);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//get the selected symbology item
SymbologyItems symbItem = (SymbologyItems) parent.getItemAtPosition(position);
CheckBox chkBox = (CheckBox) view.findViewById(R.id.checkBoxStatus);
if(chkBox.isChecked())
{
//uncheck item if it was checked
chkBox.setChecked(false);
setSymbologyStatus(symbItem.getId(), false);
}
else
{
//check item if it was unchecked
chkBox.setChecked(true);
setSymbologyStatus(symbItem.getId(), true);
}
}
});
}
private ArrayList<Object> getSymbologyStatus(int id)
{
boolean status = false;
String name = null;
ArrayList<Object> dataList = new ArrayList<Object>();
switch (id)
{
case 1:
name = "Australian Post";
status = bcr.symbology.australianPost.isEnabled();
break;
case 2:
name = "Aztec";
status = bcr.symbology.aztec.isEnabled();
break;
case 3:
name = "Bpo";
status = bcr.symbology.bpo.isEnabled();
break;
case 4:
name = "Canada Post";
status = bcr.symbology.canadaPost.isEnabled();
break;
case 5:
name = "Codabar";
status = bcr.symbology.codabar.isEnabled();
break;
case 6:
name = "Codablock A";
status = bcr.symbology.codablockA.isEnabled();
break;
case 7:
name = "Codablock F";
status = bcr.symbology.codablockF.isEnabled();
break;
case 8:
name = "Code 11";
status = bcr.symbology.code11.isEnabled();
break;
case 9:
name = "Code 128";
status = bcr.symbology.code128.isEnabled();
break;
case 10:
name = "Code 39";
status = bcr.symbology.code39.isEnabled();
break;
case 11:
name = "Code 93";
status = bcr.symbology.code93.isEnabled();
break;
case 12:
name = "Datamatrix";
status = bcr.symbology.datamatrix.isEnabled();
break;
case 13:
name = "Dutch Post";
status = bcr.symbology.dutchPost.isEnabled();
break;
case 14:
name = "EanUpc.Ean13";
status = bcr.symbology.eanUpc.isEan13Enabled();
break;
case 15:
name = "EanUpc.Ean8";
status = bcr.symbology.eanUpc.isEan8Enabled();
break;
case 16:
name = "EanUpc.UPCA";
status = bcr.symbology.eanUpc.isUPCAEnabled();
break;
case 17:
name = "EanUpc.UPCE";
status = bcr.symbology.eanUpc.isUPCEEnabled();
break;
case 18:
name = "EanUpc.UPCE1";
status = bcr.symbology.eanUpc.isUPCE1Enabled();
break;
case 19:
name = "Gs1 Composite";
status = bcr.symbology.gs1Composite.isEnabled();
break;
case 20:
name = "Gs1 Databar Expanded";
status = bcr.symbology.gs1DataBarExpanded.isEnabled();
break;
case 21:
name = "Gs1 Databar Limited";
status = bcr.symbology.gs1DataBarLimited.isEnabled();
break;
case 22:
name = "Gs1 Databar Omni Directional";
status = bcr.symbology.gs1DataBarOmniDirectional.isEnabled();
break;
case 23:
name = "Han Xin";
status = bcr.symbology.hanXin.isEnabled();
break;
case 24:
name = "Infomail";
status = bcr.symbology.infomail.isEnabled();
break;
case 25:
name = "Intelligen Mail";
status = bcr.symbology.intelligentMail.isEnabled();
break;
case 26:
name = "Interleaved 2 of 5";
status = bcr.symbology.interleaved2Of5.isEnabled();
break;
case 27:
name = "Japan Post";
status = bcr.symbology.japanPost.isEnabled();
break;
case 28:
name = "Matrix 2 of 5";
status = bcr.symbology.matrix2Of5.isEnabled();
break;
case 29:
name = "Maxicode";
status = bcr.symbology.maxicode.isEnabled();
break;
case 30:
name = "Micro PDF 417";
status = bcr.symbology.microPdf417.isEnabled();
break;
case 31:
name = "MSI";
status = bcr.symbology.msi.isEnabled();
break;
case 32:
name = "PDF 417";
status = bcr.symbology.pdf417.isEnabled();
break;
case 33:
name = "Planet";
status = bcr.symbology.planet.isEnabled();
break;
case 34:
name = "Plessey";
status = bcr.symbology.plessey.isEnabled();
break;
case 35:
name = "Postnet";
status = bcr.symbology.postnet.isEnabled();
break;
case 36:
name = "QR Code";
status = bcr.symbology.qrCode.isEnabled();
break;
case 37:
name = "Standard 2 of 5";
status = bcr.symbology.standard2Of5.isEnabled();
break;
case 38:
name = "Sweden Post";
status = bcr.symbology.swedenPost.isEnabled();
break;
case 39:
name = "Telepen";
status = bcr.symbology.telepen.isEnabled();
break;
case 40:
name = "TLC 39";
status = bcr.symbology.tlc39.isEnabled();
break;
}
dataList.add(0, name);
dataList.add(1, status);
return dataList;
}
private void setSymbologyStatus(int id, Boolean isEnabled)
{
switch (id)
{
case 1:
bcr.symbology.australianPost.setEnable(isEnabled);
break;
case 2:
bcr.symbology.aztec.setEnable(isEnabled);
break;
case 3:
bcr.symbology.bpo.setEnable(isEnabled);
break;
case 4:
bcr.symbology.canadaPost.setEnable(isEnabled);
break;
case 5:
bcr.symbology.codabar.setEnable(isEnabled);
break;
case 6:
bcr.symbology.codablockA.setEnable(isEnabled);
break;
case 7:
bcr.symbology.codablockF.setEnable(isEnabled);
break;
case 8:
bcr.symbology.code11.setEnable(isEnabled);
break;
case 9:
bcr.symbology.code128.setEnable(isEnabled);
break;
case 10:
bcr.symbology.code39.setEnable(isEnabled);
break;
case 11:
bcr.symbology.code93.setEnable(isEnabled);
break;
case 12:
bcr.symbology.datamatrix.setEnable(isEnabled);
break;
case 13:
bcr.symbology.dutchPost.setEnable(isEnabled);
break;
case 14:
bcr.symbology.eanUpc.setEan13Enable(isEnabled);
break;
case 15:
bcr.symbology.eanUpc.setEan8Enable(isEnabled);
break;
case 16:
bcr.symbology.eanUpc.setUPCAEnable(isEnabled);
break;
case 17:
bcr.symbology.eanUpc.setUPCEEnable(isEnabled);
break;
case 18:
bcr.symbology.eanUpc.setUPCE1Enable(isEnabled);
break;
case 19:
bcr.symbology.gs1Composite.setEnable(isEnabled);
break;
case 20:
bcr.symbology.gs1DataBarExpanded.setEnable(isEnabled);
break;
case 21:
bcr.symbology.gs1DataBarLimited.setEnable(isEnabled);
break;
case 22:
bcr.symbology.gs1DataBarOmniDirectional.setEnable(isEnabled);
break;
case 23:
bcr.symbology.hanXin.setEnable(isEnabled);
break;
case 24:
bcr.symbology.infomail.setEnable(isEnabled);
break;
case 25:
bcr.symbology.intelligentMail.setEnable(isEnabled);
break;
case 26:
bcr.symbology.interleaved2Of5.setEnable(isEnabled);
break;
case 27:
bcr.symbology.japanPost.setEnable(isEnabled);
break;
case 28:
bcr.symbology.matrix2Of5.setEnable(isEnabled);
break;
case 29:
bcr.symbology.maxicode.setEnable(isEnabled);
break;
case 30:
bcr.symbology.microPdf417.setEnable(isEnabled);
break;
case 31:
bcr.symbology.msi.setEnable(isEnabled);
break;
case 32:
bcr.symbology.pdf417.setEnable(isEnabled);
break;
case 33:
bcr.symbology.planet.setEnable(isEnabled);
break;
case 34:
bcr.symbology.plessey.setEnable(isEnabled);
break;
case 35:
bcr.symbology.postnet.setEnable(isEnabled);
break;
case 36:
bcr.symbology.qrCode.setEnable(isEnabled);
break;
case 37:
bcr.symbology.standard2Of5.setEnable(isEnabled);
break;
case 38:
bcr.symbology.swedenPost.setEnable(isEnabled);
break;
case 39:
bcr.symbology.telepen.setEnable(isEnabled);
break;
case 40:
bcr.symbology.tlc39.setEnable(isEnabled);
break;
}
}
/************************************************************
*
* SymbologyAdapter
*
***********************************************************/
private class SymbologyAdapter extends ArrayAdapter<SymbologyItems>{
private ArrayList<SymbologyItems> symbologyList;
private Context myContext;
public SymbologyAdapter(Context context, int textViewResourceId, ArrayList<SymbologyItems> symbologyList)
{
super(context, textViewResourceId, symbologyList);
this.symbologyList = new ArrayList<SymbologyItems>();
this.symbologyList.addAll(symbologyList);
this.myContext = context.getApplicationContext();
}
private class ViewHolder
{
TextView name;
CheckBox status;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.symbology_info, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.status = (CheckBox) convertView.findViewById(R.id.checkBoxStatus);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
SymbologyItems symItem = symbologyList.get(position);
holder.name.setText(symItem.getName());
holder.status.setChecked(symItem.isEnabled());
holder.name.setTag(symItem);
return convertView;
}
}
}
| gpl-2.0 |
jMotif/GI | src/main/java/net/seninp/gi/repair/RePairRule.java | 5268 | package net.seninp.gi.repair;
import java.util.ArrayList;
import net.seninp.gi.logic.RuleInterval;
/**
* The grammar rule.
*
* @author psenin
*
*/
public class RePairRule {
/** The spacer. */
private static final char SPACE = ' ';
/** The global rule enumerator counter. */
// protected static AtomicInteger numRules = new AtomicInteger(1);
/** The global rules table. */
// protected static Hashtable<Integer, RePairRule> theRules = new Hashtable<Integer,
// RePairRule>();
/** R0 is important, reserve a var for that. */
// protected String r0String;
// protected String r0ExpandedString;
/** The current rule number. */
protected int ruleNumber;
protected String expandedRuleString;
/** Both symbols, (i.e., pair). */
protected RePairSymbol first;
protected RePairSymbol second;
protected int level;
/** Occurrences. */
protected ArrayList<Integer> occurrences;
/** Which TS interval covered. */
protected ArrayList<RuleInterval> ruleIntervals;
/** A handler on the grammar this rule belongs to. */
private RePairGrammar grammar;
/**
* Constructor, assigns a rule ID using the global counter.
*
* @param rg the grammar handler.
*/
public RePairRule(RePairGrammar rg) {
this.grammar = rg;
// assign a next number to this rule and increment the global counter
this.ruleNumber = rg.numRules.intValue();
rg.numRules.incrementAndGet();
rg.theRules.put(this.ruleNumber, this);
this.occurrences = new ArrayList<Integer>();
this.ruleIntervals = new ArrayList<RuleInterval>();
}
/**
* First symbol setter.
*
* @param symbol the symbol to set.
*/
public void setFirst(RePairSymbol symbol) {
this.first = symbol;
}
public RePairSymbol getFirst() {
return this.first;
}
/**
* Second symbol setter.
*
* @param symbol the symbol to set.
*/
public void setSecond(RePairSymbol symbol) {
this.second = symbol;
}
public RePairSymbol getSecond() {
return this.second;
}
/**
* Rule ID getter.
*
* @return the rule ID.
*/
public int getId() {
return this.ruleNumber;
}
/**
* Return the prefixed with R rule.
*
* @return rule string.
*/
public String toRuleString() {
if (0 == this.ruleNumber) {
return this.grammar.r0String;
}
return this.first.toString() + SPACE + this.second.toString() + SPACE;
}
/**
* Set the expanded rule string.
*
* @param str the expanded rule value.
*
*/
public void setExpandedRule(String str) {
this.expandedRuleString = str;
}
/**
* Return the prefixed with R rule.
*
* @return rule string.
*/
public String toExpandedRuleString() {
return this.expandedRuleString;
}
/**
* Adds a rule occurrence.
*
* @param value the new value.
*/
public void addOccurrence(int value) {
if (!this.occurrences.contains(value)) {
this.occurrences.add(value);
}
}
/**
* Gets occurrences.
*
* @return all rule's occurrences.
*/
public int[] getOccurrences() {
int[] res = new int[this.occurrences.size()];
for (int i = 0; i < this.occurrences.size(); i++) {
res[i] = this.occurrences.get(i);
}
return res;
}
public String toString() {
return "R" + this.ruleNumber;
}
public void assignLevel() {
int lvl = Integer.MAX_VALUE;
lvl = Math.min(first.getLevel() + 1, lvl);
lvl = Math.min(second.getLevel() + 1, lvl);
this.level = lvl;
}
public int getLevel() {
return this.level;
}
public ArrayList<RuleInterval> getRuleIntervals() {
return this.ruleIntervals;
}
public int[] getLengths() {
if (this.ruleIntervals.isEmpty()) {
return new int[1];
}
int[] res = new int[this.ruleIntervals.size()];
int count = 0;
for (RuleInterval ri : this.ruleIntervals) {
res[count] = ri.getEnd() - ri.getStart();
count++;
}
return res;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((first == null) ? 0 : first.hashCode());
result = prime * result + ((occurrences == null) ? 0 : occurrences.hashCode());
result = prime * result + ruleNumber;
result = prime * result + ((second == null) ? 0 : second.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RePairRule other = (RePairRule) obj;
if (first == null) {
if (other.first != null)
return false;
}
else if (!first.equals(other.first))
return false;
if (occurrences == null) {
if (other.occurrences != null)
return false;
}
else if (!occurrences.equals(other.occurrences))
return false;
if (ruleNumber != other.ruleNumber)
return false;
if (second == null) {
if (other.second != null)
return false;
}
else if (!second.equals(other.second))
return false;
return true;
}
public String toInfoString() {
return this.toString() + " -> " + this.first.toString() + " " + this.second.toString();
}
}
| gpl-2.0 |
thatkide/lydia | Autosense/Autosense/src/main/java/com/autosenseapp/buttons/settingsButtons/ArduinoSettingsButton.java | 1010 | package com.autosenseapp.buttons.settingsButtons;
import android.app.Activity;
import android.app.FragmentManager;
import android.view.View;
import com.autosenseapp.R;
import com.autosenseapp.buttons.BaseButton;
import com.autosenseapp.databases.Button;
import com.autosenseapp.fragments.Settings.ArduinoSettingsFragment;
/**
* Created by eric on 2014-07-06.
*/
public class ArduinoSettingsButton extends BaseButton {
private Activity activity;
public ArduinoSettingsButton(Activity activity) {
super(activity);
this.activity = activity;
}
@Override
public void onClick(View view, Button passed) {
FragmentManager manager = activity.getFragmentManager();
// start loading the settings fragment
manager.beginTransaction()
.setCustomAnimations(R.anim.container_slide_out_up, R.anim.container_slide_in_up, R.anim.container_slide_in_down, R.anim.container_slide_out_down)
.replace(R.id.home_screen_fragment, new ArduinoSettingsFragment())
.addToBackStack(null)
.commit();
}
}
| gpl-2.0 |
icesphere/star-realms | src/main/java/org/smartreaction/starrealms/model/players/bots/EndGameBot.java | 778 | package org.smartreaction.starrealms.model.players.bots;
import org.smartreaction.starrealms.model.cards.Card;
import org.smartreaction.starrealms.model.cards.gambits.Gambit;
import org.smartreaction.starrealms.model.players.BotPlayer;
import org.smartreaction.starrealms.service.GameService;
public class EndGameBot extends BotPlayer {
public EndGameBot(GameService gameService) {
super(gameService);
}
@Override
public int getBuyCardScore(Card card) {
//don't buy anything
return 0;
}
@Override
public int getScrapForBenefitScore(Card card) {
//always scrap for benefit
return 1;
}
@Override
public int getUseGambitScore(Gambit gambit) {
//use all gambits
return 1;
}
}
| gpl-2.0 |
Wilson-Ferreira/Wp | wp/src/main/java/service/PedidoREST.java | 2359 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package service;
import br.com.wp.enumeracao.NumeroCartao;
import br.com.wp.enumeracao.TipoCobranca;
import br.com.wp.modelo.Cartao;
import br.com.wp.modelo.Configuracao;
import br.com.wp.modelo.Pedido;
import br.com.wp.service.CartaoService;
import br.com.wp.service.ConfiguracaoService;
import br.com.wp.service.PedidoService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
*
* @author Wilson F Florindo
*/
@Path("/pedido")
public class PedidoREST {
@Inject
private Configuracao configuracao;
@Inject
private Cartao cartao;
@Inject
private PedidoService pedidoService;
@Inject
private CartaoService cartaoService;
@Inject
private ConfiguracaoService configuracaoService;
List<Pedido> listaPedidos = new ArrayList<>();
@POST
@Path("/salvarPedidos")
@Consumes("application/json")
@Produces("application/json")
public String salvarPedidos(String jsonPedido) {
try {
Gson gson = new Gson();
Type type = new TypeToken<List<Pedido>>() {
}.getType();
listaPedidos = gson.fromJson(jsonPedido, type);
configuracao = configuracaoService.buscarConfiguracoes();
if (configuracao.getTipoCobranca().equalsIgnoreCase(TipoCobranca.MESA.toString())) {
cartao = cartaoService.buscarCartaoNumeroZero(NumeroCartao.ZERO.numero());
}
for (Pedido p : listaPedidos) {
if (configuracao.getTipoCobranca().equalsIgnoreCase(TipoCobranca.MESA.toString())) {
p.setCartao(cartao);
}
pedidoService.salvarAlterarPedido(p);
}
} catch (Exception ex) {
return "Erro ao salvar";
}
return "Pedidos salvos";
}
}
| gpl-2.0 |
T-A-R-L-A/Portunes | PortunesV2/src/portunesv2/PortunesV2.java | 3235 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package portunesv2;
/**
*
* @author bilal
*/
import com.pi4j.component.lcd.impl.GpioLcdDisplay;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.RaspiPin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PortunesV2 {
public final static int LCD_ROWS = 4;
public final static int LCD_ROW_1 = 0;
public final static int LCD_ROW_2 = 1;
public final static int LCD_ROW_3 = 2;
public final static int LCD_ROW_4 = 3;
public final static int LCD_COLUMNS = 20;
public final static int LCD_BITS = 4;
public static void main(String args[]) throws InterruptedException {
System.out.println("<--Pi4J--> GPIO 4 bit LCD example program");
// create gpio controller
final GpioController gpio = GpioFactory.getInstance();
// initialize LCD
final GpioLcdDisplay lcd = new GpioLcdDisplay(LCD_ROWS, // number of row supported by LCD
LCD_COLUMNS, // number of columns supported by LCD
RaspiPin.GPIO_02, // LCD RS pin
RaspiPin.GPIO_03, // LCD strobe pin
RaspiPin.GPIO_06, // LCD data bit 1
RaspiPin.GPIO_05, // LCD data bit 2
RaspiPin.GPIO_04, // LCD data bit 3
RaspiPin.GPIO_01); // LCD data bit 4
// provision gpio pins as input pins with its internal pull up resistor enabled
//Wiegand wi = new Wiegand();
//wi.begin();
lcd.clear();
lcd.write(LCD_ROW_4,"Portunes V2 by TARLA");
lcd.write(LCD_ROW_1,"Welcome,Card please.");
while(true){
try {
Process p = Runtime.getRuntime().exec("portunes-read"); // portunes read wiedgard command
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
int exitVal = p.waitFor();
String cardnoFull = null;
String cardnoBin = "";
lcd.clear();
while ((cardnoFull = stdInput.readLine()) != null) {
//s = s.replace("\n", "").replace("\r", "");
for(int a=1;a<25;a++){ // get data without checksum
cardnoBin = cardnoBin + cardnoFull.charAt(a);
}
long card_no = Long.parseLong(cardnoBin, 2);
lcd.write(LCD_ROW_1, String.valueOf(card_no) );
}
} catch (IOException ex) {
Logger.getLogger(PortunesV2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} | gpl-2.0 |
mytake/mytake | server/src/main/java/auth/AuthUser.java | 4914 | /*
* MyTake.org
*
* Copyright 2017 by its authors.
* Some rights reserved. See LICENSE, https://github.com/mytakedotorg/mytakedotorg/graphs/contributors
*/
package auth;
import static db.Tables.MODERATOR;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jsoniter.output.JsonStream;
import common.NotFound;
import common.Time;
import common.UrlEncodedPath;
import db.tables.pojos.Account;
import java.text.ParseException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java2ts.LoginCookie;
import javax.annotation.Nullable;
import org.jooby.Cookie;
import org.jooby.Mutant;
import org.jooby.Registry;
import org.jooby.Request;
import org.jooby.Response;
import org.jooq.DSLContext;
public class AuthUser {
public static final int LOGIN_DAYS = 7;
final int id;
final String username;
public AuthUser(int id, String username) {
this.id = id;
this.username = username;
}
public int id() {
return id;
}
public String username() {
return username;
}
public void requireMod(DSLContext dsl) {
boolean isMod = dsl.fetchCount(dsl.selectFrom(MODERATOR).where(MODERATOR.ID.eq(id))) == 1;
if (!isMod) {
throw NotFound.exception();
}
}
static JWTCreator.Builder forUser(Account account, Time time) {
return JWT.create()
.withIssuer(ISSUER_AUDIENCE)
.withAudience(ISSUER_AUDIENCE)
.withIssuedAt(time.nowDate())
.withSubject(Integer.toString(account.getId()))
.withClaim(CLAIM_USERNAME, account.getUsername());
}
static String jwtToken(Registry registry, Account user) {
return forUser(user, registry.require(Time.class))
.sign(registry.require(Algorithm.class));
}
static final String ISSUER_AUDIENCE = "mytake.org";
static final String CLAIM_USERNAME = "username";
/**
* If there's a cookie, validate the user, else return empty.
* If there's an invalid cookie, throw a JWTVerificationException
*/
public static Optional<AuthUser> authOpt(Request req) throws JWTVerificationException {
Mutant loginCookie = req.cookie(LOGIN_COOKIE);
if (!loginCookie.isSet()) {
return Optional.empty();
} else {
return Optional.of(auth(req));
}
}
/** Extracts the current AuthUser from the request, or throws a JWTVerificationException. */
public static AuthUser auth(Request req) throws JWTVerificationException {
// we might have done this for the request already, let's check
AuthUser existing = req.get(REQ_LOGIN_STATUS, null);
if (existing != null) {
return existing;
}
// check that the cookie exists
Mutant loginCookie = req.cookie(LOGIN_COOKIE);
if (!loginCookie.isSet()) {
throw new JWTVerificationException("We can show that to you after you log in.");
}
// and that it is authorized
Algorithm algorithm = req.require(Algorithm.class);
DecodedJWT decoded = JWT.require(algorithm)
.withIssuer(ISSUER_AUDIENCE)
.withAudience(ISSUER_AUDIENCE)
.build()
.verify(loginCookie.value());
if (!req.require(Time.class).isBeforeNowPlus(decoded.getIssuedAt(), LOGIN_DAYS, TimeUnit.DAYS)) {
throw new TokenExpiredException("Your login timed out.");
}
// create the logged-in AuthUser
int userId = Integer.parseInt(decoded.getSubject());
String username = decoded.getClaim(CLAIM_USERNAME).asString();
AuthUser user = new AuthUser(userId, username);
req.set(REQ_LOGIN_STATUS, user);
return user;
}
static final String LOGIN_COOKIE = "login";
static final String LOGIN_UI_COOKIE = "loginui";
private static final String REQ_LOGIN_STATUS = "reqLoginStatus";
/** Attempts to parse the user's email, even if it isn't an otherwise valid login. */
static @Nullable String usernameForError(Request req) throws ParseException {
Mutant loginCookie = req.cookie(LOGIN_COOKIE);
if (!loginCookie.isSet()) {
return null;
} else {
return JWT.decode(loginCookie.value()).getClaim(CLAIM_USERNAME).asString();
}
}
static void login(Account account, Request req, Response rsp) {
boolean isSecurable = UrlEncodedPath.isSecurable(req);
Cookie.Definition httpCookie = new Cookie.Definition(LOGIN_COOKIE, jwtToken(req, account));
httpCookie.httpOnly(true);
httpCookie.secure(isSecurable);
httpCookie.maxAge((int) TimeUnit.DAYS.toSeconds(LOGIN_DAYS));
rsp.cookie(httpCookie);
LoginCookie cookie = new LoginCookie();
cookie.username = account.getUsername();
Cookie.Definition uiCookie = new Cookie.Definition(LOGIN_UI_COOKIE, JsonStream.serialize(cookie));
uiCookie.secure(isSecurable);
uiCookie.maxAge((int) TimeUnit.DAYS.toSeconds(LOGIN_DAYS));
rsp.cookie(uiCookie);
}
static void clearCookies(Response rsp) {
rsp.clearCookie(AuthUser.LOGIN_COOKIE);
rsp.clearCookie(AuthUser.LOGIN_UI_COOKIE);
}
}
| gpl-2.0 |
hou80houzhu/rocserver | src/main/java/com/rocui/docs/excel/JTextExcel.java | 2516 | package com.rocui.docs.excel;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class JTextExcel {
private HashMap<String, TextSheet> sheets = new HashMap<String, TextSheet>();
public JTextExcel addSheet(String name, TextSheet sheet) {
this.sheets.put(name, sheet);
return this;
}
public void save(String fullname) throws Exception {
HSSFWorkbook book = this.getBook();
FileOutputStream fOut = new FileOutputStream(fullname);
book.write(fOut);
fOut.flush();
fOut.close();
}
public void save(OutputStream stream) {
HSSFWorkbook book = this.getBook();
try {
book.write(stream);
} catch (Exception e) {
e.printStackTrace();
}
}
private HSSFWorkbook getBook() {
HSSFWorkbook book = new HSSFWorkbook();
int i = 0;
for (Entry<String, TextSheet> x : this.sheets.entrySet()) {
HSSFSheet sheet = book.createSheet();
book.setSheetName(i, x.getKey());
List<HashMap<String, String>> rows = x.getValue().getRows();
for (int k = 0; k < rows.size(); k++) {
HSSFRow row = sheet.createRow(k);
HashMap<String, String> c = rows.get(k);
int n = 0;
for (Entry<String, String> d : c.entrySet()) {
HSSFCell cell = row.createCell((short) n);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(d.getValue().toString());
n++;
}
}
i++;
}
return book;
}
public static void main(String[] args) {
TextSheet sheet = new TextSheet();
HashMap<String, String> map = new HashMap<String, String>();
map.put("xx", "xxxx");
map.put("xx2", "eeee");
map.put("xx3", "ffff");
sheet.addRow(map);
JTextExcel excel = new JTextExcel();
try {
excel.addSheet("xxx", sheet).save("E:\\xx.xls");
} catch (Exception e) {
e.printStackTrace();
}
}
}
| gpl-2.0 |
kimajakobsen/bibm-sesame | src/com/openlinksw/util/json/DefaultJsonWalker.java | 1372 | /*
* Big Database Semantic Metric Tools
*
* Copyright (C) 2011 OpenLink Software <bdsmt@openlinksw.com>
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; only Version 2 of the License dated
* June 1991.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.openlinksw.util.json;
public class DefaultJsonWalker extends JsonWalker {
@Override
public void end() {
}
@Override
public void endElement() {
}
@Override
public void endEntry(String key) {
}
@Override
public void pushValue(String value) {
}
@Override
public void startEntry(String key) {
}
@Override
public JsonList<?> startList() {
return null;
}
@Override
public JsonObject startObject() {
return null;
}
}
| gpl-2.0 |
jboss/jboss-jaxrpc-api_spec | src/main/java/javax/xml/rpc/handler/HandlerInfo.java | 2931 | package javax.xml.rpc.handler;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
/** This represents information about a handler in the HandlerChain. A
* HandlerInfo instance is passed in the Handler.init method to initialize a
* Handler instance.
*
* @author Scott.Stark@jboss.org
*/
public class HandlerInfo implements Serializable
{
private static final long serialVersionUID = -6735139577513563610L;
private Class handlerClass;
private Map configMap = new HashMap();
private QName[] headers;
/** Default constructor */
public HandlerInfo()
{
}
/** Constructor for HandlerInfo
*
* @param handlerClass Java Class for the Handler
* @param config Handler Configuration as a java.util.Map
* @param headers QNames for the header blocks processed by this Handler.
* QName is the qualified name of the outermost element of a header block
*/
public HandlerInfo(Class handlerClass, Map config, QName[] headers)
{
this.handlerClass = handlerClass;
this.headers = headers;
if (config != null)
this.configMap.putAll(config);
}
/** Gets the Handler class
*
* @return Returns null if no Handler class has been set; otherwise the set handler class
*/
public Class getHandlerClass()
{
return handlerClass;
}
/** Sets the Handler class
*
* @param handlerClass Class for the Handler
*/
public void setHandlerClass(Class handlerClass)
{
this.handlerClass = handlerClass;
}
/** Gets the Handler configuration
*
* @return Returns empty Map if no configuration map has been set; otherwise returns the set configuration map
*/
public Map getHandlerConfig()
{
return new HashMap(configMap);
}
/** Sets the Handler configuration as java.util.Map
*
* @param config Configuration map
*/
public void setHandlerConfig(Map config)
{
configMap.clear();
if (config != null)
configMap.putAll(config);
}
/** Gets the header blocks processed by this Handler.
*
* @return Array of QNames for the header blocks. Returns null if no header blocks have been set using the setHeaders method.
*/
public QName[] getHeaders()
{
return headers;
}
/** Sets the header blocks processed by this Handler.
*
* @param qnames QNames of the header blocks. QName is the qualified name of the outermost element of the SOAP header block
*/
public void setHeaders(QName[] qnames)
{
headers = qnames;
}
/** Returns a string representation of the object.
*/
public String toString()
{
List hlist = (headers != null ? Arrays.asList(headers) : null);
return "[class=" + handlerClass.getName() + ",headers=" + hlist + ",config=" + configMap + "]";
}
}
| gpl-2.0 |
smeny/JPC | src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/rm/fdivp_ST4_ST6.java | 2148 | /*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package com.github.smeny.jpc.emulator.execution.opcodes.rm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class fdivp_ST4_ST6 extends Executable
{
public fdivp_ST4_ST6(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double freg0 = cpu.fpu.ST(4);
double freg1 = cpu.fpu.ST(6);
if (((freg0 == 0.0) && (freg1 == 0.0)) || (Double.isInfinite(freg0) && Double.isInfinite(freg1)))
cpu.fpu.setInvalidOperation();
if ((freg1 == 0.0) && !Double.isNaN(freg0) && !Double.isInfinite(freg0))
cpu.fpu.setZeroDivide();
cpu.fpu.setST(4, freg0/freg1);
cpu.fpu.pop();
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
Robert0Trebor/robert | TMessagesProj/src/main/java/org/vidogram/messenger/exoplayer/f/l.java | 3048 | package org.vidogram.messenger.exoplayer.f;
public final class l
{
public byte[] a;
private int b;
private int c;
private int d;
public l()
{
}
public l(byte[] paramArrayOfByte)
{
this(paramArrayOfByte, paramArrayOfByte.length);
}
public l(byte[] paramArrayOfByte, int paramInt)
{
this.a = paramArrayOfByte;
this.d = paramInt;
}
private int f()
{
int j = 0;
int i = 0;
while (!b())
i += 1;
if (i > 0)
j = c(i);
return (1 << i) - 1 + j;
}
private void g()
{
if ((this.b >= 0) && (this.c >= 0) && (this.c < 8) && ((this.b < this.d) || ((this.b == this.d) && (this.c == 0))));
for (boolean bool = true; ; bool = false)
{
b.b(bool);
return;
}
}
public int a()
{
return (this.d - this.b) * 8 - this.c;
}
public void a(int paramInt)
{
this.b = (paramInt / 8);
this.c = (paramInt - this.b * 8);
g();
}
public void a(byte[] paramArrayOfByte)
{
a(paramArrayOfByte, paramArrayOfByte.length);
}
public void a(byte[] paramArrayOfByte, int paramInt)
{
this.a = paramArrayOfByte;
this.b = 0;
this.c = 0;
this.d = paramInt;
}
public void b(int paramInt)
{
this.b += paramInt / 8;
this.c += paramInt % 8;
if (this.c > 7)
{
this.b += 1;
this.c -= 8;
}
g();
}
public boolean b()
{
return c(1) == 1;
}
public int c(int paramInt)
{
if (paramInt == 0)
return 0;
int m = paramInt / 8;
int i = 0;
int k = 0;
int j = paramInt;
paramInt = k;
if (i < m)
{
if (this.c != 0);
for (k = (this.a[this.b] & 0xFF) << this.c | (this.a[(this.b + 1)] & 0xFF) >>> 8 - this.c; ; k = this.a[this.b])
{
j -= 8;
paramInt |= (k & 0xFF) << j;
this.b += 1;
i += 1;
break;
}
}
if (j > 0)
{
k = this.c + j;
i = (byte)(255 >> 8 - j);
if (k > 8)
{
paramInt = i & ((this.a[this.b] & 0xFF) << k - 8 | (this.a[(this.b + 1)] & 0xFF) >> 16 - k) | paramInt;
this.b += 1;
this.c = (k % 8);
}
}
while (true)
{
g();
return paramInt;
i = i & (this.a[this.b] & 0xFF) >> 8 - k | paramInt;
paramInt = i;
if (k != 8)
break;
this.b += 1;
paramInt = i;
break;
}
}
public boolean c()
{
int k = this.b;
int m = this.c;
int i = 0;
while ((this.b < this.d) && (!b()))
i += 1;
if (this.b == this.d);
for (int j = 1; ; j = 0)
{
this.b = k;
this.c = m;
if ((j != 0) || (a() < i * 2 + 1))
break;
return true;
}
return false;
}
public int d()
{
return f();
}
public int e()
{
int j = f();
if (j % 2 == 0);
for (int i = -1; ; i = 1)
return i * ((j + 1) / 2);
}
}
/* Location: G:\programs\dex2jar-2.0\vidogram-dex2jar.jar
* Qualified Name: org.vidogram.messenger.exoplayer.f.l
* JD-Core Version: 0.6.0
*/ | gpl-2.0 |
itsazzad/zanata-server | zanata-war/src/test/java/org/zanata/seam/test/ChildBroken.java | 1340 | /*
* Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the
* @author tags. See the copyright.txt file in the distribution for a full
* listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
* site: http://www.fsf.org.
*/
package org.zanata.seam.test;
import org.jboss.seam.annotations.Name;
/**
* A component that cannot be built because it doesn't follow Seam's bean spec.
*
* @author Carlos Munoz <a
* href="mailto:camunoz@redhat.com">camunoz@redhat.com</a>
*/
@Name("childBroken")
public class ChildBroken {
public ChildBroken(String unboundArgument) {
}
}
| gpl-2.0 |
itmplog/git-osc-android | gitoscandroid/src/main/java/net/oschina/gitapp/util/RecyclerList.java | 702 | package net.oschina.gitapp.util;
import android.content.Context;
import android.view.View;
import java.util.LinkedList;
/**
* 关于本类,详情请见http://kymjs.com/code/2015/11/26/01/
*
* @author kymjs (http://www.kymjs.com/) on 12/28/15.
*/
public class RecyclerList extends LinkedList<View> {
private Context cxt;
private int layoutId;
public RecyclerList(Context cxt, int id) {
this.cxt = cxt;
this.layoutId = id;
}
public View get() {
View view;
if (size() > 0) {
view = getFirst();
removeFirst();
} else {
view = View.inflate(cxt, layoutId, null);
}
return view;
}
} | gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest19878.java | 2168 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest19878")
public class BenchmarkTest19878 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getQueryString();
String bar = doSomething(param);
try {
java.io.FileInputStream fis = new java.io.FileInputStream(org.owasp.benchmark.helpers.Utils.testfileDir + bar);
} catch (Exception e) {
// OK to swallow any exception
// TODO: Fix this.
System.out.println("File exception caught and swallowed: " + e.getMessage());
}
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing();
String bar = thing.doSomething(param);
return bar;
}
}
| gpl-2.0 |
forax/kija | src/com/github/kija/parser/ast/Use.java | 296 | package com.github.kija.parser.ast;
import java.util.Objects;
public class Use extends Node {
private final String name;
public Use(String name, int lineNumber) {
super(lineNumber);
this.name = Objects.requireNonNull(name);
}
public String getName() {
return name;
}
}
| gpl-2.0 |
CleverCloud/Bianca | bianca/src/main/java/com/clevercloud/util/CompileException.java | 1172 | /*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
* Copyright (c) 2011-2012 Clever Cloud SAS -- all rights reserved
*
* This file is part of Bianca(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Bianca Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Bianca Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Bianca Open Source; if not, write to the
* Free SoftwareFoundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.clevercloud.util;
public interface CompileException {
}
| gpl-2.0 |
h3xstream/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00294.java | 2781 | /**
* OWASP Benchmark Project v1.2
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>.
*
* The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Nick Sanidas
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(value="/cmdi-00/BenchmarkTest00294")
public class BenchmarkTest00294 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String param = "";
java.util.Enumeration<String> headers = request.getHeaders("BenchmarkTest00294");
if (headers != null && headers.hasMoreElements()) {
param = headers.nextElement(); // just grab first element
}
// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
param = java.net.URLDecoder.decode(param, "UTF-8");
String bar;
// Simple ? condition that assigns param to bar on false condition
int num = 106;
bar = (7*42) - num > 200 ? "This should never happen" : param;
java.util.List<String> argList = new java.util.ArrayList<String>();
String osName = System.getProperty("os.name");
if (osName.indexOf("Windows") != -1) {
argList.add("cmd.exe");
argList.add("/c");
} else {
argList.add("sh");
argList.add("-c");
}
argList.add("echo " + bar);
ProcessBuilder pb = new ProcessBuilder(argList);
try {
Process p = pb.start();
org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response);
} catch (IOException e) {
System.out.println("Problem executing cmdi - java.lang.ProcessBuilder(java.util.List) Test Case");
throw new ServletException(e);
}
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/langtools/test/tools/javac/foreach/T6682380.java | 1578 | /*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6682380 6679509
* @summary Foreach loop with generics inside finally block crashes javac with -target 1.5
* @author Jan Lahoda, Maurizio Cimadamore
* @compile -source 1.5 -target 1.5 T6682380.java
*/
import java.util.List;
public class T6682380<X> {
public static void main(String[] args) {
try {
} finally {
List<T6682380<?>> l = null;
T6682380<?>[] a = null;
for (T6682380<?> e1 : l);
for (T6682380<?> e2 : a);
}
}
}
| gpl-2.0 |
DIY-green/AndroidStudyDemo | AnimationStudy/src/main/java/com/cheng/animationstudy/customview/pulltorefresh02/CustomListView.java | 21813 | package com.cheng.animationstudy.customview.pulltorefresh02;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.cheng.animationstudy.R;
/**
* ListView下拉刷新和加载更多<p>
*
* <strong>变更说明:</strong>
* <p>默认如果设置了OnRefreshListener接口和OnLoadMoreListener接口,<br>并且不为null,则打开这两个功能了。
* <p>剩余两个Flag:mIsAutoLoadMore(是否自动加载更多)和
* <br>mIsMoveToFirstItemAfterRefresh(下拉刷新后是否显示第一条Item)
*
* <p><strong>有改进意见,请发送到俺的邮箱哈~ 多谢各位小伙伴了!^_^</strong>
*
* @date 2013-11-11 下午10:09:26
* @change JohnWatson
* @mail xxzhaofeng5412@gmail.com
* @version 1.0
*/
public class CustomListView extends ListView implements OnScrollListener {
/** 显示格式化日期模板 */
private final static String DATE_FORMAT_STR = "yyyy年MM月dd日 HH:mm";
/** 实际的padding的距离与界面上偏移距离的比例 */
private final static int RATIO = 3;
private final static int RELEASE_TO_REFRESH = 0;
private final static int PULL_TO_REFRESH = 1;
private final static int REFRESHING = 2;
private final static int DONE = 3;
private final static int LOADING = 4;
/** 加载中 */
private final static int ENDINT_LOADING = 1;
/** 手动完成刷新 */
private final static int ENDINT_MANUAL_LOAD_DONE = 2;
/** 自动完成刷新 */
private final static int ENDINT_AUTO_LOAD_DONE = 3;
/** 0:RELEASE_TO_REFRESH;
* <p> 1:PULL_To_REFRESH;
* <p> 2:REFRESHING;
* <p> 3:DONE;
* <p> 4:LOADING */
private int mHeadState;
/** 0:完成/等待刷新 ;
* <p> 1:加载中 */
private int mEndState;
// ================================= 功能设置Flag ================================
/** 可以加载更多? */
private boolean mCanLoadMore = false;
/** 可以下拉刷新? */
private boolean mCanRefresh = false;
/** 可以自动加载更多吗?(注意,先判断是否有加载更多,如果没有,这个flag也没有意义) */
private boolean mIsAutoLoadMore = true;
/** 下拉刷新后是否显示第一条Item */
private boolean mIsMoveToFirstItemAfterRefresh = false;
public boolean isCanLoadMore() {
return mCanLoadMore;
}
public void setCanLoadMore(boolean pCanLoadMore) {
mCanLoadMore = pCanLoadMore;
if(mCanLoadMore && getFooterViewsCount() == 0){
addFooterView();
}
}
public boolean isCanRefresh() {
return mCanRefresh;
}
public void setCanRefresh(boolean pCanRefresh) {
mCanRefresh = pCanRefresh;
}
public boolean isAutoLoadMore() {
return mIsAutoLoadMore;
}
public void setAutoLoadMore(boolean pIsAutoLoadMore) {
mIsAutoLoadMore = pIsAutoLoadMore;
}
public boolean isMoveToFirstItemAfterRefresh() {
return mIsMoveToFirstItemAfterRefresh;
}
public void setMoveToFirstItemAfterRefresh(
boolean pIsMoveToFirstItemAfterRefresh) {
mIsMoveToFirstItemAfterRefresh = pIsMoveToFirstItemAfterRefresh;
}
// ============================================================================
private LayoutInflater mInflater;
private LinearLayout mHeadView;
private TextView mTipsTextView;
private TextView mLastUpdatedTextView;
private ImageView mArrowImageView;
private ProgressBar mProgressBar;
private View mEndRootView;
private ProgressBar mEndLoadProgressBar;
private TextView mEndLoadTipsTextView;
/** headView动画 */
private RotateAnimation mArrowAnim;
/** headView反转动画 */
private RotateAnimation mArrowReverseAnim;
/** 用于保证startY的值在一个完整的touch事件中只被记录一次 */
private boolean mIsRecored;
private int mHeadViewWidth;
private int mHeadViewHeight;
private int mStartY;
private boolean mIsBack;
private int mFirstItemIndex;
private int mLastItemIndex;
private int mCount;
private boolean mEnoughCount;//足够数量充满屏幕?
private OnRefreshListener mRefreshListener;
private OnLoadMoreListener mLoadMoreListener;
public CustomListView(Context pContext, AttributeSet pAttrs) {
super(pContext, pAttrs);
init(pContext);
}
public CustomListView(Context pContext) {
super(pContext);
init(pContext);
}
public CustomListView(Context pContext, AttributeSet pAttrs, int pDefStyle) {
super(pContext, pAttrs, pDefStyle);
init(pContext);
}
/**
* 初始化操作
* @param pContext
* @date 2013-11-20 下午4:10:46
* @change JohnWatson
* @version 1.0
*/
private void init(Context pContext) {
setCacheColorHint(pContext.getResources().getColor(android.R.color.transparent));
mInflater = LayoutInflater.from(pContext);
addHeadView();
setOnScrollListener(this);
initPullImageAnimation(0);
}
/**
* 添加下拉刷新的HeadView
* @date 2013-11-11 下午9:48:26
* @change JohnWatson
* @version 1.0
*/
private void addHeadView() {
mHeadView = (LinearLayout) mInflater.inflate(R.layout.head, null);
mArrowImageView = (ImageView) mHeadView
.findViewById(R.id.head_arrowImageView);
mArrowImageView.setMinimumWidth(70);
mArrowImageView.setMinimumHeight(50);
mProgressBar = (ProgressBar) mHeadView
.findViewById(R.id.head_progressBar);
mTipsTextView = (TextView) mHeadView.findViewById(
R.id.head_tipsTextView);
mLastUpdatedTextView = (TextView) mHeadView
.findViewById(R.id.head_lastUpdatedTextView);
measureView(mHeadView);
mHeadViewHeight = mHeadView.getMeasuredHeight();
mHeadViewWidth = mHeadView.getMeasuredWidth();
mHeadView.setPadding(0, -1 * mHeadViewHeight, 0, 0);
mHeadView.invalidate();
Log.v("size", "width:" + mHeadViewWidth + " height:"
+ mHeadViewHeight);
addHeaderView(mHeadView, null, false);
mHeadState = DONE;
}
/**
* 添加加载更多FootView
* @date 2013-11-11 下午9:52:37
* @change JohnWatson
* @version 1.0
*/
private void addFooterView() {
mEndRootView = mInflater.inflate(R.layout.listfooter_more, null);
mEndRootView.setVisibility(View.VISIBLE);
mEndLoadProgressBar = (ProgressBar) mEndRootView
.findViewById(R.id.pull_to_refresh_progress);
mEndLoadTipsTextView = (TextView) mEndRootView.findViewById(R.id.load_more);
mEndRootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mCanLoadMore){
if(mCanRefresh){
// 当可以下拉刷新时,如果FootView没有正在加载,并且HeadView没有正在刷新,才可以点击加载更多。
if(mEndState != ENDINT_LOADING && mHeadState != REFRESHING){
mEndState = ENDINT_LOADING;
onLoadMore();
}
}else if(mEndState != ENDINT_LOADING){
// 当不能下拉刷新时,FootView不正在加载时,才可以点击加载更多。
mEndState = ENDINT_LOADING;
onLoadMore();
}
}
}
});
addFooterView(mEndRootView);
if(mIsAutoLoadMore){
mEndState = ENDINT_AUTO_LOAD_DONE;
}else{
mEndState = ENDINT_MANUAL_LOAD_DONE;
}
}
/**
* 实例化下拉刷新的箭头的动画效果
* @param pAnimDuration 动画运行时长
* @date 2013-11-20 上午11:53:22
* @change JohnWatson
* @version 1.0
*/
private void initPullImageAnimation(final int pAnimDuration) {
int _Duration;
if(pAnimDuration > 0){
_Duration = pAnimDuration;
}else{
_Duration = 250;
}
// Interpolator _Interpolator;
// switch (pAnimType) {
// case 0:
// _Interpolator = new AccelerateDecelerateInterpolator();
// break;
// case 1:
// _Interpolator = new AccelerateInterpolator();
// break;
// case 2:
// _Interpolator = new AnticipateInterpolator();
// break;
// case 3:
// _Interpolator = new AnticipateOvershootInterpolator();
// break;
// case 4:
// _Interpolator = new BounceInterpolator();
// break;
// case 5:
// _Interpolator = new CycleInterpolator(1f);
// break;
// case 6:
// _Interpolator = new DecelerateInterpolator();
// break;
// case 7:
// _Interpolator = new OvershootInterpolator();
// break;
// default:
// _Interpolator = new LinearInterpolator();
// break;
// }
Interpolator _Interpolator = new LinearInterpolator();
mArrowAnim = new RotateAnimation(0, -180,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
mArrowAnim.setInterpolator(_Interpolator);
mArrowAnim.setDuration(_Duration);
mArrowAnim.setFillAfter(true);
mArrowReverseAnim = new RotateAnimation(-180, 0,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
mArrowReverseAnim.setInterpolator(_Interpolator);
mArrowReverseAnim.setDuration(_Duration);
mArrowReverseAnim.setFillAfter(true);
}
/**
* 测量HeadView宽高(注意:此方法仅适用于LinearLayout,请读者自己测试验证。)
* @param pChild
* @date 2013-11-20 下午4:12:07
* @change JohnWatson
* @version 1.0
*/
private void measureView(View pChild) {
ViewGroup.LayoutParams p = pChild.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
}
pChild.measure(childWidthSpec, childHeightSpec);
}
/**
*为了判断滑动到ListView底部没
*/
@Override
public void onScroll(AbsListView pView, int pFirstVisibleItem,
int pVisibleItemCount, int pTotalItemCount) {
mFirstItemIndex = pFirstVisibleItem;
mLastItemIndex = pFirstVisibleItem + pVisibleItemCount - 2;
mCount = pTotalItemCount - 2;
if (pTotalItemCount > pVisibleItemCount ) {
mEnoughCount = true;
// endingView.setVisibility(View.VISIBLE);
} else {
mEnoughCount = false;
}
}
/**
*这个方法,可能有点乱,大家多读几遍就明白了。
*/
@Override
public void onScrollStateChanged(AbsListView pView, int pScrollState) {
if(mCanLoadMore){// 存在加载更多功能
if (mLastItemIndex == mCount && pScrollState == SCROLL_STATE_IDLE) {
//SCROLL_STATE_IDLE=0,滑动停止
if (mEndState != ENDINT_LOADING) {
if(mIsAutoLoadMore){// 自动加载更多,我们让FootView显示 “更 多”
if(mCanRefresh){
// 存在下拉刷新并且HeadView没有正在刷新时,FootView可以自动加载更多。
if(mHeadState != REFRESHING){
// FootView显示 : 更 多 ---> 加载中...
mEndState = ENDINT_LOADING;
onLoadMore();
changeEndViewByState();
}
}else{// 没有下拉刷新,我们直接进行加载更多。
// FootView显示 : 更 多 ---> 加载中...
mEndState = ENDINT_LOADING;
onLoadMore();
changeEndViewByState();
}
}else{// 不是自动加载更多,我们让FootView显示 “点击加载”
// FootView显示 : 点击加载 ---> 加载中...
mEndState = ENDINT_MANUAL_LOAD_DONE;
changeEndViewByState();
}
}
}
}else if(mEndRootView != null && mEndRootView.getVisibility() == VISIBLE){
// 突然关闭加载更多功能之后,我们要移除FootView。
System.out.println("this.removeFooterView(endRootView);...");
mEndRootView.setVisibility(View.GONE);
this.removeFooterView(mEndRootView);
}
}
/**
* 改变加载更多状态
* @date 2013-11-11 下午10:05:27
* @change JohnWatson
* @version 1.0
*/
private void changeEndViewByState() {
if (mCanLoadMore) {
//允许加载更多
switch (mEndState) {
case ENDINT_LOADING://刷新中
// 加载中...
if(mEndLoadTipsTextView.getText().equals(
R.string.p2refresh_doing_end_refresh)){
break;
}
mEndLoadTipsTextView.setText(R.string.p2refresh_doing_end_refresh);
mEndLoadTipsTextView.setVisibility(View.VISIBLE);
mEndLoadProgressBar.setVisibility(View.VISIBLE);
break;
case ENDINT_MANUAL_LOAD_DONE:// 手动刷新完成
// 点击加载
mEndLoadTipsTextView.setText(R.string.p2refresh_end_click_load_more);
mEndLoadTipsTextView.setVisibility(View.VISIBLE);
mEndLoadProgressBar.setVisibility(View.GONE);
mEndRootView.setVisibility(View.VISIBLE);
break;
case ENDINT_AUTO_LOAD_DONE:// 自动刷新完成
// 更 多
mEndLoadTipsTextView.setText(R.string.p2refresh_end_load_more);
mEndLoadTipsTextView.setVisibility(View.VISIBLE);
mEndLoadProgressBar.setVisibility(View.GONE);
mEndRootView.setVisibility(View.VISIBLE);
break;
default:
// 原来的代码是为了: 当所有item的高度小于ListView本身的高度时,
// 要隐藏掉FootView,大家自己去原作者的代码参考。
// if (enoughCount) {
// endRootView.setVisibility(View.VISIBLE);
// } else {
// endRootView.setVisibility(View.GONE);
// }
break;
}
}
}
/**
*原作者的,我没改动,请读者自行优化。
*/
public boolean onTouchEvent(MotionEvent event) {
if (mCanRefresh) {
if(mCanLoadMore && mEndState == ENDINT_LOADING){
// 如果存在加载更多功能,并且当前正在加载更多,默认不允许下拉刷新,必须加载完毕后才能使用。
return super.onTouchEvent(event);
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mFirstItemIndex == 0 && !mIsRecored) {
mIsRecored = true;
mStartY = (int) event.getY();
}
break;
case MotionEvent.ACTION_UP:
if (mHeadState != REFRESHING && mHeadState != LOADING) {
if (mHeadState == DONE) {
}
if (mHeadState == PULL_TO_REFRESH) {
mHeadState = DONE;
changeHeaderViewByState();
}
if (mHeadState == RELEASE_TO_REFRESH) {
mHeadState = REFRESHING;
changeHeaderViewByState();
onRefresh();
}
}
mIsRecored = false;
mIsBack = false;
break;
case MotionEvent.ACTION_MOVE:
int tempY = (int) event.getY();
if (!mIsRecored && mFirstItemIndex == 0) {
mIsRecored = true;
mStartY = tempY;
}
if (mHeadState != REFRESHING && mIsRecored && mHeadState != LOADING) {
// 保证在设置padding的过程中,当前的位置一直是在head,
// 否则如果当列表超出屏幕的话,当在上推的时候,列表会同时进行滚动
// 可以松手去刷新了
if (mHeadState == RELEASE_TO_REFRESH) {
setSelection(0);
// 往上推了,推到了屏幕足够掩盖head的程度,但是还没有推到全部掩盖的地步
if (((tempY - mStartY) / RATIO < mHeadViewHeight)
&& (tempY - mStartY) > 0) {
mHeadState = PULL_TO_REFRESH;
changeHeaderViewByState();
}
// 一下子推到顶了
else if (tempY - mStartY <= 0) {
mHeadState = DONE;
changeHeaderViewByState();
}
// 往下拉了,或者还没有上推到屏幕顶部掩盖head的地步
}
// 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态
if (mHeadState == PULL_TO_REFRESH) {
setSelection(0);
// 下拉到可以进入RELEASE_TO_REFRESH的状态
if ((tempY - mStartY) / RATIO >= mHeadViewHeight) {
mHeadState = RELEASE_TO_REFRESH;
mIsBack = true;
changeHeaderViewByState();
} else if (tempY - mStartY <= 0) {
mHeadState = DONE;
changeHeaderViewByState();
}
}
if (mHeadState == DONE) {
if (tempY - mStartY > 0) {
mHeadState = PULL_TO_REFRESH;
changeHeaderViewByState();
}
}
if (mHeadState == PULL_TO_REFRESH) {
mHeadView.setPadding(0, -1 * mHeadViewHeight
+ (tempY - mStartY) / RATIO, 0, 0);
}
if (mHeadState == RELEASE_TO_REFRESH) {
mHeadView.setPadding(0, (tempY - mStartY) / RATIO
- mHeadViewHeight, 0, 0);
}
}
break;
}
}
return super.onTouchEvent(event);
}
/**
* 当HeadView状态改变时候,调用该方法,以更新界面
* @date 2013-11-20 下午4:29:44
* @change JohnWatson
* @version 1.0
*/
private void changeHeaderViewByState() {
switch (mHeadState) {
case RELEASE_TO_REFRESH:
mArrowImageView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
mTipsTextView.setVisibility(View.VISIBLE);
mLastUpdatedTextView.setVisibility(View.VISIBLE);
mArrowImageView.clearAnimation();
mArrowImageView.startAnimation(mArrowAnim);
// 松开刷新
mTipsTextView.setText(R.string.p2refresh_release_refresh);
break;
case PULL_TO_REFRESH:
mProgressBar.setVisibility(View.GONE);
mTipsTextView.setVisibility(View.VISIBLE);
mLastUpdatedTextView.setVisibility(View.VISIBLE);
mArrowImageView.clearAnimation();
mArrowImageView.setVisibility(View.VISIBLE);
// 是由RELEASE_To_REFRESH状态转变来的
if (mIsBack) {
mIsBack = false;
mArrowImageView.clearAnimation();
mArrowImageView.startAnimation(mArrowReverseAnim);
// 下拉刷新
mTipsTextView.setText(R.string.p2refresh_pull_to_refresh);
} else {
// 下拉刷新
mTipsTextView.setText(R.string.p2refresh_pull_to_refresh);
}
break;
case REFRESHING:
mHeadView.setPadding(0, 0, 0, 0);
// 华生的建议: 实际上这个的setPadding可以用动画来代替。我没有试,但是我见过。其实有的人也用Scroller可以实现这个效果,
// 我没时间研究了,后期再扩展,这个工作交给小伙伴你们啦~ 如果改进了记得发到我邮箱噢~
// 本人邮箱: xxzhaofeng5412@gmail.com
mProgressBar.setVisibility(View.VISIBLE);
mArrowImageView.clearAnimation();
mArrowImageView.setVisibility(View.GONE);
// 正在刷新...
mTipsTextView.setText(R.string.p2refresh_doing_head_refresh);
mLastUpdatedTextView.setVisibility(View.VISIBLE);
break;
case DONE:
mHeadView.setPadding(0, -1 * mHeadViewHeight, 0, 0);
// 此处可以改进,同上所述。
mProgressBar.setVisibility(View.GONE);
mArrowImageView.clearAnimation();
mArrowImageView.setImageResource(R.mipmap.arrow);
// 下拉刷新
mTipsTextView.setText(R.string.p2refresh_pull_to_refresh);
mLastUpdatedTextView.setVisibility(View.VISIBLE);
break;
}
}
/**
* 下拉刷新监听接口
* @date 2013-11-20 下午4:50:51
* @change JohnWatson
* @version 1.0
*/
public interface OnRefreshListener {
public void onRefresh();
}
/**
* 加载更多监听接口
* @date 2013-11-20 下午4:50:51
* @change JohnWatson
* @version 1.0
*/
public interface OnLoadMoreListener {
public void onLoadMore();
}
public void setOnRefreshListener(OnRefreshListener pRefreshListener) {
if(pRefreshListener != null){
mRefreshListener = pRefreshListener;
mCanRefresh = true;
}
}
public void setOnLoadListener(OnLoadMoreListener pLoadMoreListener) {
if(pLoadMoreListener != null){
mLoadMoreListener = pLoadMoreListener;
mCanLoadMore = true;
if(mCanLoadMore && getFooterViewsCount() == 0){
addFooterView();
}
}
}
/**
* 正在下拉刷新
* @date 2013-11-20 下午4:45:47
* @change JohnWatson
* @version 1.0
*/
private void onRefresh() {
if (mRefreshListener != null) {
mRefreshListener.onRefresh();
}
}
/**
* 下拉刷新完成
* @date 2013-11-20 下午4:44:12
* @change JohnWatson
* @version 1.0
*/
public void onRefreshComplete() {
// 下拉刷新后是否显示第一条Item
if(mIsMoveToFirstItemAfterRefresh)setSelection(0);
mHeadState = DONE;
// 最近更新: Time
mLastUpdatedTextView.setText(
getResources().getString(R.string.p2refresh_refresh_lasttime) +
new SimpleDateFormat(DATE_FORMAT_STR, Locale.CHINA).format(new Date()));
changeHeaderViewByState();
}
/**
* 正在加载更多,FootView显示 : 加载中...
* @date 2013-11-20 下午4:35:51
* @change JohnWatson
* @version 1.0
*/
private void onLoadMore() {
if (mLoadMoreListener != null) {
// 加载中...
mEndLoadTipsTextView.setText(R.string.p2refresh_doing_end_refresh);
mEndLoadTipsTextView.setVisibility(View.VISIBLE);
mEndLoadProgressBar.setVisibility(View.VISIBLE);
mLoadMoreListener.onLoadMore();
}
}
/**
* 加载更多完成
* @date 2013-11-11 下午10:21:38
* @change JohnWatson
* @version 1.0
*/
public void onLoadMoreComplete() {
if(mIsAutoLoadMore){
mEndState = ENDINT_AUTO_LOAD_DONE;
}else{
mEndState = ENDINT_MANUAL_LOAD_DONE;
}
changeEndViewByState();
}
/**
* 主要更新一下刷新时间啦!
* @param adapter
* @date 2013-11-20 下午5:35:51
* @change JohnWatson
* @version 1.0
*/
public void setAdapter(BaseAdapter adapter) {
// 最近更新: Time
mLastUpdatedTextView.setText(
getResources().getString(R.string.p2refresh_refresh_lasttime) +
new SimpleDateFormat(DATE_FORMAT_STR, Locale.CHINA).format(new Date()));
super.setAdapter(adapter);
}
}
| gpl-2.0 |
delafer/j7project | jasper352/csb-jasperreport-dep/src/net/sf/jasperreports/engine/util/JRJdk14ImageEncoder.java | 2615 | /*
* ============================================================================
* GNU Lesser General Public License
* ============================================================================
*
* JasperReports - Free Java report-generating library.
* Copyright (C) 2001-2009 JasperSoft Corporation http://www.jaspersoft.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
* JasperSoft Corporation
* 539 Bryant Street, Suite 100
* San Francisco, CA 94107
* http://www.jaspersoft.com
*/
package net.sf.jasperreports.engine.util;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRRenderable;
/**
* @author Teodor Danciu (teodord@users.sourceforge.net)
* @version $Id: JRJdk14ImageEncoder.java 2697 2009-03-24 18:41:23Z teodord $
*/
public class JRJdk14ImageEncoder extends JRAbstractImageEncoder
{
/**
*
*/
public byte[] encode(BufferedImage bi, byte imageType) throws JRException
{
String formatName = null;
switch (imageType)
{
case JRRenderable.IMAGE_TYPE_GIF :
{
formatName = "gif";
break;
}
case JRRenderable.IMAGE_TYPE_PNG :
{
formatName = "png";
break;
}
case JRRenderable.IMAGE_TYPE_TIFF :
{
formatName = "tiff";
break;
}
case JRRenderable.IMAGE_TYPE_JPEG :
case JRRenderable.IMAGE_TYPE_UNKNOWN :
default:
{
formatName = "jpeg";
break;
}
}
boolean success = false;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try
{
success = ImageIO.write(bi, formatName, baos);
}
catch (IOException e)
{
throw new JRException(e);
}
if (!success)
{
throw new JRException("No appropriate image writer found for the \"" + formatName + "\" format.");
}
return baos.toByteArray();
}
}
| gpl-2.0 |
MarginallyClever/Makelangelo-software | src/main/java/com/marginallyclever/makelangelo/makeArt/ScaleTurtle.java | 223 | package com.marginallyclever.makelangelo.makeArt;
import com.marginallyclever.makelangelo.turtle.Turtle;
public class ScaleTurtle {
public static void run(Turtle turtle,double sx,double sy) {
turtle.scale(sx,sy);
}
}
| gpl-2.0 |
thelasteiko/StatisticApp | src/masks/DataManager.java | 3224 | package masks;
import io.FileIO;
import io.XYChartIO;
import java.io.File;
import java.util.Iterator;
import java.util.Observable;
import javafx.collections.ObservableList;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Data;
import scatter.Statistics;
/**
* Manages the data for display in various JavaFX tables and charts.
* So in the future it would be nice for this to have optional data type displays.
*
* @author Melinda Robertson
* @version 20151011
*/
public class DataManager extends Observable {
/**
* Loads and saves the data.
*/
private final static FileIO<ObservableList<Data<Number,Number>>,Data<Number, Number>> io = new XYChartIO();
/**
* The data.
*/
private ObservableList<XYChart.Data<Number, Number>> data;
/**
* Performs calculations on the data.
*/
private Statistics<ObservableList<Data<Number, Number>>,Data<Number, Number>> st;
/**
* Creates a new DataManager without adding any data
* to the initial set.
*/
public DataManager() {
begin(null);
}
/**
* Creates the manager with initial data.
* @param data is the x y pair data.
*/
public DataManager(File filename) {
begin(filename);
}
/**
* Retrieve the current data in an observable list as a reference.
* @return the data.
*/
public ObservableList<XYChart.Data<Number, Number>> getData() {
return data;
}
/**
* Adds a new x y pair to the data set.
* @param x is the x coordinate.
* @param y is the y coordinate.
*/
public void add(double x, double y) {
if (data == null) return;
XYChart.Data<Number, Number> e = new XYChart.Data<Number, Number>(x, y);
data.add(e);
setChanged();
notifyObservers();
}
/**
* Finds and removes the first occurrence of the given x y pair.
* @param x is the x coordinate.
* @param y is the y coordinate.
*/
public void remove(double x, double y) {
if (data == null) return;
Iterator<Data<Number, Number>> it = data.iterator();
while(it.hasNext()) {
Data<Number, Number> temp = it.next();
if((Double) temp.getXValue() == x && (Double) temp.getYValue() == y) {
it.remove();
setChanged();
break;
}
}
notifyObservers();
}
/**
* Retrieve the statistical data calculator.
* @return the data calculator.
*/
public Statistics<ObservableList<Data<Number, Number>>,Data<Number, Number>> stat() {
return st;
}
/**
* Load the appropriate data structure using the IO object.
* @param filename is the file to load.
*/
public void load(File filename) {
begin(filename);
}
/**
* Loads the last file accessed.
*/
public void load() {
begin(io.lastfile());
}
/**
* Saves data to the indicated file using the IO object.
* @param filename is the file to save to.
*/
public void save(File filename) {
io.save(filename, data);
}
/**
* Saves data to the last file accessed.
*/
public void save() {
io.savelast(data);
}
/**
* Starting point to overwrite data.
* @param filename is the file to load data from.
*/
private void begin(File filename) {
data = io.load(filename);
XYMask m = new XYMask(data);
st = new Statistics<ObservableList<Data<Number, Number>>,Data<Number, Number>>(m);
setChanged();
notifyObservers();
}
}
| gpl-2.0 |
DennisUniville/MascadaPet | MascadaEJB/ejbModule/ejb/exception/ValidationException.java | 392 | package ejb.exception;
public class ValidationException extends Exception {
private static final long serialVersionUID = 1L;
public ValidationException() {
}
public ValidationException(String message) {
super(message);
}
public ValidationException(Throwable cause) {
super(cause);
}
public ValidationException(String message, Throwable cause) {
super(message, cause);
}
}
| gpl-2.0 |
adamfisk/littleshoot-client | common/ice/src/main/java/org/lastbamboo/common/ice/transport/IceUdpStunChecker.java | 5680 | package org.lastbamboo.common.ice.transport;
import java.net.InetSocketAddress;
import org.apache.commons.id.uuid.UUID;
import org.littleshoot.mina.common.IoSession;
import org.lastbamboo.common.stun.stack.message.BindingRequest;
import org.lastbamboo.common.stun.stack.message.CanceledStunMessage;
import org.lastbamboo.common.stun.stack.message.NullStunMessage;
import org.lastbamboo.common.stun.stack.message.StunMessage;
import org.lastbamboo.common.stun.stack.transaction.StunTransactionTracker;
import org.littleshoot.util.RuntimeIoException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class that performs STUN connectivity checks for ICE over UDP. Each
* ICE candidate pair has its own connectivity checker.
*/
public class IceUdpStunChecker extends AbstractIceStunChecker
{
private static final Logger m_log =
LoggerFactory.getLogger(IceUdpStunChecker.class);
/**
* Creates a new UDP STUN connectivity checker.
*
* @param session The MINA session over which the checks will take place.
* @param transactionTracker The class for keeping track of STUN
* transactions for checks.
*/
public IceUdpStunChecker(final IoSession session,
final StunTransactionTracker<StunMessage> transactionTracker)
{
super(session, transactionTracker);
}
@Override
protected StunMessage writeInternal(final BindingRequest bindingRequest,
final long rto)
{
if (this.m_transactionCanceled)
{
return new CanceledStunMessage();
}
if (this.m_writeCallsForChecker > 1)
{
throw new RuntimeIoException("Too many write calls: "+
this.m_writeCallsForChecker);
}
if (bindingRequest == null)
{
throw new NullPointerException("Null Binding Request");
}
// This method will retransmit the same request multiple times because
// it's being sent unreliably. All of these requests will be
// identical, using the same transaction ID.
final UUID id = bindingRequest.getTransactionId();
final InetSocketAddress localAddress =
(InetSocketAddress) this.m_ioSession.getLocalAddress();
final InetSocketAddress remoteAddress =
(InetSocketAddress) this.m_ioSession.getRemoteAddress();
this.m_transactionTracker.addTransaction(bindingRequest, this,
localAddress, remoteAddress);
synchronized (m_requestLock)
{
int requests = 0;
long waitTime = 0L;
while (!m_idsToResponses.containsKey(id) && requests < 7 &&
!this.m_transactionCanceled)
{
waitIfNoResponse(bindingRequest, waitTime);
// If the transaction was canceled during the wait, then
// don't send the request.
if (this.m_transactionCanceled)
{
break;
}
// See draft-ietf-behave-rfc3489bis-06.txt section 7.1. We
// continually send the same request until we receive a
// response, never sending more that 7 requests and using
// an expanding interval between requests based on the
// estimated round-trip-time to the server. This is because
// some requests can be lost with UDP.
// We only send if its connected because another thread might
// have close the session (if ICE processing has finished and
// this pair is not being used, for example).
if (this.m_ioSession.isConnected())
{
this.m_ioSession.write(bindingRequest);
}
// Wait a little longer with each send.
waitTime = (2 * waitTime) + rto;
requests++;
m_log.debug("Wrote Binding Request number: {}", requests);
}
// Now we wait for 1.6 seconds after the last request was sent.
// If we still don't receive a response, then the transaction
// has failed.
if (!this.m_transactionCanceled)
{
waitIfNoResponse(bindingRequest, 1600);
}
// Even if the transaction was canceled, we still may have
// received a successful response. If we did, we process it as
// usual. This is specified in 7.2.1.4.
if (m_idsToResponses.containsKey(id))
{
final StunMessage response = this.m_idsToResponses.remove(id);
m_log.debug("Received STUN response: {}", response);
return response;
}
if (this.m_transactionCanceled ||
this.m_closed ||
this.m_ioSession.isClosing())
{
m_log.debug("The transaction was canceled!");
return new CanceledStunMessage();
}
else
{
// This will happen quite often, such as when we haven't
// yet successfully punched a hole in the firewall.
m_log.debug("Did not get response on: {}", this.m_ioSession);
return new NullStunMessage();
}
}
}
}
| gpl-2.0 |
Siatas/BotMaker | core/src/com/thetruthbeyond/gui/objects/buttons/simple/ArrowBotButton.java | 1878 | /*
* Copyleft (C) 2015 Piotr Siatkowski find me on Facebook;
* This file is part of BotMaker. BotMaker is free software; you can
* redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version. BotMaker is distributed in
* the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details. You should have received a
* copy of the GNU General Public License along with BotMaker (look at the
* Documents directory); if not, either write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA, or visit
* (http://www.gnu.org/licenses/gpl.txt).
*/
package com.thetruthbeyond.gui.objects.buttons.simple;
import com.thetruthbeyond.gui.interfaces.FileManager;
import com.thetruthbeyond.gui.objects.Clickable;
import com.thetruthbeyond.gui.objects.buttons.Button;
import com.thetruthbeyond.gui.structures.Area;
/**
* Created by Peter Siatkowski on 2015-10-30.
* One of many button types.
*/
public class ArrowBotButton extends Button {
public ArrowBotButton(FileManager loader, Clickable parent) {
super(parent);
initialize(loader);
}
public ArrowBotButton(Area area, FileManager loader, Clickable parent) {
super(area, parent);
initialize(loader);
}
@Override
protected void initialize(FileManager loader) {
button = loader.getTexture("ScrollBarArrowBot");
buttonHover = loader.getTexture("ScrollBarArrowBotHover");
shape = Button.Shape.Oval;
soundHover = loader.getSound("ButtonHover2");
soundPressed = loader.getSound("ButtonClick2");
}
}
| gpl-2.0 |
petalyaa/Launchpet2 | src/org/pet/launchpet2/layout/NowCardLayout.java | 1462 | package org.pet.launchpet2.layout;
import org.pet.launchpet2.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
public class NowCardLayout extends LinearLayout implements OnGlobalLayoutListener {
public NowCardLayout(Context context, AttributeSet attrs) {
super(context, attrs, R.style.nowCardStyle);
initLayoutObserver();
}
public NowCardLayout(Context context) {
super(context);
initLayoutObserver();
}
private void initLayoutObserver() {
setOrientation(LinearLayout.VERTICAL);
getViewTreeObserver().addOnGlobalLayoutListener(this);
}
@Override
public void onGlobalLayout() {
getViewTreeObserver().removeOnGlobalLayoutListener(this);
final int heightPx = getContext().getResources().getDisplayMetrics().heightPixels;
boolean inversed = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
int[] location = new int[2];
child.getLocationOnScreen(location);
if (location[1] > heightPx) {
break;
}
if (!inversed) {
child.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.slide_up_left));
} else {
child.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.slide_up_right));
}
inversed = !inversed;
}
}
}
| gpl-2.0 |
LeonardCohen/coding | IDDD_Samples-master/identityaccess/src/main/java/com/saasovation/identityaccess/domain/model/identity/GroupMemberType.java | 1008 | // Copyright 2012,2013 Vaughn Vernon
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.saasovation.identityaccess.domain.model.identity;
public enum GroupMemberType {
Group {
public boolean isGroup() {
return true;
}
},
User {
public boolean isUser() {
return true;
}
};
public boolean isGroup() {
return false;
}
public boolean isUser() {
return false;
}
}
| gpl-2.0 |
teabo/wholly-framework | wholly-ddltools/src/main/java/com/whollyframework/ddltools/model/DuplicateException.java | 305 | package com.whollyframework.ddltools.model;
/**
*
* @author chris
* @since 2011-12-20
*
*/
public class DuplicateException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public DuplicateException(String message) {
super(message);
}
}
| gpl-2.0 |
ptesavol/t-time | MobileApp/Midlet/src/com/enporia/util/ByteArrayHolder.java | 133 | package com.enporia.util;
public class ByteArrayHolder
{
public byte[] data=null;
public ByteArrayHolder(byte[] d)
{
data=d;
}
}
| gpl-2.0 |
lhfei/forestry-university-app | src/main/java/cn/lhfei/fu/service/IFilePathBuilder.java | 2261 | /*
* Copyright 2010-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.lhfei.fu.service;
import cn.lhfei.fu.web.model.HomeworkBaseModel;
import cn.lhfei.fu.web.model.ThesisBaseModel;
/**
* @version 1.0.0
*
* @author Hefei Li
*
* @since Dec 5, 2014
*/
public interface IFilePathBuilder {
String getRootPath();
String mkdirs(String path);
/**
* Build home work name。
*
* The file name like this <tt>{学号班级姓名}.{学年}.{学期}.{课程名称}.{作业名称}_{附件张数}</tt>
*
* eg.
*
* @param model
* @param studentName
* @param 附件编号
* @return
*/
String buildFileName(HomeworkBaseModel model, String studentName, int num);
/**
* Build homework file path.
*
* {学号}{班级}{姓名}
*
* @param model
* @param studentName
* @return
*/
String buildFilePath(HomeworkBaseModel model, String studentName);
/**
* Make homework archives persistence full directory.
* @param model
* @param studentName
* @return
* @throws NullPointerException
*/
String buildFullPath(HomeworkBaseModel model, String studentName) throws NullPointerException;
// ======================== Thesis =============================
/**
* @param model
* @param studentName
* @param num
* @return
*/
String buildThesisFileName(ThesisBaseModel model, String studentName, int num);
/**
* @param model
* @param studentName
* @return
*/
String buildThesisFilePath(ThesisBaseModel model, String studentName);
/**
* @param model
* @param studentName
* @return
* @throws NullPointerException
*/
String buildThesisFullPath(ThesisBaseModel model, String studentName) throws NullPointerException;
}
| gpl-2.0 |
bwagner/utf-x-framework-svn-trunk | src/java/utfx/framework/WrapperStylesheetGenerator.java | 14222 | package utfx.framework;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.log4j.Logger;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Generates the wrapper XSLT stylesheets for executing the tests
*
* <p>
* Copyright © 2006 UTF-X Development Team.
* </p>
*
* <p>
* This program is free software; you can redistribute it and/or modify it under
* the terms of the <a href="http://www.gnu.org/licenses/gpl.txt">GNU General
* Public License v2 </a> as published by the Free Software Foundation.
* </p>
*
* <p>
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* </p>
*
* <code>
* $Source: /cvs/utf-x/framework/src/java/utfx/framework/Attic/WrapperStylesheetGenerator.java,v $
* </code>
*
* @author Alex Daniel
* @version $Revision: 67 $ $Date: 2006-11-18 01:40:44 +0100 (Sat, 18 Nov 2006) $ $Name: $
*/
public class WrapperStylesheetGenerator {
/** XPath factory */
private XPathFactory xpf;
/** Xpath */
private XPath xpath;
/** DOM Document builder factory */
private DocumentBuilderFactory dbf;
/** DOM Document builder */
private DocumentBuilder db;
/** URI of stylesheet under test */
String stylesheetUnderTestURI;
/** log4j logging facility */
private Logger log;
/**
* Construct a new WrapperStylesheetGenerator
*
* @param stylesheetUnderTestURI
* Uniform Resource Identifier to the stylesheet under test
* @throws ParserConfigurationException
*/
public WrapperStylesheetGenerator(String stylesheetUnderTestURI)
throws ParserConfigurationException {
this.stylesheetUnderTestURI = stylesheetUnderTestURI;
log = Logger.getLogger("utfx.framework");
xpf = XPathFactory.newInstance();
xpath = xpf.newXPath();
xpath.setNamespaceContext(new UTFXNamespaceContext());
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setExpandEntityReferences(false);
dbf.setValidating(false);
db = dbf.newDocumentBuilder();
db.setEntityResolver(new CatalogResolver());
}
/**
* Get the Uniform Resource Identifier to the stylesheet under test
*
* @return Uniform Resource Identifier to the stylesheet under test
*/
public String getStylesheetUnderTestURI() {
return stylesheetUnderTestURI;
}
/**
* Constructs a wrapper document for executing a test
*
* @param testElement
* utfx:test element
* @return wrapper document for executing a test
* @throws Exception
*/
public Document getWrapper(Element testElement) throws Exception {
Document wrapperDoc;
InputStream xsltInStream = getClass().getResourceAsStream(
"/xsl/wrapper.xsl");
try {
wrapperDoc = db.parse(xsltInStream);
} catch (Exception e) {
throw new AssertionError(e);
}
try {
Attr hrefAttr = (Attr) xpath.evaluate("//xsl:import/@href",
wrapperDoc, XPathConstants.NODE);
hrefAttr.setValue(stylesheetUnderTestURI);
} catch (XPathExpressionException e) {
throw new AssertionError(e);
}
Element stylesheetParamsElement = (Element) xpath.evaluate(
"utfx:stylesheet-params", testElement, XPathConstants.NODE);
if (stylesheetParamsElement != null) {
addStylesheetParams(wrapperDoc, stylesheetParamsElement);
}
String sourceContextNode = getSourceContextNode(testElement);
Element utfxWrapperElement = (Element) xpath.evaluate("//utfx-wrapper",
wrapperDoc.getDocumentElement(), XPathConstants.NODE);
Element callTemplateElement = (Element) xpath.evaluate(
"utfx:call-template", testElement, XPathConstants.NODE);
if (callTemplateElement == null) {
addApplyTemplates(wrapperDoc, utfxWrapperElement, sourceContextNode);
} else {
addCallTemplate(wrapperDoc, utfxWrapperElement,
callTemplateElement, sourceContextNode);
}
return wrapperDoc;
}
/**
* Get the content of the context-node attribute of utfx:source element
*
* Empty string is returned when attribute isn't present. When the slash at
* the beginning of context-node is missing it is added.
*
* @param testElement
* @return content of the context-node attribute of utfx:source element
* @throws Exception
*/
private String getSourceContextNode(Element testElement) throws Exception {
StringBuffer sourceContextNode = new StringBuffer();
Element utfxSourceElement = (Element) xpath.evaluate(
"utfx:assert-equal/utfx:source", testElement,
XPathConstants.NODE);
if (utfxSourceElement != null) {
sourceContextNode.append(utfxSourceElement
.getAttribute("context-node"));
if (sourceContextNode.length() > 0) {
if (!sourceContextNode.toString().startsWith("/")) {
sourceContextNode.insert(0, "/");
}
}
}
return sourceContextNode.toString();
}
/**
* Adds code for stylesheet parameters to wrapperDoc
*
* @param wrapperDoc
* DOM Document representing the UTF-X test definition file.
* @param elem
* stylesheet-params element
* @return void
* @throws Exception
*/
private void addStylesheetParams(Document wrapperDoc, Element elem)
throws Exception {
// find refElement (for insertBefore)
Element xslOutputElement = (Element) xpath.evaluate("xsl:output",
wrapperDoc.getDocumentElement(), XPathConstants.NODE);
Node refNode = xslOutputElement.getNextSibling();
NodeList params;
try {
params = (NodeList) xpath.evaluate("*[name() = 'utfx:with-param']",
elem, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
throw new AssertionError(e);
}
for (int i = 0; i < params.getLength(); i++) {
Element withParamElement = (Element) params.item(i);
// create xsl:param element
Element xslParam = wrapperDoc.createElementNS(
UTFXNamespaceContext.XSL_NS_URI, "xsl:param");
xslParam
.setAttribute("name", withParamElement.getAttribute("name"));
copySelectAttrOrChildNodes(withParamElement, wrapperDoc, xslParam);
wrapperDoc.getDocumentElement().insertBefore(xslParam, refNode);
}
}
/**
* Adds XSLT-elements for apply-templates to wrapperDoc
*
* creates the element <xsl:apply-templates
* select="$utfx-wrapper-removed/child::node()"/> and appends
* it to utfxWrapperElement
*
* @param wrapperDoc
* DOM Document representing the UTF-X test definition file
* @param utfxWrapperElement
* the utfx-wrapper element from wrapper.xsl
*/
private void addApplyTemplates(Document wrapperDoc,
Element utfxWrapperElement, String sourceContextNode) {
// compose select expression for xsl:apply-templates
StringBuffer selectExpression = new StringBuffer(
"$utfx-wrapper-removed");
if (sourceContextNode.length() == 0) {
selectExpression.append("/child::node()");
} else if (sourceContextNode.equals("/")) {
log.error("when using context-node=\"/\" for template match an infinite recursion will happen");
// adding a slash to $utfx-wrapper-removed would
// result in an invalid XPath expression. therefore we don't add
// anything
} else {
selectExpression.append(sourceContextNode);
}
Element xslApplyTemplates = wrapperDoc.createElementNS(
UTFXNamespaceContext.XSL_NS_URI, "xsl:apply-templates");
xslApplyTemplates.setAttribute("select", selectExpression.toString());
utfxWrapperElement.appendChild(xslApplyTemplates);
}
/**
* Adds XSLT-elements for calling a named template to wrapperDoc
*
* Following elements are added to utfxWrapperElement as childs
* <xsl:for-each select="$utfx-wrapper-removed/*[1]"> or
* context-node attribute <xsl:call-template name="NAME OF TEMPLATE"/>
* </xsl:for-each> <xsl:apply-templates
* select="$utfx-wrapper-removed/*[position() > 1]"/>
*
* @param wrapperDoc
* DOM Document representing the UTF-X test definition file
* @param utfxWrapperElement
* the utfx-wrapper element from wrapper.xsl
* @param elem
* call-template element
* @return void
* @throws Exception
*/
private void addCallTemplate(Document wrapperDoc,
Element utfxWrapperElement, Element elem, String sourceContextNode)
throws Exception {
String templateName = elem.getAttribute("name");
Element xslCallTemplate = wrapperDoc.createElementNS(
UTFXNamespaceContext.XSL_NS_URI, "xsl:call-template");
xslCallTemplate.setAttribute("name", templateName);
addCallTemplateParameters(wrapperDoc, elem, xslCallTemplate);
// compose select expression for xsl:for-each
StringBuffer selectExpression = new StringBuffer(
"$utfx-wrapper-removed");
if (sourceContextNode.length() == 0) {
selectExpression.append("/*[1]");
} else if (sourceContextNode.equals("/")) {
// adding a slash to $utfx-wrapper-removed would
// result in an invalid XPath expression. therefore we don't add
// anything
} else {
selectExpression.append(sourceContextNode);
}
Element xslForEach = wrapperDoc.createElementNS(
UTFXNamespaceContext.XSL_NS_URI, "xsl:for-each");
xslForEach.setAttribute("select", selectExpression.toString());
xslForEach.appendChild(xslCallTemplate);
Element xslApplyTemplates = wrapperDoc.createElementNS(
UTFXNamespaceContext.XSL_NS_URI, "xsl:apply-templates");
xslApplyTemplates.setAttribute("select",
"$utfx-wrapper-removed/*[position() > 1]");
utfxWrapperElement.appendChild(xslForEach);
utfxWrapperElement.appendChild(xslApplyTemplates);
}
/**
* Adds with-param elements to wrapperDoc
*
* @param wrapperDoc
* DOM Document representing the UTF-X test definition file.
* @param elem
* stylesheet-params element
* @param xslCallTemplate
* call-template element in wrapperDoc
* @return void
*/
private void addCallTemplateParameters(Document wrapperDoc, Element elem,
Element xslCallTemplate) {
NodeList params;
try {
params = (NodeList) xpath.evaluate("*[name() = 'utfx:with-param']",
elem, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
throw new AssertionError(e);
}
int paramsCount = params.getLength();
for (int i = 0; i < paramsCount; i++) {
Element paramElem = (Element) params.item(i);
Element xslWithParam = wrapperDoc.createElementNS(
UTFXNamespaceContext.XSL_NS_URI, "xsl:with-param");
String name = paramElem.getAttribute("name");
xslWithParam.setAttribute("name", name);
copySelectAttrOrChildNodes(paramElem, wrapperDoc, xslWithParam);
xslCallTemplate.appendChild(xslWithParam);
}
}
/**
* Copies the select attribute if available or its childnodes to destination
* element
*
* @param src
* source element
* @param doc
* destination document
* @param dst
* destination element
* @return void
*/
private void copySelectAttrOrChildNodes(Element src, Document doc,
Element dst) {
String selectAttrName = "select";
if (src.hasAttribute(selectAttrName)) {
dst.setAttribute(selectAttrName, src.getAttribute(selectAttrName));
} else {
importAndAppendChildNodes(src, doc, dst);
}
}
/**
* Copies childnodes to destination element
*
* @param src
* source element
* @param doc
* destination document
* @param dst
* destination element
* @return void
*/
private void importAndAppendChildNodes(Element src, Document doc,
Element dst) {
NodeList childNodes = src.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node node = childNodes.item(j);
Node importedNode = doc.importNode(node, true);
dst.appendChild(importedNode);
}
}
}
| gpl-2.0 |
mzmine/mzmine3 | src/main/java/io/github/mzmine/modules/dataprocessing/id_localcsvsearch/LocalCSVDatabaseSearchParameters.java | 7044 | /*
* Copyright 2006-2021 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* MZmine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with MZmine; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
package io.github.mzmine.modules.dataprocessing.id_localcsvsearch;
import io.github.mzmine.datamodel.features.types.DataType;
import io.github.mzmine.datamodel.features.types.annotations.CommentType;
import io.github.mzmine.datamodel.features.types.annotations.CompoundNameType;
import io.github.mzmine.datamodel.features.types.annotations.SmilesStructureType;
import io.github.mzmine.datamodel.features.types.annotations.formula.FormulaType;
import io.github.mzmine.datamodel.features.types.annotations.iin.IonAdductType;
import io.github.mzmine.datamodel.features.types.numbers.CCSType;
import io.github.mzmine.datamodel.features.types.numbers.MobilityType;
import io.github.mzmine.datamodel.features.types.numbers.NeutralMassType;
import io.github.mzmine.datamodel.features.types.numbers.PrecursorMZType;
import io.github.mzmine.datamodel.features.types.numbers.RTType;
import io.github.mzmine.parameters.Parameter;
import io.github.mzmine.parameters.impl.IonMobilitySupport;
import io.github.mzmine.parameters.impl.SimpleParameterSet;
import io.github.mzmine.parameters.parametertypes.ImportType;
import io.github.mzmine.parameters.parametertypes.ImportTypeParameter;
import io.github.mzmine.parameters.parametertypes.PercentParameter;
import io.github.mzmine.parameters.parametertypes.StringParameter;
import io.github.mzmine.parameters.parametertypes.filenames.FileNameParameter;
import io.github.mzmine.parameters.parametertypes.filenames.FileSelectionType;
import io.github.mzmine.parameters.parametertypes.ionidentity.IonLibraryParameterSet;
import io.github.mzmine.parameters.parametertypes.selectors.FeatureListsParameter;
import io.github.mzmine.parameters.parametertypes.submodules.OptionalModuleParameter;
import io.github.mzmine.parameters.parametertypes.tolerances.MZToleranceParameter;
import io.github.mzmine.parameters.parametertypes.tolerances.RTToleranceParameter;
import io.github.mzmine.parameters.parametertypes.tolerances.mobilitytolerance.MobilityTolerance;
import io.github.mzmine.parameters.parametertypes.tolerances.mobilitytolerance.MobilityToleranceParameter;
import java.util.Collection;
import java.util.List;
import org.jetbrains.annotations.NotNull;
/**
*
*/
public class LocalCSVDatabaseSearchParameters extends SimpleParameterSet {
public static final FeatureListsParameter peakLists = new FeatureListsParameter();
public static final FileNameParameter dataBaseFile = new FileNameParameter("Database file",
"Name of file that contains information for peak identification", FileSelectionType.OPEN);
public static final StringParameter fieldSeparator = new StringParameter("Field separator",
"Character(s) used to separate fields in the database file", ",");
public static final MZToleranceParameter mzTolerance = new MZToleranceParameter();
public static final RTToleranceParameter rtTolerance = new RTToleranceParameter();
public static final MobilityToleranceParameter mobTolerance = new MobilityToleranceParameter(
new MobilityTolerance(0.01f));
public static final PercentParameter ccsTolerance = new PercentParameter("CCS tolerance (%)",
"Maximum allowed difference (in per cent) for two ccs values.", 0.05);
public static final OptionalModuleParameter<IonLibraryParameterSet> ionLibrary = new OptionalModuleParameter<>(
"Use adducts",
"If enabled, m/z values for multiple adducts will be calculated and matched against the feature list.",
(IonLibraryParameterSet) new IonLibraryParameterSet().cloneParameterSet());
private static final List<ImportType> importTypes = List.of(
new ImportType(true, "neutral mass", new NeutralMassType()),
new ImportType(true, "mz", new PrecursorMZType()), //
new ImportType(true, "rt", new RTType()), new ImportType(true, "formula", new FormulaType()),
new ImportType(true, "smiles", new SmilesStructureType()),
new ImportType(false, "name", new CompoundNameType()),
new ImportType(false, "CCS", new CCSType()),
new ImportType(false, "mobility", new MobilityType()),
new ImportType(true, "comment", new CommentType()),
new ImportType(false, "adduct", new IonAdductType()),
new ImportType(false, "PubChemCID", new PubChemIdType()));
public static final ImportTypeParameter columns = new ImportTypeParameter("Columns",
"Select the columns you want to import from the library file.", importTypes);
public LocalCSVDatabaseSearchParameters() {
super(
new Parameter[]{peakLists, dataBaseFile, fieldSeparator, columns, mzTolerance, rtTolerance,
mobTolerance, ccsTolerance, ionLibrary});
}
@Override
public boolean checkParameterValues(Collection<String> errorMessages) {
final boolean superCheck = super.checkParameterValues(errorMessages);
final List<ImportType> selectedTypes = getParameter(columns).getValue().stream()
.filter(ImportType::isSelected).toList();
boolean compoundNameSelected = true;
if (!importTypeListContainsType(selectedTypes, new CompoundNameType())) {
compoundNameSelected = false;
errorMessages.add(new CompoundNameType().getHeaderString() + " must be selected.");
}
boolean canDetermineMz = false;
if (importTypeListContainsType(selectedTypes, new NeutralMassType()) && getValue(ionLibrary)) {
canDetermineMz = true;
} else if (importTypeListContainsType(selectedTypes, new PrecursorMZType())) {
canDetermineMz = true;
} else if (importTypeListContainsType(selectedTypes, new FormulaType()) && getValue(
ionLibrary)) {
canDetermineMz = true;
} else if (importTypeListContainsType(selectedTypes, new SmilesStructureType()) && getValue(
ionLibrary)) {
canDetermineMz = true;
}
if (!canDetermineMz) {
errorMessages.add("Cannot determine precursor mz with currently selected data types.");
}
return superCheck && compoundNameSelected && canDetermineMz;
}
private boolean importTypeListContainsType(List<ImportType> importTypes, DataType<?> type) {
return importTypes.stream().anyMatch(importType -> importType.getDataType().equals(type));
}
@Override
public @NotNull IonMobilitySupport getIonMobilitySupport() {
return IonMobilitySupport.SUPPORTED;
}
}
| gpl-2.0 |
UnboundID/ldapsdk | tests/unit/src/com/unboundid/ldap/sdk/AggregatePostConnectProcessorTestCase.java | 10444 | /*
* Copyright 2015-2020 Ping Identity Corporation
* All Rights Reserved.
*/
/*
* Copyright 2015-2020 Ping Identity Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2015-2020 Ping Identity Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPLv2 only)
* or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
*/
package com.unboundid.ldap.sdk;
import java.util.Collection;
import org.testng.annotations.Test;
import com.unboundid.ldap.listener.InMemoryDirectoryServer;
/**
* This class provides a set of test cases for the aggregate post-connect
* processor.
*/
public final class AggregatePostConnectProcessorTestCase
extends LDAPSDKTestCase
{
/**
* Tests the behavior of the aggregate post-connect processor that wraps a
* single post-connect processors that should succeed.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testSuccessfulSingleProcessor()
throws Exception
{
final InMemoryDirectoryServer ds = getTestDS();
final SingleServerSet serverSet =
new SingleServerSet("127.0.0.1", ds.getListenPort());
final LDAPConnectionPool pool =
new LDAPConnectionPool(serverSet, null, 0, 1,
new AggregatePostConnectProcessor(
new TestPostConnectProcessor(null, null)));
assertNotNull(pool.getRootDSE());
pool.close();
}
/**
* Tests the behavior of the aggregate post-connect processor that wraps an
* empty set of post-connect processors.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testSuccessfulEmptyProcessor()
throws Exception
{
final InMemoryDirectoryServer ds = getTestDS();
final SingleServerSet serverSet =
new SingleServerSet("127.0.0.1", ds.getListenPort());
final LDAPConnectionPool pool =
new LDAPConnectionPool(serverSet, null, 0, 1,
new AggregatePostConnectProcessor());
assertNotNull(pool.getRootDSE());
pool.close();
}
/**
* Tests the behavior of the aggregate post-connect processor that wraps a
* {@code null} collection of post-connect processors.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testSuccessfulNullProcessor()
throws Exception
{
final InMemoryDirectoryServer ds = getTestDS();
final SingleServerSet serverSet =
new SingleServerSet("127.0.0.1", ds.getListenPort());
final Collection<PostConnectProcessor> nullCollection = null;
final LDAPConnectionPool pool =
new LDAPConnectionPool(serverSet, null, 0, 1,
new AggregatePostConnectProcessor(nullCollection));
assertNotNull(pool.getRootDSE());
pool.close();
}
/**
* Tests the behavior of the aggregate post-connect processor that wraps
* several post-connect processors that should all succeed.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testSuccessfulMultipleProcessors()
throws Exception
{
final InMemoryDirectoryServer ds = getTestDS();
final SingleServerSet serverSet =
new SingleServerSet("127.0.0.1", ds.getListenPort());
final LDAPConnectionPool pool =
new LDAPConnectionPool(serverSet, null, 0, 1,
new AggregatePostConnectProcessor(
new TestPostConnectProcessor(null, null),
new TestPostConnectProcessor(null, null),
new TestPostConnectProcessor(null, null)));
assertNotNull(pool.getRootDSE());
pool.close();
}
/**
* Tests the behavior of the aggregate post-connect processor that wraps
* several post-connect processors in which the first should fail in
* pre-authentication processing.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testFailInFirstPreAuth()
throws Exception
{
final InMemoryDirectoryServer ds = getTestDS();
final SingleServerSet serverSet =
new SingleServerSet("127.0.0.1", ds.getListenPort());
final LDAPConnectionPool pool =
new LDAPConnectionPool(serverSet, null, 0, 1,
new AggregatePostConnectProcessor(
new TestPostConnectProcessor(
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"preAuth1"),
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"postAuth1")),
new TestPostConnectProcessor(
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"preAuth2"),
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"postAuth2")),
new TestPostConnectProcessor(
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"preAuth3"),
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"postAuth3"))));
try
{
pool.getRootDSE();
fail("Expected an exception from the first pre-auth processor");
}
catch (final LDAPException le)
{
assertEquals(le.getMessage(), "preAuth1");
}
pool.close();
}
/**
* Tests the behavior of the aggregate post-connect processor that wraps
* several post-connect processors in which the first should succeed but a
* subsequent processor should fail in pre-authentication processing.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testFailInSubsequentPreAuth()
throws Exception
{
final InMemoryDirectoryServer ds = getTestDS();
final SingleServerSet serverSet =
new SingleServerSet("127.0.0.1", ds.getListenPort());
final LDAPConnectionPool pool =
new LDAPConnectionPool(serverSet, null, 0, 1,
new AggregatePostConnectProcessor(
new TestPostConnectProcessor(null, null),
new TestPostConnectProcessor(
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"preAuth2"),
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"postAuth2")),
new TestPostConnectProcessor(
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"preAuth3"),
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"postAuth3"))));
try
{
pool.getRootDSE();
fail("Expected an exception from a subsequent pre-auth processor");
}
catch (final LDAPException le)
{
assertEquals(le.getMessage(), "preAuth2");
}
pool.close();
}
/**
* Tests the behavior of the aggregate post-connect processor that wraps
* several post-connect processors in which the first should fail in
* post-authentication processing.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testFailInFirstPostAuth()
throws Exception
{
final InMemoryDirectoryServer ds = getTestDS();
final SingleServerSet serverSet =
new SingleServerSet("127.0.0.1", ds.getListenPort());
final LDAPConnectionPool pool =
new LDAPConnectionPool(serverSet, null, 0, 1,
new AggregatePostConnectProcessor(
new TestPostConnectProcessor(null,
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"postAuth1")),
new TestPostConnectProcessor(null,
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"postAuth2")),
new TestPostConnectProcessor(null,
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"postAuth3"))));
try
{
pool.getRootDSE();
fail("Expected an exception from the first post-auth processor");
}
catch (final LDAPException le)
{
assertEquals(le.getMessage(), "postAuth1");
}
pool.close();
}
/**
* Tests the behavior of the aggregate post-connect processor that wraps
* several post-connect processors in which the first should succeed but a
* subsequent processor should fail in post-authentication processing.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testFailInSubsequentPostAuth()
throws Exception
{
final InMemoryDirectoryServer ds = getTestDS();
final SingleServerSet serverSet =
new SingleServerSet("127.0.0.1", ds.getListenPort());
final LDAPConnectionPool pool =
new LDAPConnectionPool(serverSet, null, 0, 1,
new AggregatePostConnectProcessor(
new TestPostConnectProcessor(null, null),
new TestPostConnectProcessor(null,
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"postAuth2")),
new TestPostConnectProcessor(null,
new LDAPException(ResultCode.UNWILLING_TO_PERFORM,
"postAuth3"))));
try
{
pool.getRootDSE();
fail("Expected an exception from a subsequent post-auth processor");
}
catch (final LDAPException le)
{
assertEquals(le.getMessage(), "postAuth2");
}
pool.close();
}
}
| gpl-2.0 |
nologic/nabs | client/trunk/shared/libraries/je-3.2.74/test/com/sleepycat/persist/test/ConvertAndAddTest.java | 4971 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002,2008 Oracle. All rights reserved.
*
* $Id: ConvertAndAddTest.java,v 1.1.2.4 2008/01/07 15:14:35 cwl Exp $
*/
package com.sleepycat.persist.test;
import java.io.File;
import java.io.IOException;
import junit.framework.TestCase;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.util.TestUtils;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.StoreConfig;
import com.sleepycat.persist.evolve.Conversion;
import com.sleepycat.persist.evolve.Converter;
import com.sleepycat.persist.evolve.Mutations;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.EntityModel;
import com.sleepycat.persist.model.PrimaryKey;
/**
* Test a bug fix where an IndexOutOfBoundsException occurs when adding a field
* and converting another field, where the latter field is alphabetically
* higher than the former. This is also tested by
* EvolveClasses.FieldAddAndConvert, but that class does not test evolving an
* entity that was created by catalog version 0. [#15797]
*
* A modified version of this program was run manually with JE 3.2.30 to
* produce a log, which is the result of the testSetup() test. The sole log
* file was renamed from 00000000.jdb to ConvertAndAddTest.jdb and added to CVS
* in this directory. When that log file is opened here, the bug is
* reproduced. The modifications to this program for 3.2.30 are:
*
* + X in testSetup
* + X out testConvertAndAddField
* + don't remove log files in tearDown
* + @Entity version is 0
* + removed field MyEntity.a
*
* This test should be excluded from the BDB build because it uses a stored JE
* log file and it tests a fix for a bug that was never present in BDB.
*
* @author Mark Hayes
*/
public class ConvertAndAddTest extends TestCase {
private static final String STORE_NAME = "test";
private File envHome;
private Environment env;
public void setUp()
throws IOException {
envHome = new File(System.getProperty(TestUtils.DEST_DIR));
TestUtils.removeLogFiles("Setup", envHome, false);
}
public void tearDown()
throws IOException {
if (env != null) {
try {
env.close();
} catch (DatabaseException e) {
System.out.println("During tearDown: " + e);
}
}
try {
TestUtils.removeLogFiles("TearDown", envHome, false);
} catch (Error e) {
System.out.println("During tearDown: " + e);
}
envHome = null;
env = null;
}
private EntityStore open(boolean addConverter)
throws DatabaseException {
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
env = new Environment(envHome, envConfig);
Mutations mutations = new Mutations();
mutations.addConverter(new Converter
(MyEntity.class.getName(), 0, "b", new MyConversion()));
StoreConfig storeConfig = new StoreConfig();
storeConfig.setAllowCreate(true);
storeConfig.setMutations(mutations);
return new EntityStore(env, "foo", storeConfig);
}
private void close(EntityStore store)
throws DatabaseException {
store.close();
env.close();
env = null;
}
public void testConvertAndAddField()
throws DatabaseException, IOException {
/* Copy log file resource to log file zero. */
TestUtils.loadLog(getClass(), "ConvertAndAddTest.jdb", envHome);
EntityStore store = open(true /*addConverter*/);
PrimaryIndex<Long, MyEntity> index =
store.getPrimaryIndex(Long.class, MyEntity.class);
MyEntity entity = index.get(1L);
assertNotNull(entity);
assertEquals(123, entity.b);
close(store);
}
public void xtestSetup()
throws DatabaseException {
EntityStore store = open(false /*addConverter*/);
PrimaryIndex<Long, MyEntity> index =
store.getPrimaryIndex(Long.class, MyEntity.class);
MyEntity entity = new MyEntity();
entity.key = 1;
entity.b = 123;
index.put(entity);
close(store);
}
@Entity(version=1)
static class MyEntity {
@PrimaryKey
long key;
int a; // added in version 1
int b;
private MyEntity() {}
}
public static class MyConversion implements Conversion {
public void initialize(EntityModel model) {
}
public Object convert(Object fromValue) {
return fromValue;
}
@Override
public boolean equals(Object o) {
return o instanceof MyConversion;
}
}
}
| gpl-2.0 |
hajdam/frinthesia | modules/frinika-sequencer/src/main/java/com/frinika/sequencer/gui/menu/AudioPartToMidiAction.java | 2585 | /*
*
* Copyright (c) 2006-2007 Paul John Leonard
*
* http://www.frinika.com
*
* This file is part of Frinika.
*
* Frinika is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Frinika is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Frinika; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.frinika.sequencer.gui.menu;
import static com.frinika.localization.CurrentLocale.getMessage;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.AbstractAction;
import com.frinika.sequencer.model.audio.AudioPartToMidi;
import com.frinika.sequencer.gui.ProjectFrame;
import com.frinika.sequencer.model.AudioPart;
import com.frinika.sequencer.model.MidiLane;
import com.frinika.sequencer.model.MidiPart;
import com.frinika.sequencer.model.Part;
public class AudioPartToMidiAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private ProjectFrame project;
public AudioPartToMidiAction(ProjectFrame project) {
super(getMessage("sequencer.project.audiopart_to_midi"));
this.project = project;
}
public void actionPerformed(ActionEvent arg0) {
Thread t = new Thread() {
public void run() {
Part part = project.getProjectContainer()
.getPartSelection().getFocus();
if (part == null || !(part instanceof AudioPart))
return;
MidiPart midiPart = null;
try {
midiPart = AudioPartToMidi.process((AudioPart) part);
project
.getProjectContainer()
.getEditHistoryContainer()
.mark(
getMessage("sequencer.project.audiopart_to_midi"));
MidiLane lane = project.getProjectContainer()
.createMidiLane();
lane.add(midiPart);
project.getProjectContainer()
.getEditHistoryContainer()
.notifyEditHistoryListeners();
project.getProjectContainer().getPartSelection()
.notifyListeners();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
// TODO make a cancel button.
}
} | gpl-2.0 |
tmmcguire/ashurbanipal | src/net/crsr/ashurbanipal/pool/TaggerCallable.java | 4014 | package net.crsr.ashurbanipal.pool;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.function.Supplier;
import net.crsr.ashurbanipal.reader.FragmentingReader;
import net.crsr.ashurbanipal.reader.GutenbergLicenseReader;
import net.crsr.ashurbanipal.reader.ZippedTextFileReader;
import net.crsr.ashurbanipal.tagger.Tagger;
import net.crsr.ashurbanipal.tagger.TaggerResult;
public class TaggerCallable implements Callable<TaggerResult> {
private static final ThreadLocal<Map<String,Integer>> threadTaggerUseCount = ThreadLocal.withInitial(new Supplier<Map<String,Integer>>() {
@Override public Map<String,Integer> get() { return new HashMap<>(); }
});
private static final ThreadLocal<Map<String,Tagger>> threadTagger = ThreadLocal.withInitial(new Supplier<Map<String,Tagger>>() {
@Override public Map<String,Tagger> get() { return new HashMap<>(); }
});
private final int etextNo;
private final File file;
private final String lang;
public TaggerCallable(int etextNo, String lang, File file) {
this.etextNo = etextNo;
this.file = file;
this.lang = lang;
}
@Override
public TaggerResult call() throws Exception {
FragmentingReader fragments = null;
try {
Tagger tagger = threadTagger.get().get(lang);
Integer useCount = threadTaggerUseCount.get().get(lang);
if (useCount == null || tagger == null || useCount > 32) {
tagger = Tagger.getTaggerFor(lang, file);
if (tagger == null) {
return null;
}
threadTagger.get().put(lang, tagger);
useCount = 0;
}
threadTaggerUseCount.get().put(lang, useCount+1);
// Process text in fragments, then coalesce data from fragments.
fragments = new FragmentingReader(new GutenbergLicenseReader(new ZippedTextFileReader(file)), 10240);
int nWords = 0;
final Map<String,Double> posData = new HashMap<>();
final Map<String,Map<String,Integer>> wordBags = new HashMap<>();
while (fragments.hasFragments()) {
final TaggerResult taggerResult = tagger.process(etextNo, fragments.nextFragment());
// Total number of words.
nWords += taggerResult.nWords;
// Total POS data.
for (Entry<String,Double> entry : taggerResult.posData.entrySet()) {
posData.put(entry.getKey(), posData.getOrDefault(entry.getKey(), 0.0) + entry.getValue());
}
// Total word collections.
for (Entry<String,Map<String,Integer>> entry : taggerResult.wordCounts.entrySet()) {
Map<String,Integer> wordCounts = wordBags.get(entry.getKey());
if (wordCounts == null) {
wordCounts = new TreeMap<>();
wordBags.put(entry.getKey(), wordCounts);
}
for (Entry<String,Integer> subEntry : entry.getValue().entrySet()) {
wordCounts.put(subEntry.getKey(), wordCounts.getOrDefault(subEntry.getKey(), 0) + subEntry.getValue());
}
}
}
return new TaggerResult(etextNo, tagProportions(nWords, posData), wordBags, nWords);
} catch (ZippedTextFileReader.Exception e) {
throw new Exception("error reading text " + etextNo + ": " + file.getAbsolutePath(), e);
} catch (IOException e) {
throw new Exception("error reading text " + etextNo + ": " + file.getAbsolutePath(), e);
} finally {
if (fragments != null) { try { fragments.close(); } catch (Throwable t) { } }
}
}
private static Map<String,Double> tagProportions(int words, Map<String,Double> result) {
for (Entry<String,Double> entry : result.entrySet()) {
entry.setValue(entry.getValue() / words);
}
return result;
}
@SuppressWarnings("serial")
public static class Exception extends java.lang.Exception {
public Exception(String message, Throwable cause) {
super(message, cause);
}
}
}
| gpl-2.0 |
tomas-pluskal/mzmine3 | src/main/java/io/github/mzmine/modules/visualization/twod/FeatureDataRenderer.java | 1814 | /*
* Copyright 2006-2020 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* MZmine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with MZmine; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.github.mzmine.modules.visualization.twod;
import java.awt.Color;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
/**
*
*/
class FeatureDataRenderer extends XYLineAndShapeRenderer {
private static final long serialVersionUID = 1L;
private static final Color peakColor = Color.green;
// data points shape
private static final Shape dataPointsShape = new Ellipse2D.Double(-2, -2, 5, 5);
FeatureDataRenderer() {
setDefaultShapesFilled(true);
setDrawOutlines(false);
setUseFillPaint(false);
setDefaultShapesVisible(false);
setDefaultShape(dataPointsShape);
FeatureToolTipGenerator toolTipGenerator = new FeatureToolTipGenerator();
setDefaultToolTipGenerator(toolTipGenerator);
setDrawSeriesLineAsPath(true);
}
public Paint getItemPaint(int row, int column) {
return peakColor;
}
public Shape getItemShape(int row, int column) {
return dataPointsShape;
}
}
| gpl-2.0 |
FrantaM/gitlab-plugin | src/main/java/com/dabsquared/gitlabjenkins/GitLabRequest.java | 1861 | package com.dabsquared.gitlabjenkins;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class GitLabRequest {
protected enum Builder {
INSTANCE;
private final Gson gson;
Builder() {
gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(Date.class, new GitLabRequest.DateSerializer())
.create();
}
public Gson get() {
return gson;
}
};
private static final String[] DATE_FORMATS = new String[] {
"yyyy-MM-dd HH:mm:ss Z", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" };
private static class DateSerializer implements JsonDeserializer<Date> {
public Date deserialize(JsonElement jsonElement, Type typeOF,
JsonDeserializationContext context) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format, Locale.US)
.parse(jsonElement.getAsString());
} catch (ParseException e) {
}
}
throw new JsonParseException("Unparseable date: \""
+ jsonElement.getAsString() + "\". Supported formats: "
+ Arrays.toString(DATE_FORMATS));
}
}
}
| gpl-2.0 |
titokone/titotrainer | WEB-INF/src/fi/helsinki/cs/titotrainer/app/model/criteria/DataReferencesCriterion.java | 695 | package fi.helsinki.cs.titotrainer.app.model.criteria;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import fi.helsinki.cs.titotrainer.app.model.titokone.TitokoneState;
/**
* A criterion that checks againts the number of data area memory references.
*/
@DiscriminatorValue("DATAREFERENCES")
@Entity
public class DataReferencesCriterion extends MetricCriterion {
public DataReferencesCriterion() {
}
public DataReferencesCriterion(Relation rel, long rightValue) {
super(rel, rightValue);
}
@Override
protected long getLeftParameterValue(TitokoneState state) {
return state.getMemoryDataReferences();
}
}
| gpl-2.0 |
calimero-project/calimero | src/tuwien/auto/calimero/Settings.java | 5499 | /*
Calimero 2 - A library for KNX network access
Copyright (c) 2006, 2021 B. Malinowsky
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under terms
of your choice, provided that you also meet, for each linked independent
module, the terms and conditions of the license of that module. An
independent module is a module which is not derived from or based on
this library. If you modify this library, you may extend this exception
to your version of the library, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from your
version.
*/
package tuwien.auto.calimero;
import static java.util.stream.Collectors.joining;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* General settings used in Calimero as well as library user information.
*
* @author B. Malinowsky
*/
public final class Settings
{
private static final String version = "2.5-M1";
private static final String library = "Calimero";
private static final String desc = "A library for KNX network access";
private static final String tuwien = "Vienna University of Technology";
private static final String group = "Automation Systems Group";
private static final String copyright = "Copyright \u00A9 2006-2021";
// just use newline, it's easier to deal with
private static final String sep = "\n";
private Settings() {}
/**
* Returns the core library version as string representation.
* <p>
* The returned version is formatted something similar to
* "main.minor[.milli][-phase]", for example, "2.0" or "2.0.0-alpha".
*
* @return version as string
*/
public static String getLibraryVersion()
{
return version;
}
/**
* Returns a default library header representation with general/usage information.
* <p>
* It includes stuff like the library name, library version, name and institute of the
* Vienna University of Technology where the library was developed, and copyright.
* The returned information parts are divided using the newline ('\n') character.
*
* @param verbose <code>true</code> to return all header information just mentioned,
* <code>false</code> to only return library name and version comprised of
* one line (no line separators)
* @return header as string
*/
public static String getLibraryHeader(final boolean verbose)
{
if (!verbose)
return library + " version " + version;
final StringBuilder buf = new StringBuilder();
buf.append(library).append(" version ").append(version).append(" - ");
buf.append(desc).append(sep);
buf.append(group).append(", ");
buf.append(tuwien).append(sep);
buf.append(copyright);
return buf.toString();
}
/**
* This entry routine of the library prints information to the standard
* output stream (System.out), mainly for user information.
* <p>
* Recognized options for output:
* <ul>
* <li>no options: default library header information and bundle listing</li>
* <li>-v, --version: prints library name and version</li>
* </ul>
*
* @param args argument list with options controlling output information
*/
public static void main(final String[] args)
{
if (args.length > 0 && (args[0].equals("--version") || args[0].equals("-v")))
out(getLibraryHeader(false));
else {
out(getLibraryHeader(true));
out(sep + "Supported protocols: " + supportedProtocols().collect(joining(", ")));
}
}
private static Stream<String> supportedProtocols() {
final String[] proto = { "KNXnet/IP (Secure)", "KNX IP", "FT1.2", "TP-Uart", "KNX USB", "KNX RF USB", "BAOS" };
final String prefix = "tuwien.auto.calimero.";
final String[] check = { "knxnetip.KNXnetIPConnection", "knxnetip.KNXnetIPConnection", "serial.FT12Connection",
"serial.TpuartConnection", "serial.usb.UsbConnection", "serial.usb.UsbConnection", "baos.Baos" };
return IntStream.range(0, proto.length).filter(i -> loadable(prefix + check[i])).mapToObj(i -> proto[i]);
}
private static boolean loadable(final String className) {
try {
final ClassLoader cl = Settings.class.getClassLoader();
cl.loadClass(className);
return true;
}
catch (ClassNotFoundException | NoClassDefFoundError ignored) {}
return false;
}
private static void out(final String s)
{
System.out.println(s);
}
}
| gpl-2.0 |
dlazerka/mf | android/src/main/java/me/lazerka/mf/android/activity/ContactFragment.java | 5947 | /*
* Find Us: privacy oriented location tracker for your friends and family.
* Copyright (C) 2015 Dzmitry Lazerka dlazerka@gmail.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
package me.lazerka.mf.android.activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import me.lazerka.mf.android.Application;
import me.lazerka.mf.android.FriendsManager;
import me.lazerka.mf.android.R;
import me.lazerka.mf.android.adapter.FriendViewHolder;
import me.lazerka.mf.android.adapter.PersonInfo;
import static android.provider.ContactsContract.QuickContact.MODE_LARGE;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* @author Dzmitry Lazerka
* TODO: add null activity handling
*/
public class ContactFragment extends Fragment {
private static final Logger logger = LoggerFactory.getLogger(ContactFragment.class);
private static final String PERSON_INFO = "PERSON_INFO";
private PersonInfo personInfo;
private int[] durationValues;
private Spinner spinner;
private final FriendsManager friendsManager = Application.friendsManager;
public static Bundle makeArguments(PersonInfo personInfo) {
Bundle arguments = new Bundle(1);
arguments.putParcelable(PERSON_INFO, checkNotNull(personInfo));
return arguments;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle arguments = getArguments();
personInfo = checkNotNull(arguments.<PersonInfo>getParcelable(PERSON_INFO));
}
@Nullable
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState
) {
View view = inflater.inflate(R.layout.fragment_contact, container, false);
FriendViewHolder friendViewHolder = new FriendViewHolder(view);
friendViewHolder.bindFriend(personInfo, new OnClickListener() {
@Override
public void onClick(View v) {
ContactsContract.QuickContact.showQuickContact(
getActivity(), v, personInfo.lookupUri, MODE_LARGE, new String[0]
);
}
});
TextView findMsg = (TextView) view.findViewById(R.id.find_msg);
findMsg.setText(getString(R.string.find_person, personInfo.displayName));
View removeFriend = view.findViewById(R.id.remove_friend);
removeFriend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String message = getString(R.string.confirm_remove, personInfo.displayName);
AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
.setMessage(message)
.setPositiveButton(R.string.remove, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
friendsManager.removeFriend(personInfo.lookupUri);
getFragmentManager().popBackStack();
}
})
.setNegativeButton(R.string.cancel, null)
.create();
alertDialog.show();
}
});
spinner = (Spinner) view.findViewById(R.id.duration);
CharSequence[] durationTexts = getResources().getTextArray(R.array.durations_text);
durationValues = getResources().getIntArray(R.array.durations_seconds);
checkState(durationTexts.length == durationValues.length);
final DurationsAdapter durationsAdapter = new DurationsAdapter(getActivity(), durationTexts);
spinner.setAdapter(durationsAdapter);
// Remember user selection in preferences.
spinner.setSelection(2);
View locate = view.findViewById(R.id.fab_locate);
locate.setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
MainActivity activity = (MainActivity) getActivity();
if (!personInfo.emails.isEmpty()) {
Duration duration = getSelectedDuration();
activity.requestLocationUpdates(personInfo, duration);
} else {
// TODO disable FAB at all and show red warning instead
String msg = getString(R.string.contact_no_emails, personInfo.displayName);
Toast.makeText(activity, msg, Toast.LENGTH_LONG)
.show();
}
}
});
return view;
}
public Duration getSelectedDuration() {
int position = spinner.getSelectedItemPosition();
int selectedValue = durationValues[position];
return Duration.standardSeconds(selectedValue);
}
private static class DurationsAdapter extends ArrayAdapter<CharSequence> {
public DurationsAdapter(Context context, CharSequence[] itemLabels) {
//super(context, R.layout.view_dropdown_item, itemLabels);
super(context, android.R.layout.simple_spinner_item, itemLabels);
// Item in opened dropdown.
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
}
}
| gpl-2.0 |
Naamanly/FirstJava | src/test/Test.java | 357 | package test;
import org.hello.ibatis.bean.UserInfo;
import org.hello.ibatis.dao.IUserInfoDao;
import org.hello.ibatis.dao.impl.IUserInfoDaoImpl;
import junit.framework.TestCase;
public class Test extends TestCase{
public void testFindOne(){
IUserInfoDao iud = new IUserInfoDaoImpl();
UserInfo ui = iud.queryById(2);
System.out.println(ui);
}
}
| gpl-2.0 |
christianfriedl/Vality | src/vality/transformer/applier/MultiTransformer.java | 1143 | /*
* apply the same transformer a few times over, each time replacing the exression
*/
package vality.transformer.applier;
import vality.expression.Expressable;
import vality.transformer.BaseTransformer;
import vality.transformer.Transformer;
public class MultiTransformer extends BaseTransformer {
public static int COUNT_APPLICATIONS = 5;
private int countApplications;
private Transformer transformer;
public MultiTransformer(Transformer transformer, Expressable expression) {
super(expression);
this.transformer = transformer;
this.countApplications = COUNT_APPLICATIONS;
}
public void setCountApplications(int countApplications) {
this.countApplications = countApplications;
}
@Override
public boolean canTransform() {
return true;
}
@Override
public Expressable transform() {
for (int i=0; i < COUNT_APPLICATIONS; ++i) {
transformer.setExpression(expression);
if (transformer.canTransform())
expression = transformer.transform();
}
return expression;
}
}
| gpl-2.0 |
FauxFaux/jdk9-langtools | test/tools/javap/T7004698.java | 3785 | /*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 7004698
* @summary javap does not output CharacterRangeTable attributes correctly
* @modules jdk.jdeps/com.sun.tools.javap
*/
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class T7004698 {
public static void main(String... args) throws Exception {
new T7004698().run();
}
void run() throws Exception {
File srcDir = new File(System.getProperty("test.src"));
File srcFile = new File(srcDir, T7004698.class.getSimpleName() + ".java");
File classesDir = new File(".");
compile("-Xjcov",
"--add-exports", "jdk.jdeps/com.sun.tools.javap=ALL-UNNAMED",
"-d", classesDir.getPath(),
srcFile.getPath());
File classFile = new File(classesDir, T7004698.class.getSimpleName() + ".class");
String out = javap("-v", classFile.getPath());
Pattern attrBody = Pattern.compile("[0-9a-f, ]+//[-0-9a-z:, ]+");
Pattern endOfAttr = Pattern.compile("(^$|[A-Z][A-Za-z0-9_]+:.*|})");
boolean inAttr = false;
int count = 0;
int errors = 0;
for (String line: out.split(System.getProperty("line.separator"))) {
line = line.trim();
if (line.equals("CharacterRangeTable:")) {
inAttr = true;
count++;
} else if (inAttr) {
if (endOfAttr.matcher(line).matches()) {
inAttr = false;
} else if (!attrBody.matcher(line).matches()) {
System.err.println("unexpected line found: " + line);
errors++;
}
}
}
if (count == 0)
throw new Exception("no attribute instances found");
if (errors > 0)
throw new Exception(errors + " errors found");
}
void compile(String... args) throws Exception {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
int rc = com.sun.tools.javac.Main.compile(args, pw);
pw.close();
String out = sw.toString();
if (!out.isEmpty())
System.err.println(out);
if (rc != 0)
throw new Exception("javac failed unexpectedly; rc=" + rc);
}
String javap(String... args) throws Exception {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
int rc = com.sun.tools.javap.Main.run(args, pw);
pw.close();
String out = sw.toString();
if (!out.isEmpty())
System.err.println(out);
if (rc != 0)
throw new Exception("javap failed unexpectedly; rc=" + rc);
return out;
}
}
| gpl-2.0 |
vanjo9800/SensortagSAPCloud | src/main/java/com/example/ti/ble/sensortag/SensorTagTestProfile.java | 4169 | /**************************************************************************************************
Filename: SensorTagTestProfile.java
Copyright (c) 2013 - 2015 Texas Instruments Incorporated
All rights reserved not granted herein.
Limited License.
Texas Instruments Incorporated grants a world-wide, royalty-free,
non-exclusive license under copyrights and patents it now or hereafter
owns or controls to make, have made, use, import, offer to sell and sell ("Utilize")
this software subject to the terms herein. With respect to the foregoing patent
license, such license is granted solely to the extent that any such patent is necessary
to Utilize the software alone. The patent license shall not apply to any combinations which
include this software, other than combinations with devices manufactured by or for TI ('TI Devices').
No hardware patent is licensed hereunder.
Redistributions must preserve existing copyright notices and reproduce this license (including the
above copyright notice and the disclaimer and (if applicable) source code license limitations below)
in the documentation and/or other materials provided with the distribution
Redistribution and use in binary form, without modification, are permitted provided that the following
conditions are met:
* No reverse engineering, decompilation, or disassembly of this software is permitted with respect to any
software provided in binary form.
* any redistribution and use are licensed by TI for use only with TI Devices.
* Nothing shall obligate TI to provide you with source code for the software licensed and provided to you in object code.
If software source code is provided to you, modification and redistribution of the source code are permitted
provided that the following conditions are met:
* any redistribution and use of the source code, including any resulting derivative works, are licensed by
TI for use only with TI Devices.
* any redistribution and use of any object code compiled from the source code and any resulting derivative
works, are licensed by TI for use only with TI Devices.
Neither the name of Texas Instruments Incorporated nor the names of its suppliers may be used to endorse or
promote products derived from this software without specific prior written permission.
DISCLAIMER.
THIS SOFTWARE IS PROVIDED BY TI AND TI'S LICENSORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL TI AND TI'S LICENSORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**************************************************************************************************/
package com.example.ti.ble.sensortag;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import com.example.ti.ble.common.BluetoothLeService;
import com.example.ti.ble.common.GenericBluetoothProfile;
public class SensorTagTestProfile extends GenericBluetoothProfile {
public SensorTagTestProfile(Context con,BluetoothDevice device,BluetoothGattService service,BluetoothLeService controller) {
super(con, device, service, controller);
}
public static boolean isCorrectService(BluetoothGattService service) {
if ((service.getUuid().toString().compareTo(SensorTagGatt.UUID_TST_SERV.toString())) == 0) {
return true;
}
else return false;
}
@Override
public void configureService() {
}
@Override
public void deConfigureService() {
}
@Override
public void enableService() {
}
@Override
public void disableService() {
}
}
| gpl-2.0 |
odit/rv042 | linux/embedded_rootfs/pkg_addon/EasyAccess/src/WWW/Java/TelSsh/de/mud/jta/event/TelnetCommandListener.java | 1152 | /*
* This file is part of "The Java Telnet Application".
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* "The Java Telnet Application" is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING. If not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package de.mud.jta.event;
import de.mud.jta.PluginListener;
import java.io.IOException;
public interface TelnetCommandListener extends PluginListener {
/** Called by code in the terminal interface or somewhere for sending
* telnet commands
*/
public void sendTelnetCommand(byte command) throws IOException;
}
| gpl-2.0 |
luthx/tung-commons | tung-commons-utils/src/main/java/com/tung/commons/lang/DateUtils.java | 4609 | package com.tung.commons.lang;
import java.util.Calendar;
import java.util.Date;
/**
* Utility class for date manipulation.
*
* @author Lu Tung Huang
*/
public class DateUtils extends org.apache.commons.lang.time.DateUtils {
private static final int[] DATE_FIELDS = new int[]{Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_YEAR};
/**
* Constructor
*/
private DateUtils() {
// private constructor to prevent utility class instantiation.
}
/**
* Get the calendar instance of a given date
* @param date
* The date
* @return The calendar instance
*/
public static Calendar getCalendarInstance(final Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
/**
* Compare two dates considering "day" as the most significant field.
*
* @param date1
* First date
* @param date2
* Second date
* @return If the first date is before the second date, a negative number
* will be returned. If the first date is same day of the second
* date, zero will be returned. If the first date is after the
* second date, a positive number will be returned
*/
public static int compareDays(final Date date1, final Date date2) {
Calendar calendar1 = getCalendarInstance(date1);
Calendar calendar2 = getCalendarInstance(date2);
for (int field : DATE_FIELDS) {
int fieldValue1 = calendar1.get(field);
int fieldValue2 = calendar2.get(field);
if (fieldValue1 != fieldValue2) {
return fieldValue1 - fieldValue2;
}
}
return 0;
}
/**
* Get the first time of a given date.
*
* @param date
* The date
* @return The first time of a given date
*/
public static Date getFirstTimeOfDay(final Date date) {
return truncate(date, Calendar.DAY_OF_MONTH);
}
/**
* Get the last time of a given date.
*
* @param date
* The date
* @return The last time of a given date
*/
public static Date getLastTimeOfDay(final Date date) {
Date _date = getFirstTimeOfDay(date);
Calendar cal = getCalendarInstance(_date);
cal.add(Calendar.DAY_OF_YEAR, 1);
cal.add(Calendar.MILLISECOND, -1);
return cal.getTime();
}
/**
* Get the first time of a given month.
*
* @param date
* The date
* @return The first time of a given month
*/
public static Date getFirstTimeOfMonth(final Date date) {
return truncate(date, Calendar.MONTH);
}
/**
* Get the last time of a given month.
*
* @param date
* The date
* @return The last time of a given month
*/
public static Date getLastTimeOfMonth(final Date date) {
Calendar cal = getCalendarInstance(date);
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, maxDay);
return getLastTimeOfDay(cal.getTime());
}
/**
* Get the difference in days of two given dates.
*
* @param data1
* The first date
* @param data2
* The second date
* @return The difference in days of two given dates
*/
public static int daysDiff(final Date data1, final Date data2) {
long ini = getCalendarInstance(data1).getTimeInMillis();
long fim = getCalendarInstance(data2).getTimeInMillis();
long nroHoras = (fim - ini) / 1000 / 3600;
int nroDias = (int) nroHoras / 24;
return nroDias;
}
/**
* Get the difference in months of two given dates.
*
* @param data1
* The first date
* @param data2
* The second date
* @return The difference in months of two given dates
*/
public static int monthsDiff(final Date data1, final Date data2) {
Calendar cal = Calendar.getInstance();
cal.setTime(data1);
int monthA = cal.get(Calendar.MONTH);
int yearA = cal.get(Calendar.YEAR);
cal.setTime(data2);
int monthB = cal.get(Calendar.MONTH);
int yearB = cal.get(Calendar.YEAR);
return ((yearA - yearB) * cal.getMaximum(Calendar.MONTH)) + (monthA - monthB);
}
} | gpl-2.0 |
nologic/nabs | client/trunk/shared/libraries/je-3.2.74/src/com/sleepycat/persist/ValueAdapter.java | 2125 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002,2008 Oracle. All rights reserved.
*
* $Id: ValueAdapter.java,v 1.5.2.2 2008/01/07 15:14:18 cwl Exp $
*/
package com.sleepycat.persist;
import com.sleepycat.je.DatabaseEntry;
/**
* An adapter that translates between database entries (key, primary key, data)
* and a "value", which may be either the key, primary key, or entity. This
* interface is used to implement a generic index and cursor (BasicIndex and
* BasicCursor). If we didn't use this approach, we would need separate index
* and cursor implementations for each type of value that can be returned. In
* other words, this interface is used to reduce class explosion.
*
* @author Mark Hayes
*/
interface ValueAdapter<V> {
/**
* Creates a DatabaseEntry for the key or returns null if the key is not
* needed.
*/
DatabaseEntry initKey();
/**
* Creates a DatabaseEntry for the primary key or returns null if the
* primary key is not needed.
*/
DatabaseEntry initPKey();
/**
* Creates a DatabaseEntry for the data or returns null if the data is not
* needed. BasicIndex.NO_RETURN_ENTRY may be returned if the data argument
* is required but we don't need it.
*/
DatabaseEntry initData();
/**
* Sets the data array of the given entries to null, based on knowledge of
* which entries are non-null and are not NO_RETURN_ENTRY.
*/
void clearEntries(DatabaseEntry key,
DatabaseEntry pkey,
DatabaseEntry data);
/**
* Returns the appropriate "value" (key, primary key, or entity) using the
* appropriate bindings for that purpose.
*/
V entryToValue(DatabaseEntry key,
DatabaseEntry pkey,
DatabaseEntry data);
/**
* Converts an entity value to a data entry using an entity binding, or
* throws UnsupportedOperationException if this is not appropriate. Called
* by BasicCursor.update.
*/
void valueToData(V value, DatabaseEntry data);
}
| gpl-2.0 |
YeLuo45/coreJavaVolume1 | ch6/src/main/java/com/yeluo/mvn/ch5/ProxyTest.java | 3810 | package com.yeluo.mvn.ch5;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Random;
/**
*
* @author YeLuo
* @function
*/
/*
* 1.利用代理可以在运行时创建一个实现了一组给定接口的新类。这种功能只有在编译时无法确定需要实现哪个接口时才有必要使用。
* 这对于应用程序设计人员来说,遇到这种情况的机会很少。
* 然而对于系统程序设计人员来说,代理带来的灵活性却十分重要。
*
* 2.代理类可以在运行时创建全新的类。这样的代理类能够实现指定的接口。尤其是,它具有下列方法:
* 1.指定接口的全部方法
* 2.Object类的全部方法
*
* 3.要想创建一个代理对象,需要使用Proxy类的newProxyInstance方法,这个方法有3个参数
* 1.一个类加载器。对于系统类和从因特网上下载下来的类,可以使用不同的类加载器。为null,表示使用默认的类加载器。
* 2.一个Class对象数组,每个元素都是需要实现的接口。
* 3.一个调用处理器。
*
* 4.还有两个需要解决的问题。如何定义一个处理器?能够用结果代理对象做些什么?
* 1.路由对远程服务器的方法调用
* 2.在程序运行期间,将用户接口事件与动作关联起来。
* 3.为调式,跟踪方法调用。
*
* 5.需要记住,代理类是在程序运行中创建的。然而,一旦被创建,就变成了常规类,与虚拟机中的任何其他类没有什么区别。
*
* 6.所有的代理类都扩展于Proxy类。一个代理类只有一个实例域——调用处理器,它定义在超类Proxy中。
* 为了履行代理对象的职责,所需要的任何附加数据都必须存储在调用处理器中。
*
* 7.对于特定的类加载器和预设的一组接口来说,只能有一个代理类。也就是说,
* 如果使用同一个类加载器和接口数组调用两次newProxyInstance方法的话,那么只能够得到同一个类的两个对象。
* 可以使用getProxyClass方法来获得这个类:
* Class proxyClass=Proxy.getProxyClass(null,interfaces);
*
* 8.代理类一定是public和final。如果代理类实现的接口都是public,则代理类就不属于特定的包。
* 否则,所有的非公有的接口都必须属于同一个包,同时,代理类属于这个包。
*/
public class ProxyTest {
/*
* 该示例的作用:使用代理和调用处理器跟踪方法调用,并且定义了一个TraceHandler包装器类存储包装的对象。
*/
public static void main(String[] args) {
Object[] elements=new Object[1000];
Class[] interfaces=null;
//fill elements with proxies for the integers 1...1000
for(int i=0;i<elements.length;i++){
Integer value=i+1;
//创建调用处理器对象
InvocationHandler handler=new TraceHandler(value);
interfaces=new Class[]{Comparable.class};
//创建代理对象
Object proxy=Proxy.newProxyInstance(null, interfaces, handler);
elements[i]=proxy;
}
//construct a random integer
Integer key=new Random().nextInt(elements.length)+1;
//search for the key
int result=Arrays.binarySearch(elements, key);
//print match if found
if(result>=0){
/*
* 无论何时调用代理对象的方法,调用处理器的invoke方法都会被调用,并向其传递Method对象和原始的调用参数。
* 该处调用了代理对象的toString方法,这个调用也会被重定向到滴啊用处理器上。
*/
System.out.println(elements[result]);
}
//Proxy类的getProxyClass方法
Class proxyClass=Proxy.getProxyClass(null, interfaces);
System.out.println(proxyClass); //class com.sun.proxy.$Proxy0
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | frameworks/base/core/java/com/android/internal/os/BinderInternal.java | 3553 | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.os;
import android.os.Binder;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.EventLog;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.lang.reflect.Modifier;
import com.mediatek.common.featureoption.FeatureOption; /// M: ALPS00497111 [Volunteer free] LCA Memory Optimized
/**
* Private and debugging Binder APIs.
*
* @see IBinder
*/
public class BinderInternal {
static WeakReference<GcWatcher> mGcWatcher
= new WeakReference<GcWatcher>(new GcWatcher());
static long mLastGcTime;
static final class GcWatcher {
@Override
protected void finalize() throws Throwable {
handleGc();
mLastGcTime = SystemClock.uptimeMillis();
mGcWatcher = new WeakReference<GcWatcher>(new GcWatcher());
}
}
/**
* Add the calling thread to the IPC thread pool. This function does
* not return until the current process is exiting.
*/
public static final native void joinThreadPool();
/**
* Return the system time (as reported by {@link SystemClock#uptimeMillis
* SystemClock.uptimeMillis()}) that the last garbage collection occurred
* in this process. This is not for general application use, and the
* meaning of "when a garbage collection occurred" will change as the
* garbage collector evolves.
*
* @return Returns the time as per {@link SystemClock#uptimeMillis
* SystemClock.uptimeMillis()} of the last garbage collection.
*/
public static long getLastGcTime() {
return mLastGcTime;
}
/**
* Return the global "context object" of the system. This is usually
* an implementation of IServiceManager, which you can use to find
* other services.
*/
public static final native IBinder getContextObject();
/**
* Special for system process to not allow incoming calls to run at
* background scheduling priority.
* @hide
*/
public static final native void disableBackgroundScheduling(boolean disable);
static native final void handleGc();
public static void forceGc(String reason) {
EventLog.writeEvent(2741, reason);
/// M: ALPS00497111 [Volunteer free] LCA Memory Optimized @{
if(FeatureOption.MTK_LCA_RAM_OPTIMIZE)
{
if(reason.equals("lowmem")||reason.equals("trimmem"))
{
Runtime.getRuntime().gc2();
}
else
{
Runtime.getRuntime().gc();
}
}
else
{
Runtime.getRuntime().gc();
}
/// @}
}
static void forceBinderGc() {
forceGc("Binder");
}
}
| gpl-2.0 |
erpragatisingh/androidTraining | Android_6_weekTraning/Activitylife/src/com/example/activitylife/MainActivity.java | 538 | package com.example.activitylife;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Intent i;
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| gpl-2.0 |
Telewa/shoppingcart | MyShopingCart_3/src/java/controler/Addstock.java | 2756 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controler;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author wndessy
*/
public class Addstock extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
DbModules db = new DbModules();
try {
String Item = request.getParameter("name");
int Quantity = Integer.parseInt(request.getParameter("quantity"));
out.print(db.AddStock(Item, Quantity));
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| gpl-2.0 |
favedit/MoPlatform | mo-4-web/src/web-system/org/mo/jfa/common/xmlobjects/FAbsXmlObjectPage.java | 4266 | package org.mo.jfa.common.xmlobjects;
import org.mo.com.lang.IAttributes;
import org.mo.com.xml.IXmlObject;
import org.mo.jfa.common.page.FAbstractFormPage;
import org.mo.web.protocol.context.IWebContext;
//============================================================
// <T>配置对象表单页面基类。</T>
//============================================================
public abstract class FAbsXmlObjectPage<V>
extends FAbstractFormPage
{
private static final long serialVersionUID = 1L;
public final static String PTY_NODE_FILTER = "node_filter";
public final static String PTY_NODE_SORT = "node_sort";
public final static String PTY_NODE_TYPE = "node_type";
public final static String PTY_SEL_COLLECTION = "sel_collection";
public final static String PTY_SEL_COMPONENT = "sel_component";
public final static String PTY_SEL_TYPE = "sel_type";
private String _componentType;
private String _help;
private String _nodeFilter;
private String _nodeSort;
private String _nodeType;
private String _pageAction;
private String _selectCollection;
private String _selectComponent;
private String _selectType;
private V _xcollection;
private IXmlObject _xcomponent;
@Override
public void appachContext(IWebContext context){
super.appachContext(context);
// 获得选中的数据
IAttributes parameters = context.parameters();
_pageAction = parameters.get("do", null);
_nodeType = parameters.get(PTY_NODE_TYPE, null);
_nodeFilter = parameters.get(PTY_NODE_FILTER, null);
_nodeSort = parameters.get(PTY_NODE_SORT, null);
_selectType = parameters.get(PTY_SEL_TYPE, null);
_selectCollection = parameters.get(PTY_SEL_COLLECTION, null);
_selectComponent = parameters.get(PTY_SEL_COMPONENT, null);
_componentType = parameters.get("component_type", null);
// 设置环境对象
if(parameters.contains(PTY_NODE_TYPE)){
setEnv(PTY_NODE_TYPE, _nodeType);
}
if(parameters.contains(PTY_NODE_FILTER)){
setEnv(PTY_NODE_FILTER, _nodeFilter);
}
if(parameters.contains(PTY_NODE_SORT)){
setEnv(PTY_NODE_SORT, _nodeSort);
}
if(parameters.contains(PTY_SEL_TYPE)){
setEnv("sel_type", _selectType);
}
if(parameters.contains(PTY_SEL_COLLECTION)){
setEnv(PTY_SEL_COLLECTION, _selectCollection);
}
if(parameters.contains(PTY_SEL_COMPONENT)){
setEnv(PTY_SEL_COMPONENT, _selectComponent);
}
}
public V getCollection(){
return _xcollection;
}
public IXmlObject getComponent(){
return _xcomponent;
}
public String getComponentType(){
return _componentType;
}
public String getHelp(){
return _help;
}
public String getNodeFilter(){
return _nodeFilter;
}
public String getNodeSort(){
return _nodeSort;
}
public String getNodeType(){
return _nodeType;
}
public String getPageAction(){
return _pageAction;
}
public String getSelectCollection(){
return _selectCollection;
}
public String getSelectComponent(){
return _selectComponent;
}
public String getSelectType(){
return _selectType;
}
public void setCollection(V xcollection){
_xcollection = xcollection;
}
public void setComponent(IXmlObject xcomponent){
_xcomponent = xcomponent;
}
public void setComponentType(String componentType){
_componentType = componentType;
}
public void setHelp(String help){
_help = help;
}
public void setNodeFilter(String nodeFilter){
_nodeFilter = nodeFilter;
}
public void setNodeSort(String nodeSort){
_nodeSort = nodeSort;
}
public void setNodeType(String _nodeType){
this._nodeType = _nodeType;
}
public void setPageAction(String pageAction){
_pageAction = pageAction;
}
public void setSelectCollection(String selectCollection){
_selectCollection = selectCollection;
}
public void setSelectComponent(String selectComponent){
_selectComponent = selectComponent;
}
public void setSelectType(String selectType){
_selectType = selectType;
}
}
| gpl-2.0 |
tomas-pluskal/mzmine3 | src/main/java/io/github/mzmine/parameters/parametertypes/submodules/OptionalModuleParameter.java | 4459 | /*
* Copyright 2006-2020 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* MZmine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with MZmine; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.github.mzmine.parameters.parametertypes.submodules;
import org.w3c.dom.Element;
import io.github.mzmine.parameters.Parameter;
import io.github.mzmine.parameters.ParameterContainer;
import io.github.mzmine.parameters.ParameterSet;
import io.github.mzmine.parameters.UserParameter;
import java.util.Collection;
/**
* Parameter represented by check box with additional sub-module
*/
public class OptionalModuleParameter<T extends ParameterSet>
implements UserParameter<Boolean, OptionalModuleComponent>, ParameterContainer {
private String name, description;
private T embeddedParameters;
private Boolean value;
public OptionalModuleParameter(String name, String description, T embeddedParameters,
boolean defaultVal) {
this(name, description, embeddedParameters);
value = defaultVal;
}
public OptionalModuleParameter(String name, String description, T embeddedParameters) {
this.name = name;
this.description = description;
this.embeddedParameters = embeddedParameters;
}
public T getEmbeddedParameters() {
return embeddedParameters;
}
/**
* @see io.github.mzmine.data.Parameter#getName()
*/
@Override
public String getName() {
return name;
}
/**
* @see io.github.mzmine.data.Parameter#getDescription()
*/
@Override
public String getDescription() {
return description;
}
@Override
public OptionalModuleComponent createEditingComponent() {
return new OptionalModuleComponent(embeddedParameters);
}
@Override
public Boolean getValue() {
// If the option is selected, first check that the module has all
// parameters set
if ((value != null) && (value)) {
for (Parameter<?> p : embeddedParameters.getParameters()) {
if (p instanceof UserParameter) {
UserParameter<?, ?> up = (UserParameter<?, ?>) p;
Object upValue = up.getValue();
if (upValue == null)
return null;
}
}
}
return value;
}
@Override
public void setValue(Boolean value) {
this.value = value;
}
@Override
public OptionalModuleParameter<T> cloneParameter() {
final T embeddedParametersClone = (T) embeddedParameters.cloneParameterSet();
final OptionalModuleParameter<T> copy =
new OptionalModuleParameter<>(name, description, embeddedParametersClone);
copy.setValue(this.getValue());
return copy;
}
@Override
public void setValueFromComponent(OptionalModuleComponent component) {
this.value = component.isSelected();
}
@Override
public void setValueToComponent(OptionalModuleComponent component, Boolean newValue) {
component.setSelected(newValue);
}
@Override
public void loadValueFromXML(Element xmlElement) {
embeddedParameters.loadValuesFromXML(xmlElement);
String selectedAttr = xmlElement.getAttribute("selected");
this.value = Boolean.valueOf(selectedAttr);
}
@Override
public void saveValueToXML(Element xmlElement) {
if (value != null)
xmlElement.setAttribute("selected", value.toString());
embeddedParameters.saveValuesToXML(xmlElement);
}
@Override
public boolean checkValue(Collection<String> errorMessages) {
if (value == null) {
errorMessages.add(name + " is not set properly");
return false;
}
if (value == true) {
return embeddedParameters.checkParameterValues(errorMessages);
}
return true;
}
@Override
public void setSkipSensitiveParameters(boolean skipSensitiveParameters) {
// delegate skipSensitiveParameters to embedded ParameterSet
embeddedParameters.setSkipSensitiveParameters(skipSensitiveParameters);
}
}
| gpl-2.0 |
Slaan/vsp | MonopolyClient/src/main/java/services/Exception/ClientException.java | 213 | package services.Exception;
import java.io.IOException;
/**
* Created by slaan on 25.11.15.
*/
public class ClientException extends RuntimeException {
public ClientException(String s) {
super(s);
}
}
| gpl-2.0 |
CvO-Theory/apt | src/module/uniol/apt/analysis/ac/AsymmetricChoiceModule.java | 3043 | /*-
* APT - Analysis of Petri Nets and labeled Transition systems
* Copyright (C) 2015 vsp
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package uniol.apt.analysis.ac;
import uniol.apt.adt.pn.PetriNet;
import uniol.apt.adt.pn.Place;
import uniol.apt.module.AbstractModule;
import uniol.apt.module.AptModule;
import uniol.apt.module.Category;
import uniol.apt.module.InterruptibleModule;
import uniol.apt.module.ModuleInput;
import uniol.apt.module.ModuleInputSpec;
import uniol.apt.module.ModuleOutput;
import uniol.apt.module.ModuleOutputSpec;
import uniol.apt.module.exception.ModuleException;
import uniol.apt.util.Pair;
/**
* Checks whether a given plain Petri net is an asymmetric choice net.
* @author vsp
*/
@AptModule
public class AsymmetricChoiceModule extends AbstractModule implements InterruptibleModule {
@Override
public String getName() {
return "ac";
}
@Override
public void require(ModuleInputSpec inputSpec) {
inputSpec.addParameter("net", PetriNet.class, "The Petri net that should be examined");
}
@Override
public void provide(ModuleOutputSpec outputSpec) {
outputSpec.addReturnValue("ac", Boolean.class, ModuleOutputSpec.PROPERTY_SUCCESS);
outputSpec.addReturnValue("witness1", Place.class);
outputSpec.addReturnValue("witness2", Place.class);
}
@Override
public void run(ModuleInput input, ModuleOutput output) throws ModuleException {
PetriNet pn = input.getParameter("net", PetriNet.class);
AsymmetricChoice ac = new AsymmetricChoice();
Pair<Place, Place> counterexample = ac.check(pn);
output.setReturnValue("ac", Boolean.class, counterexample == null);
if (counterexample != null) {
output.setReturnValue("witness1", Place.class, counterexample.getFirst());
output.setReturnValue("witness2", Place.class, counterexample.getSecond());
}
}
@Override
public String getTitle() {
return "Asymmetric Choice";
}
@Override
public String getShortDescription() {
return "Check if a Petri net is asymmetric-choice";
}
@Override
public String getLongDescription() {
return getShortDescription() + ".\n\nA Petri net is an asymmetric choice net if " +
"∀p₁,p₂∈P: p₁°∩p₂°≠∅ ⇒ p₁°⊆p₂° ∨ p₁°⊇p₂°";
}
@Override
public Category[] getCategories() {
return new Category[]{Category.PN};
}
}
// vim: ft=java:noet:sw=8:sts=8:ts=8:tw=120
| gpl-2.0 |
meijmOrg/Repo-test | freelance-hr-component/src/java/com/yh/hr/component/worktop/facade/WbWorkBenchFacade.java | 1107 | package com.yh.hr.component.worktop.facade;
import com.yh.hr.component.worktop.dto.WbWorkBenchForwardDTO;
import com.yh.hr.component.worktop.service.WbWorkBenchService;
import com.yh.platform.core.exception.ServiceException;
/**
* 事项树跳转工作台 facade
* @author huw
* @time 2016-09-29
*/
public class WbWorkBenchFacade
{
private WbWorkBenchService wbWorkBenchService;
public void setWbWorkBenchService(WbWorkBenchService wbWorkBenchService) {
this.wbWorkBenchService = wbWorkBenchService;
}
/**
* 获取itemNodeCode 业务事项环节码
* @param menuCode 事项树节点
* @return
* @throws ServiceException
*/
public String getItemNodeCode(String menuCode) throws ServiceException
{
return wbWorkBenchService.getItemNodeCode(menuCode);
}
/**
* 根据事项节点码查询工作台
* @param itemNodeCode
* @return WbWorkBenchForwardDTO
* @throws DataAccessException
*/
public WbWorkBenchForwardDTO findBizWorkTopDTOByNodeCode(String itemNodeCode) throws ServiceException
{
return wbWorkBenchService.findBizWorkTopDTOByNodeCode(itemNodeCode);
}
}
| gpl-2.0 |
callakrsos/Gargoyle | VisualFxVoEditor/src/main/java/com/kyj/fx/voeditor/visual/exceptions/ProgramSpecIoException.java | 946 | /**
* package : com.kyj.fx.voeditor.visual.exceptions
* fileName : ProgramSpecIoException.java
* date : 2016. 02. 15.
* user : KYJ
*/
package com.kyj.fx.voeditor.visual.exceptions;
/**
* @author KYJ
*
*/
public class ProgramSpecIoException extends GargoyleException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public ProgramSpecIoException() {
// TODO Auto-generated constructor stub
}
/**
* @param arg0
*/
public ProgramSpecIoException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
/**
* @param arg0
*/
public ProgramSpecIoException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
/**
* @param arg0
* @param arg1
*/
public ProgramSpecIoException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
}
| gpl-2.0 |
giulianobg/quantocusta | quantocusta-service/src/main/java/sb/quantocusta/QuantoCustaService.java | 3653 | package sb.quantocusta;
import java.net.UnknownHostException;
import org.eclipse.jetty.server.session.SessionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sb.quantocusta.api.User;
import sb.quantocusta.auth.QcAuthProvider;
import sb.quantocusta.auth.QcAuthenticator;
import sb.quantocusta.dao.CategoryDao;
import sb.quantocusta.dao.CityDao;
import sb.quantocusta.dao.CommentDao;
import sb.quantocusta.dao.Daos;
import sb.quantocusta.dao.ReviewDao;
import sb.quantocusta.dao.SessionDao;
import sb.quantocusta.dao.UserDao;
import sb.quantocusta.dao.VenueDao;
import sb.quantocusta.dao.VoteDao;
import sb.quantocusta.health.MongoHealthCheck;
import sb.quantocusta.resources.CommentResource;
import sb.quantocusta.resources.OAuthResource;
import sb.quantocusta.resources.SessionResource;
import sb.quantocusta.resources.UserResource;
import sb.quantocusta.resources.VenueResource;
import sb.quantocusta.resources.VoteResource;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.yammer.dropwizard.Service;
import com.yammer.dropwizard.assets.AssetsBundle;
import com.yammer.dropwizard.config.Bootstrap;
import com.yammer.dropwizard.config.Environment;
import com.yammer.dropwizard.views.ViewBundle;
/**
*
* @author giuliano.griffante
*
*/
public class QuantoCustaService extends Service<QuantoCustaConfiguration> {
static final Logger LOG = LoggerFactory.getLogger(QuantoCustaService.class);
private QuantoCustaConfiguration configuration;
public QuantoCustaService() {
}
public void initialize(Bootstrap<QuantoCustaConfiguration> bootstrap) {
bootstrap.setName("quantocusta-api-app");
bootstrap.addBundle(new ViewBundle());
bootstrap.addBundle(new AssetsBundle());
}
public void run(QuantoCustaConfiguration configuration, Environment environment) {
this.configuration = configuration;
environment.setSessionHandler(new SessionHandler());
/* MongoDB */
DB db = null;
try {
MongoClient client = new MongoClient(configuration.getMongo().getHost(), configuration.getMongo().getPort());
db = client.getDB(configuration.getMongo().getDb());
//boolean auth = db.authenticate(configuration.getMongo().getUser(), configuration.getMongo().getPwd().toCharArray());
MongoManaged mongoManaged = new MongoManaged(client);
environment.manage(mongoManaged);
} catch (UnknownHostException e) {
e.printStackTrace();
LOG.error("Cannot connect with the DB :(", e);
System.exit(1);
}
/* DAOs */
Daos.addDao(new CategoryDao(db));
Daos.addDao(new CityDao(db));
Daos.addDao(new CommentDao(db));
Daos.addDao(new ReviewDao(db));
Daos.addDao(new SessionDao(db));
Daos.addDao(new UserDao(db));
Daos.addDao(new VenueDao(db));
Daos.addDao(new VoteDao(db));
/* OAuth2 */
environment.addProvider(new QcAuthProvider<User>(new QcAuthenticator(), "QuantoCusta-OAuth"));
/* Resources */
environment.addResource(new OAuthResource());
environment.addResource(new CommentResource());
environment.addResource(new SessionResource());
environment.addResource(new UserResource());
environment.addResource(new VenueResource());
environment.addResource(new VoteResource());
/* Health checkers */
environment.addHealthCheck(new MongoHealthCheck(null));
/* Cache */
// Cache<String, String> c1 = CacheBuilder.newBuilder().build();
// c1.getIfPresent(key)
// Cache<String, String> c = new CacheBuilder<String, String>().build()
}
public QuantoCustaConfiguration getConfiguration() {
return configuration;
}
public static void main(String[] args) throws Exception {
new QuantoCustaService().run(args);
}
}
| gpl-2.0 |
chenxiuheng/contacta | contacta-webapp/src/main/java/mic/contacta/util/AgentUtil.java | 3936 | /**
* Contacta webapp, http://www.openinnovation.it - Michele Bianchi
* Copyright(C) 1999-2012 info@openinnovation.it
*
* This program is free software; you can redistribute it and/or modify it under the terms
* of the GNU General Public License v2 as published by the Free Software Foundation
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details. http://gnu.org/licenses/gpl-2.0.txt
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
package mic.contacta.util;
import java.io.*;
/**
* This class implements...
*
* @author michele.bianchi@gmail.com
* @version $Revision: 621 $
*/
public class AgentUtil
{
/*
*
*/
public static String percent(long l, long totalTime)
{
double d = (l/(double)totalTime);
return String.valueOf(((int)(d*1000)));
}
/*
*
*/
public static long parseLong(String value)
{
long i = -1;
try
{
i = Long.parseLong(value);
}
catch(NumberFormatException e)
{
}
return i;
}
/*
*
*/
public static int parseInt(String value)
{
int i = -1;
try
{
i = Integer.parseInt(value);
}
catch(NumberFormatException e)
{
}
return i;
}
/*
*
*/
public static float parseFloat(String value)
{
float i = -1;
try
{
i = Float.parseFloat(value);
}
catch(NumberFormatException e)
{
}
return i;
}
/*
*
*/
public static void printItemLong(PrintWriter writer) throws IOException
{
}
/*
*
*/
public static void printItemShort(PrintWriter writer) throws IOException
{
}
/*
*
*
private String sendCommand(String command) throws IOException, TimeoutException
{
CommandAction commandAction = new CommandAction();
commandAction.setCommand(command);
CommandResponse commandResponse = (CommandResponse)(managerConnection.sendAction(commandAction, 1000));
StringBuffer sb = new StringBuffer();
sb.append("actionId: "+commandResponse.getActionId());
sb.append("\nuniqueId: "+commandResponse.getUniqueId());
sb.append("\nmessage: "+commandResponse.getMessage());
sb.append("\nresponse: "+commandResponse.getResponse());
Map attrs = commandResponse.getAttributes();
for (Object o : attrs.keySet())
{
sb.append("\nattribute: "+o.toString()+"="+attrs.get(o).toString());
}
for (Object o : commandResponse.getResult())
{
sb.append("\nresult: "+o.toString());
}
sb.append("\n\n");
return sb.toString();
}*/
/*
*
*
public String sendEventGenerating(EventGeneratingAction action) throws IOException, TimeoutException
{
ResponseEvents responseEvents = managerConnection.sendEventGeneratingAction(action);
StringBuffer sb = new StringBuffer();
sb.append(responseEvents.getResponse().toString());
for (Object o : responseEvents.getEvents())
{
sb.append("\nevent: ["+o.getClass().getName()+"] "+o.toString());
}
sb.append("\n\n");
return sb.toString();
}*/
/*
*
*
public void measureAsterisk(StatisticsBean statistics) throws IOException
{
String commandResult = "cannot access to asterisk";
if (managerConnection == null)
{
return commandResult;
}
try
{
commandResult = this.sendCommand("show channels");
commandResult += this.sendEventGenerating(new SipPeersAction());
commandResult += this.sendEventGenerating(new ZapShowChannelsAction());
}
catch(TimeoutException e)
{
log().warn(e.getMessage());
}
return commandResult;
}*/
}
| gpl-2.0 |
BuddhaLabs/DeD-OSX | soot/polyglot-1.3.5/src/polyglot/visit/ReachChecker.java | 8194 | package polyglot.visit;
import java.util.*;
import polyglot.ast.*;
import polyglot.frontend.Job;
import polyglot.main.Report;
import polyglot.types.SemanticException;
import polyglot.types.TypeSystem;
import polyglot.util.InternalCompilerError;
/**
* Visitor which checks that all statements must be reachable
*/
public class ReachChecker extends DataFlow
{
public ReachChecker(Job job, TypeSystem ts, NodeFactory nf) {
super(job, ts, nf,
true /* forward analysis */,
true /* perform dataflow on entry to CodeDecls */);
}
protected static class DataFlowItem extends Item {
final boolean reachable;
final boolean normalReachable;
protected DataFlowItem(boolean reachable, boolean normalReachable) {
this.reachable = reachable;
this.normalReachable = normalReachable;
}
// terms that are reachable through normal control flow
public static final DataFlowItem REACHABLE = new DataFlowItem(true, true);
// terms that are reachable only through exception control flow, but
// not by normal control flow.
public static final DataFlowItem REACHABLE_EX_ONLY = new DataFlowItem(true, false);
// terms that are not reachable
public static final DataFlowItem NOT_REACHABLE = new DataFlowItem(false, false);
public String toString() {
return (reachable?"":"not ") + "reachable" +
(normalReachable?"":" by exceptions only");
}
public boolean equals(Object o) {
if (o instanceof DataFlowItem) {
return this.reachable == ((DataFlowItem)o).reachable &&
this.normalReachable == ((DataFlowItem)o).normalReachable;
}
return false;
}
public int hashCode() {
return (reachable ? 5423 : 5753) + (normalReachable ? 31 : -2);
}
}
public Item createInitialItem(FlowGraph graph, Term node) {
if (node == graph.entryNode()) {
return DataFlowItem.REACHABLE;
}
else {
return DataFlowItem.NOT_REACHABLE;
}
}
public Map flow(Item in, FlowGraph graph, Term n, Set succEdgeKeys) {
if (in == DataFlowItem.NOT_REACHABLE) {
return itemToMap(in, succEdgeKeys);
}
// in is either REACHABLE or REACHABLE_EX_ONLY.
// return a map where all exception edges are REACHABLE_EX_ONLY,
// and all non-exception edges are REACHABLE.
Map m = itemToMap(DataFlowItem.REACHABLE_EX_ONLY, succEdgeKeys);
if (succEdgeKeys.contains(FlowGraph.EDGE_KEY_OTHER)) {
m.put(FlowGraph.EDGE_KEY_OTHER, DataFlowItem.REACHABLE);
}
if (succEdgeKeys.contains(FlowGraph.EDGE_KEY_TRUE)) {
m.put(FlowGraph.EDGE_KEY_TRUE, DataFlowItem.REACHABLE);
}
if (succEdgeKeys.contains(FlowGraph.EDGE_KEY_FALSE)) {
m.put(FlowGraph.EDGE_KEY_FALSE, DataFlowItem.REACHABLE);
}
return m;
}
public Item confluence(List inItems, Term node, FlowGraph graph) {
throw new InternalCompilerError("Should never be called.");
}
public Item confluence(List inItems, List itemKeys, Term node, FlowGraph graph) {
// if any predecessor is reachable, so is this one, and if any
// predecessor is normal reachable, and the edge key is not an
// exception edge key, then so is this one.
List l = this.filterItemsNonException(inItems, itemKeys);
for (Iterator i = l.iterator(); i.hasNext(); ) {
if (i.next() == DataFlowItem.REACHABLE) {
// this term is reachable via a non-exception edge
return DataFlowItem.REACHABLE;
}
}
// If we fall through to here, then there were
// no non-exception edges that were normally reachable.
// We now need to determine if this node is
// reachable via an exception edge key, or if
// it is not reachable at all.
for (Iterator i = inItems.iterator(); i.hasNext(); ) {
if (((DataFlowItem)i.next()).reachable) {
// this term is reachable, but only through an
// exception edge.
return DataFlowItem.REACHABLE_EX_ONLY;
}
}
return DataFlowItem.NOT_REACHABLE;
}
public Node leaveCall(Node old, Node n, NodeVisitor v) throws SemanticException {
// check for reachability.
if (n instanceof Term) {
n = checkReachability((Term)n);
}
return super.leaveCall(old, n, v);
}
protected Node checkReachability(Term n) throws SemanticException {
FlowGraph g = currentFlowGraph();
if (g != null) {
Collection peers = g.peers(n);
if (peers != null && !peers.isEmpty()) {
boolean isInitializer = (n instanceof Initializer);
for (Iterator iter = peers.iterator(); iter.hasNext(); ) {
FlowGraph.Peer p = (FlowGraph.Peer) iter.next();
// the peer is reachable if at least one of its out items
// is reachable. This would cover all cases, except that some
// peers may have no successors (e.g. peers that throw an
// an exception that is not caught by the method). So we need
// to also check the inItem.
if (p.inItem() != null) {
DataFlowItem dfi = (DataFlowItem)p.inItem();
// there will only be one peer for an initializer,
// as it cannot occur in a finally block.
if (isInitializer && !dfi.normalReachable) {
throw new SemanticException("Initializers must be able to complete normally.",
n.position());
}
if (dfi.reachable) {
return n.reachable(true);
}
}
if (p.outItems != null) {
for (Iterator k = p.outItems.values().iterator(); k.hasNext(); ) {
DataFlowItem item = (DataFlowItem) k.next();
if (item != null && item.reachable) {
// n is reachable.
return n.reachable(true);
}
}
}
}
// if we fall through to here, then no peer for n was reachable.
n = n.reachable(false);
// Compound statements are allowed to be unreachable
// (e.g., "{ // return; }" or "while (true) S"). If a compound
// statement is truly unreachable, one of its sub-statements will
// be also and we will report an error there.
if ((n instanceof Block && ((Block) n).statements().isEmpty()) ||
(n instanceof Stmt && ! (n instanceof CompoundStmt))) {
throw new SemanticException("Unreachable statement.",
n.position());
}
}
}
return n;
}
public void post(FlowGraph graph, Term root) throws SemanticException {
// There is no need to do any checking in this method, as this will
// be handled by leaveCall and checkReachability.
if (Report.should_report(Report.cfg, 2)) {
dumpFlowGraph(graph, root);
}
}
public void check(FlowGraph graph, Term n, Item inItem, Map outItems) throws SemanticException {
throw new InternalCompilerError("ReachChecker.check should " +
"never be called.");
}
}
| gpl-2.0 |
drftpd-ng/drftpd3 | src/plugins/sitebot/src/test/java/org/drftpd/master/sitebot/BlowfishTest.java | 1624 | /*
* This file is part of DrFTPD, Distributed FTP Daemon.
*
* DrFTPD is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* DrFTPD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with DrFTPD; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.drftpd.master.sitebot;
import org.junit.jupiter.api.RepeatedTest;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BlowfishTest {
@RepeatedTest(10000)
public void testCBC() {
BlowfishManager manager = new BlowfishManager("drftpd", "CBC");
String text = "You need to specify a Ident@IP to add " + Math.random();
String encrypt = manager.encrypt(text);
String decrypt = manager.decrypt(encrypt);
assertEquals(decrypt, text);
}
@RepeatedTest(10000)
public void testECB() {
BlowfishManager ecb = new BlowfishManager("drftpd", "ECB");
String text = "You need to specify a Ident@IP to add " + Math.random();
String encrypt = ecb.encrypt(text);
String decrypt = ecb.decrypt(encrypt);
assertEquals(decrypt, text);
}
}
| gpl-2.0 |
ezScrum/ezScrum | test/ntut/csie/ezScrum/web/mapper/SprintBacklogMapperTest.java | 29062 | package ntut.csie.ezScrum.web.mapper;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import ntut.csie.ezScrum.issue.sql.service.core.Configuration;
import ntut.csie.ezScrum.refactoring.manager.ProjectManager;
import ntut.csie.ezScrum.test.CreateData.AddStoryToSprint;
import ntut.csie.ezScrum.test.CreateData.AddTaskToStory;
import ntut.csie.ezScrum.test.CreateData.CreateProject;
import ntut.csie.ezScrum.test.CreateData.CreateSprint;
import ntut.csie.ezScrum.test.CreateData.InitialSQL;
import ntut.csie.ezScrum.web.dataInfo.TaskInfo;
import ntut.csie.ezScrum.web.dataObject.ProjectObject;
import ntut.csie.ezScrum.web.dataObject.StoryObject;
import ntut.csie.ezScrum.web.dataObject.TaskObject;
import ntut.csie.jcis.core.util.DateUtil;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class SprintBacklogMapperTest {
private SprintBacklogMapper mSprintBacklogMapper;
private Configuration mConfig = null;
private CreateProject mCP;
private CreateSprint mCS;
private AddStoryToSprint mASTS;
private AddTaskToStory mATTS;
private static long mProjectId = 1;
@Before
public void setUp() throws Exception {
// Initialize database
mConfig = new Configuration();
mConfig.setTestMode(true);
mConfig.save();
// 初始化 SQL
InitialSQL ini = new InitialSQL(mConfig);
ini.exe();
ini = null;
// create test data
int projectCount = 1;
int sprintCount = 1;
int storyCount = 3;
int storyEstimate = 5;
int taskCount = 3;
int taskEstimate = 8;
String columnBeSet = "EST";
mCP = new CreateProject(projectCount);
mCP.exeCreate();
mCS = new CreateSprint(sprintCount, mCP);
mCS.exe();
mASTS = new AddStoryToSprint(storyCount, storyEstimate, mCS, mCP,
columnBeSet);
mASTS.exe();
mATTS = new AddTaskToStory(taskCount, taskEstimate, mASTS, mCP);
mATTS.exe();
ProjectObject project = mCP.getAllProjects().get(0);
mSprintBacklogMapper = new SprintBacklogMapper(project);
}
@After
public void tearDown() throws Exception {
InitialSQL ini = new InitialSQL(mConfig);
ini.exe();
// 刪除外部檔案
ProjectManager projectManager = new ProjectManager();
projectManager.deleteAllProject();
// 讓 config 回到 Production 模式
mConfig.setTestMode(false);
mConfig.save();
ini = null;
mCP = null;
mCS = null;
mASTS = null;
mATTS = null;
mConfig = null;
mSprintBacklogMapper = null;
projectManager = null;
}
@Test(expected = RuntimeException.class)
public void testConstructor() {
long sprintId = 5;
try {
new SprintBacklogMapper(mCP.getAllProjects().get(0), sprintId);
} catch (RuntimeException e) {
String message = "Sprint#" + sprintId + " is not existed.";
assertEquals(message, e.getMessage());
throw e;
}
Assert.fail("Sprint Id Null exception did not throw!");
}
@Test
public void testGetAllTasks() {
ArrayList<TaskObject> tasks = mSprintBacklogMapper.getTasksInSprint();
assertEquals(9, tasks.size());
// check project id
for (TaskObject task : tasks) {
assertEquals(1, task.getProjectId());
}
// check story id
assertEquals(1, tasks.get(0).getStoryId());
assertEquals(1, tasks.get(1).getStoryId());
assertEquals(1, tasks.get(2).getStoryId());
assertEquals(2, tasks.get(3).getStoryId());
assertEquals(2, tasks.get(4).getStoryId());
assertEquals(2, tasks.get(5).getStoryId());
assertEquals(3, tasks.get(6).getStoryId());
assertEquals(3, tasks.get(7).getStoryId());
assertEquals(3, tasks.get(8).getStoryId());
// check task id
for (int i = 0; i < tasks.size(); i++) {
assertEquals(i + 1, tasks.get(i).getId());
}
}
@Test
public void testGetStoriesInSprint_WithNullSprint() {
ProjectObject project = new ProjectObject("testProject");
project.setComment("testComment").setDisplayName("testDisplayName")
.setManager("testManager").setAttachFileSize(2).save();
SprintBacklogMapper sprintBacklogMapper = new SprintBacklogMapper(project);
ArrayList<StoryObject> stories = sprintBacklogMapper
.getStoriesInSprint();
assertEquals(0, stories.size());
}
@Test
public void testGetStoriesInSprint() {
long projectId = mCP.getAllProjects().get(0).getId();
ArrayList<StoryObject> stories = mSprintBacklogMapper
.getStoriesInSprint();
assertEquals(3, stories.size());
// check project id
assertEquals(projectId, stories.get(0).getProjectId());
assertEquals(projectId, stories.get(1).getProjectId());
assertEquals(projectId, stories.get(2).getProjectId());
// check story id
assertEquals(1, stories.get(0).getId());
assertEquals(2, stories.get(1).getId());
assertEquals(3, stories.get(2).getId());
}
@Test
public void testGetTasksByStoryId_WithNotExistStory() {
long notExistStoryId = -1;
ArrayList<TaskObject> tasks = mSprintBacklogMapper
.getTasksByStoryId(notExistStoryId);
assertEquals(0, tasks.size());
}
@Test
public void testGetTasksByStoryId_WithStory1() {
long story1Id = 1;
ArrayList<TaskObject> tasks = mSprintBacklogMapper
.getTasksByStoryId(story1Id);
assertEquals(3, tasks.size());
// check project id
assertEquals(1, tasks.get(0).getProjectId());
assertEquals(1, tasks.get(1).getProjectId());
assertEquals(1, tasks.get(2).getProjectId());
// check story id
assertEquals(1, tasks.get(0).getStoryId());
assertEquals(1, tasks.get(1).getStoryId());
assertEquals(1, tasks.get(2).getStoryId());
// check task id
assertEquals(1, tasks.get(0).getId());
assertEquals(2, tasks.get(1).getId());
assertEquals(3, tasks.get(2).getId());
}
@Test
public void testGetTasksByStoryId_WithStory2() {
long story2Id = 2;
ArrayList<TaskObject> tasks = mSprintBacklogMapper
.getTasksByStoryId(story2Id);
assertEquals(3, tasks.size());
// check project id
assertEquals(1, tasks.get(0).getProjectId());
assertEquals(1, tasks.get(1).getProjectId());
assertEquals(1, tasks.get(2).getProjectId());
// check story id
assertEquals(2, tasks.get(0).getStoryId());
assertEquals(2, tasks.get(1).getStoryId());
assertEquals(2, tasks.get(2).getStoryId());
// check task id
assertEquals(4, tasks.get(0).getId());
assertEquals(5, tasks.get(1).getId());
assertEquals(6, tasks.get(2).getId());
}
@Test
public void testGetTasksByStoryId_WithStory3() {
long story3Id = 3;
ArrayList<TaskObject> tasks = mSprintBacklogMapper
.getTasksByStoryId(story3Id);
assertEquals(3, tasks.size());
// check project id
assertEquals(1, tasks.get(0).getProjectId());
assertEquals(1, tasks.get(1).getProjectId());
assertEquals(1, tasks.get(2).getProjectId());
// check story id
assertEquals(3, tasks.get(0).getStoryId());
assertEquals(3, tasks.get(1).getStoryId());
assertEquals(3, tasks.get(2).getStoryId());
// check task id
assertEquals(7, tasks.get(0).getId());
assertEquals(8, tasks.get(1).getId());
assertEquals(9, tasks.get(2).getId());
}
@Test
public void testGetStoriesWithNoParent() {
// check existed stories before test
ArrayList<StoryObject> existedStories = mSprintBacklogMapper
.getStoriesWithNoParent();
assertEquals(0, existedStories.size());
ArrayList<StoryObject> storiesInSprint = mSprintBacklogMapper
.getStoriesInSprint();
assertEquals(1, storiesInSprint.get(0).getSprintId());
assertEquals(1, storiesInSprint.get(1).getSprintId());
assertEquals(1, storiesInSprint.get(2).getSprintId());
// remove story#1 from sprint
storiesInSprint.get(0).setSprintId(StoryObject.DEFAULT_VALUE).save();
// check dropped stories after add a dropped story
existedStories = mSprintBacklogMapper.getStoriesWithNoParent();
storiesInSprint = mSprintBacklogMapper.getStoriesInSprint();
assertEquals(StoryObject.DEFAULT_VALUE, existedStories.get(0)
.getSprintId());
assertEquals(1, storiesInSprint.get(0).getSprintId());
assertEquals(1, storiesInSprint.get(1).getSprintId());
assertEquals(1, existedStories.size());
assertEquals(2, storiesInSprint.size());
}
@Test
public void testGetStory_WithNotExistStoryId() {
long notExistStoryId = -1;
StoryObject story = mSprintBacklogMapper.getStory(notExistStoryId);
assertEquals(null, story);
}
@Test
public void testGetStory() {
long projectId = mCP.getAllProjects().get(0).getId();
StoryObject story1 = mSprintBacklogMapper.getStory(1);
StoryObject story2 = mSprintBacklogMapper.getStory(2);
StoryObject story3 = mSprintBacklogMapper.getStory(3);
// check project id
assertEquals(projectId, story1.getProjectId());
assertEquals(projectId, story2.getProjectId());
assertEquals(projectId, story3.getProjectId());
// check story id
assertEquals(1, story1.getId());
assertEquals(2, story2.getId());
assertEquals(3, story3.getId());
}
@Test
public void testGetTask() {
TaskObject task = null, expectTask = null;
// assert first task
task = mSprintBacklogMapper.getTask(mATTS.getTasksId().get(0));
expectTask = mATTS.getTasks().get(0);
assertEquals(expectTask.getName(), task.getName());
assertEquals(expectTask.getNotes(), task.getNotes());
assertEquals(expectTask.getActual(), task.getActual());
assertEquals(expectTask.getEstimate(), task.getEstimate());
assertEquals(expectTask.getStoryId(), task.getStoryId());
assertEquals(expectTask.getProjectId(), task.getProjectId());
assertEquals(expectTask.getRemains(), task.getRemains());
// assert second task
task = mSprintBacklogMapper.getTask(mATTS.getTasksId().get(1));
expectTask = mATTS.getTasks().get(1);
assertEquals(expectTask.getName(), task.getName());
assertEquals(expectTask.getNotes(), task.getNotes());
assertEquals(expectTask.getActual(), task.getActual());
assertEquals(expectTask.getEstimate(), task.getEstimate());
assertEquals(expectTask.getStoryId(), task.getStoryId());
assertEquals(expectTask.getProjectId(), task.getProjectId());
assertEquals(expectTask.getRemains(), task.getRemains());
// assert third task
task = mSprintBacklogMapper.getTask(mATTS.getTasksId().get(2));
expectTask = mATTS.getTasks().get(2);
assertEquals(expectTask.getName(), task.getName());
assertEquals(expectTask.getNotes(), task.getNotes());
assertEquals(expectTask.getActual(), task.getActual());
assertEquals(expectTask.getEstimate(), task.getEstimate());
assertEquals(expectTask.getStoryId(), task.getStoryId());
assertEquals(expectTask.getProjectId(), task.getProjectId());
assertEquals(expectTask.getRemains(), task.getRemains());
// assert fourth task
task = mSprintBacklogMapper.getTask(mATTS.getTasksId().get(3));
expectTask = mATTS.getTasks().get(3);
assertEquals(expectTask.getName(), task.getName());
assertEquals(expectTask.getNotes(), task.getNotes());
assertEquals(expectTask.getActual(), task.getActual());
assertEquals(expectTask.getEstimate(), task.getEstimate());
assertEquals(expectTask.getStoryId(), task.getStoryId());
assertEquals(expectTask.getProjectId(), task.getProjectId());
assertEquals(expectTask.getRemains(), task.getRemains());
// assert fifth task
task = mSprintBacklogMapper.getTask(mATTS.getTasksId().get(4));
expectTask = mATTS.getTasks().get(4);
assertEquals(expectTask.getName(), task.getName());
assertEquals(expectTask.getNotes(), task.getNotes());
assertEquals(expectTask.getActual(), task.getActual());
assertEquals(expectTask.getEstimate(), task.getEstimate());
assertEquals(expectTask.getStoryId(), task.getStoryId());
assertEquals(expectTask.getProjectId(), task.getProjectId());
assertEquals(expectTask.getRemains(), task.getRemains());
// assert sixth task
task = mSprintBacklogMapper.getTask(mATTS.getTasksId().get(5));
expectTask = mATTS.getTasks().get(5);
assertEquals(expectTask.getName(), task.getName());
assertEquals(expectTask.getNotes(), task.getNotes());
assertEquals(expectTask.getActual(), task.getActual());
assertEquals(expectTask.getEstimate(), task.getEstimate());
assertEquals(expectTask.getStoryId(), task.getStoryId());
assertEquals(expectTask.getProjectId(), task.getProjectId());
assertEquals(expectTask.getRemains(), task.getRemains());
// assert seventh task
task = mSprintBacklogMapper.getTask(mATTS.getTasksId().get(6));
expectTask = mATTS.getTasks().get(6);
assertEquals(expectTask.getName(), task.getName());
assertEquals(expectTask.getNotes(), task.getNotes());
assertEquals(expectTask.getActual(), task.getActual());
assertEquals(expectTask.getEstimate(), task.getEstimate());
assertEquals(expectTask.getStoryId(), task.getStoryId());
assertEquals(expectTask.getProjectId(), task.getProjectId());
assertEquals(expectTask.getRemains(), task.getRemains());
// assert eighth task
task = mSprintBacklogMapper.getTask(mATTS.getTasksId().get(7));
expectTask = mATTS.getTasks().get(7);
assertEquals(expectTask.getName(), task.getName());
assertEquals(expectTask.getNotes(), task.getNotes());
assertEquals(expectTask.getActual(), task.getActual());
assertEquals(expectTask.getEstimate(), task.getEstimate());
assertEquals(expectTask.getStoryId(), task.getStoryId());
assertEquals(expectTask.getProjectId(), task.getProjectId());
assertEquals(expectTask.getRemains(), task.getRemains());
// assert nine task
task = mSprintBacklogMapper.getTask(mATTS.getTasksId().get(8));
expectTask = mATTS.getTasks().get(8);
assertEquals(expectTask.getName(), task.getName());
assertEquals(expectTask.getNotes(), task.getNotes());
assertEquals(expectTask.getActual(), task.getActual());
assertEquals(expectTask.getEstimate(), task.getEstimate());
assertEquals(expectTask.getStoryId(), task.getStoryId());
assertEquals(expectTask.getProjectId(), task.getProjectId());
assertEquals(expectTask.getRemains(), task.getRemains());
}
@Test
public void testUpdateTask() {
long taskId = 1;
// get old task
TaskObject oldTask = TaskObject.get(taskId);
// check task status before update task
assertEquals(1, oldTask.getId());
assertEquals("TEST_TASK_1", oldTask.getName());
assertEquals(-1, oldTask.getHandlerId());
assertEquals(8, oldTask.getEstimate());
assertEquals(8, oldTask.getRemains());
assertEquals(0, oldTask.getActual());
assertEquals("TEST_TASK_NOTES_1", oldTask.getNotes());
assertEquals(0, oldTask.getPartnersId().size());
// create task info
TaskInfo taskInfo = new TaskInfo();
taskInfo.taskId = taskId;
// set new value
taskInfo.name = "NEW_TEST_TASK_NAME";
taskInfo.handlerId = 1;
taskInfo.estimate = 5;
taskInfo.remains = 3;
taskInfo.actual = 6;
taskInfo.notes = "NEW_TEST_TASK_NOTES";
ArrayList<Long> partnersId = new ArrayList<Long>();
partnersId.add(1L);
partnersId.add(2L);
taskInfo.partnersId = partnersId;
// update task
mSprintBacklogMapper.updateTask(taskId, taskInfo);
// get new task
TaskObject newTask = TaskObject.get(taskId);
// check new task status after update
assertEquals(1, newTask.getId());
assertEquals("NEW_TEST_TASK_NAME", newTask.getName());
assertEquals(1, newTask.getHandlerId());
assertEquals(5, newTask.getEstimate());
assertEquals(3, newTask.getRemains());
assertEquals(6, newTask.getActual());
assertEquals("NEW_TEST_TASK_NOTES", newTask.getNotes());
assertEquals(2, newTask.getPartnersId().size());
assertEquals(1, newTask.getPartnersId().get(0));
assertEquals(2, newTask.getPartnersId().get(1));
}
@Test
public void testAddTask() {
// create task info
TaskInfo taskInfo = new TaskInfo();
taskInfo.name = "NEW_TEST_TASK_NAME";
taskInfo.handlerId = 1;
taskInfo.estimate = 5;
taskInfo.actual = 6;
taskInfo.notes = "NEW_TEST_TASK_NOTES";
taskInfo.partnersId.add(1L);
long taskId = mSprintBacklogMapper.addTask(mProjectId, taskInfo);
TaskObject actualTask = TaskObject.get(taskId);
assertEquals(taskInfo.name, actualTask.getName());
assertEquals(taskInfo.notes, actualTask.getNotes());
assertEquals(taskInfo.estimate, actualTask.getEstimate());
assertEquals(taskInfo.estimate, actualTask.getRemains());
assertEquals(0, actualTask.getActual());
assertEquals(taskInfo.handlerId, actualTask.getHandlerId());
assertEquals(taskInfo.partnersId.get(0), actualTask.getPartnersId()
.get(0));
}
@Test
public void testAddExistingTasksToStory() {
// get story
StoryObject story = mASTS.getStories().get(0);
// check story tasks status before test
ArrayList<TaskObject> oldTaskIds = story.getTasks();
assertEquals(3, oldTaskIds.size());
assertEquals(1, oldTaskIds.get(0).getId());
assertEquals(2, oldTaskIds.get(1).getId());
assertEquals(3, oldTaskIds.get(2).getId());
// create a new task
TaskObject newTask = new TaskObject(1);
newTask.save();
// check new task status before be added to story
assertEquals(1, newTask.getProjectId());
assertEquals(-1, newTask.getStoryId());
assertEquals(10, newTask.getId());
// add new existing task to story
ArrayList<Long> tasksId = new ArrayList<Long>();
tasksId.add(newTask.getId());
mSprintBacklogMapper.addExistingTasksToStory(tasksId, 1);
// get story again
story.reload();
// check story tasks status after add new existing task
List<TaskObject> newTaskIds = story.getTasks();
assertEquals(4, newTaskIds.size());
assertEquals(1, newTaskIds.get(0).getId());
assertEquals(2, newTaskIds.get(1).getId());
assertEquals(3, newTaskIds.get(2).getId());
assertEquals(10, newTaskIds.get(3).getId());
}
@Test
public void testAddExistingTasksToStory_WithTwoExistingTasks() {
StoryObject story = mASTS.getStories().get(0);
// create a new task 1
TaskObject newTask1 = new TaskObject(1);
newTask1.save();
// check new task status before be added to story
assertEquals(1, newTask1.getProjectId());
assertEquals(-1, newTask1.getStoryId());
assertEquals(10, newTask1.getId());
// create a new task 2
TaskObject newTask2 = new TaskObject(1);
newTask2.save();
// check new existing task status before be added to story
assertEquals(1, newTask2.getProjectId());
assertEquals(-1, newTask2.getStoryId());
assertEquals(11, newTask2.getId());
// add new task 1 and new task 2 to story
ArrayList<Long> tasksId = new ArrayList<Long>();
tasksId.add(10L);
tasksId.add(11L);
mSprintBacklogMapper.addExistingTasksToStory(tasksId, story.getId());
// reload story again
story.reload();
// check story tasks status after add existing new tasks
ArrayList<TaskObject> tasks = story.getTasks();
assertEquals(5, tasks.size());
assertEquals(1, tasks.get(0).getId());
assertEquals(2, tasks.get(1).getId());
assertEquals(3, tasks.get(2).getId());
assertEquals(10, tasks.get(3).getId());
assertEquals(11, tasks.get(4).getId());
}
@Test(expected = RuntimeException.class)
public void testAddExistingTasksToStory_WithNotExistingTask() {
// get story
StoryObject story = mASTS.getStories().get(0);
// check story tasks status before test
ArrayList<TaskObject> oldTaskIds = story.getTasks();
assertEquals(3, oldTaskIds.size());
assertEquals(1, oldTaskIds.get(0).getId());
assertEquals(2, oldTaskIds.get(1).getId());
assertEquals(3, oldTaskIds.get(2).getId());
// create a new task
TaskObject newTask = new TaskObject(1);
// check new task status before be added to story
assertEquals(1, newTask.getProjectId());
assertEquals(-1, newTask.getStoryId());
assertEquals(-1, newTask.getId());
// add new existing task to story
ArrayList<Long> tasksId = new ArrayList<Long>();
tasksId.add(newTask.getId());
try {
mSprintBacklogMapper.addExistingTasksToStory(tasksId, 1);
} catch (RuntimeException e) {
String message = "Task#-1 is not existed.";
assertEquals(message, e.getMessage());
throw e;
}
Assert.fail("Add Task Failure exception did not throw!");
}
@Test
public void testGetTasksWithNoParent() {
long projectId = mCP.getAllProjects().get(0).getId();
// add two task, no parent
String TEST_NAME = "NEW_TEST_TASK_NAME_";
String TEST_NOTE = "NEW_TEST_TASK_NOTE_";
int TEST_EST = 5;
int TEST_HANDLER = 1;
int TEST_ACTUAL = 3;
TaskObject expectTask1 = new TaskObject(projectId);
expectTask1.setName(TEST_NAME + 1).setNotes(TEST_NOTE + 1)
.setEstimate(TEST_EST).setHandlerId(TEST_HANDLER)
.setActual(TEST_ACTUAL).save();
TaskObject expectTask2 = new TaskObject(projectId);
expectTask2.setName(TEST_NAME + 2).setNotes(TEST_NOTE + 2)
.setEstimate(TEST_EST + 2).setHandlerId(TEST_HANDLER)
.setActual(TEST_ACTUAL + 2).save();
// assert size
ArrayList<TaskObject> tasks = mSprintBacklogMapper
.getTasksWithNoParent(projectId);
assertEquals(2, tasks.size());
// assert first task
TaskObject actualTask = tasks.get(0);
assertEquals(expectTask1.getName(), actualTask.getName());
assertEquals(expectTask1.getNotes(), actualTask.getNotes());
assertEquals(expectTask1.getEstimate(), actualTask.getEstimate());
assertEquals(expectTask1.getActual(), actualTask.getActual());
assertEquals(expectTask1.getHandlerId(), actualTask.getHandlerId());
// assert second task
actualTask = tasks.get(1);
assertEquals(expectTask2.getName(), actualTask.getName());
assertEquals(expectTask2.getNotes(), actualTask.getNotes());
assertEquals(expectTask2.getEstimate(), actualTask.getEstimate());
assertEquals(expectTask2.getActual(), actualTask.getActual());
assertEquals(expectTask2.getHandlerId(), actualTask.getHandlerId());
}
@Test
public void testDeleteExistingTasks() {
long projectId = mCP.getAllProjects().get(0).getId();
// add two task, no parent
String TEST_NAME = "NEW_TEST_TASK_NAME_";
String TEST_NOTE = "NEW_TEST_TASK_NOTE_";
int TEST_EST = 5;
int TEST_HANDLER = 1;
int TEST_ACTUAL = 3;
TaskObject expectTask1 = new TaskObject(projectId);
expectTask1.setName(TEST_NAME + 1).setNotes(TEST_NOTE + 1)
.setEstimate(TEST_EST).setHandlerId(TEST_HANDLER)
.setActual(TEST_ACTUAL).save();
TaskObject expectTask2 = new TaskObject(projectId);
expectTask2.setName(TEST_NAME + 2).setNotes(TEST_NOTE + 2)
.setEstimate(TEST_EST + 2).setHandlerId(TEST_HANDLER)
.setActual(TEST_ACTUAL + 2).save();
long[] deleteId = new long[2];
deleteId[0] = expectTask1.getId();
deleteId[1] = expectTask2.getId();
// delete these tasks
mSprintBacklogMapper.deleteExistingTasks(deleteId);
assertEquals(null, TaskObject.get(expectTask1.getId()));
assertEquals(null, TaskObject.get(expectTask2.getId()));
}
@Test
public void testDropTask() {
long taskId = mATTS.getTasks().get(0).getId();
mSprintBacklogMapper.dropTask(taskId);
TaskObject task = TaskObject.get(taskId);
assertEquals(TaskObject.NO_PARENT, task.getStoryId());
}
@Test
public void testCloseStory() {
String closeNote = "CLOSE_NOTE";
String closeName = "CLOSE_NAME";
StoryObject story = mASTS.getStories().get(0);
long storyId = story.getId();
Date updateTime = DateUtil.dayFillter("2015/03/30-11:35:27",
DateUtil._16DIGIT_DATE_TIME);
// story default status is UNCHECK
assertEquals(StoryObject.STATUS_UNCHECK, story.getStatus());
mSprintBacklogMapper.closeStory(storyId, closeName, closeNote,
updateTime);
story = StoryObject.get(storyId);
assertEquals(StoryObject.STATUS_DONE, story.getStatus());
}
@Test
public void testReopenStory() {
String reopenName = "REOPEN_NAME";
String reopenNote = "REOPEN_NOTE";
String closeName = "CLOSE_NAME";
StoryObject story = mASTS.getStories().get(0);
long storyId = story.getId();
Date updateTime = DateUtil.dayFillter("2015/03/30-11:35:27",
DateUtil._16DIGIT_DATE_TIME);
// story default status is UNCHECK
assertEquals(StoryObject.STATUS_UNCHECK, story.getStatus());
// set story's status to DONE and assert it
mSprintBacklogMapper.closeStory(storyId, closeName, reopenNote,
updateTime);
story = StoryObject.get(storyId);
assertEquals(StoryObject.STATUS_DONE, story.getStatus());
// reopen the story
updateTime = DateUtil.dayFillter("2015/03/30-11:40:27",
DateUtil._16DIGIT_DATE_TIME);
;
mSprintBacklogMapper.reopenStory(storyId, reopenName, reopenName,
updateTime);
story = StoryObject.get(storyId);
assertEquals(StoryObject.STATUS_UNCHECK, story.getStatus());
assertEquals(reopenName, story.getName());
}
@Test
public void testCloseTask() {
String closeName = "CLOSE_NAME";
String closeNote = "CLOSE_NOTE";
int actual = 3;
Date specificDate = new Date(System.currentTimeMillis());
// assert status, default status should be UNCHECK
TaskObject task = mATTS.getTasks().get(0);
assertEquals(TaskObject.STATUS_UNCHECK, task.getStatus());
assertEquals(8, task.getRemains());
mSprintBacklogMapper.closeTask(task.getId(), closeName, closeNote,
actual, specificDate);
TaskObject closedTask = TaskObject.get(task.getId());
assertEquals(closeName, closedTask.getName());
assertEquals(closeNote, closedTask.getNotes());
assertEquals(0, closedTask.getRemains());
assertEquals(TaskObject.STATUS_DONE, closedTask.getStatus());
assertEquals(specificDate.getTime(), closedTask.getUpdateTime());
}
@Test
public void testResetTask() {
String RESET_NAME = "RESET_NAME";
String RESET_NOTE = "RESET_NOTE";
Date SPECIFIC_DATE = new Date(System.currentTimeMillis());
// assert status, default status should be UNCHECK
TaskObject task = mATTS.getTasks().get(0);
task.setStatus(TaskObject.STATUS_CHECK).save();
assertEquals(TaskObject.STATUS_CHECK, task.getStatus());
mSprintBacklogMapper.resetTask(task.getId(), RESET_NAME, RESET_NOTE,
SPECIFIC_DATE);
TaskObject resetTask = TaskObject.get(task.getId());
assertEquals(RESET_NAME, resetTask.getName());
assertEquals(RESET_NOTE, resetTask.getNotes());
assertEquals(TaskObject.STATUS_UNCHECK, resetTask.getStatus());
assertEquals(SPECIFIC_DATE.getTime(), resetTask.getUpdateTime());
}
@Test
public void testReopenTask() {
String REOPEN_NAME = "REOPEN_NAME";
String REOPEN_NOTE = "REOPEN_NOTE";
Date SPECIFIC_DATE = new Date(System.currentTimeMillis());
// assert status, default status should be UNCHECK
TaskObject task = mATTS.getTasks().get(0);
task.setStatus(TaskObject.STATUS_DONE).save();
assertEquals(TaskObject.STATUS_DONE, task.getStatus());
mSprintBacklogMapper.reopenTask(task.getId(), REOPEN_NAME, REOPEN_NOTE,
SPECIFIC_DATE);
TaskObject reopenTask = TaskObject.get(task.getId());
assertEquals(REOPEN_NAME, reopenTask.getName());
assertEquals(REOPEN_NOTE, reopenTask.getNotes());
assertEquals(TaskObject.STATUS_CHECK, reopenTask.getStatus());
assertEquals(SPECIFIC_DATE.getTime(), reopenTask.getUpdateTime());
}
@Test
public void testCheckOutTask() {
String CHECKOUT_NAME = "CHECKOUT_NAME";
String CHECKOUT_NOTE = "CHECKOUT_NOTE";
long CHECKOUT_HANDLER = 1;
ArrayList<Long> CHECKOUT_PARTNERS = new ArrayList<Long>();
CHECKOUT_PARTNERS.add(1L);
Date SPECIFIC_DATE = new Date(System.currentTimeMillis());
// assert status, default status should be UNCHECK
TaskObject task = mATTS.getTasks().get(0);
assertEquals(TaskObject.STATUS_UNCHECK, task.getStatus());
mSprintBacklogMapper.checkOutTask(task.getId(), CHECKOUT_NAME,
CHECKOUT_HANDLER, CHECKOUT_PARTNERS, CHECKOUT_NOTE,
SPECIFIC_DATE);
TaskObject checkoutTask = TaskObject.get(task.getId());
assertEquals(CHECKOUT_NAME, checkoutTask.getName());
assertEquals(CHECKOUT_NOTE, checkoutTask.getNotes());
assertEquals(TaskObject.STATUS_CHECK, checkoutTask.getStatus());
assertEquals(1L, checkoutTask.getHandlerId());
assertEquals(1L, checkoutTask.getPartnersId().get(0));
assertEquals(SPECIFIC_DATE.getTime(), checkoutTask.getUpdateTime());
}
@Test
public void testDeleteTask() {
// get all tasks id
ArrayList<Long> tasksId = mATTS.getTasksId();
// delete the tasks
for (long taskId : tasksId) {
mSprintBacklogMapper.deleteTask(taskId);
}
// all tasks should be deleted
for (long taskId : tasksId) {
TaskObject task = TaskObject.get(taskId);
assertEquals(null, task);
}
}
@Test
public void testGetSprintId() {
ProjectObject project = new ProjectObject("testGetSprintId");
project.setAttachFileSize(2).save();
SprintBacklogMapper sprintBacklogMapper = new SprintBacklogMapper(project);
assertEquals(-1, sprintBacklogMapper.getSprintId());
}
@Test
public void testGetSprintGoal() {
ProjectObject project = new ProjectObject("testGetSprintId");
project.setAttachFileSize(2).save();
SprintBacklogMapper sprintBacklogMapper = new SprintBacklogMapper(project);
assertEquals("", sprintBacklogMapper.getSprintGoal());
}
@Test
public void testUpdateStoryRelation() {
StoryObject story = mASTS.getStories().get(0);
assertEquals("TEST_STORY_1", story.getName());
assertEquals(1, story.getSprintId());
assertEquals(100, story.getImportance());
assertEquals(5, story.getEstimate());
mSprintBacklogMapper.updateStoryRelation(story.getId(), 1, 5, 10, new Date());
story.reload();
assertEquals("TEST_STORY_1", story.getName());
assertEquals(1, story.getSprintId());
assertEquals(10, story.getImportance());
assertEquals(5, story.getEstimate());
}
}
| gpl-2.0 |
Corvu/dbeaver | plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/tools/transfer/wizard/DataTransferJob.java | 3858 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2016 Serge Rieder (serge@jkiss.org)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (version 2)
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.jkiss.dbeaver.tools.transfer.wizard;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.tools.transfer.IDataTransferConsumer;
import org.jkiss.dbeaver.tools.transfer.IDataTransferProducer;
import org.jkiss.dbeaver.tools.transfer.IDataTransferSettings;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;
/**
* Data transfer job
*/
public class DataTransferJob extends AbstractJob {
private DataTransferSettings settings;
public DataTransferJob(DataTransferSettings settings)
{
super(CoreMessages.data_transfer_wizard_job_name);
this.settings = settings;
setUser(true);
}
@Override
public boolean belongsTo(Object family)
{
return family == settings;
}
@Override
protected IStatus run(DBRProgressMonitor monitor)
{
boolean hasErrors = false;
long startTime = System.currentTimeMillis();
for (; ;) {
DataTransferPipe transferPipe = settings.acquireDataPipe(monitor);
if (transferPipe == null) {
break;
}
if (!transferData(monitor, transferPipe)) {
hasErrors = true;
}
}
showResult(System.currentTimeMillis() - startTime, hasErrors);
return Status.OK_STATUS;
}
private void showResult(final long time, final boolean hasErrors)
{
UIUtils.showMessageBox(
null,
"Data transfer",
"Data transfer completed " + (hasErrors ? "with errors " : "") + "(" + RuntimeUtils.formatExecutionTime(time) + ")",
hasErrors ? SWT.ICON_ERROR : SWT.ICON_INFORMATION);
}
private boolean transferData(DBRProgressMonitor monitor, DataTransferPipe transferPipe)
{
IDataTransferProducer producer = transferPipe.getProducer();
IDataTransferConsumer consumer = transferPipe.getConsumer();
IDataTransferSettings consumerSettings = settings.getNodeSettings(consumer);
setName(NLS.bind(CoreMessages.data_transfer_wizard_job_container_name,
CommonUtils.truncateString(producer.getSourceObject().getName(), 200)));
IDataTransferSettings nodeSettings = settings.getNodeSettings(producer);
try {
//consumer.initTransfer(producer.getSourceObject(), consumerSettings, );
producer.transferData(
monitor,
consumer,
nodeSettings);
consumer.finishTransfer(monitor, false);
return true;
} catch (Exception e) {
new DataTransferErrorJob(e).schedule();
return false;
}
}
}
| gpl-2.0 |
kaisenlean/troca.co | src/main/java/co/icesi/troca/services/proyecto/ProyectoUsuarioService.java | 1689 | /**
*
*/
package co.icesi.troca.services.proyecto;
import java.util.List;
import co.icesi.troca.model.proyecto.Proyecto;
import co.icesi.troca.model.proyecto.ProyectoUsuario;
import co.icesi.troca.model.usuario.Usuario;
import co.icesi.troca.services.GenericService;
/**
* @author <a href="mailto:elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a>
* @project troca-co
* @class ProyectoUsuarioService
* @date 1/12/2013
*
*/
public interface ProyectoUsuarioService extends
GenericService<ProyectoUsuario, Integer> {
/**
* Método que consulta los usuarios relacionados a un proyecto parametrizado
*
* @author <a href="elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a>
* @date 1/12/2013
* @param proyecto
* @return
*/
List<ProyectoUsuario> findByProyecto(Proyecto proyecto);
/**
* Método que extrae los proyectos por un usuario en especifico
*
* @author <a href="elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a>
* @date 19/12/2013
* @param usuario
* @return
*/
List<Proyecto> findByUsuario(Usuario usuario);
/**
* Método que consulta un registro de {@link ProyectoUsuario} por criterio
* de {@link Usuario} y {@link Proyecto}
*
* @author <a href="elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a>
* @date 1/12/2013
* @param usuario
* @param proyecto
* @return
*/
ProyectoUsuario getByUsuarioAndProyecto(Usuario usuario,
Proyecto proyecto);
/**
* Método que busca los usuarios participantes de un proyecto
* @author <a href="elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a>
* @date 7/01/2014
* @param proyecto
* @return
*/
List<Usuario> findParticipantesByProyecto(Proyecto proyecto);
}
| gpl-2.0 |
lexaxa/Auction | src/main/java/com/govauction/entity/Lot.java | 1511 | package com.govauction.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = "lots")
public class Lot extends BaseEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "lot_id")
private Long lotId;
@Column(name = "description")
private String description;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "owner_id")
private LotOwner lotOwner;
@Column(name = "lot_date")
private Date lotDate;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "lot")
private List<LotOrder> lotOrders;
public Long getLotId() {
return lotId;
}
public void setLotId(Long lotId) {
this.lotId = lotId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LotOwner getLotOnwer() {
return lotOwner;
}
public void setLotOnwer(LotOwner lotOwner) {
this.lotOwner = lotOwner;
}
public Date getLotDate() {
return lotDate;
}
public void setLotDate(Date lotDate) {
this.lotDate = lotDate;
}
public List<LotOrder> getLotOrders() {
return lotOrders;
}
public void setLotOrders(List<LotOrder> lotOrders) {
this.lotOrders = lotOrders;
}
}
| gpl-2.0 |
help3r/civcraft-1 | civcraft/src/com/avrgaming/civcraft/war/WarAntiCheat.java | 1591 | package com.avrgaming.civcraft.war;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.avrgaming.anticheat.ACManager;
import com.avrgaming.civcraft.exception.CivException;
import com.avrgaming.civcraft.main.CivGlobal;
import com.avrgaming.civcraft.main.CivMessage;
import com.avrgaming.civcraft.object.Resident;
import com.avrgaming.civcraft.threading.TaskMaster;
import com.avrgaming.civcraft.threading.tasks.PlayerKickBan;
import com.avrgaming.civcraft.util.CivColor;
public class WarAntiCheat {
public static void kickUnvalidatedPlayers() {
if (CivGlobal.isCasualMode()) {
return;
}
if (!ACManager.isEnabled()) {
return;
}
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.isOp()) {
continue;
}
if (player.hasPermission("civ.ac_exempt")) {
continue;
}
Resident resident = CivGlobal.getResident(player);
onWarTimePlayerCheck(resident);
}
CivMessage.global(CivColor.LightGray+"All 'at war' players not using CivCraft's Anti-Cheat have been expelled during WarTime.");
}
public static void onWarTimePlayerCheck(Resident resident) {
if (!resident.hasTown()) {
return;
}
if (!resident.getCiv().getDiplomacyManager().isAtWar()) {
return;
}
try {
if (!resident.isUsesAntiCheat()) {
TaskMaster.syncTask(new PlayerKickBan(resident.getName(), true, false,
"Kicked: You are required to have CivCraft's Anti-Cheat plugin installed to participate in WarTime."+
"Visit https://www.minetexas.com/ to get it."));
}
} catch (CivException e) {
}
}
}
| gpl-2.0 |
dmcennis/jMir | jMIR_2_4_developer/jSymbolic/src/jsymbolic/features/MostCommonPitchFeature.java | 3527 | /*
* MostCommonPitchFeature.java
* Version 1.2
*
* Last modified on April 11, 2010.
* McGill University
*/
package jsymbolic.features;
import java.util.LinkedList;
import javax.sound.midi.*;
import ace.datatypes.FeatureDefinition;
import jsymbolic.processing.MIDIIntermediateRepresentations;
/**
* A feature exractor that finds the bin label of the most common pitch divided
* by the number of possible pitches.
*
* <p>No extracted feature values are stored in objects of this class.
*
* @author Cory McKay
*/
public class MostCommonPitchFeature
extends MIDIFeatureExtractor
{
/* CONSTRUCTOR ***********************************************************/
/**
* Basic constructor that sets the definition and dependencies (and their
* offsets) of this feature.
*/
public MostCommonPitchFeature()
{
String name = "Most Common Pitch";
String description = "Bin label of the most common pitch divided by the\n" +
"number of possible pitches.";
boolean is_sequential = true;
int dimensions = 1;
definition = new FeatureDefinition( name,
description,
is_sequential,
dimensions );
dependencies = null;
offsets = null;
}
/* PUBLIC METHODS ********************************************************/
/**
* Extracts this feature from the given MIDI sequence given the other
* feature values.
*
* <p>In the case of this feature, the other_feature_values parameters
* are ignored.
*
* @param sequence The MIDI sequence to extract the feature
* from.
* @param sequence_info Additional data about the MIDI sequence.
* @param other_feature_values The values of other features that are
* needed to calculate this value. The
* order and offsets of these features
* must be the same as those returned by
* this class's getDependencies and
* getDependencyOffsets methods
* respectively. The first indice indicates
* the feature/window and the second
* indicates the value.
* @return The extracted feature value(s).
* @throws Exception Throws an informative exception if the
* feature cannot be calculated.
*/
public double[] extractFeature( Sequence sequence,
MIDIIntermediateRepresentations sequence_info,
double[][] other_feature_values )
throws Exception
{
double value;
if (sequence_info != null)
{
// Find the highest bin
double max = 0;
int max_index = 0;
for (int bin = 0; bin < sequence_info.basic_pitch_histogram.length; bin++)
if (sequence_info.basic_pitch_histogram[bin] > max)
{
max = sequence_info.basic_pitch_histogram[bin];
max_index = bin;
}
// Calculate the value
value = (double) max_index / (double) sequence_info.basic_pitch_histogram.length;
}
else value = -1.0;
double[] result = new double[1];
result[0] = value;
return result;
}
} | gpl-2.0 |
simplelist/ShanWoXing | src/com/yxtar/server/service/AppDataUpdateService.java | 77 | package com.yxtar.server.service;
public interface AppDataUpdateService{
}
| gpl-2.0 |
fozziethebeat/C-Cat | wordnet/src/main/java/gov/llnl/ontology/wordnet/builder/OntologicalSortWordNetBuilder.java | 3476 | /*
* Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
* the Lawrence Livermore National Laboratory. Written by Keith Stevens,
* kstevens@cs.ucla.edu OCEC-10-073 All rights reserved.
*
* This file is part of the C-Cat package and is covered under the terms and
* conditions therein.
*
* The C-Cat package is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation and distributed hereunder to you.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES,
* EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE
* NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY
* PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION
* WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER
* RIGHTS.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package gov.llnl.ontology.wordnet.builder;
import edu.ucla.sspace.util.Duple;
import gov.llnl.ontology.wordnet.BaseLemma;
import gov.llnl.ontology.wordnet.BaseSynset;
import gov.llnl.ontology.wordnet.Synset;
import gov.llnl.ontology.wordnet.SynsetRelations;
import gov.llnl.ontology.wordnet.Synset.PartsOfSpeech;
import gov.llnl.ontology.wordnet.Synset.Relation;
import gov.llnl.ontology.wordnet.OntologyReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author Keith Stevens
*/
public class OntologicalSortWordNetBuilder implements WordNetBuilder {
private final OntologyReader wordnet;
private Set<String> knownTerms;
private List<TermToAdd> termsToAdd;
private boolean compareInWn;
public OntologicalSortWordNetBuilder(OntologyReader wordnet,
boolean compareInWn) {
this.wordnet = wordnet;
this.compareInWn = compareInWn;
knownTerms = new HashSet<String>();
termsToAdd = new ArrayList<TermToAdd>();
}
public void addEvidence(String child,
String[] parents,
double[] parentScores,
Map<String, Double> cousinScores) {
knownTerms.add(child);
termsToAdd.add(new TermToAdd(
child, parents, parentScores, cousinScores, compareInWn));
}
public void addTerms(OntologyReader wordnet, BuilderScorer scorer) {
for (TermToAdd termToAdd : termsToAdd) {
termToAdd.checkParentsInWordNet(wordnet);
termToAdd.checkParentsInList(knownTerms);
}
Collections.sort(termsToAdd);
for (TermToAdd termToAdd : termsToAdd) {
Duple<Synset,Double> bestAttachment =
SynsetRelations.bestAttachmentPointWithError(
wordnet,termToAdd.parents,termToAdd.parentScores,.95);
Synset newSynset = new BaseSynset(PartsOfSpeech.NOUN);
newSynset.addLemma(new BaseLemma(newSynset, termToAdd.term,
"", 0, 0, "n"));
newSynset.addRelation(Relation.HYPERNYM, bestAttachment.x);
wordnet.addSynset(newSynset);
}
scorer.scoreAdditions(wordnet);
}
}
| gpl-2.0 |
rafaelkalan/metastone | src/main/java/net/demilich/metastone/game/spells/trigger/AfterSpellCastedTrigger.java | 1090 | package net.demilich.metastone.game.spells.trigger;
import net.demilich.metastone.game.entities.Entity;
import net.demilich.metastone.game.events.AfterSpellCastedEvent;
import net.demilich.metastone.game.events.GameEvent;
import net.demilich.metastone.game.events.GameEventType;
import net.demilich.metastone.game.spells.TargetPlayer;
import net.demilich.metastone.game.spells.desc.trigger.EventTriggerDesc;
public class AfterSpellCastedTrigger extends GameEventTrigger {
public AfterSpellCastedTrigger(EventTriggerDesc desc) {
super(desc);
}
@Override
protected boolean fire(GameEvent event, Entity host) {
AfterSpellCastedEvent spellCastedEvent = (AfterSpellCastedEvent) event;
TargetPlayer targetPlayer = desc.getTargetPlayer();
switch (targetPlayer) {
case BOTH:
return true;
case SELF:
case OWNER:
return spellCastedEvent.getPlayerId() == host.getOwner();
case OPPONENT:
return spellCastedEvent.getPlayerId() != host.getOwner();
}
return false;
}
@Override
public GameEventType interestedIn() {
return GameEventType.AFTER_SPELL_CASTED;
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | packages/apps/Contacts/src/com/mediatek/contacts/list/DataKindPickerBaseAdapter.java | 8542 |
package com.mediatek.contacts.list;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.ContactCounts;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.android.contacts.list.ContactEntryListAdapter;
import com.android.contacts.list.ContactListFilter;
import com.android.contacts.list.ContactListItemView;
import com.mediatek.contacts.ExtensionManager;
import com.mediatek.phone.SIMInfoWrapper;
public abstract class DataKindPickerBaseAdapter extends ContactEntryListAdapter {
private static final String TAG = DataKindPickerBaseAdapter.class.getSimpleName();
private ListView mListView;
private ContactListItemView.PhotoPosition mPhotoPosition;
private Context mContext;
public DataKindPickerBaseAdapter(Context context, ListView lv) {
super(context);
mListView = lv;
mContext = context;
}
protected ListView getListView() {
return mListView;
}
@Override
public final void configureLoader(CursorLoader loader, long directoryId) {
loader.setUri(configLoaderUri(directoryId));
loader.setProjection(configProjection());
configureSelection(loader, directoryId, getFilter());
// Set the Contacts sort key as sort order
String sortOrder;
if (getSortOrder() == ContactsContract.Preferences.SORT_ORDER_PRIMARY) {
sortOrder = Contacts.SORT_KEY_PRIMARY;
} else {
sortOrder = Contacts.SORT_KEY_ALTERNATIVE;
}
loader.setSortOrder(sortOrder);
}
protected abstract String[] configProjection();
protected abstract Uri configLoaderUri(long directoryId);
protected abstract void configureSelection(CursorLoader loader, long directoryId,
ContactListFilter filter);
protected static Uri buildSectionIndexerUri(Uri uri) {
return uri.buildUpon()
.appendQueryParameter(ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, "true").build();
}
@Override
protected View newView(Context context, int partition, Cursor cursor, int position,
ViewGroup parent) {
ContactListItemView view = new ContactListItemView(context, null);
view.setUnknownNameText(context.getText(android.R.string.unknownName));
view.setQuickContactEnabled(isQuickContactEnabled());
// Enable check box
view.setCheckable(true);
if (mPhotoPosition != null) {
view.setPhotoPosition(mPhotoPosition);
}
view.setActivatedStateSupported(true);
return view;
}
public void displayPhotoOnLeft() {
mPhotoPosition = ContactListItemView.PhotoPosition.LEFT;
}
@Override
protected void bindView(View itemView, int partition, Cursor cursor, int position) {
final ContactListItemView view = (ContactListItemView) itemView;
// Look at elements before and after this position, checking if contact
// IDs are same.
// If they have one same contact ID, it means they can be grouped.
//
// In one group, only the first entry will show its photo and names
// (display name and
// phonetic name), and the other entries in the group show just their
// data (e.g. phone
// number, email address).
cursor.moveToPosition(position);
boolean isFirstEntry = true;
boolean showBottomDivider = true;
final long currentContactId = cursor.getLong(getContactIDColumnIndex());
if (cursor.moveToPrevious() && !cursor.isBeforeFirst()) {
final long previousContactId = cursor.getLong(getContactIDColumnIndex());
if (currentContactId == previousContactId) {
isFirstEntry = false;
}
}
cursor.moveToPosition(position);
if (cursor.moveToNext() && !cursor.isAfterLast()) {
final long nextContactId = cursor.getLong(getContactIDColumnIndex());
if (currentContactId == nextContactId) {
// The following entry should be in the same group, which means
// we don't want a
// divider between them.
// TODO: we want a different divider than the divider between
// groups. Just hiding
// this divider won't be enough.
showBottomDivider = false;
}
}
cursor.moveToPosition(position);
bindSectionHeaderAndDivider(view, position, cursor);
if (isFirstEntry) {
bindName(view, cursor);
if (isQuickContactEnabled()) {
bindQuickContact(view, partition, cursor);
} else {
bindPhoto(view, cursor);
}
} else {
unbindName(view);
view.removePhotoView(true, false);
}
bindData(view, cursor);
if (!isSearchMode()) {
view.setSnippet(null);
}
view.setDividerVisible(showBottomDivider);
view.getCheckBox().setChecked(mListView.isItemChecked(position));
}
protected void bindSectionHeaderAndDivider(ContactListItemView view, int position, Cursor cursor) {
if (isSectionHeaderDisplayEnabled()) {
Placement placement = getItemPlacementInSection(position);
view.setSectionHeader(placement.sectionHeader);
view.setDividerVisible(!placement.lastInSection);
} else {
view.setSectionHeader(null);
view.setDividerVisible(true);
}
}
protected void bindPhoto(final ContactListItemView view, Cursor cursor) {
long photoId = 0;
if (!cursor.isNull(getPhotoIDColumnIndex())) {
photoId = cursor.getLong(getPhotoIDColumnIndex());
}
int indicatePhoneSim = cursor.getInt(getIndicatePhoneSIMColumnIndex());
if (indicatePhoneSim > 0) {
photoId = getSimType(indicatePhoneSim, cursor.getInt(getIsSdnContactColumnIndex()));
}
getPhotoLoader().loadThumbnail(view.getPhotoView(), photoId, false);
}
protected void bindData(ContactListItemView view, Cursor cursor) {
CharSequence label = null;
if (!cursor.isNull(getDataTypeColumnIndex())) {
final int type = cursor.getInt(getDataTypeColumnIndex());
final String customLabel = cursor.getString(getDataLabelColumnIndex());
// TODO cache
/** M:AAS @ { original code:
label = Phone.getTypeLabel(mContext.getResources(), type, customLabel); */
int indicateIndex = cursor.getColumnIndex(Contacts.INDICATE_PHONE_SIM);
int slotId = -1;
if (indicateIndex != -1) {
int simId = cursor.getInt(indicateIndex);
slotId = SIMInfoWrapper.getDefault().getSimSlotById(simId);
}
Log.v(TAG, "DataKindPoickerBaseAdapter, the default flow to get label.");
label = ExtensionManager.getInstance().getContactAccountExtension().getTypeLabel(mContext.getResources(),
type, customLabel, slotId, ExtensionManager.COMMD_FOR_AAS);
/** M: @ } */
}
view.setLabel(label);
view.showData(cursor, getDataColumnIndex());
}
protected void unbindName(final ContactListItemView view) {
view.hideDisplayName();
view.hidePhoneticName();
}
public abstract Uri getDataUri(int position);
public abstract long getDataId(int position);
public abstract void bindName(final ContactListItemView view, Cursor cursor);
public abstract void bindQuickContact(final ContactListItemView view, int partitionIndex,
Cursor cursor);
public abstract int getPhotoIDColumnIndex();
public abstract int getDataTypeColumnIndex();
public abstract int getDataLabelColumnIndex();
public abstract int getDataColumnIndex();
public abstract int getContactIDColumnIndex();
public abstract int getPhoneticNameColumnIndex();
public abstract int getIndicatePhoneSIMColumnIndex();
public abstract int getIsSdnContactColumnIndex();
public boolean hasStableIds() {
return false;
}
public long getItemId(int position) {
return getDataId(position);
}
}
| gpl-2.0 |
specialk1st/messenger | src/main/java/org/kelly_ann/messenger/service/ProfileService.java | 1247 | package org.kelly_ann.messenger.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.kelly_ann.messenger.database.DatabaseClass;
import org.kelly_ann.messenger.model.Profile;
// this class and the MessageService class are very similar except for the fact that the lookup for ProfileService is the
// profile's name vs. the id as it is in the MessageService.
public class ProfileService {
private Map<String, Profile> profiles = DatabaseClass.getProfiles();
public ProfileService() {
profiles.put("specialk1st", new Profile(1L, "specialk1st", "Kelly-Ann", "P"));
}
public List<Profile> getAllProfiles() {
return new ArrayList<Profile>(profiles.values());
}
public Profile getProfile(String profileName) {
return profiles.get(profileName);
}
public Profile addProfile(Profile profile) {
profile.setId(profiles.size() + 1);
profiles.put(profile.getProfileName(), profile);
return profile;
}
public Profile updateProfile(Profile profile) {
if(profile.getProfileName().isEmpty()) {
return null;
}
profiles.put(profile.getProfileName(), profile);
return profile;
}
public Profile removeProfile(String profileName) {
return profiles.remove(profileName);
}
}
| gpl-2.0 |
ZippyIO/MinersTech | src/Blocks/Ores/oreZondo.java | 840 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package MinersTech.Blocks.Ores;
import MinersTech.MinersTech;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
/**
*
* @author ZippyBling
*/
public class oreZondo extends Block{
public oreZondo(int id, Material par2Material) {
super(id, par2Material);
}
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister iconRegister){
this.blockIcon = iconRegister.registerIcon(MinersTech.modid + ":" + "oreZondo");
}
}
| gpl-2.0 |
isandlaTech/cohorte-utilities | org.cohorte.utilities/src/org/psem2m/utilities/measurement/CXTimeMeters.java | 8871 | package org.psem2m.utilities.measurement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.psem2m.utilities.CXTimer;
import org.psem2m.utilities.json.JSONException;
import org.psem2m.utilities.json.JSONObject;
/**
*
*
* TEXT:
*
* <pre>
* Id=[TimeMeterName1] Main=[429,455] Timer1B=[251,226] Timer1C=[176,954] Info00=[ResultOfSomethingB:0.4310281000591685] Info01=[ResultOfSomethingC:0.46446065255875946]
* </pre>
*
* CVS (separated by a tab character)
*
* <pre>
* Id TimeMeterName1 Main 429,455 Timer1B 251,226 Timer1C 176,954 Info00 ResultOfSomethingB:0.4310281000591685 Info01 ResultOfSomethingC:0.46446065255875946
* </pre>
*
* JSON:
*
* <pre>
* {"Main":"429.455","Info00":"ResultOfSomethingB:0.4310281000591685","Id":"TimeMeterName1","Timer1B":"251.226","Info01":"ResultOfSomethingC:0.46446065255875946","Timer1C":"176.954"}
* </pre>
*
* XML :
*
* <pre>
* <TimeMeterName1><Main>429,455</Main><Timer1B>251,226</Timer1B><Timer1C>176,954</Timer1C><Info00>ResultOfSomethingB:0.4310281000591685</Info00><Info01>ResultOfSomethingC:0.46446065255875946</Info01></TimeMeterName1>
* </pre>
*
* @author ogattaz
*
*/
public class CXTimeMeters {
private static final String COL_NAME_FREE = "FreeMem";
private static final String COL_NAME_ID = "Id";
private static final List<String> NO_INFO = new ArrayList<String>();
public static final String SEPARATOR_TAB = "\t";
private static final String TIMER_NAME_MAIN = "Main";
public static final boolean WITH_FREEMEM = true;
private long pFreeMemory = -1;
private List<String> pInfos = NO_INFO;
private final CXNamedTimer pMainTimer;
/**
* teh flag to return or not the amount of free memory in the Java Virtual
* Machine.
*/
private final boolean pMustMeasureFreeMem;
private final CXNamedTimers pNamedTimers = new CXNamedTimers();
private String pTimeMetersId;
/**
* @param aTimeMetersId
* the id of this TimeMeters instance
*/
public CXTimeMeters(final String aId) {
this(aId, !WITH_FREEMEM);
}
/**
* @param aTimeMetersId
* the id of this TimeMeters instance
* @param aMustMeasureFreeMem
* measure the free memory when the timer will be stopped
*/
public CXTimeMeters(final String aTimeMetersId,
final boolean aMustMeasureFreeMem) {
this(aTimeMetersId, aMustMeasureFreeMem, TIMER_NAME_MAIN);
}
/**
* @param aTimeMetersId
* the id of this TimeMeters instance
* @param aMustMeasureFreeMem
* measure the free memory when the timer will be stopped
* @param aMainTimerName
* the id of the main timer of this TimeMeters
*/
public CXTimeMeters(final String aTimeMetersId,
final boolean aMustMeasureFreeMem, final String aMainTimerName) {
super();
pTimeMetersId = aTimeMetersId;
pMustMeasureFreeMem = aMustMeasureFreeMem;
if (mustMeasureFreeMem()) {
Runtime.getRuntime().gc();
pFreeMemory = Runtime.getRuntime().freeMemory();
}
pMainTimer = addNewTimer(aMainTimerName);
}
/**
* @param aTimeMetersId
* the id of this TimeMeters instance
* @param aMainTimerName
* the id of the main timer of this TimeMeters
*/
public CXTimeMeters(final String aTimeMetersId, final String aMainTimerName) {
this(aTimeMetersId, !WITH_FREEMEM, aMainTimerName);
}
/**
* Adds information to this TimeMeters instance. These informations will be
* add to the final report
*
* @param aFormat
* the format used by the java string formatter
* @param aInfos
* an array of object used by the java string formatter
*/
public void addInfos(final String aFormat, final Object... aInfos) {
if (NO_INFO.equals(pInfos)) {
pInfos = new ArrayList<String>();
}
pInfos.add(String.format(aFormat, aInfos));
}
/**
* @param aName
* @return a new instance of named timer
*/
public CXNamedTimer addNewTimer(final String aName) {
CXNamedTimer wNamedTimer = new CXNamedTimer(aName);
pNamedTimers.add(wNamedTimer);
return wNamedTimer;
}
/**
* @return
*/
public long getFreeMemory() {
return pFreeMemory;
}
/**
* @return the identifier of the instance
*/
public String getId() {
return pTimeMetersId;
}
/**
* @return
*/
public List<String> getInfos() {
return pInfos;
}
/**
* @return a formated string ("%6.3f") containing the duration in in
* milliseconds with microesconds (eg. "175,044" milliseconds)
*/
public String getMainDurationStrMicroSec() {
return getMainTimer().getDurationStrMicroSec();
}
/**
* @return a formated string ("%06d") containing the duration in
* milliseconds (eg. "000256" milliseconds)
*/
public String getMainDurationStrMilliSec() {
return getMainTimer().getDurationStrMilliSec();
}
/**
* @return the instance of CXTimer
*/
public CXTimer getMainTimer() {
return pMainTimer.getTimer();
}
/**
* @return the list of timers
*/
public List<CXNamedTimer> getNamedTimers() {
return pNamedTimers;
}
/**
* @return a string containing the set of the names of the timeMeters
* sperarated by a "tab" character
*/
public String getNamesInStr() {
return getNamesInStr(CXTimeMeters.SEPARATOR_TAB);
}
/**
* @param aSeparator
* @return a string containing the set of the names of this TimeMeters
* sperarated by "aSeparator"
*/
public String getNamesInStr(final String aSeparator) {
return String.format("%s%s%s%s", COL_NAME_ID, aSeparator,
COL_NAME_FREE, pNamedTimers.getNamesInStr(aSeparator),
aSeparator);
}
/**
* @return true if some info is stored in this TimeMeters instance
*/
public boolean hasInfos() {
return getInfos().size() > 0;
}
/**
* eg.
*
* @return true id the amount of the free memory will be add in the report
* of this TimeMeters
*/
protected boolean mustMeasureFreeMem() {
return pMustMeasureFreeMem;
}
/**
* @param aId
* the new identifier of the instance
*/
public void setId(final String aId) {
pTimeMetersId = aId;
}
/**
* Stops all the named timers and get free memory amount if wanted
*/
public void stopAll() {
pNamedTimers.stopAll();
if (mustMeasureFreeMem()) {
Runtime.getRuntime().gc();
pFreeMemory = Runtime.getRuntime().freeMemory();
}
}
/**
* @return
*/
public String toCvs() {
return toCvs(CXTimeMeters.SEPARATOR_TAB);
}
/**
* @param aSeparator
* @return
*/
public String toCvs(final String aSeparator) {
stopAll();
StringBuilder wSB = new StringBuilder();
wSB.append(String.format("%2$s%1$s%3$s", aSeparator, COL_NAME_ID,
getId()));
if (mustMeasureFreeMem()) {
wSB.append(String.format("%1$s%2$s%1$s%3$s", aSeparator,
COL_NAME_FREE, pFreeMemory));
}
wSB.append(pNamedTimers.toCsv(aSeparator));
if (hasInfos()) {
int wMax = getInfos().size();
for (int wIdx = 0; wIdx < wMax; wIdx++) {
wSB.append(String.format("%1$sInfo%2$02d%1$s%3$s", aSeparator,
wIdx, getInfos().get(wIdx)));
}
}
return wSB.toString();
}
/**
* @return
* @throws JSONException
*/
public JSONObject toJson() throws JSONException {
stopAll();
Map<String, Object> wJsonAttributesHashMap = pNamedTimers
.toJsonAttributesHashMap();
JSONObject wJsonObj = new JSONObject(wJsonAttributesHashMap);
wJsonObj.accumulate(COL_NAME_ID, getId());
if (mustMeasureFreeMem()) {
wJsonObj.accumulate(COL_NAME_FREE, pFreeMemory);
}
if (hasInfos()) {
int wMax = getInfos().size();
for (int wIdx = 0; wIdx < wMax; wIdx++) {
wJsonObj.accumulate(String.format("Info%02d", wIdx), getInfos()
.get(wIdx));
}
}
return wJsonObj;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
stopAll();
StringBuilder wSB = new StringBuilder();
wSB.append(String.format("%s=[%s]", COL_NAME_ID, getId()));
if (mustMeasureFreeMem()) {
wSB.append(String.format(" %s=[%d]", COL_NAME_FREE, pFreeMemory));
}
wSB.append(pNamedTimers.toString());
if (hasInfos()) {
int wMax = getInfos().size();
for (int wIdx = 0; wIdx < wMax; wIdx++) {
wSB.append(String.format(" Info%02d=[%s]", wIdx, getInfos()
.get(wIdx)));
}
}
return wSB.toString();
}
/**
* @return
*/
public String toXml() {
StringBuilder wSB = new StringBuilder();
wSB.append(String.format("<%s>", getId()));
if (mustMeasureFreeMem()) {
wSB.append(String.format("<%1$s>%2$s</%1$s>", COL_NAME_FREE,
pFreeMemory));
}
wSB.append(pNamedTimers.toXml());
if (hasInfos()) {
int wMax = getInfos().size();
for (int wIdx = 0; wIdx < wMax; wIdx++) {
wSB.append(String.format("<Info%1$02d>%2$s</Info%1$02d>", wIdx,
getInfos().get(wIdx)));
}
}
wSB.append(String.format("</%s>", getId()));
return wSB.toString();
}
}
| gpl-2.0 |
zhuming1987/mywork | TvApplication/src/com/tv/ui/widgets/ButtonConfigView.java | 1900 | package com.tv.ui.widgets;
import com.tv.app.R;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
public class ButtonConfigView extends ConfigView
{
private Button button;
private static int textSize = (int) (36 / dipDiv);
private static int textColorSelected = Color.BLACK;
private static int textColor = Color.WHITE;
public ButtonConfigView(Context context)
{
super(context);
button = new Button(context);
button.setTextSize(textSize);
button.setTextColor(textColor);
button.setGravity(Gravity.CENTER);
button.setBackgroundResource(R.drawable.btnbg);
button.setOnFocusChangeListener(new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
setSelected(hasFocus);
}
});
this.addView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
@Override
public void setSelected(boolean selected)
{
if (selected)
{
this.setScaleX(selectedScale);
this.setScaleY(selectedScale);
button.setBackgroundResource(R.drawable.btnbg_focus);
button.setTextColor(textColorSelected);
} else
{
this.setScaleX(1.0f);
this.setScaleY(1.0f);
button.setBackgroundResource(R.drawable.btnbg);
button.setTextColor(textColor);
}
}
public void setOnClickListener(OnClickListener listener)
{
button.setOnClickListener(listener);
}
public void setButtonText(String textStr)
{
button.setText(textStr);
}
public void setButtonText(int textResId)
{
button.setText(textResId);
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest10377.java | 2250 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest10377")
public class BenchmarkTest10377 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
java.util.Map<String,String[]> map = request.getParameterMap();
String param = "";
if (!map.isEmpty()) {
param = map.get("foo")[0];
}
String bar = new Test().doSomething(param);
new java.io.File(bar, "/Test.txt");
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
java.util.List<String> valuesList = new java.util.ArrayList<String>( );
valuesList.add("safe");
valuesList.add( param );
valuesList.add( "moresafe" );
valuesList.remove(0); // remove the 1st safe value
String bar = valuesList.get(0); // get the param value
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
KouChengjian/CamelCrown_Map | CamelCrown/CamelCrown/src/com/camel/redpenguin/view/code/decode/InactivityTimer.java | 1409 | package com.camel.redpenguin.view.code.decode;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
/**
* 作者: 陈涛(1076559197@qq.com)
*
* 时间: 2014年5月9日 下午12:25:12
*
* 版本: V_1.0.0
*
*/
public final class InactivityTimer {
private static final int INACTIVITY_DELAY_SECONDS = 5 * 60;
private final ScheduledExecutorService inactivityTimer = Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory());
private final Activity activity;
private ScheduledFuture<?> inactivityFuture = null;
public InactivityTimer(Activity activity) {
this.activity = activity;
onActivity();
}
public void onActivity() {
cancel();
inactivityFuture = inactivityTimer.schedule(new FinishListener(activity), INACTIVITY_DELAY_SECONDS, TimeUnit.SECONDS);
}
private void cancel() {
if (inactivityFuture != null) {
inactivityFuture.cancel(true);
inactivityFuture = null;
}
}
public void shutdown() {
cancel();
inactivityTimer.shutdown();
}
private static final class DaemonThreadFactory implements ThreadFactory {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
}
}
}
| gpl-2.0 |
nvllsvm/GZDoom-Android | doom/src/main/java/net/nullsum/doom/ModSelectDialog.java | 9187 | package net.nullsum.doom;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
class ModSelectDialog {
private final Dialog dialog;
private final String basePath;
private final boolean PrBoomMode;
private final ArrayList<String> filesArray = new ArrayList<>();
private final ArrayList<String> selectedArray = new ArrayList<>();
private final Activity activity;
private final TextView resultTextView;
private final TextView infoTextView;
private final ModsListAdapter listAdapter;
private String extraPath = "";
ModSelectDialog(Activity act, String path) {
basePath = path;
activity = act;
PrBoomMode = false;
dialog = new Dialog(activity);
dialog.setContentView(R.layout.dialog_select_mods_wads);
dialog.setTitle("Touch Control Sensitivity Settings");
dialog.setCancelable(true);
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
@Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (extraPath.isEmpty() || !extraPath.contains("/"))
return false;
else {
extraPath = extraPath.substring(0, extraPath.lastIndexOf("/"));
populateList(extraPath);
return true;
}
}
return false;
}
});
resultTextView = dialog.findViewById(R.id.result_textView);
infoTextView = dialog.findViewById(R.id.info_textView);
ListView listView = dialog.findViewById(R.id.listview);
listAdapter = new ModsListAdapter();
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (filesArray.get(position).startsWith("/")) {
populateList(extraPath + filesArray.get(position));
} else //select/deselect
{
boolean removed = false;
for (Iterator<String> iter = selectedArray.listIterator(); iter.hasNext(); ) {
String s = iter.next();
if (s.contentEquals(extraPath + "/" + filesArray.get(position))) {
iter.remove();
removed = true;
}
}
if (!removed)
selectedArray.add(extraPath + "/" + filesArray.get(position));
// Log.d("TEST","list size = " + selectedArray.size());
listAdapter.notifyDataSetChanged();
resultTextView.setText(getResult());
}
}
});
//Add folders on long press
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
if (filesArray.get(position).startsWith("/")) {
boolean removed = false;
String name = filesArray.get(position).substring(1, filesArray.get(position).length());
for (Iterator<String> iter = selectedArray.listIterator(); iter.hasNext(); ) {
String s = iter.next();
if (s.contentEquals(extraPath + "/" + name)) {
iter.remove();
removed = true;
}
}
if (!removed)
selectedArray.add(extraPath + "/" + name);
// Log.d("TEST","list size = " + selectedArray.size());
listAdapter.notifyDataSetChanged();
resultTextView.setText(getResult());
return true;
}
return false;
}
});
Button wads_button = dialog.findViewById(R.id.wads_button);
wads_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
populateList("wads");
}
});
Button mods_button = dialog.findViewById(R.id.mods_button);
mods_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
populateList("mods");
}
});
Button ok_button = dialog.findViewById(R.id.ok_button);
ok_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
resultResult(getResult());
}
});
populateList("wads");
dialog.show();
}
public void resultResult(String result) {
}
private String getResult() {
StringBuilder result = new StringBuilder();
if (PrBoomMode && selectedArray.size() > 0)
result = new StringBuilder("-file");
for (int n = 0; n < selectedArray.size(); n++) {
if (PrBoomMode)
result.append(" ").append(selectedArray.get(n));
else {
if ((selectedArray.get(n).endsWith(".deh")) || (selectedArray.get(n).endsWith(".bex")))
result.append("-deh ").append(selectedArray.get(n)).append(" ");
else
result.append("-file ").append(selectedArray.get(n)).append(" ");
}
}
return result.toString();
}
private void populateList(String path) {
extraPath = path;
dialog.setTitle(extraPath);
String wad_dir = basePath + "/" + path;
File files[] = new File(wad_dir).listFiles();
filesArray.clear();
if (files != null)
for (File f : files) {
if (!f.isDirectory()) {
String file = f.getName().toLowerCase();
if (file.endsWith(".wad") || file.endsWith(".pk3") || file.endsWith(".pk7") || file.endsWith(".deh")) {
filesArray.add(f.getName());
}
} else //Now also do directories
{
filesArray.add("/" + f.getName());
}
}
Collections.sort(filesArray);
if (filesArray.size() == 0)
infoTextView.setText("Please copy wad/mods to here: \"" + basePath + "/" + path + "\"");
else
infoTextView.setText("");
listAdapter.notifyDataSetChanged();
resultTextView.setText(getResult());
}
class ModsListAdapter extends BaseAdapter {
public ModsListAdapter() {
}
public int getCount() {
return filesArray.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup list) {
View view;
if (convertView == null)
view = activity.getLayoutInflater().inflate(R.layout.listview_item_mods_wads, null);
else
view = convertView;
boolean selected = false;
for (String s : selectedArray) {
if (s.contentEquals(extraPath + "/" + filesArray.get(position))) {
selected = true;
}
}
if (selected)
view.setBackgroundResource(R.drawable.layout_sel_background);
else
view.setBackgroundResource(0);
TextView title = view.findViewById(R.id.name_textview);
title.setText(filesArray.get(position));
return view;
}
}
}
| gpl-2.0 |
Esleelkartea/aon-employee | aonemployee_v2.3.0_src/paquetes descomprimidos/aon.ui.employee-2.3.0-sources/com/code/aon/common/tree/ITreeNode.java | 1017 | /*
* Created on 05-sep-2006
*
*/
package com.code.aon.common.tree;
import org.apache.myfaces.custom.tree2.TreeNode;
/**
*
* @author Consulting & Development. Iñaki Ayerbe - 05-sep-2006
* @since 1.0
*
*/
public interface ITreeNode extends TreeNode {
/**
* Devuelve un Object el elemento que representa el nodo.
*
* @return Devuelve el elemento que representa el nodo.
*/
Object getUserObject();
/**
* Devuelve un String con la acción a ejecutar.
*
* @return Devuelve la acción a ejecutar.
*/
String getReference();
/**
* Devuelve un String con el icono representando que el nodo está expandido.
*
* @return Devuelve el icono de elemento abierto.
*/
String getIconOpen();
/**
* Devuelve un String con el icono representando que el nodo está comprimido.
*
* @return Devuelve el icono de elemento cerrado.
*/
String getIconClose();
}
| gpl-2.0 |
imclab/WebImageBrowser | GWTspl/src/java/edu/ucsd/ncmir/spl/Graphics/Color.java | 15471 | package edu.ucsd.ncmir.spl.Graphics;
import java.util.HashMap;
/**
* A utility class to define and parse colors.
* @author spl
*/
public class Color
{
private final float _red;
private final float _green;
private final float _blue;
private final float _alpha;
public Color( float red, float green, float blue, float alpha )
{
this._red = red;
this._green = green;
this._blue = blue;
this._alpha = alpha;
}
public float getRed()
{
return this._red;
}
public float getGreen()
{
return this._green;
}
public float getBlue()
{
return this._blue;
}
public float getAlpha()
{
return this._alpha;
}
private static HashMap<String,Integer> _color =
new HashMap<String,Integer>();
static {
Color._color.put( "aliceblue", Color.rgb( 240, 248, 255 ) );
Color._color.put( "antiquewhite", Color.rgb( 250, 235, 215 ) );
Color._color.put( "aqua", Color.rgb( 0, 255, 255 ) );
Color._color.put( "aquamarine", Color.rgb( 127, 255, 212 ) );
Color._color.put( "azure", Color.rgb( 240, 255, 255 ) );
Color._color.put( "beige", Color.rgb( 245, 245, 220 ) );
Color._color.put( "bisque", Color.rgb( 255, 228, 196 ) );
Color._color.put( "black", Color.rgb( 0, 0, 0 ) );
Color._color.put( "blanchedalmond", Color.rgb( 255, 235, 205 ) );
Color._color.put( "blue", Color.rgb( 0, 0, 255 ) );
Color._color.put( "blueviolet", Color.rgb( 138, 43, 226 ) );
Color._color.put( "brown", Color.rgb( 165, 42, 42 ) );
Color._color.put( "burlywood", Color.rgb( 222, 184, 135 ) );
Color._color.put( "cadetblue", Color.rgb( 95, 158, 160 ) );
Color._color.put( "chartreuse", Color.rgb( 127, 255, 0 ) );
Color._color.put( "chocolate", Color.rgb( 210, 105, 30 ) );
Color._color.put( "coral", Color.rgb( 255, 127, 80 ) );
Color._color.put( "cornflowerblue", Color.rgb( 100, 149, 237 ) );
Color._color.put( "cornsilk", Color.rgb( 255, 248, 220 ) );
Color._color.put( "crimson", Color.rgb( 220, 20, 60 ) );
Color._color.put( "cyan", Color.rgb( 0, 255, 255 ) );
Color._color.put( "darkblue", Color.rgb( 0, 0, 139 ) );
Color._color.put( "darkcyan", Color.rgb( 0, 139, 139 ) );
Color._color.put( "darkgoldenrod", Color.rgb( 184, 134, 11 ) );
Color._color.put( "darkgray", Color.rgb( 169, 169, 169 ) );
Color._color.put( "darkgreen", Color.rgb( 0, 100, 0 ) );
Color._color.put( "darkgrey", Color.rgb( 169, 169, 169 ) );
Color._color.put( "darkkhaki", Color.rgb( 189, 183, 107 ) );
Color._color.put( "darkmagenta", Color.rgb( 139, 0, 139 ) );
Color._color.put( "darkolivegreen", Color.rgb( 85, 107, 47 ) );
Color._color.put( "darkorange", Color.rgb( 255, 140, 0 ) );
Color._color.put( "darkorchid", Color.rgb( 153, 50, 204 ) );
Color._color.put( "darkred", Color.rgb( 139, 0, 0 ) );
Color._color.put( "darksalmon", Color.rgb( 233, 150, 122 ) );
Color._color.put( "darkseagreen", Color.rgb( 143, 188, 143 ) );
Color._color.put( "darkslateblue", Color.rgb( 72, 61, 139 ) );
Color._color.put( "darkslategray", Color.rgb( 47, 79, 79 ) );
Color._color.put( "darkslategrey", Color.rgb( 47, 79, 79 ) );
Color._color.put( "darkturquoise", Color.rgb( 0, 206, 209 ) );
Color._color.put( "darkviolet", Color.rgb( 148, 0, 211 ) );
Color._color.put( "deeppink", Color.rgb( 255, 20, 147 ) );
Color._color.put( "deepskyblue", Color.rgb( 0, 191, 255 ) );
Color._color.put( "dimgray", Color.rgb( 105, 105, 105 ) );
Color._color.put( "dimgrey", Color.rgb( 105, 105, 105 ) );
Color._color.put( "dodgerblue", Color.rgb( 30, 144, 255 ) );
Color._color.put( "firebrick", Color.rgb( 178, 34, 34 ) );
Color._color.put( "floralwhite", Color.rgb( 255, 250, 240 ) );
Color._color.put( "forestgreen", Color.rgb( 34, 139, 34 ) );
Color._color.put( "fuchsia", Color.rgb( 255, 0, 255 ) );
Color._color.put( "gainsboro", Color.rgb( 220, 220, 220 ) );
Color._color.put( "ghostwhite", Color.rgb( 248, 248, 255 ) );
Color._color.put( "gold", Color.rgb( 255, 215, 0 ) );
Color._color.put( "goldenrod", Color.rgb( 218, 165, 32 ) );
Color._color.put( "gray", Color.rgb( 128, 128, 128 ) );
Color._color.put( "grey", Color.rgb( 128, 128, 128 ) );
Color._color.put( "green", Color.rgb( 0, 128, 0 ) );
Color._color.put( "greenyellow", Color.rgb( 173, 255, 47 ) );
Color._color.put( "honeydew", Color.rgb( 240, 255, 240 ) );
Color._color.put( "hotpink", Color.rgb( 255, 105, 180 ) );
Color._color.put( "indianred", Color.rgb( 205, 92, 92 ) );
Color._color.put( "indigo", Color.rgb( 75, 0, 130 ) );
Color._color.put( "ivory", Color.rgb( 255, 255, 240 ) );
Color._color.put( "khaki", Color.rgb( 240, 230, 140 ) );
Color._color.put( "lavender", Color.rgb( 230, 230, 250 ) );
Color._color.put( "lavenderblush", Color.rgb( 255, 240, 245 ) );
Color._color.put( "lawngreen", Color.rgb( 124, 252, 0 ) );
Color._color.put( "lemonchiffon", Color.rgb( 255, 250, 205 ) );
Color._color.put( "lightblue", Color.rgb( 173, 216, 230 ) );
Color._color.put( "lightcoral", Color.rgb( 240, 128, 128 ) );
Color._color.put( "lightcyan", Color.rgb( 224, 255, 255 ) );
Color._color.put( "lightgoldenrodyellow", Color.rgb( 250, 250, 210 ) );
Color._color.put( "lightgray", Color.rgb( 211, 211, 211 ) );
Color._color.put( "lightgreen", Color.rgb( 144, 238, 144 ) );
Color._color.put( "lightgrey", Color.rgb( 211, 211, 211 ) );
Color._color.put( "lightpink", Color.rgb( 255, 182, 193 ) );
Color._color.put( "lightsalmon", Color.rgb( 255, 160, 122 ) );
Color._color.put( "lightseagreen", Color.rgb( 32, 178, 170 ) );
Color._color.put( "lightskyblue", Color.rgb( 135, 206, 250 ) );
Color._color.put( "lightslategray", Color.rgb( 119, 136, 153 ) );
Color._color.put( "lightslategrey", Color.rgb( 119, 136, 153 ) );
Color._color.put( "lightsteelblue", Color.rgb( 176, 196, 222 ) );
Color._color.put( "lightyellow", Color.rgb( 255, 255, 224 ) );
Color._color.put( "lime", Color.rgb( 0, 255, 0 ) );
Color._color.put( "limegreen", Color.rgb( 50, 205, 50 ) );
Color._color.put( "linen", Color.rgb( 250, 240, 230 ) );
Color._color.put( "magenta", Color.rgb( 255, 0, 255 ) );
Color._color.put( "maroon", Color.rgb( 128, 0, 0 ) );
Color._color.put( "mediumaquamarine", Color.rgb( 102, 205, 170 ) );
Color._color.put( "mediumblue", Color.rgb( 0, 0, 205 ) );
Color._color.put( "mediumorchid", Color.rgb( 186, 85, 211 ) );
Color._color.put( "mediumpurple", Color.rgb( 147, 112, 219 ) );
Color._color.put( "mediumseagreen", Color.rgb( 60, 179, 113 ) );
Color._color.put( "mediumslateblue", Color.rgb( 123, 104, 238 ) );
Color._color.put( "mediumspringgreen", Color.rgb( 0, 250, 154 ) );
Color._color.put( "mediumturquoise", Color.rgb( 72, 209, 204 ) );
Color._color.put( "mediumvioletred", Color.rgb( 199, 21, 133 ) );
Color._color.put( "midnightblue", Color.rgb( 25, 25, 112 ) );
Color._color.put( "mintcream", Color.rgb( 245, 255, 250 ) );
Color._color.put( "mistyrose", Color.rgb( 255, 228, 225 ) );
Color._color.put( "moccasin", Color.rgb( 255, 228, 181 ) );
Color._color.put( "navajowhite", Color.rgb( 255, 222, 173 ) );
Color._color.put( "navy", Color.rgb( 0, 0, 128 ) );
Color._color.put( "oldlace", Color.rgb( 253, 245, 230 ) );
Color._color.put( "olive", Color.rgb( 128, 128, 0 ) );
Color._color.put( "olivedrab", Color.rgb( 107, 142, 35 ) );
Color._color.put( "orange", Color.rgb( 255, 165, 0 ) );
Color._color.put( "orangered", Color.rgb( 255, 69, 0 ) );
Color._color.put( "orchid", Color.rgb( 218, 112, 214 ) );
Color._color.put( "palegoldenrod", Color.rgb( 238, 232, 170 ) );
Color._color.put( "palegreen", Color.rgb( 152, 251, 152 ) );
Color._color.put( "paleturquoise", Color.rgb( 175, 238, 238 ) );
Color._color.put( "palevioletred", Color.rgb( 219, 112, 147 ) );
Color._color.put( "papayawhip", Color.rgb( 255, 239, 213 ) );
Color._color.put( "peachpuff", Color.rgb( 255, 218, 185 ) );
Color._color.put( "peru", Color.rgb( 205, 133, 63 ) );
Color._color.put( "pink", Color.rgb( 255, 192, 203 ) );
Color._color.put( "plum", Color.rgb( 221, 160, 221 ) );
Color._color.put( "powderblue", Color.rgb( 176, 224, 230 ) );
Color._color.put( "purple", Color.rgb( 128, 0, 128 ) );
Color._color.put( "red", Color.rgb( 255, 0, 0 ) );
Color._color.put( "rosybrown", Color.rgb( 188, 143, 143 ) );
Color._color.put( "royalblue", Color.rgb( 65, 105, 225 ) );
Color._color.put( "saddlebrown", Color.rgb( 139, 69, 19 ) );
Color._color.put( "salmon", Color.rgb( 250, 128, 114 ) );
Color._color.put( "sandybrown", Color.rgb( 244, 164, 96 ) );
Color._color.put( "seagreen", Color.rgb( 46, 139, 87 ) );
Color._color.put( "seashell", Color.rgb( 255, 245, 238 ) );
Color._color.put( "sienna", Color.rgb( 160, 82, 45 ) );
Color._color.put( "silver", Color.rgb( 192, 192, 192 ) );
Color._color.put( "skyblue", Color.rgb( 135, 206, 235 ) );
Color._color.put( "slateblue", Color.rgb( 106, 90, 205 ) );
Color._color.put( "slategray", Color.rgb( 112, 128, 144 ) );
Color._color.put( "slategrey", Color.rgb( 112, 128, 144 ) );
Color._color.put( "snow", Color.rgb( 255, 250, 250 ) );
Color._color.put( "springgreen", Color.rgb( 0, 255, 127 ) );
Color._color.put( "steelblue", Color.rgb( 70, 130, 180 ) );
Color._color.put( "tan", Color.rgb( 210, 180, 140 ) );
Color._color.put( "teal", Color.rgb( 0, 128, 128 ) );
Color._color.put( "thistle", Color.rgb( 216, 191, 216 ) );
Color._color.put( "tomato", Color.rgb( 255, 99, 71 ) );
Color._color.put( "turquoise", Color.rgb( 64, 224, 208 ) );
Color._color.put( "violet", Color.rgb( 238, 130, 238 ) );
Color._color.put( "wheat", Color.rgb( 245, 222, 179 ) );
Color._color.put( "white", Color.rgb( 255, 255, 255 ) );
Color._color.put( "whitesmoke", Color.rgb( 245, 245, 245 ) );
Color._color.put( "yellow", Color.rgb( 255, 255, 0 ) );
Color._color.put( "yellowgreen", Color.rgb( 154, 205, 50 ) );
}
private static Integer rgb( int red, int green, int blue )
{
return new Integer( Color.concatenateRGB( red, green, blue ) );
}
/**
* Concatenates the <i>red</i>, <i>green</i>, and <i>blue</i>
* values into a packed integer. Out of range values (outside
* 0..255) are clamped to modulo 256.
* @param red The <i>red</i> component.
* @param green The <i>green</i> component.
* @param blue The <i>blue</i> component.
* @return A packed integer value of the form 0x00rrggbb.
*/
public static int concatenateRGB( int red, int green, int blue )
{
return ( ( red & 0x000000ff ) << 16 ) |
( ( green & 0x000000ff ) << 8 ) |
( blue & 0x000000ff );
}
/**
* Parses a <code>String</code> either by name, a hexadecimal
* string, a decimal string, or an CSS rgb() triplet, returning
* packed integer. Handles hex strings of the form
* "#rgb", "#rrggbb", or
* "#rrrrggggbbbb". 16 bit values are truncated to 8
* bits by shifting.
* @param color The string representation.
* @return The packed integer value of the string.
*/
public static int parseRGB( String color )
{
Integer rgb = Color._color.get( color );
return ( rgb != null ) ? rgb.intValue() : Color.parse( color );
}
/**
* Parses a <code>String</code> either by name, a hexadecimal
* string, a decimal string, or an CSS rgb() triplet, returning
* packed integer. Handles hex strings of the form
* "#rgb", "#rrggbb", or
* "#rrrrggggbbbb". 16 bit values are truncated to 8
* bits by shifting.
* @param color The string representation.
* @return An array of length 3 containing, in order, the
* <i>red</i>, <i>green</i>, and <i>blue</i> components of the
* color. Values are constrained to be within the range 0..255.
*/
public static int[] parseRGBToTriplet( String color )
{
int rgb = Color.parseRGB( color );
return new int[] {
( rgb >> 16 ) & 0xff,
( rgb >> 8 ) & 0xff,
rgb & 0xff
};
}
private static final String HEX = "0123456789abcdef";
private static int hexconv( String hex, int shift )
{
int hexval = 0;
for ( int i = 0; i < hex.length(); i++ )
hexval =
( hexval << 4 ) | HEX.indexOf( hex.substring( i, i + 1 ) );
return hexval << shift;
}
private static int parse( String color )
{
int rgb = 0xffff00;
if ( color != null ) {
color = color.toLowerCase();
if ( color.matches( "^#[0-9a-f]+$" ) ) {
int hexlength = 0;
int shift = 0;
if ( color.length() == 4 ) {
hexlength = 1;
shift = 4;
} else if ( color.length() == 7 )
hexlength = 2;
else if ( color.length() == 13 ) {
hexlength = 4;
shift = -8;
}
rgb = 0;
for ( int i = 1; i < color.length(); i += hexlength )
rgb = ( rgb << 8 ) +
Color.hexconv( color.substring( i, i + hexlength ),
shift );
} else if ( color.matches( "^[0-9]+$" ) )
rgb = Integer.parseInt( color );
else if ( color.startsWith( "rgb" ) ) {
String[] c = color.replaceAll( "[^0-9 ]+", "" ).split( " " );
rgb = Color.concatenateRGB( Integer.parseInt( c[0] ),
Integer.parseInt( c[1] ),
Integer.parseInt( c[2] ) );
}
}
return rgb;
}
public static byte RGBToGray( byte r, byte g, byte b )
{
int R = ( ( ( int ) r ) + 256 ) & 0xff;
int G = ( ( ( int ) g ) + 256 ) & 0xff;
int B = ( ( ( int ) b ) + 256 ) & 0xff;
return ( byte ) ( ( 0.30* R ) + ( 0.59 * G ) + ( 0.11 * B ) );
}
public static double[] HSVToRGB( double h, double s, double v )
{
double[] rgb = new double[3];
if ( s == 0.0 ) {
if ( h < 0.0 ) {
rgb[0] = v;
rgb[1] = v;
rgb[2] = v;
} else
throw new IllegalArgumentException( "hsv2rgb error, " +
"Invalid combination." );
} else {
if ( !( ( 0 <= h ) && ( h < 360 ) ) )
h = h - ( ( ( int ) ( h / 360.0 ) ) * 360.0 );
if ( h < 0.0 )
h += 360.0;
if ( h == 360.0 )
h = 0.0;
h /= 60.0;
int i = ( int ) Math.floor( h );
double f = h - i;
double p = v * ( 1.0 - s );
double q = v * ( 1.0 - ( s * f ) );
double t = v * ( 1.0 - ( s * ( 1.0 - f ) ) );
switch ( i ) {
case 0: {
rgb[0] = v;
rgb[1] = t;
rgb[2] = p;
break;
}
case 1: {
rgb[0] = q;
rgb[1] = v;
rgb[2] = p;
break;
}
case 2: {
rgb[0] = p;
rgb[1] = v;
rgb[2] = t;
break;
}
case 3: {
rgb[0] = p;
rgb[1] = q;
rgb[2] = v;
break;
}
case 4: {
rgb[0] = t;
rgb[1] = p;
rgb[2] = v;
break;
}
case 5: {
rgb[0] = v;
rgb[1] = p;
rgb[2] = q;
break;
}
default: {
String message =
"hsv2rgb error, Invalid case! case = " + i;
throw new IllegalArgumentException( message );
}
}
}
return rgb;
}
private static final double _M = 3.0;
private static final double _BR = 0.0;
private static final double _BG = -1.0;
private static final double _BB = -2.0;
public static double[] heatmap( double x )
{
double r = ( Color._M * x ) + Color._BR;
double g = ( Color._M * x ) + Color._BG;
double b = ( Color._M * x ) + Color._BB;
if ( r < 0 )
r = 0;
else if ( r > 1 )
r = 1;
if ( g < 0 )
g = 0;
else if ( g > 1 )
g = 1;
if ( b < 0 )
b = 0;
else if ( b > 1 )
b = 1;
return new double[] { r, g, b };
}
}
| gpl-2.0 |
flaviolima/uri-problems-solved | src/Problem1020.java | 472 | import java.util.Scanner;
public class Problem1020 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int idade = scan.nextInt();
int anos = idade / 365;
int meses = (idade % 365) / 30;
int dias =(idade % 365) % 30;
System.out.printf("%d ano(s)\n",anos);
System.out.printf("%d mes(es)\n",meses);
System.out.printf("%d dia(s)\n",dias);
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/corba/src/share/classes/com/sun/corba/se/impl/resolver/BootstrapResolverImpl.java | 6060 | /*
* Copyright 2002-2004 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.corba.se.impl.resolver ;
import org.omg.CORBA.portable.InputStream ;
import org.omg.CORBA.portable.OutputStream ;
import org.omg.CORBA.portable.ApplicationException ;
import org.omg.CORBA.portable.RemarshalException ;
import com.sun.corba.se.spi.ior.IOR ;
import com.sun.corba.se.spi.ior.IORFactories ;
import com.sun.corba.se.spi.ior.IORTemplate ;
import com.sun.corba.se.spi.ior.ObjectKey ;
import com.sun.corba.se.spi.ior.ObjectKeyFactory ;
import com.sun.corba.se.spi.ior.iiop.IIOPAddress ;
import com.sun.corba.se.spi.ior.iiop.IIOPProfileTemplate ;
import com.sun.corba.se.spi.ior.iiop.IIOPFactories ;
import com.sun.corba.se.spi.ior.iiop.GIOPVersion ;
import com.sun.corba.se.spi.logging.CORBALogDomains ;
import com.sun.corba.se.spi.orb.ORB ;
import com.sun.corba.se.spi.resolver.Resolver ;
import com.sun.corba.se.impl.logging.ORBUtilSystemException ;
import com.sun.corba.se.impl.orbutil.ORBUtility ;
public class BootstrapResolverImpl implements Resolver {
private org.omg.CORBA.portable.Delegate bootstrapDelegate ;
private ORBUtilSystemException wrapper ;
public BootstrapResolverImpl(ORB orb, String host, int port) {
wrapper = ORBUtilSystemException.get( orb,
CORBALogDomains.ORB_RESOLVER ) ;
// Create a new IOR with the magic of INIT
byte[] initialKey = "INIT".getBytes() ;
ObjectKey okey = orb.getObjectKeyFactory().create(initialKey) ;
IIOPAddress addr = IIOPFactories.makeIIOPAddress( orb, host, port ) ;
IIOPProfileTemplate ptemp = IIOPFactories.makeIIOPProfileTemplate(
orb, GIOPVersion.V1_0, addr);
IORTemplate iortemp = IORFactories.makeIORTemplate( okey.getTemplate() ) ;
iortemp.add( ptemp ) ;
IOR initialIOR = iortemp.makeIOR( (com.sun.corba.se.spi.orb.ORB)orb,
"", okey.getId() ) ;
bootstrapDelegate = ORBUtility.makeClientDelegate( initialIOR ) ;
}
/**
* For the BootStrap operation we do not expect to have more than one
* parameter. We do not want to extend BootStrap protocol any further,
* as INS handles most of what BootStrap can handle in a portable way.
*
* @return InputStream which contains the response from the
* BootStrapOperation.
*/
private InputStream invoke( String operationName, String parameter )
{
boolean remarshal = true;
// Invoke.
InputStream inStream = null;
// If there is a location forward then you will need
// to invoke again on the updated information.
// Just calling this same routine with the same host/port
// does not take the location forward info into account.
while (remarshal) {
org.omg.CORBA.Object objref = null ;
remarshal = false;
OutputStream os = (OutputStream) bootstrapDelegate.request( objref,
operationName, true);
if ( parameter != null ) {
os.write_string( parameter );
}
try {
// The only reason a null objref is passed is to get the version of
// invoke used by streams. Otherwise the PortableInterceptor
// call stack will become unbalanced since the version of
// invoke which only takes the stream does not call
// PortableInterceptor ending points.
// Note that the first parameter is ignored inside invoke.
inStream = bootstrapDelegate.invoke( objref, os);
} catch (ApplicationException e) {
throw wrapper.bootstrapApplicationException( e ) ;
} catch (RemarshalException e) {
// XXX log this
remarshal = true;
}
}
return inStream;
}
public org.omg.CORBA.Object resolve( String identifier )
{
InputStream inStream = null ;
org.omg.CORBA.Object result = null ;
try {
inStream = invoke( "get", identifier ) ;
result = inStream.read_Object();
// NOTE: do note trap and ignore errors.
// Let them flow out.
} finally {
bootstrapDelegate.releaseReply( null, inStream ) ;
}
return result ;
}
public java.util.Set list()
{
InputStream inStream = null ;
java.util.Set result = new java.util.HashSet() ;
try {
inStream = invoke( "list", null ) ;
int count = inStream.read_long();
for (int i=0; i < count; i++)
result.add( inStream.read_string() ) ;
// NOTE: do note trap and ignore errors.
// Let them flow out.
} finally {
bootstrapDelegate.releaseReply( null, inStream ) ;
}
return result ;
}
}
| gpl-2.0 |