repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
loftuxab/community-edition-old | projects/cmis-tck-ws/source/generated/org/alfresco/repo/cmis/ws/CmisTypeContainer.java | 7050 | /**
* CmisTypeContainer.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package org.alfresco.repo.cmis.ws;
public class CmisTypeContainer implements java.io.Serializable, org.apache.axis.encoding.AnyContentType {
private org.alfresco.repo.cmis.ws.CmisTypeDefinitionType type;
private org.alfresco.repo.cmis.ws.CmisTypeContainer[] children;
private org.apache.axis.message.MessageElement [] _any;
public CmisTypeContainer() {
}
public CmisTypeContainer(
org.alfresco.repo.cmis.ws.CmisTypeDefinitionType type,
org.alfresco.repo.cmis.ws.CmisTypeContainer[] children,
org.apache.axis.message.MessageElement [] _any) {
this.type = type;
this.children = children;
this._any = _any;
}
/**
* Gets the type value for this CmisTypeContainer.
*
* @return type
*/
public org.alfresco.repo.cmis.ws.CmisTypeDefinitionType getType() {
return type;
}
/**
* Sets the type value for this CmisTypeContainer.
*
* @param type
*/
public void setType(org.alfresco.repo.cmis.ws.CmisTypeDefinitionType type) {
this.type = type;
}
/**
* Gets the children value for this CmisTypeContainer.
*
* @return children
*/
public org.alfresco.repo.cmis.ws.CmisTypeContainer[] getChildren() {
return children;
}
/**
* Sets the children value for this CmisTypeContainer.
*
* @param children
*/
public void setChildren(org.alfresco.repo.cmis.ws.CmisTypeContainer[] children) {
this.children = children;
}
public org.alfresco.repo.cmis.ws.CmisTypeContainer getChildren(int i) {
return this.children[i];
}
public void setChildren(int i, org.alfresco.repo.cmis.ws.CmisTypeContainer _value) {
this.children[i] = _value;
}
/**
* Gets the _any value for this CmisTypeContainer.
*
* @return _any
*/
public org.apache.axis.message.MessageElement [] get_any() {
return _any;
}
/**
* Sets the _any value for this CmisTypeContainer.
*
* @param _any
*/
public void set_any(org.apache.axis.message.MessageElement [] _any) {
this._any = _any;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof CmisTypeContainer)) return false;
CmisTypeContainer other = (CmisTypeContainer) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.type==null && other.getType()==null) ||
(this.type!=null &&
this.type.equals(other.getType()))) &&
((this.children==null && other.getChildren()==null) ||
(this.children!=null &&
java.util.Arrays.equals(this.children, other.getChildren()))) &&
((this._any==null && other.get_any()==null) ||
(this._any!=null &&
java.util.Arrays.equals(this._any, other.get_any())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getType() != null) {
_hashCode += getType().hashCode();
}
if (getChildren() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getChildren());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getChildren(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (get_any() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(get_any());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(get_any(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(CmisTypeContainer.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://docs.oasis-open.org/ns/cmis/messaging/200908/", "cmisTypeContainer"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("type");
elemField.setXmlName(new javax.xml.namespace.QName("http://docs.oasis-open.org/ns/cmis/messaging/200908/", "type"));
elemField.setXmlType(new javax.xml.namespace.QName("http://docs.oasis-open.org/ns/cmis/core/200908/", "cmisTypeDefinitionType"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("children");
elemField.setXmlName(new javax.xml.namespace.QName("http://docs.oasis-open.org/ns/cmis/messaging/200908/", "children"));
elemField.setXmlType(new javax.xml.namespace.QName("http://docs.oasis-open.org/ns/cmis/messaging/200908/", "cmisTypeContainer"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| lgpl-3.0 |
DANCEcollaborative/bazaar | FancyDemoAgent/src/basilica2/myagent/operation/FancyTalkRunner.java | 1048 | package basilica2.myagent.operation;
import basilica2.agents.operation.BaseAgentOperation;
import basilica2.agents.operation.BaseAgentUI;
import basilica2.agents.operation.ConditionAgentUI;
public class FancyTalkRunner extends BaseAgentOperation
{
public static void main(String[] args)
{
initializeSystemProperties("system.properties");
java.awt.EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
FancyTalkRunner thisOperation = new FancyTalkRunner();
String[] conditions = thisOperation.getProperties().getProperty("operation.conditions", "").split("[\\s,]+");
String room = thisOperation.getProperties().getProperty("operation.room", "Test01");
BaseAgentUI thisUI = new ConditionAgentUI(thisOperation, room, conditions);
thisOperation.setUI(thisUI);
thisOperation.startOperation();
thisUI.operationStarted();
}
});
}
}
| lgpl-3.0 |
mckayb24/Ushahidi_Android | Core/src/com/ushahidi/android/app/Preferences.java | 3529 |
package com.ushahidi.android.app;
import java.io.File;
import android.content.Context;
import android.content.SharedPreferences;
public class Preferences {
public static boolean httpRunning = false;
public static boolean AutoFetch = false;
public static boolean vibrate = false;
public static boolean ringtone = false;
public static boolean flashLed = false;
public static int countries = 0;
public static int AutoUpdateDelay = 0;
public static final int NOTIFICATION_ID = 1;
public static final String PREFS_NAME = "UshahidiService";
public static String incidentsResponse = "";
public static String categoriesResponse = "";
public static String savePath = "";
public static String domain = "";
public static String firstname = "";
public static String lastname = "";
public static String email = "";
public static String totalReports = "";
public static String fileName = "";
public static int isCheckinEnabled = 0;
public static int appRunsFirstTime = 0;
public static int activeDeployment = 0;
public static int photoWidth = 200;
public static String deploymentLatitude = "0.0";
public static String deploymentLongitude = "0.0";
private static SharedPreferences settings;
private static SharedPreferences.Editor editor;
public static String totalReportsFetched = "";
public static String username = "";
public static String password = "";
public static void loadSettings(Context context) {
final SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
final String path = context.getDir("",
Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE).toString();
savePath = settings.getString("savePath", path);
domain = settings.getString("Domain", Preferences.domain);
firstname = settings.getString("Firstname", "");
lastname = settings.getString("Lastname", "");
email = settings.getString("Email", "");
countries = settings.getInt("Countries", 0);
AutoUpdateDelay = settings.getInt("AutoUpdateDelay", 5);
AutoFetch = settings.getBoolean("AutoFetch", false);
totalReports = settings.getString("TotalReports", "20");
isCheckinEnabled = settings.getInt("CheckinEnabled", isCheckinEnabled);
activeDeployment = settings.getInt("ActiveDeployment", 0);
deploymentLatitude = settings.getString("DeploymentLatitude", "0.0");
deploymentLongitude = settings.getString("DeploymentLongitude", "0.0");
photoWidth = settings.getInt("PhotoWidth", 200);
appRunsFirstTime = settings.getInt("AppRunsFirstTime", appRunsFirstTime);
username = settings.getString("username", "");
password = settings.getString("password","");
// make sure folder exists
final File dir = new File(Preferences.savePath);
dir.mkdirs();
}
public static void saveSettings(Context context) {
settings = context.getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
editor.putString("Domain", domain);
editor.putInt("CheckinEnabled", isCheckinEnabled);
editor.putInt("ActiveDeployment", activeDeployment);
editor.putString("DeploymentLatitude", deploymentLatitude);
editor.putString("DeploymentLongitude", deploymentLongitude);
editor.putInt("AppRunsFirstTime", appRunsFirstTime);
editor.commit();
}
}
| lgpl-3.0 |
FunThomas424242/forge.example | src/test/java/com/github/funthomas/examples/forge/CreateSpringBootStarterProjectTest.java | 302 | package com.github.funthomas.examples.forge;
import org.junit.Ignore;
import org.junit.Test;
public class CreateSpringBootStarterProjectTest {
@Test
@Ignore
public void test() {
final CreateSpringBootStarterProject excecutor = new CreateSpringBootStarterProject();
excecutor.run();
}
}
| lgpl-3.0 |
racodond/sonar-css-plugin | css-frontend/src/main/java/org/sonar/plugins/css/api/tree/css/DeclarationTree.java | 1128 | /*
* SonarQube CSS / SCSS / Less Analyzer
* Copyright (C) 2013-2017 David RACODON
* mailto: david.racodon@gmail.com
*
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.css.api.tree.css;
import org.sonar.plugins.css.api.tree.Tree;
import javax.annotation.Nullable;
public interface DeclarationTree extends Tree {
SyntaxToken colon();
ValueTree value();
@Nullable
SyntaxToken semicolon();
}
| lgpl-3.0 |
UniTime/cpsolver | src/org/cpsolver/ifs/solver/Solver.java | 29279 | package org.cpsolver.ifs.solver;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.concurrent.locks.Lock;
import org.cpsolver.ifs.assignment.DefaultSingleAssignment;
import org.cpsolver.ifs.extension.ConflictStatistics;
import org.cpsolver.ifs.extension.Extension;
import org.cpsolver.ifs.extension.MacPropagation;
import org.cpsolver.ifs.heuristics.NeighbourSelection;
import org.cpsolver.ifs.heuristics.StandardNeighbourSelection;
import org.cpsolver.ifs.heuristics.ValueSelection;
import org.cpsolver.ifs.heuristics.VariableSelection;
import org.cpsolver.ifs.model.Model;
import org.cpsolver.ifs.model.Neighbour;
import org.cpsolver.ifs.model.Value;
import org.cpsolver.ifs.model.Variable;
import org.cpsolver.ifs.perturbations.DefaultPerturbationsCounter;
import org.cpsolver.ifs.perturbations.PerturbationsCounter;
import org.cpsolver.ifs.solution.GeneralSolutionComparator;
import org.cpsolver.ifs.solution.Solution;
import org.cpsolver.ifs.solution.SolutionComparator;
import org.cpsolver.ifs.termination.GeneralTerminationCondition;
import org.cpsolver.ifs.termination.TerminationCondition;
import org.cpsolver.ifs.util.DataProperties;
import org.cpsolver.ifs.util.JProf;
import org.cpsolver.ifs.util.Progress;
import org.cpsolver.ifs.util.ToolBox;
/**
* IFS Solver. <br>
* <br>
* The iterative forward search (IFS) algorithm is based on ideas of local
* search methods. However, in contrast to classical local search techniques, it
* operates over feasible, though not necessarily complete solutions. In such a
* solution, some variables can be left unassigned. Still all hard constraints
* on assigned variables must be satisfied. Similarly to backtracking based
* algorithms, this means that there are no violations of hard constraints. <br>
* <br>
* This search works in iterations. During each step, an unassigned or assigned
* variable is initially selected. Typically an unassigned variable is chosen
* like in backtracking-based search. An assigned variable may be selected when
* all variables are assigned but the solution is not good enough (for example,
* when there are still many violations of soft constraints). Once a variable is
* selected, a value from its domain is chosen for assignment. Even if the best
* value is selected (whatever "best" means), its assignment to the selected
* variable may cause some hard conflicts with already assigned variables. Such
* conflicting variables are removed from the solution and become unassigned.
* Finally, the selected value is assigned to the selected variable. <br>
* <br>
* Algorithm schema:
* <pre><code>
* procedure org.cpsolver.ifs(initial) // initial solution is the parameter
* iteration = 0; // iteration counter
* current = initial; // current (partial) feasible solution
* best = initial; // best solution
* while canContinue(current, iteration) do
* iteration = iteration + 1;
* variable = selectVariable(current);
* value = selectValue(current, variable);
* UNASSIGN(current, CONFLICTING_VARIABLES(current, variable, value));
* ASSIGN(current, variable, value);
* if better(current, best) then best = current;
* end while
* return best;
* end procedure
* </code></pre>
* The algorithm attempts to move from one (partial) feasible solution to
* another via repetitive assignment of a selected value to a selected variable.
* During this search, the feasibility of all hard constraints in each iteration
* step is enforced by unassigning the conflicting variables. The search is
* terminated when the requested solution is found or when there is a timeout,
* expressed e.g., as a maximal number of iterations or available time being
* reached. The best solution found is then returned. <br>
* <br>
* The above algorithm schema is parameterized by several functions, namely:
* <ul>
* <li>the termination condition (function canContinue, see
* {@link TerminationCondition}),
* <li>the solution comparator (function better, see {@link SolutionComparator}
* ),
* <li>the neighbour selection (function selectNeighbour, see
* {@link NeighbourSelection}) and
* </ul>
* <br>
* Usage:
* <pre><code>
* DataProperties cfg = ToolBox.loadProperties(inputCfg); //input configuration
* Solver solver = new Solver(cfg);
* solver.setInitalSolution(model); //sets initial solution
*
* solver.start(); //server is executed in a thread
*
* try { //wait untill the server finishes
* solver.getSolverThread().join();
* } catch (InterruptedException e) {}
*
* Solution solution = solver.lastSolution(); //last solution
* solution.restoreBest(); //restore best solution ever found
* </code></pre>
* Solver's parameters: <br>
* <table border='1' summary='Related Solver Parameters'>
* <tr>
* <th>Parameter</th>
* <th>Type</th>
* <th>Comment</th>
* </tr>
* <tr>
* <td>General.SaveBestUnassigned</td>
* <td>{@link Integer}</td>
* <td>During the search, solution is saved when it is the best ever found
* solution and if the number of assigned variables is less or equal this
* parameter (if set to -1, the solution is always saved)</td>
* </tr>
* <tr>
* <td>General.Seed</td>
* <td>{@link Long}</td>
* <td>If set, random number generator is initialized with this seed</td>
* </tr>
* <tr>
* <td>General.SaveConfiguration</td>
* <td>{@link Boolean}</td>
* <td>If true, given configuration is stored into the output folder (during
* initialization of the solver,
* ${General.Output}/${General.ProblemName}.properties)</td>
* </tr>
* <tr>
* <td>Solver.AutoConfigure</td>
* <td>{@link Boolean}</td>
* <td>If true, IFS Solver is configured according to the following parameters</td>
* </tr>
* <tr>
* <td>Termination.Class</td>
* <td>{@link String}</td>
* <td>Fully qualified class name of the termination condition (see
* {@link TerminationCondition}, e.g. {@link GeneralTerminationCondition})</td>
* </tr>
* <tr>
* <td>Comparator.Class</td>
* <td>{@link String}</td>
* <td>Fully qualified class name of the solution comparator (see
* {@link SolutionComparator}, e.g. {@link GeneralSolutionComparator})</td>
* </tr>
* <tr>
* <td>Neighbour.Class</td>
* <td>{@link String}</td>
* <td>Fully qualified class name of the neighbour selection criterion (see
* {@link NeighbourSelection}, e.g. {@link StandardNeighbourSelection})</td>
* </tr>
* <tr>
* <td>PerturbationCounter.Class</td>
* <td>{@link String}</td>
* <td>Fully qualified class name of the perturbation counter in case of solving
* minimal perturbation problem (see {@link PerturbationsCounter}, e.g.
* {@link DefaultPerturbationsCounter})</td>
* </tr>
* <tr>
* <td>Extensions.Classes</td>
* <td>{@link String}</td>
* <td>Semi-colon separated list of fully qualified class names of IFS
* extensions (see {@link Extension}, e.g. {@link ConflictStatistics} or
* {@link MacPropagation})</td>
* </tr>
* </table>
*
* @see SolverListener
* @see Model
* @see Solution
* @see TerminationCondition
* @see SolutionComparator
* @see PerturbationsCounter
* @see VariableSelection
* @see ValueSelection
* @see Extension
*
* @version IFS 1.3 (Iterative Forward Search)<br>
* Copyright (C) 2006 - 2014 Tomas Muller<br>
* <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
* <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
* <br>
* 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 3 of the
* License, or (at your option) any later version. <br>
* <br>
* 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. <br>
* <br>
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not see <a href='http://www.gnu.org/licenses'>http://www.gnu.org/licenses</a>.
*
* @param <V> Variable
* @param <T> Value
**/
public class Solver<V extends Variable<V, T>, T extends Value<V, T>> {
public static int THREAD_PRIORITY = 3;
/** log */
protected static org.apache.logging.log4j.Logger sLogger = org.apache.logging.log4j.LogManager.getLogger(Solver.class);
/** current solution */
protected Solution<V, T> iCurrentSolution = null;
/** last solution (after IFS Solver finishes) */
protected Solution<V, T> iLastSolution = null;
/** solver is stopped */
protected boolean iStop = false;
/** solver thread */
protected SolverThread iSolverThread = null;
/** configuration */
private DataProperties iProperties = null;
private TerminationCondition<V, T> iTerminationCondition = null;
private SolutionComparator<V, T> iSolutionComparator = null;
private PerturbationsCounter<V, T> iPerturbationsCounter = null;
private NeighbourSelection<V, T> iNeighbourSelection = null;
private List<Extension<V, T>> iExtensions = new ArrayList<Extension<V, T>>();
protected List<SolverListener<V, T>> iSolverListeners = new ArrayList<SolverListener<V, T>>();
protected int iSaveBestUnassigned = 0;
private boolean iUpdateProgress = true;
protected Progress iProgress;
/**
* Constructor.
*
* @param properties
* input configuration
*/
public Solver(DataProperties properties) {
iProperties = properties;
}
/** Dispose solver */
public void dispose() {
iExtensions.clear();
iSolverListeners.clear();
iTerminationCondition = null;
iSolutionComparator = null;
iPerturbationsCounter = null;
iNeighbourSelection = null;
}
/** Sets termination condition
* @param terminationCondition termination condition
**/
public void setTerminalCondition(TerminationCondition<V, T> terminationCondition) {
iTerminationCondition = terminationCondition;
}
/** Sets solution comparator
* @param solutionComparator solution comparator
**/
public void setSolutionComparator(SolutionComparator<V, T> solutionComparator) {
iSolutionComparator = solutionComparator;
}
/** Sets neighbour selection criterion
* @param neighbourSelection neighbour selection criterion
**/
public void setNeighbourSelection(NeighbourSelection<V, T> neighbourSelection) {
iNeighbourSelection = neighbourSelection;
}
/** Sets perturbation counter (minimal perturbation problem)
* @param perturbationsCounter perturbation counter
**/
public void setPerturbationsCounter(PerturbationsCounter<V, T> perturbationsCounter) {
iPerturbationsCounter = perturbationsCounter;
}
/** Add an IFS extension
* @param extension an extension
**/
public void addExtension(Extension<V, T> extension) {
iExtensions.add(extension);
}
/** Returns termination condition
* @return termination condition
**/
public TerminationCondition<V, T> getTerminationCondition() {
return iTerminationCondition;
}
/** Returns solution comparator
* @return solution comparator
**/
public SolutionComparator<V, T> getSolutionComparator() {
return iSolutionComparator;
}
/** Returns neighbour selection criterion
* @return neighbour selection criterion
**/
public NeighbourSelection<V, T> getNeighbourSelection() {
return iNeighbourSelection;
}
/** Returns perturbation counter (minimal perturbation problem)
* @return perturbation counter
**/
public PerturbationsCounter<V, T> getPerturbationsCounter() {
return iPerturbationsCounter;
}
/** Returns list of all used extensions
* @return list of all registered extensions
**/
public List<Extension<V, T>> getExtensions() {
return iExtensions;
}
/** Adds a solver listener
* @param listener solver listener
**/
public void addSolverListener(SolverListener<V, T> listener) {
iSolverListeners.add(listener);
}
/** Removes a solver listener
* @param listener solver listener
**/
public void removeSolverListener(SolverListener<V, T> listener) {
iSolverListeners.remove(listener);
}
/** Registered solver listeners
* @return list of all registered solver listeners
**/
public List<SolverListener<V, T>> getSolverListeners() {
return iSolverListeners;
}
/** Returns configuration
* @return solver configuration
**/
public DataProperties getProperties() {
return iProperties;
}
/**
* Automatic configuratin of the solver -- when Solver.AutoConfigure is true
*/
@SuppressWarnings("unchecked")
protected void autoConfigure() {
try {
boolean mpp = getProperties().getPropertyBoolean("General.MPP", false);
String terminationConditionClassName = getProperties().getProperty(
"Termination.Class",
(mpp ? "org.cpsolver.ifs.termination.MPPTerminationCondition"
: "org.cpsolver.ifs.termination.GeneralTerminationCondition"));
sLogger.info("Using " + terminationConditionClassName);
Class<?> terminationConditionClass = Class.forName(terminationConditionClassName);
Constructor<?> terminationConditionConstructor = terminationConditionClass
.getConstructor(new Class[] { DataProperties.class });
setTerminalCondition((TerminationCondition<V, T>) terminationConditionConstructor
.newInstance(new Object[] { getProperties() }));
String solutionComparatorClassName = getProperties().getProperty(
"Comparator.Class",
(mpp ? "org.cpsolver.ifs.solution.MPPSolutionComparator"
: "org.cpsolver.ifs.solution.GeneralSolutionComparator"));
sLogger.info("Using " + solutionComparatorClassName);
Class<?> solutionComparatorClass = Class.forName(solutionComparatorClassName);
Constructor<?> solutionComparatorConstructor = solutionComparatorClass
.getConstructor(new Class[] { DataProperties.class });
setSolutionComparator((SolutionComparator<V, T>) solutionComparatorConstructor
.newInstance(new Object[] { getProperties() }));
String neighbourSelectionClassName = getProperties().getProperty("Neighbour.Class",
"org.cpsolver.ifs.heuristics.StandardNeighbourSelection");
sLogger.info("Using " + neighbourSelectionClassName);
Class<?> neighbourSelectionClass = Class.forName(neighbourSelectionClassName);
Constructor<?> neighbourSelectionConstructor = neighbourSelectionClass
.getConstructor(new Class[] { DataProperties.class });
setNeighbourSelection((NeighbourSelection<V, T>) neighbourSelectionConstructor
.newInstance(new Object[] { getProperties() }));
String perturbationCounterClassName = getProperties().getProperty("PerturbationCounter.Class",
"org.cpsolver.ifs.perturbations.DefaultPerturbationsCounter");
sLogger.info("Using " + perturbationCounterClassName);
Class<?> perturbationCounterClass = Class.forName(perturbationCounterClassName);
Constructor<?> perturbationCounterConstructor = perturbationCounterClass
.getConstructor(new Class[] { DataProperties.class });
setPerturbationsCounter((PerturbationsCounter<V, T>) perturbationCounterConstructor
.newInstance(new Object[] { getProperties() }));
for (Extension<V, T> extension : iExtensions) {
extension.unregister(iCurrentSolution.getModel());
}
iExtensions.clear();
String extensionClassNames = getProperties().getProperty("Extensions.Classes", null);
if (extensionClassNames != null) {
StringTokenizer extensionClassNameTokenizer = new StringTokenizer(extensionClassNames, ";");
while (extensionClassNameTokenizer.hasMoreTokens()) {
String extensionClassName = extensionClassNameTokenizer.nextToken().trim();
if (extensionClassName.isEmpty()) continue;
sLogger.info("Using " + extensionClassName);
Class<?> extensionClass = Class.forName(extensionClassName);
Constructor<?> extensionConstructor = extensionClass.getConstructor(new Class[] { Solver.class,
DataProperties.class });
addExtension((Extension<V, T>) extensionConstructor.newInstance(new Object[] { this,
getProperties() }));
}
}
} catch (Exception e) {
sLogger.error("Unable to autoconfigure solver.", e);
}
}
/** Clears best solution */
public void clearBest() {
if (iCurrentSolution != null)
iCurrentSolution.clearBest();
}
/** Sets initial solution
* @param solution initial solution
**/
public void setInitalSolution(Solution<V, T> solution) {
iCurrentSolution = solution;
iLastSolution = null;
}
/** Sets initial solution
* @param model problem model
**/
public void setInitalSolution(Model<V, T> model) {
setInitalSolution(new Solution<V, T>(model, new DefaultSingleAssignment<V, T>(), 0, 0));
}
/** Starts solver */
public void start() {
iSolverThread = new SolverThread();
iSolverThread.setPriority(THREAD_PRIORITY);
iSolverThread.start();
}
/** Returns solver's thread
* @return solver's thread
**/
public Thread getSolverThread() {
return iSolverThread;
}
/** Initialization */
public void init() {
}
/** True, when solver should update progress (see {@link Progress})
* @return true if the solver should update process
**/
protected boolean isUpdateProgress() {
return iUpdateProgress;
}
/** True, when solver should update progress (see {@link Progress})
* @param updateProgress true if the solver should update process (default is true)
**/
public void setUpdateProgress(boolean updateProgress) {
iUpdateProgress = updateProgress;
}
/** Last solution (when solver finishes)
* @return last solution
**/
public Solution<V, T> lastSolution() {
return (iLastSolution == null ? iCurrentSolution : iLastSolution);
}
/** Current solution (during the search)
* @return current solution
**/
public Solution<V, T> currentSolution() {
return iCurrentSolution;
}
public void initSolver() {
long seed = getProperties().getPropertyLong("General.Seed", System.currentTimeMillis());
ToolBox.setSeed(seed);
iSaveBestUnassigned = getProperties().getPropertyInt("General.SaveBestUnassigned", 0);
clearBest();
if (iProperties.getPropertyBoolean("Solver.AutoConfigure", true)) {
autoConfigure();
}
// register extensions
for (Extension<V, T> extension : iExtensions) {
extension.register(iCurrentSolution.getModel());
}
// register solution
iCurrentSolution.init(Solver.this);
// register and intialize neighbour selection
getNeighbourSelection().init(Solver.this);
// register and intialize perturbations counter
if (getPerturbationsCounter() != null)
getPerturbationsCounter().init(Solver.this);
// save initial configuration
if (iProperties.getPropertyBoolean("General.SaveConfiguration", false)) {
FileOutputStream f = null;
try {
f = new FileOutputStream(iProperties.getProperty("General.Output") + File.separator
+ iProperties.getProperty("General.ProblemName", "ifs") + ".properties");
iProperties.store(f, iProperties.getProperty("General.ProblemNameLong", "Iterative Forward Search")
+ " -- configuration file");
f.flush();
f.close();
f = null;
} catch (Exception e) {
sLogger.error("Unable to store configuration file :-(", e);
} finally {
try {
if (f != null)
f.close();
} catch (IOException e) {
}
}
}
}
/** Stop running solver */
public void stopSolver() {
stopSolver(true);
}
/** Stop running solver
* @param join wait for the solver thread to finish
**/
public void stopSolver(boolean join) {
if (getSolverThread() != null) {
iStop = true;
if (join) {
try {
getSolverThread().join();
} catch (InterruptedException ex) {
}
}
}
}
/** True, if the solver is running
* @return true if the solver is running
**/
public boolean isRunning() {
return (getSolverThread() != null);
}
/** Called when the solver is stopped */
protected void onStop() {
}
/** Called when the solver is started */
protected void onStart() {
}
/** Called when the solver is finished */
protected void onFinish() {
}
/** Called when the solver fails */
protected void onFailure() {
}
/** Called in each iteration, after a neighbour is assigned
* @param startTime solver start time in seconds
* @param solution current solution
**/
protected void onAssigned(double startTime, Solution<V, T> solution) {
}
/**
* Returns true if the solver works only with one solution (regardless the number of threads it is using)
* @return true
*/
public boolean hasSingleSolution() {
return currentSolution().getAssignment() instanceof DefaultSingleAssignment;
}
/** Solver thread */
protected class SolverThread extends Thread {
/** Solving rutine */
@Override
public void run() {
try {
iStop = false;
// Sets thread name
setName("Solver");
// Initialization
iProgress = Progress.getInstance(iCurrentSolution.getModel());
iProgress.setStatus("Solving problem ...");
iProgress.setPhase("Initializing solver");
initSolver();
onStart();
double startTime = JProf.currentTimeSec();
int timeout = getProperties().getPropertyInt("Termination.TimeOut", 1800);
if (isUpdateProgress()) {
if (iCurrentSolution.getBestInfo() == null) {
iProgress.setPhase("Searching for initial solution ...", iCurrentSolution.getModel()
.variables().size());
} else {
iProgress.setPhase("Improving found solution ...");
}
}
sLogger.info("Initial solution:" + ToolBox.dict2string(iCurrentSolution.getExtendedInfo(), 1));
if ((iSaveBestUnassigned < 0 || iSaveBestUnassigned >= iCurrentSolution.getAssignment().nrUnassignedVariables(iCurrentSolution.getModel()))
&& (iCurrentSolution.getBestInfo() == null || getSolutionComparator().isBetterThanBestSolution(iCurrentSolution))) {
if (iCurrentSolution.getModel().variables().size() == iCurrentSolution.getAssignment().nrAssignedVariables())
sLogger.info("Complete solution " + ToolBox.dict2string(iCurrentSolution.getExtendedInfo(), 1) + " was found.");
iCurrentSolution.saveBest();
}
if (iCurrentSolution.getModel().variables().isEmpty()) {
iProgress.error("Nothing to solve.");
iStop = true;
}
// Iterations: until solver can continue
while (!iStop && getTerminationCondition().canContinue(iCurrentSolution)) {
// Neighbour selection
Neighbour<V, T> neighbour = getNeighbourSelection().selectNeighbour(iCurrentSolution);
for (SolverListener<V, T> listener : iSolverListeners) {
if (!listener.neighbourSelected(iCurrentSolution.getAssignment(), iCurrentSolution.getIteration(), neighbour)) {
neighbour = null;
continue;
}
}
if (neighbour == null) {
sLogger.debug("No neighbour selected.");
// still update the solution (increase iteration etc.)
iCurrentSolution.update(JProf.currentTimeSec() - startTime, false);
continue;
}
// Assign selected value to the selected variable
Lock lock = iCurrentSolution.getLock().writeLock();
lock.lock();
try {
neighbour.assign(iCurrentSolution.getAssignment(), iCurrentSolution.getIteration());
} finally {
lock.unlock();
}
double time = JProf.currentTimeSec() - startTime;
iCurrentSolution.update(time);
onAssigned(startTime, iCurrentSolution);
// Check if the solution is the best ever found one
if ((iSaveBestUnassigned < 0 || iSaveBestUnassigned >= iCurrentSolution.getAssignment().nrUnassignedVariables(iCurrentSolution.getModel())) && (iCurrentSolution.getBestInfo() == null || getSolutionComparator().isBetterThanBestSolution(iCurrentSolution))) {
if (iCurrentSolution.getModel().variables().size() == iCurrentSolution.getAssignment().nrAssignedVariables()) {
iProgress.debug("Complete solution of value " + iCurrentSolution.getModel().getTotalValue(iCurrentSolution.getAssignment()) + " was found.");
}
iCurrentSolution.saveBest();
}
// Increment progress bar
if (isUpdateProgress()) {
if (iCurrentSolution.getBestInfo() != null && iCurrentSolution.getModel().getBestUnassignedVariables() == 0) {
if (!"Improving found solution ...".equals(iProgress.getPhase()))
iProgress.setPhase("Improving found solution ...");
iProgress.setProgress(Math.min(100, (int)Math.round(100 * time / timeout)));
} else if ((iCurrentSolution.getBestInfo() == null || iCurrentSolution.getModel().getBestUnassignedVariables() > 0) && (iCurrentSolution.getAssignment().nrAssignedVariables() > iProgress.getProgress())) {
iProgress.setProgress(iCurrentSolution.getAssignment().nrAssignedVariables());
}
}
}
// Finalization
iLastSolution = iCurrentSolution;
iProgress.setPhase("Done", 1);
iProgress.incProgress();
if (iStop) {
sLogger.debug("Solver stopped.");
iProgress.setStatus("Solver stopped.");
onStop();
} else {
sLogger.debug("Solver done.");
iProgress.setStatus("Solver done.");
onFinish();
}
} catch (Exception ex) {
sLogger.error(ex.getMessage(), ex);
iProgress.fatal("Solver failed, reason:" + ex.getMessage(), ex);
iProgress.setStatus("Solver failed.");
onFailure();
} finally {
iSolverThread = null;
}
}
}
/** Return true if {@link Solver#stopSolver()} was called
* @return true if the solver is to be stopped
**/
public boolean isStop() {
return iStop;
}
}
| lgpl-3.0 |
BlockServerProject/BlockServer | src/main/java/org/blockserver/core/modules/world/positions/Location.java | 1506 | /*
* This file is part of BlockServer.
*
* BlockServer 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.
*
* BlockServer 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 BlockServer. If not, see <http://www.gnu.org/licenses/>.
*/
package org.blockserver.core.modules.world.positions;
import lombok.Getter;
/**
* Written by Exerosis!
*
* @author BlockServer Team
* @see org.blockserver.core.modules.world.positions.Vector
* @see org.blockserver.core.modules.world.WorldModule
*/
public class Location extends Vector {
@Getter long yaw;
@Getter long pitch;
public Location(Vector vector) {
super(vector);
}
public Location(Location location) {
this(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
}
public Location(float x, float y, float z) {
super(x, y, z);
}
public Location(float x, float y, float z, long yaw, long pitch) {
this(x, y, z);
this.yaw = yaw;
this.pitch = pitch;
}
} | lgpl-3.0 |
btrplace/scheduler-UCC-15 | btrpsl/src/test/java/org/btrplace/btrpsl/constraint/ReadyBuilderTest.java | 2986 | /*
* Copyright (c) 2014 University Nice Sophia Antipolis
*
* This file is part of btrplace.
* 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 3 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 program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.btrplace.btrpsl.constraint;
import org.btrplace.btrpsl.ScriptBuilder;
import org.btrplace.btrpsl.ScriptBuilderException;
import org.btrplace.model.DefaultModel;
import org.btrplace.model.VM;
import org.btrplace.model.constraint.Ready;
import org.btrplace.model.constraint.SatConstraint;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.HashSet;
import java.util.Set;
/**
* Unit tests for {@link ReadyBuilder}.
*
* @author Fabien Hermenier
*/
@Test
public class ReadyBuilderTest {
@DataProvider(name = "badReadys")
public Object[][] getBadSignatures() {
return new String[][]{
new String[]{"ready({});"},
new String[]{"ready({@N1});"},
new String[]{">>ready({VM[1..5]});"},
};
}
@Test(dataProvider = "badReadys", expectedExceptions = {ScriptBuilderException.class})
public void testBadSignatures(String str) throws ScriptBuilderException {
ScriptBuilder b = new ScriptBuilder(new DefaultModel());
try {
b.build("namespace test; VM[1..10] : tiny;\n@N[1..20] : defaultNode;" + str);
} catch (ScriptBuilderException ex) {
System.out.println(str + " " + ex.getMessage());
throw ex;
}
}
@DataProvider(name = "goodReadys")
public Object[][] getGoodSignatures() {
return new Object[][]{
new Object[]{">>ready(VM1);", 1, false},
new Object[]{"ready(VM[1..10]);", 10, true}
};
}
@Test(dataProvider = "goodReadys")
public void testGoodSignatures(String str, int nbVMs, boolean c) throws Exception {
ScriptBuilder b = new ScriptBuilder(new DefaultModel());
Set<SatConstraint> cstrs = b.build("namespace test; VM[1..10] : tiny;\n@N[1..20] : defaultNode;" + str).getConstraints();
Assert.assertEquals(cstrs.size(), nbVMs);
Set<VM> vms = new HashSet<>();
for (SatConstraint x : cstrs) {
Assert.assertTrue(x instanceof Ready);
Assert.assertTrue(vms.addAll(x.getInvolvedVMs()));
Assert.assertEquals(x.isContinuous(), c);
}
}
}
| lgpl-3.0 |
stygianguest/SXPathAnnotations | xml2csv/XML2CSV.java | 1690 | package xml2csv;
import java.io.File;
import java.util.Iterator;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import filters.*;
@SuppressWarnings("unchecked")
public class XML2CSV extends DefaultHandler {
SaxFilter filter;
public XML2CSV() {
}
public XML2CSV(String xpath) {
FilterParser parser = new FilterParser();
filter = parser.parseFilter(xpath);
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
//FIXME: can we match twice?
printRows(filter.startElement(uri, localName, qName));
printRows(filter.attributes(attributes));
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
printRows(filter.characters(ch, start, length));
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
printRows(filter.endElement(uri, localName, qName));
}
void printRows(Iterator it) {
while (it.hasNext())
System.out.println(it.next().toString());
}
public static void main(String[] args) {
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
if (args.length < 2) {
System.out.println("Usage: xml2csv XPATH FILES");
return;
}
XML2CSV driver = new XML2CSV(args[0]);
SAXParser saxParser = factory.newSAXParser();
for (int i = 1; i < args.length; i++) {
saxParser.parse(new File(args[i]), driver);
}
} catch (Throwable err) {
err.printStackTrace();
}
}
}
| lgpl-3.0 |
legidio/fenixedu-academic | src/main/java/org/fenixedu/academic/domain/serviceRequests/PartialRegistrationRegimeRequest.java | 4248 | /**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic 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.
*
* FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.domain.serviceRequests;
import org.fenixedu.academic.domain.ExecutionYear;
import org.fenixedu.academic.domain.accounting.EventType;
import org.fenixedu.academic.domain.serviceRequests.documentRequests.AcademicServiceRequestType;
import org.fenixedu.academic.domain.student.RegistrationRegime;
import org.fenixedu.academic.domain.student.RegistrationRegimeType;
import org.fenixedu.academic.dto.serviceRequests.AcademicServiceRequestBean;
import org.fenixedu.academic.dto.serviceRequests.RegistrationAcademicServiceRequestCreateBean;
public class PartialRegistrationRegimeRequest extends PartialRegistrationRegimeRequest_Base {
private PartialRegistrationRegimeRequest() {
super();
}
public PartialRegistrationRegimeRequest(final RegistrationAcademicServiceRequestCreateBean bean) {
this();
super.init(bean);
}
@Override
protected void checkRulesToChangeState(AcademicServiceRequestSituationType situationType) {
super.checkRulesToChangeState(situationType);
if (situationType == AcademicServiceRequestSituationType.PROCESSING) {
RegistrationRegime.getRegistrationRegimeVerifier().checkEctsCredits(getRegistration(), getExecutionYear(),
RegistrationRegimeType.PARTIAL_TIME);
}
}
@Override
protected void internalChangeState(final AcademicServiceRequestBean academicServiceRequestBean) {
if (academicServiceRequestBean.isToConclude()) {
academicServiceRequestBean.setSituationDate(getActiveSituation().getSituationDate().toYearMonthDay());
}
}
@Override
protected boolean isPayed() {
return super.isPayed();
}
@Override
protected void createAcademicServiceRequestSituations(AcademicServiceRequestBean academicServiceRequestBean) {
super.createAcademicServiceRequestSituations(academicServiceRequestBean);
if (academicServiceRequestBean.isToConclude()) {
AcademicServiceRequestSituation.create(this, new AcademicServiceRequestBean(
AcademicServiceRequestSituationType.DELIVERED, academicServiceRequestBean.getResponsible()));
if (!getRegistration().isPartialRegime(getExecutionYear())) {
new RegistrationRegime(getRegistration(), getExecutionYear(), RegistrationRegimeType.PARTIAL_TIME);
}
}
}
@Override
public boolean isAvailableForTransitedRegistrations() {
return false;
}
@Override
public AcademicServiceRequestType getAcademicServiceRequestType() {
return AcademicServiceRequestType.PARTIAL_REGIME_REQUEST;
}
@Override
public EventType getEventType() {
/*
* For 2010/2011 partial registration is not charged
*/
if (getExecutionYear().isAfterOrEquals(ExecutionYear.readExecutionYearByName("2010/2011"))) {
return null;
}
return EventType.PARTIAL_REGISTRATION_REGIME_REQUEST;
}
@Override
public boolean hasPersonalInfo() {
return false;
}
@Override
public boolean isPayedUponCreation() {
return false;
}
@Override
public boolean isPossibleToSendToOtherEntity() {
return false;
}
@Override
public boolean isManagedWithRectorateSubmissionBatch() {
return false;
}
@Override
public boolean isToPrint() {
return false;
}
}
| lgpl-3.0 |
discoverydns/dnsapi-client | src/main/java/com/discoverydns/dnsapiclient/command/user/UserGetCommand.java | 1657 | package com.discoverydns.dnsapiclient.command.user;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
/**
* Command sent from a {@link com.discoverydns.dnsapiclient.DNSAPIClient} to the DNSAPI server,
* to get the details of a User.
*
* A User is a member of an Account, who can connect to the DNSAPI server
* to perform operations on his behalf.
*
* @author Chris Wright
*/
@JsonRootName("UserGetCommand")
@JsonPropertyOrder({ "idOrUsername" })
public class UserGetCommand {
@JsonProperty("idOrUsername")
private String idOrUsername;
/**
* Builder used to build the desired command.
*/
public static class Builder {
private String idOrUsername;
/**
* Sets the UUID or username of the User to look for.
* @param idOrUsername The UUID or username of the User to look for
* @return The {@link Builder}
*/
public Builder withIdOrUsername(final String idOrUsername) {
this.idOrUsername = idOrUsername;
return this;
}
/**
* Builds the {@link UserGetCommand} from the parameters set on the {@link Builder}.
* @return The built {@link UserGetCommand}
*/
public UserGetCommand build() {
final UserGetCommand userGetCommand = new UserGetCommand();
userGetCommand.idOrUsername = idOrUsername;
return userGetCommand;
}
}
private UserGetCommand() {
}
/**
* @return The UUID or username of the User to look for, set on the command.
*/
public String getIdOrUsername() {
return idOrUsername;
}
}
| lgpl-3.0 |
ethereum/ethereumj | ethereumj-core/src/main/java/org/ethereum/sync/BlockDownloader.java | 19430 | /*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ 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 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ 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 the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.sync;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.ethereum.core.*;
import org.ethereum.crypto.HashUtil;
import org.ethereum.net.server.Channel;
import org.ethereum.validator.BlockHeaderValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import java.util.*;
import java.util.concurrent.*;
import static java.lang.Math.max;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* Created by Anton Nashatyrev on 27.10.2016.
*/
public abstract class BlockDownloader {
private final static Logger logger = LoggerFactory.getLogger("sync");
private int blockQueueLimit = 2000;
private int headerQueueLimit = 10000;
// Max number of Blocks / Headers in one request
public static int MAX_IN_REQUEST = 192;
private static int REQUESTS = 32;
private BlockHeaderValidator headerValidator;
private SyncPool pool;
private SyncQueueIfc syncQueue;
private boolean headersDownload = true;
private boolean blockBodiesDownload = true;
private CountDownLatch receivedHeadersLatch = new CountDownLatch(0);
private CountDownLatch receivedBlocksLatch = new CountDownLatch(0);
private Thread getHeadersThread;
private Thread getBodiesThread;
protected boolean headersDownloadComplete;
private boolean downloadComplete;
private CountDownLatch stopLatch = new CountDownLatch(1);
protected String name = "BlockDownloader";
private long estimatedBlockSize = 0;
private final CircularFifoQueue<Long> lastBlockSizes = new CircularFifoQueue<>(10 * MAX_IN_REQUEST);
public BlockDownloader(BlockHeaderValidator headerValidator) {
this.headerValidator = headerValidator;
}
protected abstract void pushBlocks(List<BlockWrapper> blockWrappers);
protected abstract void pushHeaders(List<BlockHeaderWrapper> headers);
protected abstract int getBlockQueueFreeSize();
protected abstract int getMaxHeadersInQueue();
protected void finishDownload() {}
public boolean isDownloadComplete() {
return downloadComplete;
}
public void setBlockBodiesDownload(boolean blockBodiesDownload) {
this.blockBodiesDownload = blockBodiesDownload;
}
public void setHeadersDownload(boolean headersDownload) {
this.headersDownload = headersDownload;
}
public void init(SyncQueueIfc syncQueue, final SyncPool pool, String name) {
this.syncQueue = syncQueue;
this.pool = pool;
this.name = name;
logger.info("{}: Initializing BlockDownloader.", name);
if (headersDownload) {
getHeadersThread = new Thread(this::headerRetrieveLoop, "SyncThreadHeaders");
getHeadersThread.start();
}
if (blockBodiesDownload) {
getBodiesThread = new Thread(this::blockRetrieveLoop, "SyncThreadBlocks");
getBodiesThread.start();
}
}
public void stop() {
if (getHeadersThread != null) getHeadersThread.interrupt();
if (getBodiesThread != null) getBodiesThread.interrupt();
stopLatch.countDown();
}
public void waitForStop() {
try {
stopLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void setHeaderQueueLimit(int headerQueueLimit) {
this.headerQueueLimit = headerQueueLimit;
}
public int getBlockQueueLimit() {
return blockQueueLimit;
}
public int getHeaderQueueLimit() {
return headerQueueLimit;
}
public void setBlockQueueLimit(int blockQueueLimit) {
this.blockQueueLimit = blockQueueLimit;
}
private void headerRetrieveLoop() {
List<SyncQueueIfc.HeadersRequest> hReq = emptyList();
while(!Thread.currentThread().isInterrupted()) {
try {
if (hReq.isEmpty()) {
synchronized (this) {
hReq = syncQueue.requestHeaders(MAX_IN_REQUEST, 128, getMaxHeadersInQueue());
if (hReq == null) {
logger.info("{}: Headers download complete.", name);
headersDownloadComplete = true;
if (!blockBodiesDownload) {
finishDownload();
downloadComplete = true;
}
return;
}
String l = "########## " + name + ": New header requests (" + hReq.size() + "):\n";
for (SyncQueueIfc.HeadersRequest request : hReq) {
l += " " + request + "\n";
}
logger.debug(l);
}
}
int reqHeadersCounter = 0;
for (Iterator<SyncQueueIfc.HeadersRequest> it = hReq.iterator(); it.hasNext();) {
SyncQueueIfc.HeadersRequest headersRequest = it.next();
final Channel any = getAnyPeer();
if (any == null) {
logger.debug("{} headerRetrieveLoop: No IDLE peers found", name);
break;
} else {
logger.debug("{} headerRetrieveLoop: request headers (" + headersRequest.toString() + ") from " + any.getNode(), name);
ListenableFuture<List<BlockHeader>> futureHeaders = headersRequest.getHash() == null ?
any.getEthHandler().sendGetBlockHeaders(headersRequest.getStart(), headersRequest.getCount(), headersRequest.isReverse()) :
any.getEthHandler().sendGetBlockHeaders(headersRequest.getHash(), headersRequest.getCount(), headersRequest.getStep(), headersRequest.isReverse());
if (futureHeaders != null) {
Futures.addCallback(futureHeaders, new FutureCallback<List<BlockHeader>>() {
@Override
public void onSuccess(List<BlockHeader> result) {
if (!validateAndAddHeaders(result, any.getNodeId())) {
onFailure(new RuntimeException("Received headers validation failed"));
}
}
@Override
public void onFailure(Throwable t) {
logger.debug("{}: Error receiving headers. Dropping the peer.", name, t);
any.getEthHandler().dropConnection();
}
}, MoreExecutors.directExecutor());
it.remove();
reqHeadersCounter++;
}
}
}
receivedHeadersLatch = new CountDownLatch(max(reqHeadersCounter / 2, 1));
receivedHeadersLatch.await(isSyncDone() ? 10000 : 500, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
break;
} catch (Exception e) {
logger.error("Unexpected: ", e);
}
}
}
private void blockRetrieveLoop() {
class BlocksCallback implements FutureCallback<List<Block>> {
private Channel peer;
public BlocksCallback(Channel peer) {
this.peer = peer;
}
@Override
public void onSuccess(List<Block> result) {
addBlocks(result, peer.getNodeId());
}
@Override
public void onFailure(Throwable t) {
logger.debug("{}: Error receiving Blocks. Dropping the peer.", name, t);
peer.getEthHandler().dropConnection();
}
}
List<SyncQueueIfc.BlocksRequest> bReqs = emptyList();
while(!Thread.currentThread().isInterrupted()) {
try {
if (bReqs.isEmpty()) {
bReqs = syncQueue.requestBlocks(16 * 1024).split(MAX_IN_REQUEST);
}
if (bReqs.isEmpty() && headersDownloadComplete) {
logger.info("{}: Block download complete.", name);
finishDownload();
downloadComplete = true;
return;
}
int blocksToAsk = getBlockQueueFreeSize();
if (blocksToAsk >= MAX_IN_REQUEST) {
// SyncQueueIfc.BlocksRequest bReq = syncQueue.requestBlocks(maxBlocks);
boolean fewHeadersReqMode = false;
if (bReqs.size() == 1 && bReqs.get(0).getBlockHeaders().size() <= 3) {
// new blocks are better to request from the header senders first
// to get more chances to receive block body promptly
for (BlockHeaderWrapper blockHeaderWrapper : bReqs.get(0).getBlockHeaders()) {
Channel channel = pool.getByNodeId(blockHeaderWrapper.getNodeId());
if (channel != null) {
ListenableFuture<List<Block>> futureBlocks =
channel.getEthHandler().sendGetBlockBodies(singletonList(blockHeaderWrapper));
if (futureBlocks != null) {
Futures.addCallback(futureBlocks, new BlocksCallback(channel),
MoreExecutors.directExecutor());
fewHeadersReqMode = true;
}
}
}
}
int maxRequests = blocksToAsk / MAX_IN_REQUEST;
int maxBlocks = MAX_IN_REQUEST * Math.min(maxRequests, REQUESTS);
int reqBlocksCounter = 0;
int blocksRequested = 0;
Iterator<SyncQueueIfc.BlocksRequest> it = bReqs.iterator();
while (it.hasNext() && blocksRequested < maxBlocks) {
// for (SyncQueueIfc.BlocksRequest blocksRequest : bReq.split(MAX_IN_REQUEST)) {
SyncQueueIfc.BlocksRequest blocksRequest = it.next();
Channel any = getAnyPeer();
if (any == null) {
logger.debug("{} blockRetrieveLoop: No IDLE peers found", name);
break;
} else {
logger.debug("{} blockRetrieveLoop: Requesting " + blocksRequest.getBlockHeaders().size() + " blocks from " + any.getNode(), name);
ListenableFuture<List<Block>> futureBlocks =
any.getEthHandler().sendGetBlockBodies(blocksRequest.getBlockHeaders());
blocksRequested += blocksRequest.getBlockHeaders().size();
if (futureBlocks != null) {
Futures.addCallback(futureBlocks, new BlocksCallback(any),
MoreExecutors.directExecutor());
reqBlocksCounter++;
it.remove();
}
}
}
// Case when we have requested few headers and was not able
// to remove request from the list in above cycle because
// there were no idle peers or whatever
if (fewHeadersReqMode && !bReqs.isEmpty()) {
bReqs.clear();
}
receivedBlocksLatch = new CountDownLatch(max(reqBlocksCounter - 2, 1));
receivedBlocksLatch.await(1000, TimeUnit.MILLISECONDS);
} else {
logger.debug("{} blockRetrieveLoop: BlockQueue is full", name);
Thread.sleep(200);
}
} catch (InterruptedException e) {
break;
} catch (Exception e) {
logger.error("Unexpected: ", e);
}
}
}
/**
* Adds a list of blocks to the queue
*
* @param blocks block list received from remote peer and be added to the queue
* @param nodeId nodeId of remote peer which these blocks are received from
*/
private void addBlocks(List<Block> blocks, byte[] nodeId) {
if (blocks.isEmpty()) {
return;
}
synchronized (this) {
logger.debug("{}: Adding new " + blocks.size() + " blocks to sync queue: " +
blocks.get(0).getShortDescr() + " ... " + blocks.get(blocks.size() - 1).getShortDescr(), name);
List<Block> newBlocks = syncQueue.addBlocks(blocks);
List<BlockWrapper> wrappers = new ArrayList<>();
for (Block b : newBlocks) {
wrappers.add(new BlockWrapper(b, nodeId));
}
logger.debug("{}: Pushing " + wrappers.size() + " blocks to import queue: " + (wrappers.isEmpty() ? "" :
wrappers.get(0).getBlock().getShortDescr() + " ... " + wrappers.get(wrappers.size() - 1).getBlock().getShortDescr()), name);
pushBlocks(wrappers);
}
receivedBlocksLatch.countDown();
if (logger.isDebugEnabled()) logger.debug(
"{}: Blocks waiting to be proceed: lastBlock.number: [{}]",
name,
blocks.get(blocks.size() - 1).getNumber()
);
}
/**
* Adds list of headers received from remote host <br>
* Runs header validation before addition <br>
* It also won't add headers of those blocks which are already presented in the queue
*
* @param headers list of headers got from remote host
* @param nodeId remote host nodeId
*
* @return true if blocks passed validation and were added to the queue,
* otherwise it returns false
*/
private boolean validateAndAddHeaders(List<BlockHeader> headers, byte[] nodeId) {
if (headers.isEmpty()) return true;
List<BlockHeaderWrapper> wrappers = new ArrayList<>(headers.size());
for (BlockHeader header : headers) {
if (!isValid(header)) {
if (logger.isDebugEnabled()) {
logger.debug("{}: Invalid header RLP: {}", toHexString(header.getEncoded()), name);
}
return false;
}
wrappers.add(new BlockHeaderWrapper(header, nodeId));
}
SyncQueueIfc.ValidatedHeaders res;
synchronized (this) {
res = syncQueue.addHeadersAndValidate(wrappers);
if (res.isValid() && !res.getHeaders().isEmpty()) {
pushHeaders(res.getHeaders());
}
}
dropIfValidationFailed(res);
receivedHeadersLatch.countDown();
logger.debug("{}: {} headers added", name, headers.size());
return true;
}
/**
* Checks whether validation has been passed correctly or not
* and drops misleading peer if it hasn't
*/
protected void dropIfValidationFailed(SyncQueueIfc.ValidatedHeaders res) {
if (!res.isValid() && res.getNodeId() != null) {
if (logger.isWarnEnabled()) logger.warn("Invalid header received: {}, reason: {}, peer: {}",
res.getHeader() == null ? "" : res.getHeader().getShortDescr(),
res.getReason(),
Hex.toHexString(res.getNodeId()).substring(0, 8));
Channel peer = pool.getByNodeId(res.getNodeId());
if (peer != null) {
peer.dropConnection();
}
}
}
/**
* Runs checks against block's header. <br>
* All these checks make sense before block is added to queue
* in front of checks running by {@link BlockchainImpl#isValid(BlockHeader)}
*
* @param header block header
* @return true if block is valid, false otherwise
*/
protected boolean isValid(BlockHeader header) {
return headerValidator.validateAndLog(header, logger);
}
Channel getAnyPeer() {
return pool.getAnyIdle();
}
public boolean isSyncDone() {
return false;
}
public void close() {
try {
if (pool != null) pool.close();
stop();
} catch (Exception e) {
logger.warn("Problems closing SyncManager", e);
}
}
/**
* Estimates block size in bytes.
* Block memory size can depend on the underlying logic,
* hence ancestors should call this method on their own,
* preferably after actions that impact on block memory size (like RLP parsing, signature recover) are done
*/
protected void estimateBlockSize(BlockWrapper blockWrapper) {
synchronized (lastBlockSizes) {
lastBlockSizes.add(blockWrapper.estimateMemSize());
estimatedBlockSize = lastBlockSizes.stream().mapToLong(Long::longValue).sum() / lastBlockSizes.size();
}
logger.debug("{}: estimated block size: {}", name, estimatedBlockSize);
}
protected void estimateBlockSize(Collection<BlockWrapper> blockWrappers) {
if (blockWrappers.isEmpty())
return;
synchronized (lastBlockSizes) {
blockWrappers.forEach(b -> lastBlockSizes.add(b.estimateMemSize()));
estimatedBlockSize = lastBlockSizes.stream().mapToLong(Long::longValue).sum() / lastBlockSizes.size();
}
logger.debug("{}: estimated block size: {}", name, estimatedBlockSize);
}
public long getEstimatedBlockSize() {
return estimatedBlockSize;
}
}
| lgpl-3.0 |
nuun-io/kernel | core/src/test/java/io/nuun/kernel/core/internal/scanner/sample/MyModule1.java | 1048 | /**
* This file is part of Nuun IO Kernel Core.
*
* Nuun IO Kernel Core 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.
*
* Nuun IO Kernel Core 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 Nuun IO Kernel Core. If not, see <http://www.gnu.org/licenses/>.
*/
package io.nuun.kernel.core.internal.scanner.sample;
import com.google.inject.AbstractModule;
import io.nuun.kernel.api.annotations.KernelModule;
@KernelModule
public class MyModule1 extends AbstractModule
{
@Override
protected void configure()
{
}
}
| lgpl-3.0 |
OpenSoftwareSolutions/PDFReporter-Studio | com.jaspersoft.studio.components/src/com/jaspersoft/studio/components/chart/model/series/pie/command/DeletePieSeriesCommand.java | 2316 | /*******************************************************************************
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package com.jaspersoft.studio.components.chart.model.series.pie.command;
import net.sf.jasperreports.charts.design.JRDesignPieDataset;
import net.sf.jasperreports.charts.design.JRDesignPieSeries;
import org.eclipse.gef.commands.Command;
import com.jaspersoft.studio.components.chart.model.dataset.MChartDataset;
import com.jaspersoft.studio.components.chart.model.series.pie.MPieSeries;
/*
* link nodes & together.
*
* @author Chicu Veaceslav
*/
public class DeletePieSeriesCommand extends Command {
private JRDesignPieDataset jrGroup;
private JRDesignPieSeries jrElement;
/** The element position. */
private int oldIndex = 0;
/**
* Instantiates a new delete element command.
*
* @param destNode
* the dest node
* @param srcNode
* the src node
*/
public DeletePieSeriesCommand(MChartDataset destNode, MPieSeries srcNode) {
super();
this.jrElement = (JRDesignPieSeries) srcNode.getValue();
this.jrGroup = (JRDesignPieDataset) destNode.getValue();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.commands.Command#execute()
*/
@Override
public void execute() {
oldIndex = jrGroup.getSeriesList().indexOf(jrElement);
jrGroup.removePieSeries(jrElement);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.commands.Command#canUndo()
*/
@Override
public boolean canUndo() {
if (jrGroup == null || jrElement == null)
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.commands.Command#undo()
*/
@Override
public void undo() {
if (oldIndex >= 0 && oldIndex < jrGroup.getSeriesList().size())
jrGroup.addPieSeries(oldIndex, jrElement);
else
jrGroup.addPieSeries(jrElement);
}
}
| lgpl-3.0 |
EMResearch/EvoMaster | client-java/controller/src/test/java/com/thrift/example/artificial/GenericDto.java | 115 | package com.thrift.example.artificial;
public class GenericDto<T, U> {
public T data1;
public U data2;
}
| lgpl-3.0 |
Javlo/javlo | src/main/java/org/javlo/service/CountService.java | 4160 | package org.javlo.service;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import org.javlo.context.GlobalContext;
public class CountService {
private final Integer[] countArrayMinute = new Integer[60];
private long latestTime;
private long allTouch = 0;
private final long startTime = Calendar.getInstance().getTimeInMillis() / 1000;
private static CountService instance = null;
private static final String SERVLETCONTEXT_KEY = "globalCount";
private Map<String, Integer> chargeBySite = new HashMap<String, Integer>();
private Map<String, Integer[]> countArrayMinuteArray = new HashMap<String, Integer[]>();
public static CountService getInstance(ServletContext application) {
CountService res = (CountService) application.getAttribute(SERVLETCONTEXT_KEY);
if (res == null) {
res = new CountService();
application.setAttribute(SERVLETCONTEXT_KEY, res);
}
return res;
}
/**
* only for debug
*
* @return
*/
private static CountService getInstance() {
if (instance == null) {
instance = new CountService();
}
return instance;
}
private int getIndex(long infinityIndex) {
if (infinityIndex < 0) {
return countArrayMinute.length - (int) (infinityIndex % countArrayMinute.length);
} else {
return (int) infinityIndex % countArrayMinute.length;
}
}
public void touch() {
touch(true);
}
private synchronized void touch(boolean increment) {
long time = Calendar.getInstance().getTimeInMillis() / 1000;
if (time - countArrayMinute.length > latestTime) {
Arrays.fill(countArrayMinute, 0);
latestTime = time;
}
for (long i = time - 1; i > latestTime; i--) {
countArrayMinute[getIndex(i)] = 0;
}
if (increment) {
allTouch++;
if (time == latestTime) {
countArrayMinute[getIndex(time)]++;
} else {
countArrayMinute[getIndex(time)] = 1;
}
}
latestTime = time;
}
private synchronized void touch(GlobalContext globalContext) {
if (globalContext != null) {
String contextKey = globalContext.getContextKey();
Integer[] minuteTouch = countArrayMinuteArray.get(contextKey);
if (minuteTouch == null) {
minuteTouch = new Integer[60];
countArrayMinuteArray.put(contextKey, minuteTouch);
}
long time = Calendar.getInstance().getTimeInMillis() / 1000;
if (time - minuteTouch.length > latestTime) {
Arrays.fill(countArrayMinute, 0);
latestTime = time;
}
for (long i = time - 1; i > latestTime; i--) {
minuteTouch[getIndex(i)] = 0;
}
allTouch++;
if (time == latestTime) {
countArrayMinute[getIndex(time)]++;
} else {
countArrayMinute[getIndex(time)] = 1;
}
latestTime = time;
}
}
public int getCount() {
touch(false);
int c = 0;
for (Integer element : countArrayMinute) {
c = c + element;
}
return c;
}
public int getAverage() {
long time = Calendar.getInstance().getTimeInMillis() / 1000;
return (int) ((allTouch * countArrayMinute.length) / (time - startTime));
}
public static void main(String[] args) {
try {
CountService count = CountService.getInstance();
count.touch();
Thread.sleep(1000);
count.touch();
System.out.println("1.total : " + count.getCount());
Thread.sleep(1000);
count.touch();
System.out.println("2.total : " + count.getCount());
Thread.sleep(1000);
count.touch();
System.out.println("3.total : " + count.getCount());
Thread.sleep(1000);
count.touch();
System.out.println("4.total : " + count.getCount());
Thread.sleep(1000);
count.touch();
System.out.println("5.total : " + count.getCount());
Thread.sleep(1000);
count.touch();
System.out.println("6.total : " + count.getCount());
Thread.sleep(1000);
count.touch();
System.out.println("7.total : " + count.getCount());
Thread.sleep(8000);
count.touch();
System.out.println("8.total : " + count.getCount());
Thread.sleep(1000);
count.touch();
System.out.println("9.total : " + count.getCount());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| lgpl-3.0 |
loftuxab/community-edition-old | projects/share-po/src/test/java/org/alfresco/po/share/user/TrashCanPageTest.java | 17006 | /*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco 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.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.po.share.user;
import java.io.File;
import java.util.Calendar;
import java.util.List;
import org.alfresco.po.share.AbstractTest;
import org.alfresco.po.share.AlfrescoVersion;
import org.alfresco.po.share.DashBoardPage;
import org.alfresco.po.share.site.NewFolderPage;
import org.alfresco.po.share.site.SiteDashboardPage;
import org.alfresco.po.share.site.SiteFinderPage;
import org.alfresco.po.share.site.UploadFilePage;
import org.alfresco.po.share.site.document.DocumentLibraryPage;
import org.alfresco.po.share.util.FailedTestListener;
import org.alfresco.po.share.util.SiteUtil;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
/**
* TrashCanPage Test
*
* @author Subashni Prasanna
* @since 1.6
*/
@Listeners(FailedTestListener.class)
public class TrashCanPageTest extends AbstractTest
{
private String siteName;
private String siteName1;
private String fileName1;
private String fileName2;
private String fileName3;
private String fileName4;
private String fileName5;
private String userName ;
private String folderName;
DocumentLibraryPage docPage;
DashBoardPage dashBoard;
SiteDashboardPage site;
MyProfilePage myprofile;
TrashCanPage trashCan;
/**
* Pre test to create a content with properties set.
*
* @throws Exception
*/
@BeforeClass(groups = { "Enterprise4.2" })
public void prepare() throws Exception
{
String fname = anotherUser.getfName();
String lname = anotherUser.getlName();
AlfrescoVersion version = drone.getProperties().getVersion();
if(version.equals(AlfrescoVersion.Enterprise42))
{
userName = "Administrator";
}
else userName = fname + lname;
siteName = "TrashCanTest" + System.currentTimeMillis();
siteName1 = "TrashCanTest1" + System.currentTimeMillis();
folderName = "folder1" + System.currentTimeMillis();;
File file0 = SiteUtil.prepareFile("file1.txt");
fileName1 = file0.getName();
File file1 = SiteUtil.prepareFile("file2.txt");
fileName2 = file1.getName();
File file2 = SiteUtil.prepareFile("file3.txt");
fileName3 = file2.getName();
File file3 = SiteUtil.prepareFile("file4.txt");
fileName4 = file3.getName();
File file4 = SiteUtil.prepareFile("file5.txt");
fileName5 = file4.getName();
loginAs(username, password);
SiteUtil.createSite(drone, siteName, "Public");
SiteUtil.createSite(drone, siteName1, "Public");
SiteUtil.deleteSite(drone, siteName1);
SiteFinderPage siteFinderPage = drone.getCurrentPage().render();
siteFinderPage = siteFinderPage.searchForSite(siteName).render();
SiteDashboardPage site = siteFinderPage.selectSite(siteName).render();
docPage = site.getSiteNav().selectSiteDocumentLibrary().render();
NewFolderPage folder = docPage.getNavigation().selectCreateNewFolder().render();
docPage = folder.createNewFolder(folderName).render();
UploadFilePage upLoadPage = docPage.getNavigation().selectFileUpload().render();
upLoadPage.uploadFile(file0.getCanonicalPath()).render();
upLoadPage = docPage.getNavigation().selectFileUpload().render();
upLoadPage.uploadFile(file1.getCanonicalPath()).render();
upLoadPage = docPage.getNavigation().selectFileUpload().render();
upLoadPage.uploadFile(file2.getCanonicalPath()).render();
upLoadPage = docPage.getNavigation().selectFileUpload().render();
upLoadPage.uploadFile(file3.getCanonicalPath()).render();
upLoadPage = docPage.getNavigation().selectFileUpload().render();
upLoadPage.uploadFile(file4.getCanonicalPath()).render();
docPage = drone.getCurrentPage().render();
docPage = docPage.deleteItem(fileName1).render();
docPage = docPage.deleteItem(fileName2).render();
docPage = docPage.deleteItem(fileName3).render();
docPage = docPage.deleteItem(fileName4).render();
docPage = docPage.deleteItem(fileName5).render();
docPage = docPage.deleteItem(folderName).render();
}
@AfterClass(groups = { "Enterprise4.2" })
public void deleteSite()
{
trashCan.selectEmpty().render();
SiteUtil.deleteSite(drone, siteName);
}
public TrashCanPage getTrashCan()
{
dashBoard = docPage.getNav().selectMyDashBoard().render();
myprofile = dashBoard.getNav().selectMyProfile().render();
trashCan = myprofile.getProfileNav().selectTrashCan().render();
return trashCan;
}
/**
* Test to Check from My profile Page trashCan Page can be accessed
*/
@Test(groups = { "Enterprise4.2" }, priority=1)
public void test101TrashCanDisplayed()
{
trashCan = getTrashCan();
Assert.assertTrue(trashCan.getPageTitle().equalsIgnoreCase("User Trashcan"));
trashCan = (TrashCanPage) trashCan.itemSearch("ZZZZZ").render();
Assert.assertTrue(trashCan.checkNoItemsMessage());
trashCan = trashCan.clearSearch().render();
}
/*
* Test to check deleted files and folder are present in trashCan
*/
@Test(groups = { "Enterprise4.2" }, priority=2)
public void test102TrashCanInfoOfDeleteItems()
{
trashCan = getTrashCan();
List<TrashCanItem> item1 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE, fileName1, "documentLibrary");
if(item1.size() == 1)
{
Assert.assertTrue(item1.get(0).getFileName().equalsIgnoreCase(fileName1));
Assert.assertTrue(item1.get(0).getUserFullName().equalsIgnoreCase(userName));
Assert.assertTrue(item1.get(0).getDate().contains(Integer.toString(Calendar.getInstance().get(Calendar.YEAR))));
}
else
{
Assert.fail("Cannot find unique file");
}
List<TrashCanItem> item6 = trashCan.getTrashCanItemForContent(TrashCanValues.FOLDER, folderName, "documentLibrary");
if(item6.size() <= 1)
{
Assert.assertTrue(item6.get(0).getFileName().equalsIgnoreCase(folderName));
}
else
{
Assert.fail("Cannot find unique file");
}
List<TrashCanItem> item7 = trashCan.getTrashCanItemForContent(TrashCanValues.SITE, siteName1, "sites");
if(item7.size() <= 1)
{
Assert.assertTrue(item7.get(0).getFileName().equalsIgnoreCase(siteName1));
}
else
{
Assert.fail("Cannot find unique file");
}
}
/**
* Test to check the differnt select options ie All
*/
@Test(groups = { "Enterprise4.2" }, priority=3)
public void test103SelectActionsAll()
{
trashCan = getTrashCan();
trashCan = (TrashCanPage) trashCan.selectAction(SelectActions.ALL).render();
List<TrashCanItem> item1 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE,fileName1, "documentLibrary");
List<TrashCanItem> item2 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE,fileName2, "documentLibrary");
List<TrashCanItem> item3 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE,fileName3, "documentLibrary");
List<TrashCanItem> item4 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE,fileName4, "documentLibrary");
List<TrashCanItem> item5 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE,fileName5, "documentLibrary");
if(item1.size()<= 1)
{
Assert.assertTrue(item1.get(0).isCheckBoxSelected());
}
else
{
Assert.fail("Cannot find unique file");
}
if(item2.size()<= 1)
{
Assert.assertTrue(item2.get(0).isCheckBoxSelected());
}
else
{
Assert.fail("Cannot find unique file");
}
if(item3.size()<= 1)
{
Assert.assertTrue(item3.get(0).isCheckBoxSelected());
}
else
{
Assert.fail("Cannot find unique file");
}
if(item4.size()<= 1)
{
Assert.assertTrue(item4.get(0).isCheckBoxSelected());
}
else
{
Assert.fail("Cannot find unique file");
}
if(item5.size()<= 1)
{
Assert.assertTrue(item5.get(0).isCheckBoxSelected());
}
else
{
Assert.fail("Cannot find unique file");
}
}
/**
* Test to check the differnt select options ie invert
*/
@Test(groups = { "Enterprise4.2" }, priority=4)
public void test104SelectActionsInvert()
{
trashCan = (TrashCanPage) trashCan.selectAction(SelectActions.INVERT).render();
List<TrashCanItem> item1 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE,fileName1, "documentLibrary");
if(item1.size()<= 1)
{
Assert.assertFalse(item1.get(0).isCheckBoxSelected());
}
else
{
Assert.fail("Cannot find unique file");
}
}
/**
* Test to check the differnt select options ie none
*/
@Test(dependsOnMethods = "test104SelectActionsInvert", groups = { "Enterprise4.2" } , priority=5)
public void test105SelectActionsnone()
{
trashCan = (TrashCanPage) trashCan.selectAction(SelectActions.NONE).render();
List<TrashCanItem> item1 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE,fileName2, "documentLibrary");
if(item1.size()<= 1)
{
Assert.assertFalse(item1.get(0).isCheckBoxSelected());
}
else
{
Assert.fail("Cannot find unique file");
}
}
/**
* Test to Check searching in trashcan
*/
@Test(dependsOnMethods = "test105SelectActionsnone", groups = { "Enterprise4.2" }, priority=6)
public void test106TrashCanSearch()
{
boolean results = false;
trashCan = getTrashCan();
trashCan = (TrashCanPage) trashCan.itemSearch("ZZZZZ").render();
Assert.assertTrue(trashCan.checkNoItemsMessage());
trashCan = (TrashCanPage) trashCan.itemSearch("file").render();
List<TrashCanItem> trashCanItem = trashCan.getTrashCanItems();
Assert.assertFalse(trashCanItem.isEmpty());
for (TrashCanItem searchTerm : trashCanItem)
{
if (searchTerm.getFileName().contains("file")) results = true;
}
Assert.assertTrue(results);
}
/**
* Test to Check searching in trashcan
*/
@Test(groups = { "Enterprise4.2" }, priority=7)
public void test107TrashCanSelectCheckBox()
{
trashCan = getTrashCan();
List<TrashCanItem> item1 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE,fileName4, "documentLibrary");
if(item1.size() <= 1)
{
trashCan= item1.get(0).selectTrashCanItemCheckBox();
Assert.assertTrue(item1.get(0).isCheckBoxSelected());
}
else
{
Assert.fail("Cannot find unique file");
}
}
/**
* Test to Validated Selected items can be recovered
*/
@Test(groups = { "Enterprise4.2" }, priority=8)
public void test108TrashCanSelectedRecover()
{
boolean results = false;
trashCan = getTrashCan();
List<TrashCanItem> item1 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE,fileName4, "documentLibrary");
trashCan= item1.get(0).selectTrashCanItemCheckBox();
TrashCanRecoverConfirmDialog trashCanRecoverConfirmation = trashCan.selectedRecover().render();
trashCan = trashCanRecoverConfirmation.clickRecoverOK().render();
List<TrashCanItem> trashCanItem = trashCan.getTrashCanItems();
for (TrashCanItem itemTerm : trashCanItem)
{
if (itemTerm.getFileName().contains("fileName4")) results = true;
}
Assert.assertFalse(results);
}
/**
* Test to Validated Selected items can be recovered
*/
@Test(dependsOnMethods = "test108TrashCanSelectedRecover", groups = { "Enterprise4.2" }, priority=9)
public void test109TrashCanSelectedDelete()
{
boolean results = false;
List<TrashCanItem> item1 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE, fileName5, "documentLibrary");
if (item1.size() <= 1)
{
trashCan = item1.get(0).selectTrashCanItemCheckBox();
}
TrashCanDeleteConfirmationPage trashCanDeleteConfirmation = trashCan.selectedDelete().render();
TrashCanDeleteConfirmDialog trashCanConfrimDialog = (TrashCanDeleteConfirmDialog) trashCanDeleteConfirmation.clickOkButton().render();
trashCan = trashCanConfrimDialog.clickDeleteOK().render();
List<TrashCanItem> trashCanItemResults = trashCan.getTrashCanItems();
for (TrashCanItem itemTerm : trashCanItemResults)
{
if (itemTerm.getFileName().contains("fileName5")) results = true;
}
Assert.assertFalse(results);
}
/**
* Test to Clear the search entry trashcan
*/
@Test(dependsOnMethods = "test109TrashCanSelectedDelete", groups = { "Enterprise4.2" }, priority=10)
public void test110TrashClear()
{
trashCan = (TrashCanPage) trashCan.clearSearch().render();
Assert.assertTrue(trashCan.getPageTitle().equalsIgnoreCase("User Trashcan"));
}
/**
* Test to Recover an item trashcan
*/
@Test(dependsOnMethods = "test110TrashClear", groups = { "Enterprise4.2" }, priority=11)
public void test111TrashCanRecover()
{
List<TrashCanItem> item1 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE, fileName1, "documentLibrary");
if(item1.size() <= 1)
{
trashCan = (TrashCanPage) item1.get(0).selectTrashCanAction(TrashCanValues.RECOVER).render();
}
List<TrashCanItem> item2 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE, fileName1, "documentLibrary");
Assert.assertTrue(item2.isEmpty());
}
/**
* Test to Delete an item trashcan
*/
@Test(dependsOnMethods = "test111TrashCanRecover", groups = { "Enterprise4.2" }, priority=12)
public void test112TrashCanDelete()
{
List<TrashCanItem> item1 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE, fileName2, "documentLibrary");
if(item1.size() <= 1)
{
TrashCanDeleteConfirmationPage trashCanConfirmationDeleteDialog = (TrashCanDeleteConfirmationPage) item1.get(0).selectTrashCanAction(TrashCanValues.DELETE).render();
Assert.assertTrue(trashCanConfirmationDeleteDialog.isConfirmationDialogDisplayed());
trashCan = trashCanConfirmationDeleteDialog.clickOkButton().render();
}
List<TrashCanItem> item2 = trashCan.getTrashCanItemForContent(TrashCanValues.FILE, fileName2, "documentLibrary");
Assert.assertTrue(item2.isEmpty());
}
/**
* Test to Empty trashcan
*/
@Test(dependsOnMethods = "test112TrashCanDelete", groups = { "Enterprise4.2" }, priority=13)
public void test113TrashCanEmpty()
{
TrashCanEmptyConfirmationPage trashCanEmptyDialogPage = (TrashCanEmptyConfirmationPage) trashCan.selectEmpty().render();
Assert.assertTrue(trashCanEmptyDialogPage.isConfirmationDialogDisplayed());
trashCan = trashCanEmptyDialogPage.clickOkButton().render();
Assert.assertTrue(trashCan.getPageTitle().equalsIgnoreCase("User Trashcan"));
Assert.assertFalse(trashCan.hasTrashCanItems());
}
}
| lgpl-3.0 |
virtualcitySYSTEMS/importer-exporter | src/org/citydb/config/project/filter/FilterMode.java | 1771 | /*
* 3D City Database - The Open Source CityGML Database
* http://www.3dcitydb.org/
*
* (C) 2013 - 2015,
* Chair of Geoinformatics,
* Technische Universitaet Muenchen, Germany
* http://www.gis.bgu.tum.de/
*
* The 3D City Database is jointly developed with the following
* cooperation partners:
*
* virtualcitySYSTEMS GmbH, Berlin <http://www.virtualcitysystems.de/>
* M.O.S.S. Computer Grafik Systeme GmbH, Muenchen <http://www.moss.de/>
*
* The 3D City Database Importer/Exporter 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 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.
*/
package org.citydb.config.project.filter;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
@XmlType(name="FilterModeType")
public enum FilterMode {
@XmlEnumValue("none")
NONE("none"),
@XmlEnumValue("simple")
SIMPLE("simple"),
@XmlEnumValue("complex")
COMPLEX("complex");
private final String value;
FilterMode(String v) {
value = v;
}
public String value() {
return value;
}
public static FilterMode fromValue(String v) {
for (FilterMode c: FilterMode.values()) {
if (c.value.equals(v)) {
return c;
}
}
return COMPLEX;
}
}
| lgpl-3.0 |
daisy/pipeline-modules-common | html-utils/src/test/java/XProcSpecTest.java | 284 | import org.daisy.pipeline.junit.AbstractXSpecAndXProcSpecTest;
public class XProcSpecTest extends AbstractXSpecAndXProcSpecTest {
@Override
protected String[] testDependencies() {
return new String[] {
pipelineModule("file-utils"),
pipelineModule("zip-utils"),
};
}
}
| lgpl-3.0 |
SonarQubeCommunity/sonar-lua | lua-squid/src/main/java/org/sonar/lua/SourceFuncCall.java | 1278 | /*
* SonarQube Lua Plugin
* Copyright (C) 2016
* mailto:fati.ahmadi66 AT gmail DOT com
*
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.lua;
import org.sonar.squidbridge.api.SourceCode;
import org.sonar.squidbridge.api.SourceFile;
public class SourceFuncCall extends SourceCode {
public SourceFuncCall(String key) {
super(key);
}
public SourceFuncCall(SourceFile sourceFile, String funcCallSignature, int startAtLine) {
super(sourceFile.getKey() + "#" + funcCallSignature, funcCallSignature);
setStartAtLine(startAtLine);
}
}
| lgpl-3.0 |
rsksmart/rskj | rskj-core/src/test/java/org/ethereum/rpc/NewBlockFilterTest.java | 2251 | /*
* This file is part of RskJ
* Copyright (C) 2018 RSK Labs Ltd.
*
* 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.ethereum.rpc;
import co.rsk.blockchain.utils.BlockGenerator;
import org.ethereum.core.Block;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by ajlopez on 17/01/2018.
*/
public class NewBlockFilterTest {
@Test
public void noEvents() {
NewBlockFilter filter = new NewBlockFilter();
Object[] result = filter.getEvents();
Assert.assertNotNull(result);
Assert.assertEquals(0, result.length);
}
@Test
public void oneBlockAndEvent() {
NewBlockFilter filter = new NewBlockFilter();
Block block = new BlockGenerator().getBlock(1);
filter.newBlockReceived(block);
Object[] result = filter.getEvents();
Assert.assertNotNull(result);
Assert.assertEquals(1, result.length);
Assert.assertEquals("0x" + block.getHash(), result[0]);
}
@Test
public void twoBlocksAndEvents() {
NewBlockFilter filter = new NewBlockFilter();
Block block1 = new BlockGenerator().getBlock(1);
Block block2 = new BlockGenerator().getBlock(2);
filter.newBlockReceived(block1);
filter.newBlockReceived(block2);
Object[] result = filter.getEvents();
Assert.assertNotNull(result);
Assert.assertEquals(2, result.length);
Assert.assertEquals("0x" + block1.getHash(), result[0]);
Assert.assertEquals("0x" + block2.getHash(), result[1]);
}
}
| lgpl-3.0 |
ArticulatedSocialAgentsPlatform/HmiCore | HmiGraphics/src/hmi/graphics/collada/Perspective.java | 3602 | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer 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 Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package hmi.graphics.collada;
import hmi.xml.XMLFormatting;
import hmi.xml.XMLTokenizer;
import java.io.IOException;
/**
* Describes the field of view of an Perspective camera.
* @author Job Zwiers
*/
public class Perspective extends ColladaElement {
// attributes: none
// child elements
private XFov xfov;
private YFov yfov;
private AspectRatio aspectRatio;
private ZNear znear;
private ZFar zfar;
public Perspective(Collada collada, XMLTokenizer tokenizer) throws IOException {
super(collada);
readXML(tokenizer);
}
@Override
public StringBuilder appendContent(StringBuilder buf, XMLFormatting fmt) {
appendXMLStructure(buf, fmt, xfov);
appendXMLStructure(buf, fmt, yfov);
appendXMLStructure(buf, fmt, aspectRatio);
appendXMLStructure(buf, fmt, znear);
appendXMLStructure(buf, fmt, zfar);
return buf;
}
@Override
public void decodeContent(XMLTokenizer tokenizer) throws IOException {
while (tokenizer.atSTag()) {
String tag = tokenizer.getTagName();
if (tag.equals(XFov.xmlTag())) {
xfov = new XFov(getCollada(), tokenizer);
} else if (tag.equals(YFov.xmlTag())) {
yfov = new YFov(getCollada(), tokenizer);
} else if (tag.equals(AspectRatio.xmlTag())) {
aspectRatio = new AspectRatio(getCollada(), tokenizer);
} else if (tag.equals(ZNear.xmlTag())) {
znear = new ZNear(getCollada(), tokenizer);
} else if (tag.equals(ZFar.xmlTag())) {
zfar = new ZFar(getCollada(), tokenizer);
} else {
getCollada().warning(tokenizer.getErrorMessage("Perspective: skip : " + tokenizer.getTagName()));
tokenizer.skipTag();
}
}
addColladaNode(xfov);
addColladaNode(yfov);
addColladaNode(aspectRatio);
addColladaNode(znear);
addColladaNode(zfar);
}
/*
* The XML Stag for XML encoding
*/
private static final String XMLTAG = "perspective";
/**
* The XML Stag for XML encoding
*/
public static String xmlTag() { return XMLTAG; }
/**
* returns the XML Stag for XML encoding
*/
@Override
public String getXMLTag() {
return XMLTAG;
}
}
| lgpl-3.0 |
hlfernandez/GoL | app/src/main/java/hlfernandez/sing/ei/uvigo/es/gameoflife/Board.java | 2154 | package hlfernandez.sing.ei.uvigo.es.gameoflife;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Board {
private Set<Cell> cells;
public Board(Cell... cells) {
this.setCells(cells);
}
public Set<Cell> getCells() {
return this.cells;
}
public void setCells(Cell ... cells) {
this.cells = new HashSet<Cell>(Arrays.asList(cells));
}
public void nextGeneration() {
Set<Cell> nextGenerationCells = new HashSet<Cell>();
Map<Cell, Integer> cellNeighbourds = computeNeighbourds();
for (Cell c : cellNeighbourds.keySet()) {
Integer neigbhourds = cellNeighbourds.get(c);
if(neigbhourds == 3 ||
((neigbhourds == 3 || neigbhourds == 2) && this.cells.contains(c))){
nextGenerationCells.add(c);
}
}
this.cells = nextGenerationCells;
}
private Map<Cell, Integer> computeNeighbourds() {
Map<Cell, Integer> toret = new HashMap<Cell, Integer>();
List<Cell> allCells = new LinkedList<Cell>();
for (Cell cell : this.cells) {
allCells.addAll(cell.getNeighbourds());
}
for (Cell cell : allCells) {
if(toret.get(cell) == null) {
toret.put(cell,0);
}
toret.put(cell, toret.get(cell) + 1);
}
return toret;
}
@Override
public String toString() {
StringBuilder toString = new StringBuilder();
for (Cell c : this.cells) {
toString.append(c).append("\n");
}
return toString.toString();
}
public static final Cell[] randomCells(int rows, int cols){
Set<Cell> cells = new HashSet<Cell>();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (Math.random() > 0.7) {
cells.add(new Cell(i, j));
}
}
}
return cells.toArray(new Cell[cells.size()]);
}
}
| lgpl-3.0 |
TKlerx/jhmmt | src/main/java/be/ac/ulg/montefiore/run/jahmm/OpdfMultiGaussianFactory.java | 1785 | /*******************************************************************************
* Copyright (c) 2004-2009, Jean-Marc François. All Rights Reserved.
* Originally licensed under the New BSD license. See the LICENSE_OLD file.
* Copyright (c) 2013, Timo Klerx. All Rights Reserved.
* Now licensed under LGPL. See the LICENSE file.
* This file is part of jhmmt.
*
* jhmmt 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.
*
* jhmmt 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 jhmmt. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package be.ac.ulg.montefiore.run.jahmm;
/**
* This class can build <code>OpdfMultiGaussian</code> observation probability
* functions.
*/
public class OpdfMultiGaussianFactory
implements OpdfFactory<OpdfMultiGaussian>
{
private int dimension;
/**
* Generates a new multivariate gaussian observation probability
* distribution function.
*
* @param dimension The dimension of the vectors generated by this
* object.
*/
public OpdfMultiGaussianFactory(int dimension)
{
this.dimension = dimension;
}
public OpdfMultiGaussian factor()
{
return new OpdfMultiGaussian(dimension);
}
}
| lgpl-3.0 |
fyanardi/oanda-restlive-java | src/com/yanardi/oanda/data/Order.java | 2475 | package com.yanardi.oanda.data;
import java.util.Date;
public class Order {
private long id;
private String instrument;
private int units;
private OrderSide side;
private OrderType type;
private Date time;
private double price;
private double takeProfit;
private double stopLoss;
private Date expiry;
private double upperBound;
private double lowerBound;
private double trailingStop;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getInstrument() {
return instrument;
}
public void setInstrument(String instrument) {
this.instrument = instrument;
}
public int getUnits() {
return units;
}
public void setUnits(int units) {
this.units = units;
}
public OrderSide getSide() {
return side;
}
public void setSide(OrderSide side) {
this.side = side;
}
public OrderType getType() {
return type;
}
public void setType(OrderType type) {
this.type = type;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getTakeProfit() {
return takeProfit;
}
public void setTakeProfit(double takeProfit) {
this.takeProfit = takeProfit;
}
public double getStopLoss() {
return stopLoss;
}
public void setStopLoss(double stopLoss) {
this.stopLoss = stopLoss;
}
public Date getExpiry() {
return expiry;
}
public void setExpiry(Date expiry) {
this.expiry = expiry;
}
public double getUpperBound() {
return upperBound;
}
public void setUpperBound(double upperBound) {
this.upperBound = upperBound;
}
public double getLowerBound() {
return lowerBound;
}
public void setLowerBound(double lowerBound) {
this.lowerBound = lowerBound;
}
public double getTrailingStop() {
return trailingStop;
}
public void setTrailingStop(double trailingStop) {
this.trailingStop = trailingStop;
}
}
| lgpl-3.0 |
MingweiSamuel/Zyra | src/main/gen/com/mingweisamuel/zyra/matchV4/Matchlist.java | 1379 | package com.mingweisamuel.zyra.matchV4;
import com.google.common.base.Objects;
import java.io.Serializable;
import java.lang.Object;
import java.lang.Override;
import java.util.List;
/**
* Matchlist.<br><br>
*
* This class was automatically generated from the <a href="http://www.mingweisamuel.com/riotapi-schema/openapi-3.0.0.min.json">Riot API reference</a>. */
public class Matchlist implements Serializable {
public final int endIndex;
public final List<MatchReference> matches;
public final int startIndex;
public final int totalGames;
public Matchlist(final int endIndex, final List<MatchReference> matches, final int startIndex,
final int totalGames) {
this.endIndex = endIndex;
this.matches = matches;
this.startIndex = startIndex;
this.totalGames = totalGames;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof Matchlist)) return false;
final Matchlist other = (Matchlist) obj;
return true
&& Objects.equal(endIndex, other.endIndex)
&& Objects.equal(matches, other.matches)
&& Objects.equal(startIndex, other.startIndex)
&& Objects.equal(totalGames, other.totalGames);}
@Override
public int hashCode() {
return Objects.hashCode(0,
endIndex,
matches,
startIndex,
totalGames);}
}
| lgpl-3.0 |
almondtools/comtemplate | src/main/java/net/amygdalum/comtemplate/engine/DefaultErrorHandler.java | 1748 | package net.amygdalum.comtemplate.engine;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import net.amygdalum.comtemplate.engine.expressions.ErrorExpression;
public class DefaultErrorHandler implements ErrorHandler {
private List<Default> defaults;
public DefaultErrorHandler() {
this.defaults = new ArrayList<>();
}
@Override
public TemplateImmediateExpression handle(ErrorExpression errorExpression) {
Messages.error(errorExpression.getMessage());
return errorExpression;
}
@Override
public TemplateImmediateExpression clear(TemplateExpression expression, TemplateImmediateExpression resolvedExpression) {
if (resolvedExpression instanceof ErrorExpression) {
resolvedExpression = applyDefaults(expression).orElse(resolvedExpression);
}
if (resolvedExpression instanceof ErrorExpression) {
return handle((ErrorExpression) resolvedExpression);
}
return resolvedExpression;
}
private Optional<TemplateImmediateExpression> applyDefaults(TemplateExpression expression) {
return defaults.stream()
.filter(value -> value.expression == expression)
.findFirst()
.map(value -> value.defaultExpression.get());
}
@Override
public void addDefault(TemplateExpression expression, Supplier<TemplateImmediateExpression> defaultExpression) {
defaults.add(new Default(expression, defaultExpression));
}
private static class Default {
public TemplateExpression expression;
public Supplier<TemplateImmediateExpression> defaultExpression;
public Default(TemplateExpression expression, Supplier<TemplateImmediateExpression> defaultExpression) {
this.expression = expression;
this.defaultExpression = defaultExpression;
}
}
}
| lgpl-3.0 |
teryk/sonarqube | server/sonar-server/src/test/java/org/sonar/server/computation/AnalysisReportLogMediumTest.java | 3324 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.computation;
import com.google.common.collect.Iterables;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import org.sonar.core.activity.Activity;
import org.sonar.core.computation.db.AnalysisReportDto;
import org.sonar.core.persistence.DbSession;
import org.sonar.server.activity.ActivityService;
import org.sonar.server.activity.index.ActivityIndex;
import org.sonar.server.db.DbClient;
import org.sonar.server.tester.ServerTester;
import java.util.Map;
import static org.fest.assertions.Assertions.assertThat;
import static org.sonar.core.activity.Activity.Type.ANALYSIS_REPORT;
import static org.sonar.core.computation.db.AnalysisReportDto.Status.FAILED;
public class AnalysisReportLogMediumTest {
@ClassRule
public static ServerTester tester = new ServerTester();
private ActivityService service = tester.get(ActivityService.class);
private ActivityIndex index = tester.get(ActivityIndex.class);
private DbSession dbSession;
private AnalysisReportLog sut;
@Before
public void before() {
tester.clearDbAndIndexes();
dbSession = tester.get(DbClient.class).openSession(false);
}
@After
public void after() {
dbSession.close();
}
@Test
public void insert_find_analysis_report_log() {
AnalysisReportDto report = AnalysisReportDto.newForTests(1L)
.setProjectKey("projectKey")
.setProjectName("projectName")
.setStatus(FAILED);
report.setCreatedAt(DateUtils.parseDate("2014-10-15"))
.setUpdatedAt(DateUtils.parseDate("2014-10-16"));
service.write(dbSession, ANALYSIS_REPORT, new AnalysisReportLog(report));
dbSession.commit();
// 0. AssertBase case
assertThat(index.findAll().getHits()).hasSize(1);
Activity activity = Iterables.getFirst(index.findAll().getHits(), null);
assertThat(activity).isNotNull();
Map<String, String> details = activity.details();
assertThat(details.get("id")).isEqualTo(String.valueOf(report.getId()));
assertThat(details.get("projectKey")).isEqualTo(report.getProjectKey());
assertThat(details.get("projectName")).isEqualTo(report.getProjectName());
assertThat(details.get("status")).isEqualTo("FAILED");
assertThat(details.get("createdAt")).isEqualTo("2014-10-15T00:00:00+0200");
assertThat(details.get("updatedAt")).isEqualTo("2014-10-16T00:00:00+0200");
}
}
| lgpl-3.0 |
galleon1/chocolate-milk | src/org/chocolate_milk/model/StandardTermsAddRs.java | 3350 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: StandardTermsAddRs.java,v 1.1.1.1 2010-05-04 22:06:00 ryan Exp $
*/
package org.chocolate_milk.model;
/**
* Class StandardTermsAddRs.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:00 $
*/
@SuppressWarnings("serial")
public class StandardTermsAddRs extends StandardTermsAddRsType
implements java.io.Serializable
{
//----------------/
//- Constructors -/
//----------------/
public StandardTermsAddRs() {
super();
}
//-----------/
//- Methods -/
//-----------/
/**
* Method isValid.
*
* @return true if this object is valid according to the schema
*/
public boolean isValid(
) {
try {
validate();
} catch (org.exolab.castor.xml.ValidationException vex) {
return false;
}
return true;
}
/**
*
*
* @param out
* @throws org.exolab.castor.xml.MarshalException if object is
* null or if any SAXException is thrown during marshaling
* @throws org.exolab.castor.xml.ValidationException if this
* object is an invalid instance according to the schema
*/
public void marshal(
final java.io.Writer out)
throws org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
org.exolab.castor.xml.Marshaller.marshal(this, out);
}
/**
*
*
* @param handler
* @throws java.io.IOException if an IOException occurs during
* marshaling
* @throws org.exolab.castor.xml.ValidationException if this
* object is an invalid instance according to the schema
* @throws org.exolab.castor.xml.MarshalException if object is
* null or if any SAXException is thrown during marshaling
*/
public void marshal(
final org.xml.sax.ContentHandler handler)
throws java.io.IOException, org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
org.exolab.castor.xml.Marshaller.marshal(this, handler);
}
/**
* Method unmarshal.
*
* @param reader
* @throws org.exolab.castor.xml.MarshalException if object is
* null or if any SAXException is thrown during marshaling
* @throws org.exolab.castor.xml.ValidationException if this
* object is an invalid instance according to the schema
* @return the unmarshaled
* org.chocolate_milk.model.StandardTermsAddRs
*/
public static org.chocolate_milk.model.StandardTermsAddRs unmarshal(
final java.io.Reader reader)
throws org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
return (org.chocolate_milk.model.StandardTermsAddRs) org.exolab.castor.xml.Unmarshaller.unmarshal(org.chocolate_milk.model.StandardTermsAddRs.class, reader);
}
/**
*
*
* @throws org.exolab.castor.xml.ValidationException if this
* object is an invalid instance according to the schema
*/
public void validate(
)
throws org.exolab.castor.xml.ValidationException {
org.exolab.castor.xml.Validator validator = new org.exolab.castor.xml.Validator();
validator.validate(this);
}
}
| lgpl-3.0 |
stropa/dataglow | src/main/java/org/dataglow/v1/configuration/Schedulable.java | 314 | package org.dataglow.v1.configuration;
import java.time.LocalDateTime;
public interface Schedulable {
LocalDateTime getLastRun();
void setLastRun(LocalDateTime lastRun);
long getPeriodSeconds();
void setPeriodSeconds(long periodSeconds);
void setJob(Runnable job);
void runJob();
}
| lgpl-3.0 |
SINTEF-9012/cloudml | indicators/src/main/java/org/cloudml/indicators/Selection.java | 2812 | /**
* This file is part of CloudML [ http://cloudml.org ]
*
* Copyright (C) 2012 - SINTEF ICT
* Contact: Franck Chauvel <franck.chauvel@sintef.no>
*
* Module: root
*
* CloudML 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.
*
* CloudML 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 CloudML. If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.cloudml.indicators;
import eu.diversify.trio.filter.All;
import eu.diversify.trio.filter.Filter;
import eu.diversify.trio.filter.TaggedAs;
/**
* Represent the TRIO tags that can be generated from any CloudML models:
* internal, external and VM
*/
public enum Selection {
INTERNAL("internal", new TaggedAs("internal")),
EXTERNAL("external", new TaggedAs("external")),
VM("vm", new TaggedAs("vm")),
SERVICE("service", new TaggedAs("service")),
NOT_SERVICE("not service", new TaggedAs("service").not()),
ALL("all", All.getInstance());
private final String label;
private final Filter trioFilter;
private Selection(String label, Filter trioFilter) {
this.label = label;
this.trioFilter = trioFilter;
}
/**
* @return the label associated with this tag
*/
public String getLabel() {
return label;
}
/**
* @return the associated trio filter
*/
public Filter asTrioFilter() {
return trioFilter;
}
/**
* Build a tag from a given text.
*
* @param text the text to be parsed
* @return the related tag
*/
public static Selection readFrom(String text) {
requireValid(text);
final String escapedText = text.toLowerCase().trim();
for (Selection anyTag: Selection.values()) {
if (anyTag.getLabel().equals(escapedText)) {
return anyTag;
}
}
final String errorMessage = String.format("There is no tag matching the text '%s'", text);
throw new IllegalArgumentException(errorMessage);
}
private static void requireValid(String text) throws IllegalArgumentException {
if (text == null) {
throw new IllegalArgumentException("No tag can be read from 'null'");
}
if (text.isEmpty()) {
throw new IllegalArgumentException("No tag can be read from an empty string");
}
}
}
| lgpl-3.0 |
ljuarezr/ljuarezr-reflex | app/src/main/java/com/example/ljuarezr/ljuarezr_reflex/ReactionTimeStatsController.java | 3356 |
/*
Ljuarezr-reflex - Reaction timer and Gameshow buzzer application.
Copyright (C)2015, Laura Patricia Juarez Reyes
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 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 General Public License for more details.
*/
package com.example.ljuarezr.ljuarezr_reflex;
import java.util.ArrayList;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
/**
* Created by ljuarezr on 10/1/15.
*/
public class ReactionTimeStatsController {
//Lazy Singleton
private static ReactionTimesList reactionTimesList = null;
static public ReactionTimesList getReactionTimesList() {
if (reactionTimesList == null){
reactionTimesList = new ReactionTimesList();
}
return reactionTimesList;
}
public void clearAll(){
getReactionTimesList().clearAll();
}
public void addSingleBuzz(int singleBuzz) {
getReactionTimesList().addSingleBuzz(singleBuzz);
}
/*
public ArrayList<Integer> getLast10 () {
return getReactionTimesList().getLast10();
}
public ArrayList<Integer> getLast100 () {
return getReactionTimesList().getLast100();
}
public ArrayList<Integer> getAllTime() {
return getReactionTimesList().getAllTime();
}
*/
public List<Integer> getMinBuzz() throws EmptyReactionTimesListException{;
List<Integer> mins = new ArrayList<>();
mins.add(getReactionTimesList().getMin(getReactionTimesList().getLast10()));
mins.add(getReactionTimesList().getMin(getReactionTimesList().getLast100()));
mins.add(getReactionTimesList().getMin(getReactionTimesList().getAllTime()));
return mins;
}
public List<Integer> getMaxBuzz() throws EmptyReactionTimesListException{;
List<Integer> maxs = new ArrayList<>();
maxs.add(getReactionTimesList().getMax(getReactionTimesList().getLast10()));
maxs.add(getReactionTimesList().getMax(getReactionTimesList().getLast100()));
maxs.add(getReactionTimesList().getMax(getReactionTimesList().getAllTime()));
return maxs;
}
public List<Integer> getAvgBuzz() throws EmptyReactionTimesListException{;
List<Integer> avgs = new ArrayList<>();
avgs.add(getReactionTimesList().getAvg(getReactionTimesList().getLast10()));
avgs.add(getReactionTimesList().getAvg(getReactionTimesList().getLast100()));
avgs.add(getReactionTimesList().getAvg(getReactionTimesList().getAllTime()));
return avgs;
}
public List<Integer> getMedBuzz() throws EmptyReactionTimesListException{;
List<Integer> meds = new ArrayList<>();
meds.add(getReactionTimesList().getMed(getReactionTimesList().getLast10()));
meds.add(getReactionTimesList().getMed(getReactionTimesList().getLast100()));
meds.add(getReactionTimesList().getMed(getReactionTimesList().getAllTime()));
return meds;
}
}
| lgpl-3.0 |
android-plugin/uexAudio | src/org/zywx/wbpalmstar/plugin/uexaudio/PFMusicPlayer.java | 18359 | package org.zywx.wbpalmstar.plugin.uexaudio;
import java.io.File;
import org.zywx.wbpalmstar.base.BDebug;
import org.zywx.wbpalmstar.base.BUtility;
import org.zywx.wbpalmstar.base.ResoureFinder;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetFileDescriptor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
public abstract class PFMusicPlayer {
private static final String TAG = "PFMusicPlayer";
public final static String F_SDKARD_PATH = "/sdcard/";//SD卡
public final static String F_RES_PATH = "file:///res/";//工程的assets文件夹下
public final static String F_DATA_PATH = "file:///data/";
public final static String F_HTTP_PATH = "http://";//网络地址
public final static String F_RES_ROOT_PATH = "file:///res/widget/";//工程的assets文件夹下widget文件夹
public final static String F_WGT_PATH = "wgt://";//工程的assets文件夹下widget文件夹
public final static String F_WGTS_PATH = "wgts://";//工程的assets文件夹下widget文件夹
public final static String F_ABSOLUTE_PATH = "/";//绝对路径
public final static String F_OPPOSITE_PATH = "";//相对路径
public final static String F_BASE_RES_PATH = "res://";//工程res目录
public final static String F_BASE_PATH = "BASE_PATH";//基本路径
public String basePath = "";
private MediaPlayer m_mediaPlayer = null;
private SoundPool m_soundPool = null;
private Context m_context = null;
private final static int MEDIAPLAY_STATE_PLAYING = 0;//播放状态
private final static int MEDIAPLAY_STATE_PAUSEING = 1;//暂停状态
private final static int MEDIAPLAY_STATE_STOPING = 2;//停止状态
private int playState = 0;
public static int soundID = 0;
private ResoureFinder finder = ResoureFinder.getInstance();
private int loopCount = 0;
private int loopIndex = 0;
private boolean isModeInCall = false;
public PFMusicPlayer(Context inContext) {
m_context = inContext;
}
public int getLoopIndex() {
return loopIndex;
}
public void setModeInCall(boolean isModeInCall) {
this.isModeInCall = isModeInCall;
}
/*
* SD卡目录
*/
public String getSDDirectory() {
return Environment.getExternalStorageDirectory() + "/";
}
public void openSound(int maxStream, int streamType, int srcQuality) {
if (m_soundPool == null) {
m_soundPool = new SoundPool(maxStream, streamType, srcQuality);
}
}
public int loadSound(String inPath) {
soundID = 0;
try {
if (inPath.startsWith(PFMusicPlayer.F_SDKARD_PATH) || inPath.startsWith(PFMusicPlayer.F_HTTP_PATH) || inPath.startsWith("/mnt/sdcard/")) {//(wgt://和wgts://和sd卡开头一致)(网络)
soundID = m_soundPool.load(inPath, 1);
} else if (inPath.startsWith(BUtility.F_Widget_RES_path)) {//(res://)
final AssetFileDescriptor descriptor = this.m_context.getAssets().openFd(inPath);
if (descriptor == null) {
alertMessage(finder.getString("plugin_audio_info_nofile"), true);
} else {
soundID = m_soundPool.load(descriptor, 1);
}
} else if (inPath.startsWith("/data/data/")) {//(box://)
soundID = m_soundPool.load(inPath, 1);
} else if (inPath.startsWith("/")) {
File myFile = new File(inPath);
soundID = m_soundPool.load(myFile.getAbsolutePath(), 1);
} else {
alertMessage(finder.getString("plugin_audio_info_nofile") + inPath, true);
}
} catch (Exception e) {
e.printStackTrace();
}
return soundID;
}
//因为每次打开返回的id不同,停止方法中需要用到该id
public int playSound(int soundID) {
if (m_soundPool != null) {
int inStreamID = m_soundPool.play(soundID, 3, 3, 0, -1, 1);
if (inStreamID == 0) {
stopSound(soundID);
} else {
}
return inStreamID;
}
return 0;
}
public void stopSound(int inStreamID) {
if (m_soundPool != null) {
m_soundPool.stop(inStreamID);
checkModeEnd();
}
}
/*
* 创建meidaplayer对象,提供调用
*/
public void open() {
if (m_mediaPlayer == null) {
m_mediaPlayer = new MediaPlayer();
m_mediaPlayer.setOnCompletionListener(new mediaPlayerCompletionListener());
m_mediaPlayer.setOnErrorListener(new mediaPlayerErrorListener());
m_mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
BDebug.i(TAG, "onBufferingUpdate: " + percent + "%");
}
});
playState = MEDIAPLAY_STATE_STOPING;
}
}
/*
* 播放完音乐监听
*/
class mediaPlayerCompletionListener implements OnCompletionListener {
@Override
public void onCompletion(MediaPlayer mp) {
if (m_mediaPlayer != null) {
if(loopCount == -1){
checkModeStart();
m_mediaPlayer.start();
playState = MEDIAPLAY_STATE_PLAYING;
onPlayFinished(loopIndex);
loopIndex++;
}else if (loopCount > 0 && loopIndex < loopCount) {
checkModeStart();
m_mediaPlayer.start();
playState = MEDIAPLAY_STATE_PLAYING;
loopIndex++;
onPlayFinished(loopIndex);
} else {
m_mediaPlayer.stop();
playState = MEDIAPLAY_STATE_STOPING;
onPlayFinished(loopIndex);
checkModeEnd();
}
} else {
onPlayError();
}
}
}
/*
* 播放完音乐(提供给EUEX对象回调)
*/
public abstract void onPlayFinished(int index);
/*
* 播放完音乐(提供给EUEX对象回调)
*/
public abstract void onPlayError();
/*
* 音乐出错监听
*/
class mediaPlayerErrorListener implements OnErrorListener {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if (m_mediaPlayer != null) {
m_mediaPlayer.release();
m_mediaPlayer = null;
}
playState = MEDIAPLAY_STATE_STOPING;
BDebug.e(TAG, "onError: what=" + what + " extra=" + extra);
onPlayError();
return false;
}
}
/*
* 根据inPath路径导入播放音乐路径
*/
public void play(String inPath, int loopType) {
if (m_mediaPlayer != null) {
try {
checkModeStart();
switch (playState) {
case MEDIAPLAY_STATE_STOPING:
m_mediaPlayer.reset();
if (loadMediaPlayerFile(inPath)) {// 读取文件成功才执行
m_mediaPlayer.prepare();
switch (loopType) {
case -1:
m_mediaPlayer.setLooping(true);
loopCount = -1;
loopIndex = 0;
break;
case 0:
m_mediaPlayer.setLooping(false);
loopCount = 0;
loopIndex = 0;
break;
default:
if (loopType > 0) {
m_mediaPlayer.setLooping(false);
loopCount = loopType - 1;
loopIndex = 0;
}
break;
}
m_mediaPlayer.start();
playState = MEDIAPLAY_STATE_PLAYING;
}
break;
case MEDIAPLAY_STATE_PAUSEING:
m_mediaPlayer.start();
playState = MEDIAPLAY_STATE_PLAYING;
break;
}
} catch (Exception e) {
Toast.makeText(m_context, ResoureFinder.getInstance().getStringId(m_context, "plugin_audio_info_nofile"), Toast.LENGTH_LONG).show();
checkModeEnd();
}
}else{
onPlayError();
}
}
private AlertDialog alertDialog;
// 弹出消息框
private void alertMessage(String message, final boolean exitOnConfirm) {
alertDialog = new AlertDialog.Builder(m_context).setTitle(finder.getString("prompt")).setMessage(message)
.setCancelable(false)
.setPositiveButton(finder.getString("confirm"), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (exitOnConfirm) {
dialog.dismiss();
stop();
}
}
}).create();
alertDialog.show();
}
/*
* 根据inPath的内容判断导入方式
*/
public boolean loadMediaPlayerFile(String inPath) throws Exception {
boolean isLoadMediaPlayerFileSucceed = true;
try {
if (inPath.indexOf(BUtility.F_Widget_RES_path) >= 0) {// (res://)
final AssetFileDescriptor descriptor = this.m_context.getAssets().openFd(inPath.substring(inPath.indexOf(BUtility.F_Widget_RES_path)));
if (descriptor == null) {
alertMessage(finder.getString("plugin_audio_info_nofile"), true);
} else {
m_mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
}
} else {
Uri uri = Uri.parse(inPath);
if (uri != null)
m_mediaPlayer.setDataSource(m_context, uri);
}
} catch (Exception e) {
isLoadMediaPlayerFileSucceed = false;
throw e;
} catch (Error e) {
isLoadMediaPlayerFileSucceed = false;
throw e;
}
return isLoadMediaPlayerFileSucceed;
}
/*
* 关闭当前正在播放的音乐
*/
public void pause() {
try {
if (m_mediaPlayer != null && m_mediaPlayer.isPlaying()) {
m_mediaPlayer.pause();
playState = MEDIAPLAY_STATE_PAUSEING;
}
} catch (Exception e) {
}
checkModeEnd();
}
/*
* 停止播放当前音乐,将时间滑块调整到音乐开始处,重新播放
*/
public void replay() {
try {
checkModeStart();
if (m_mediaPlayer != null) {
m_mediaPlayer.stop();
m_mediaPlayer.prepare();
m_mediaPlayer.seekTo(0);
m_mediaPlayer.start();
playState = MEDIAPLAY_STATE_PLAYING;
}
} catch (Exception e) {
if (BDebug.DEBUG){
e.printStackTrace();
}
}
}
/*
* 停止播放当前的音乐,无论处于什么状态
*/
public void stop() {
try {
if (m_mediaPlayer != null) {
boolean isPlaying = m_mediaPlayer.isPlaying();
m_mediaPlayer.stop();
playState = MEDIAPLAY_STATE_STOPING;
if (isPlaying) {
onPlayFinished(loopIndex);
}
}
} catch (Exception e) {
}
checkModeEnd();
}
/*
* 停止播放当前音乐,根据inPath提供的路径重新导入,并开始播放
*/
public void palyNext(String inPath) {
if (m_mediaPlayer != null) {
try {
checkModeStart();
switch (playState) {
case MEDIAPLAY_STATE_PLAYING:
case MEDIAPLAY_STATE_PAUSEING:
m_mediaPlayer.stop();
m_mediaPlayer.prepareAsync();
break;
case MEDIAPLAY_STATE_STOPING:
m_mediaPlayer.prepareAsync();
break;
}
m_mediaPlayer.reset();
if (loadMediaPlayerFile(inPath)) {
m_mediaPlayer.prepare();
m_mediaPlayer.setLooping(false);
m_mediaPlayer.start();
playState = MEDIAPLAY_STATE_PLAYING;
}
} catch (Exception e) {
}
}
}
/*
* 调高音量
*/
public void volumeUp() {
AudioManager audioManager = (AudioManager) m_context.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
int maxVolum = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);// 最大音量
int currentVolum = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);// 当前音量
if (currentVolum < maxVolum) {
currentVolum++;
}
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolum, AudioManager.FLAG_SHOW_UI);
}
/*
* 调低音量
*/
public void volumeDown() {
AudioManager audioManager = (AudioManager) m_context.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
int currentVolum = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);// 当前音量
if (currentVolum > 0) {
currentVolum--;
}
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolum, AudioManager.FLAG_SHOW_UI);
}
public void checkModeStart() {
if (isModeInCall) {
playModeInCall();
}
}
public void checkModeEnd() {
playModeNormol();
}
/**
* 听筒模式
*/
private void playModeInCall() {
AudioManager audioManager = (AudioManager) m_context.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getMode() == AudioManager.MODE_NORMAL) {
audioManager.setMode(AudioManager.MODE_IN_CALL);
if (audioManager.getMode() == AudioManager.MODE_NORMAL) {
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
}
}
}
/**
* 正常模式
*/
private void playModeNormol() {
AudioManager audioManager = (AudioManager) m_context.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getMode() == AudioManager.MODE_IN_COMMUNICATION || audioManager.getMode() == AudioManager.MODE_IN_CALL) {
audioManager.setMode(AudioManager.MODE_NORMAL);
}
}
/**
* make a SensorEventListener
*
* @return
*/
public SensorEventListener getSensorEventListener() {
return new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
try {
float range = event.values[0];
SensorManager mSensorManager = (SensorManager) m_context.getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
Log.i(TAG, "uexAudio_onSensorChanged " + range + " max:" + mSensor.getMaximumRange());
if (range == 0) {
if (m_mediaPlayer != null) {
if (isModeInCall) {
return;
}
if (m_mediaPlayer.isPlaying()) {
m_mediaPlayer.pause();
playModeInCall();
m_mediaPlayer.start();
}
}
} else {
if (m_mediaPlayer != null) {
if (isModeInCall) {
return;
}
if (m_mediaPlayer.isPlaying()) {
m_mediaPlayer.pause();
playModeNormol();
m_mediaPlayer.start();
}
}
}
} catch (Exception e) {
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
}
| lgpl-3.0 |
xXKeyleXx/MyPet | modules/v1_16_R1/src/main/java/de/Keyle/MyPet/compat/v1_16_R1/entity/ai/movement/Sit.java | 3482 | /*
* This file is part of MyPet
*
* Copyright © 2011-2020 Keyle
* MyPet is licensed under the GNU Lesser General Public License.
*
* MyPet 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.
*
* MyPet 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 de.Keyle.MyPet.compat.v1_16_R1.entity.ai.movement;
import de.Keyle.MyPet.api.entity.ai.AIGoal;
import de.Keyle.MyPet.api.util.Compat;
import de.Keyle.MyPet.compat.v1_16_R1.entity.EntityMyPet;
import de.Keyle.MyPet.compat.v1_16_R1.entity.types.EntityMyCat;
import de.Keyle.MyPet.compat.v1_16_R1.entity.types.EntityMyFox;
import de.Keyle.MyPet.compat.v1_16_R1.entity.types.EntityMyPanda;
import de.Keyle.MyPet.compat.v1_16_R1.entity.types.EntityMyWolf;
@Compat("v1_16_R1")
public class Sit implements AIGoal {
private EntityMyPet entityMyPet;
private boolean sitting = false;
public Sit(EntityMyPet entityMyPet) {
this.entityMyPet = entityMyPet;
}
@Override
public boolean shouldStart() {
if (!(this.entityMyPet instanceof EntityMyWolf) &&
!(this.entityMyPet instanceof EntityMyCat) &&
!(this.entityMyPet instanceof EntityMyPanda) &&
!(this.entityMyPet instanceof EntityMyFox)) {
return false;
} else if (this.entityMyPet.isInWater()) {
return false;
} else if (!this.entityMyPet.isOnGround()) {
return false;
}
return this.sitting;
}
@Override
public void start() {
this.entityMyPet.getPetNavigation().stop();
if (this.entityMyPet instanceof EntityMyWolf) {
((EntityMyWolf) this.entityMyPet).applySitting(true);
} else if (this.entityMyPet instanceof EntityMyCat) {
((EntityMyCat) this.entityMyPet).applySitting(true);
} else if (this.entityMyPet instanceof EntityMyFox) {
((EntityMyFox) this.entityMyPet).updateActionsWatcher(1, true);
} else if (this.entityMyPet instanceof EntityMyPanda) {
((EntityMyPanda) this.entityMyPet).updateActionsWatcher(8, true);
}
entityMyPet.setGoalTarget(null);
}
@Override
public void finish() {
if (this.entityMyPet instanceof EntityMyWolf) {
((EntityMyWolf) this.entityMyPet).applySitting(false);
} else if (this.entityMyPet instanceof EntityMyCat) {
((EntityMyCat) this.entityMyPet).applySitting(false);
} else if (this.entityMyPet instanceof EntityMyFox) {
((EntityMyFox) this.entityMyPet).updateActionsWatcher(1, false);
} else if (this.entityMyPet instanceof EntityMyPanda) {
((EntityMyPanda) this.entityMyPet).updateActionsWatcher(8, false);
}
}
public void setSitting(boolean sitting) {
this.sitting = sitting;
}
public boolean isSitting() {
return this.sitting;
}
public void toggleSitting() {
this.sitting = !this.sitting;
}
} | lgpl-3.0 |
mdamis/unilabIDE | Unitex-Java/src/fr/umlv/unitex/debug/DebugDetails.java | 1999 | /*
* Unitex
*
* Copyright (C) 2001-2014 Université Paris-Est Marne-la-Vallée <unitex@univ-mlv.fr>
*
* 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.
*
*/
package fr.umlv.unitex.debug;
public class DebugDetails {
public static String[] fields = new String[] { "Tag", "Output", "Matched",
"Graph", "Box", "Line" };
public String tag, output, matched;
public int graph, box, line;
public DebugDetails(String tag, String output, String matched, int graph,
int box, int line, DebugInfos infos) {
this.tag = tag;
if (tag.startsWith((char) 5 + "<")) {
this.tag = "<< "
+ infos.graphNames
.get(Integer.parseInt(tag.substring(2)) - 1);
} else if (tag.startsWith((char) 5 + ">")) {
this.tag = ">> "
+ infos.graphNames
.get(Integer.parseInt(tag.substring(2)) - 1);
}
this.output = output;
this.matched = matched;
this.graph = graph;
this.box = box;
this.line = line;
}
public Object getField(int columnIndex) {
switch (columnIndex) {
case 0:
return tag;
case 1:
return output;
case 2:
return matched;
case 3:
return Integer.valueOf(graph);
case 4:
return Integer.valueOf(box);
case 5:
return Integer.valueOf(line);
default:
throw new IllegalArgumentException("Invalid field index: "
+ columnIndex);
}
}
}
| lgpl-3.0 |
jmecosta/sonar | sonar-plugin-api/src/test/java/org/sonar/api/workflow/condition/HasProjectPropertyConditionTest.java | 2510 | /*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2012 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.api.workflow.condition;
import org.junit.Test;
import org.sonar.api.Properties;
import org.sonar.api.Property;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.Settings;
import org.sonar.api.workflow.internal.DefaultReview;
import org.sonar.api.workflow.internal.DefaultWorkflowContext;
import static org.fest.assertions.Assertions.assertThat;
public class HasProjectPropertyConditionTest {
@Test
public void doVerify() {
HasProjectPropertyCondition condition = new HasProjectPropertyCondition("jira.url");
DefaultWorkflowContext context = new DefaultWorkflowContext();
context.setSettings(new Settings().setProperty("jira.url", "http://jira"));
assertThat(condition.doVerify(new DefaultReview(), context)).isTrue();
}
@Test
public void missingProperty() {
HasProjectPropertyCondition condition = new HasProjectPropertyCondition("jira.url");
DefaultWorkflowContext context = new DefaultWorkflowContext();
context.setSettings(new Settings());
assertThat(condition.doVerify(new DefaultReview(), context)).isFalse();
}
@Test
public void returnTrueIfDefaultValue() {
HasProjectPropertyCondition condition = new HasProjectPropertyCondition("jira.url");
DefaultWorkflowContext context = new DefaultWorkflowContext();
context.setSettings(new Settings(new PropertyDefinitions().addComponent(WithDefaultValue.class)));
assertThat(condition.doVerify(new DefaultReview(), context)).isTrue();
}
@Properties({
@Property(key = "jira.url", name = "JIRA URL", defaultValue = "http://jira.com")
})
private static class WithDefaultValue {
}
}
| lgpl-3.0 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization-tests/src/main/java/org/semanticweb/owlapi/gwt/client/OWLObjectSerializationTestMethods.java | 5548 | package org.semanticweb.owlapi.gwt.client;
/**
* Matthew Horridge
* Stanford Center for Biomedical Informatics Research
* 24 Jul 16
*/
public interface OWLObjectSerializationTestMethods {
public void testShouldSerializeOWL2DatatypeImpl();
public void testShouldSerializeOWLAnnotationAssertionAxiomImpl();
public void testShouldSerializeOWLAnnotationImpl();
public void testShouldSerializeOWLAnnotationPropertyDomainAxiomImpl();
public void testShouldSerializeOWLAnnotationPropertyImpl();
public void testShouldSerializeOWLAnnotationPropertyRangeAxiomImpl();
public void testShouldSerializeOWLAnonymousIndividualImpl();
public void testShouldSerializeOWLAsymmetricObjectPropertyAxiomImpl();
public void testShouldSerializeOWLClassAssertionAxiomImpl();
public void testShouldSerializeOWLClassImpl();
public void testShouldSerializeOWLDataAllValuesFromImpl();
public void testShouldSerializeOWLDataComplementOfImpl();
public void testShouldSerializeOWLDataExactCardinalityImpl();
public void testShouldSerializeOWLDataHasValueImpl();
public void testShouldSerializeOWLDataIntersectionOfImpl();
public void testShouldSerializeOWLDataMaxCardinalityImpl();
public void testShouldSerializeOWLDataMinCardinalityImpl();
public void testShouldSerializeOWLDataOneOfImpl();
public void testShouldSerializeOWLDataPropertyAssertionAxiomImpl();
public void testShouldSerializeOWLDataPropertyDomainAxiomImpl();
public void testShouldSerializeOWLDataPropertyImpl();
public void testShouldSerializeOWLDataPropertyRangeAxiomImpl();
public void testShouldSerializeOWLDataSomeValuesFromImpl();
public void testShouldSerializeOWLDataUnionOfImpl();
public void testShouldSerializeOWLDatatypeDefinitionAxiomImpl();
public void testShouldSerializeOWLDatatypeImpl();
public void testShouldSerializeOWLDatatypeRestrictionImpl();
public void testShouldSerializeOWLDeclarationAxiomImpl();
public void testShouldSerializeOWLDifferentIndividualsAxiomImpl();
public void testShouldSerializeOWLDisjointClassesAxiomImpl();
public void testShouldSerializeOWLDisjointDataPropertiesAxiomImpl();
public void testShouldSerializeOWLDisjointObjectPropertiesAxiomImpl();
public void testShouldSerializeOWLDisjointUnionAxiomImpl();
public void testShouldSerializeOWLEquivalentClassesAxiomImpl();
public void testShouldSerializeOWLEquivalentDataPropertiesAxiomImpl();
public void testShouldSerializeOWLEquivalentObjectPropertiesAxiomImpl();
public void testShouldSerializeOWLFacetRestrictionImpl();
public void testShouldSerializeOWLFunctionalDataPropertyAxiomImpl();
public void testShouldSerializeOWLFunctionalObjectPropertyAxiomImpl();
public void testShouldSerializeOWLHasKeyAxiomImpl();
public void testShouldSerializeOWLImportsDeclarationImpl();
public void testShouldSerializeOWLInverseFunctionalObjectPropertyAxiomImpl();
public void testShouldSerializeOWLInverseObjectPropertiesAxiomImpl();
public void testShouldSerializeOWLIrreflexiveObjectPropertyAxiomImpl();
public void testShouldSerializeOWLLiteralImpl();
public void testShouldSerializeOWLLiteralImplBoolean();
public void testShouldSerializeOWLLiteralImplDouble();
public void testShouldSerializeOWLLiteralImplFloat();
public void testShouldSerializeOWLLiteralImplInteger();
public void testShouldSerializeOWLLiteralImplNoCompression();
public void testShouldSerializeOWLLiteralImplPlain();
public void testShouldSerializeOWLLiteralImplString();
public void testShouldSerializeOWLNamedIndividualImpl();
public void testShouldSerializeOWLNegativeDataPropertyAssertionAxiomImpl();
public void testShouldSerializeOWLNegativeObjectPropertyAssertionAxiomImpl();
public void testShouldSerializeOWLObjectAllValuesFromImpl();
public void testShouldSerializeOWLObjectComplementOfImpl();
public void testShouldSerializeOWLObjectExactCardinalityImpl();
public void testShouldSerializeOWLObjectHasSelfImpl();
public void testShouldSerializeOWLObjectHasValueImpl();
public void testShouldSerializeOWLObjectIntersectionOfImpl();
public void testShouldSerializeOWLObjectInverseOfImpl();
public void testShouldSerializeOWLObjectMaxCardinalityImpl();
public void testShouldSerializeOWLObjectMinCardinalityImpl();
public void testShouldSerializeOWLObjectOneOfImpl();
public void testShouldSerializeOWLObjectPropertyAssertionAxiomImpl();
public void testShouldSerializeOWLObjectPropertyDomainAxiomImpl();
public void testShouldSerializeOWLObjectPropertyImpl();
public void testShouldSerializeOWLObjectPropertyRangeAxiomImpl();
public void testShouldSerializeOWLObjectSomeValuesFromImpl();
public void testShouldSerializeOWLObjectUnionOfImpl();
public void testShouldSerializeOWLReflexiveObjectPropertyAxiomImpl();
public void testShouldSerializeOWLSameIndividualAxiomImpl();
public void testShouldSerializeOWLSubAnnotationPropertyOfAxiomImpl();
public void testShouldSerializeOWLSubClassOfAxiomImpl();
public void testShouldSerializeOWLSubDataPropertyOfAxiomImpl();
public void testShouldSerializeOWLSubObjectPropertyOfAxiomImpl();
public void testShouldSerializeOWLSubPropertyChainAxiomImpl();
public void testShouldSerializeOWLSymmetricObjectPropertyAxiomImpl();
public void testShouldSerializeOWLTransitiveObjectPropertyAxiomImpl();
}
| lgpl-3.0 |
omadesala/sampler | sampler/src/main/java/com/sample/ui/MixGaussianSample.java | 4400 | package com.sample.ui;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Queue;
import java.util.Vector;
import java.util.concurrent.LinkedBlockingDeque;
import Jama.Matrix;
import com.panayotis.gnuplot.GNUPlotParameters;
import com.panayotis.gnuplot.JavaPlot;
import com.panayotis.gnuplot.plot.DataSetPlot;
import com.sample.sampler.ISampler;
import com.sample.sampler.implement.inverse.TwoDimGaussSampler;
public class MixGaussianSample {
private Matrix mu1 = new Matrix(2, 1);
private Matrix mu2 = new Matrix(2, 1);
private Matrix mu3 = new Matrix(2, 1);
private Matrix sigma1 = new Matrix(2, 2);
private Matrix sigma2 = new Matrix(2, 2);
private Matrix sigma3 = new Matrix(2, 2);
private Queue<Vector<Double>> samples = new LinkedBlockingDeque<Vector<Double>>();
private ISampler<Vector<Double>> sampler;
/**
*
* @Description: main method for entry point
* @param args
* 参数描述
* @throws
*/
public static void main(String[] args) {
MixGaussianSample javaGNUplot = new MixGaussianSample();
javaGNUplot.start();
}
/**
*
* @Description: start to do some real work
* @param 参数描述
* @throws
*/
public void start() {
init();
sampler = new TwoDimGaussSampler(mu1, sigma1);
sampler.doSample();
Queue<Vector<Double>> ret1 = sampler.getSampleValues();
Iterator<Vector<Double>> iterator = ret1.iterator();
while (iterator.hasNext()) {
getSamples().add(iterator.next());
}
sampler = new TwoDimGaussSampler(mu2, sigma2);
sampler.doSample();
Queue<Vector<Double>> ret2 = sampler.getSampleValues();
iterator = ret2.iterator();
while (iterator.hasNext()) {
getSamples().add(iterator.next());
}
sampler = new TwoDimGaussSampler(mu3, sigma3);
sampler.doSample();
Queue<Vector<Double>> ret3 = sampler.getSampleValues();
iterator = ret3.iterator();
while (iterator.hasNext()) {
getSamples().add(iterator.next());
}
displayData();
}
/**
*
* @Description: initial the state
* @throws
*/
private void init() {
/**
* inital mean
*/
mu1.set(0, 0, 1);
mu1.set(1, 0, 2);
mu2.set(0, 0, 5);
mu2.set(1, 0, 8);
mu3.set(0, 0, 5);
mu3.set(1, 0, 12);
/**
* initial sigma matrix
*/
sigma1.set(0, 0, 5);
sigma1.set(0, 1, 2);
sigma1.set(1, 0, 2);
sigma1.set(1, 1, 1);
sigma2.set(0, 0, 3);
sigma2.set(0, 1, -2);
sigma2.set(1, 0, -2);
sigma2.set(1, 1, 3);
sigma3.set(0, 0, 5);
sigma3.set(0, 1, 2);
sigma3.set(1, 0, 2);
sigma3.set(1, 1, 1);
}
/**
*
* @Description: display the data
* @param 参数描述
* @throws
*/
private void displayData() {
GNUPlotParameters param = new GNUPlotParameters(false);
ArrayList<String> preInit = param.getPreInit();
// preInit.add("set contour base");// draw contour
preInit.add("set xrange [-5:20]");// draw contour
preInit.add("set yrange [-5:20]");// draw contour
preInit.add("set size square");// draw contour
JavaPlot p = new JavaPlot(param, "E:/gnuplot/bin/gnuplot.exe", null);
p.setTitle("two dim gaussian Sample Demo");
p.getAxis("x").setLabel("X1 axis", "Arial", 20);
p.getAxis("y").setLabel("X2 axis");
Queue<Vector<Double>> sampleValues = getSamples();
double[][] points = new double[sampleValues.size()][2];
Iterator<Vector<Double>> iterator = sampleValues.iterator();
int i = 0;
while (iterator.hasNext()) {
Vector<Double> next = iterator.next();
points[i][0] = next.firstElement();
points[i][1] = next.lastElement();
i++;
}
DataSetPlot s = new DataSetPlot(points);
p.addPlot(s);
p.addPlot("0; pause 1000;");
p.plot();
}
public Queue<Vector<Double>> getSamples() {
return samples;
}
public void setSamples(Queue<Vector<Double>> samples) {
this.samples = samples;
}
}
| lgpl-3.0 |
PiRSquared17/zildo | zildo/src/zildo/monde/sprites/persos/PersoPlayer.java | 42256 | /**
* The Land of Alembrum
* Copyright (C) 2006-2013 Evariste Boussaton
*
*
* 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 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 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 zildo.monde.sprites.persos;
import java.util.ArrayList;
import java.util.List;
import zildo.Zildo;
import zildo.client.sound.BankSound;
import zildo.client.stage.SinglePlayer;
import zildo.fwk.bank.SpriteBank;
import zildo.fwk.gfx.EngineFX;
import zildo.fwk.gfx.filter.CircleFilter;
import zildo.fwk.script.xml.element.TriggerElement;
import zildo.fwk.ui.UIText;
import zildo.monde.collision.Collision;
import zildo.monde.collision.DamageType;
import zildo.monde.items.Inventory;
import zildo.monde.items.Item;
import zildo.monde.items.ItemCircle;
import zildo.monde.items.ItemKind;
import zildo.monde.items.StoredItem;
import zildo.monde.quest.actions.ScriptAction;
import zildo.monde.sprites.Reverse;
import zildo.monde.sprites.Rotation;
import zildo.monde.sprites.SpriteEntity;
import zildo.monde.sprites.desc.ElementDescription;
import zildo.monde.sprites.desc.PersoDescription;
import zildo.monde.sprites.desc.SpriteDescription;
import zildo.monde.sprites.desc.ZildoDescription;
import zildo.monde.sprites.desc.ZildoOutfit;
import zildo.monde.sprites.desc.ZildoSprSequence;
import zildo.monde.sprites.elements.Element;
import zildo.monde.sprites.elements.ElementArrow;
import zildo.monde.sprites.elements.ElementBoomerang;
import zildo.monde.sprites.elements.ElementDynamite;
import zildo.monde.sprites.elements.ElementGear;
import zildo.monde.sprites.elements.ElementImpact;
import zildo.monde.sprites.elements.ElementImpact.ImpactKind;
import zildo.monde.sprites.magic.Affection.AffectionKind;
import zildo.monde.sprites.magic.PersoAffections;
import zildo.monde.sprites.magic.ShieldEffect;
import zildo.monde.sprites.magic.ShieldEffect.ShieldType;
import zildo.monde.sprites.persos.action.HealAction;
import zildo.monde.sprites.persos.action.ScriptedPersoAction;
import zildo.monde.sprites.utils.MouvementPerso;
import zildo.monde.sprites.utils.MouvementZildo;
import zildo.monde.util.Angle;
import zildo.monde.util.Point;
import zildo.monde.util.Pointf;
import zildo.resource.Constantes;
import zildo.server.EngineZildo;
import zildo.server.MultiplayerManagement;
import zildo.server.Server;
/**
* A character controlled by player.
*
* @author Tchegito
*
*/
public class PersoPlayer extends Perso {
private SpriteEntity pushingSprite;
private int acceleration; // from 0 to 10
private Angle sightAngle; // For boomerang
private int touch; // number of frames zildo is touching something without moving
private boolean inventoring = false;
private boolean buying = false;
private String storeDescription;// Name of the store description (inventory of selling items)
public ItemCircle guiCircle;
private List<Item> inventory;
private ShieldEffect shieldEffect;
private ZildoOutfit outfit;
private int moonHalf;
// Linked elements
Element shield;
Element feet;
Element sword;
ZildoSprSequence swordSequence = new ZildoSprSequence();
public ControllablePerso who;
private SpriteEntity boomerang;
// Sequence for sprite animation
static int seq_1[] = { 0, 1, 2, 1 };
static int seq_2[] = { 0, 1, 2, 1, 0, 3, 4, 3 };
// ////////////////////////////////////////////////////////////////////
// Construction/Destruction
// ////////////////////////////////////////////////////////////////////
public PersoPlayer(int p_id) { // Only used to create Zildo on a client
super(p_id);
inventory = new ArrayList<Item>();
affections = new PersoAffections(this);
super.initFields();
}
// /////////////////////////////////////////////////////////////////////////////////////
// PersoZildo
// /////////////////////////////////////////////////////////////////////////////////////
// Return a perso named Zildo : this game's hero !
// with a given location.
// /////////////////////////////////////////////////////////////////////////////////////
public PersoPlayer(int p_posX, int p_posY, ZildoOutfit p_outfit) {
super();
setName("Zildo");
who = ControllablePerso.ZILDO;
// We could maybe put that somewhere else
outfit = p_outfit;
//setDesc(ZildoDescription.UP_FIXED);
x = p_posX; // 805); //601-32;//-500);
y = p_posY; // 973); //684+220;//-110);
angle = Angle.NORD;
sightAngle = angle;
setPos_seqsprite(-1);
setMouvement(MouvementZildo.VIDE);
setInfo(PersoInfo.ZILDO);
setMaxpv(6);
setPv(6);
setAlerte(false);
setCompte_dialogue(0);
setMoney(0);
setCountKey(0);
pushingSprite = null;
shield = new Element(this);
shield.setX(getX());
shield.setY(getY());
shield.setNBank(SpriteBank.BANK_ZILDO);
shield.setNSpr(ZildoDescription.SHIELD_UP.ordinal()); // Assign initial nSpr to avoid 'isNotFixe'
// returning TRUE)
shadow = new Element(this);
shadow.setDesc(ElementDescription.SHADOW);
feet = new Element(this);
feet.setNBank(SpriteBank.BANK_ZILDO);
feet.setNSpr(ZildoDescription.WATFEET1.getNSpr());
sword = new Element(this);
sword.setNBank(SpriteBank.BANK_ZILDO);
sword.setNSpr(ZildoDescription.SWORD0.getNSpr());
shieldEffect = null;
addPersoSprites(shield);
addPersoSprites(shadow);
addPersoSprites(feet);
addPersoSprites(sword);
// weapon=new Item(ItemKind.SWORD);
inventory = new ArrayList<Item>();
affections = new PersoAffections(this);
// inventory.add(weapon);
setSpeed(Constantes.ZILDO_SPEED);
setAppearance(ControllablePerso.PRINCESS_BUNNY);
}
/**
* Reset any effects zildo could have before he dies.
*/
public void resetForMultiplayer() {
weapon = new Item(ItemKind.SWORD);
inventory.clear();
inventory.add(weapon);
MultiplayerManagement.setUpZildo(this);
if (shieldEffect != null) {
shieldEffect.kill();
shieldEffect = null;
}
affections.clear();
inWater = false;
inDirt = false;
}
@Override
public boolean isZildo() {
return true;
}
@Override
public void initPersoFX() {
setSpecialEffect(EngineFX.NO_EFFECT);
}
public SpriteEntity getPushingSprite() {
return pushingSprite;
}
// /////////////////////////////////////////////////////////////////////////////////////
// attack
// /////////////////////////////////////////////////////////////////////////////////////
@Override
public void attack() {
boolean outOfOrder = false;
if (weapon == null || !who.canAttack) {
return; // No weapon ? No attack
}
String sentence;
switch (weapon.kind) {
case SWORD:
EngineZildo.soundManagement.broadcastSound(BankSound.ZildoAttaque, this);
setMouvement(MouvementZildo.ATTAQUE_EPEE);
setAttente(6 * 2);
break;
case BOW:
if (attente == 0) {
if (countArrow > 0) {
setMouvement(MouvementZildo.ATTAQUE_ARC);
setAttente(4 * 8);
} else {
outOfOrder = true;
}
}
break;
case BOOMERANG:
if (attente == 0 && (boomerang == null || !boomerang.isVisible())) {
setMouvement(MouvementZildo.ATTAQUE_BOOMERANG);
// Sightangle should not be null, but I got it once in
// multiplayer test
boomerang = new ElementBoomerang(sightAngle == null ? Angle.NORD : sightAngle, (int) x, (int) y,
(int) z, this);
EngineZildo.spriteManagement.spawnSprite(boomerang);
setAttente(16);
}
break;
case DYNAMITE:
if (attente == 0) {
if (countBomb > 0) {
Element bomb = new ElementDynamite((int) x, (int) y, 0, this);
bomb.floor = floor;
EngineZildo.spriteManagement.spawnSprite(bomb);
countBomb--;
setAttente(1);
} else {
outOfOrder = true;
}
}
break;
case FLASK_RED:
if (getPv() == getMaxpv()) { // If Zildo already has full life, do
// nothing
outOfOrder = true;
} else {
action = new HealAction(this, 6); // Give back 6 half-hearts
decrementItem(ItemKind.FLASK_RED);
}
break;
case FLASK_YELLOW:
affections.add(AffectionKind.INVINCIBILITY);
decrementItem(ItemKind.FLASK_YELLOW);
break;
case MILK:
sentence = UIText.getGameText("milk.action");
EngineZildo.dialogManagement.launchDialog(SinglePlayer.getClientState(), null, new ScriptAction(sentence));
break;
case FLUT:
if (attente == 0 && mouvement == MouvementZildo.VIDE) {
setAction(new ScriptedPersoAction(this, "flut"));
}
break;
case NECKLACE:
String hq = moonHalf > 0 ? ""+Math.min(moonHalf, 2) : "";
sentence = UIText.getGameText("necklace.action"+hq);
EngineZildo.dialogManagement.launchDialog(SinglePlayer.getClientState(), null, new ScriptAction(sentence));
break;
case ROCK_BAG:
if (attente == 0) {
Element peeble = new Element();
peeble.setDesc(ElementDescription.PEEBLE);
peeble.x = x;
peeble.y = y;
peeble.floor = floor;
EngineZildo.spriteManagement.spawnSprite(peeble);
peeble.beingThrown(x, y, sightAngle, this);
peeble.z = 12;
setMouvement(MouvementZildo.ATTAQUE_ROCKBAG);
EngineZildo.soundManagement.broadcastSound(BankSound.ZildoLance, this);
setAttente(2 * 6);
}
break;
case FIRE_RING:
if (weapon.level <= 0) {
outOfOrder = true; // Ring hasn't energy anymore
} else {
affections.toggle(AffectionKind.FIRE_DAMAGE_REDUCED, weapon);
}
break;
}
if (outOfOrder) {
EngineZildo.soundManagement.playSound(BankSound.MenuOutOfOrder, this);
}
if (weapon == null) {
weapon = inventory.get(0);
}
walkTile(false); // To activate any location trigger
// Trigger the USE one
TriggerElement trigger = TriggerElement.createUseTrigger(weapon.kind, new Point(x, y) );
EngineZildo.scriptManagement.trigger(trigger);
}
// /////////////////////////////////////////////////////////////////////////////////////
// manageCollision
// /////////////////////////////////////////////////////////////////////////////////////
// -create collision zone for Zildo
// /////////////////////////////////////////////////////////////////////////////////////
@Override
public void manageCollision() {
if (getMouvement() == MouvementZildo.ATTAQUE_EPEE) {
// La collision avec l'épée de Zildo}
double cx, cy, beta;
int rayon;
cx = getX();
cy = getY();
rayon = 4;
beta = (2.0f * Math.PI * this.getAttente()) / (7 * Constantes.speed);
switch (this.getAngle()) {
case NORD:
beta = beta + Math.PI;
cy = cy - 16;
break;
case EST:
beta = -beta + Math.PI / 2;
cy = cy - 4;
break;
case SUD:
cy = cy - 4;
break;
case OUEST:
beta = beta + Math.PI / 2;
cy = cy - 4;
cx = cx - 4;
break;
}
if (angle.isHorizontal()) {
cx = cx + 16 * Math.cos(beta);
cy = cy + 16 * Math.sin(beta);
} else {
cx = cx + 12 * Math.cos(beta);
cy = cy + 12 * Math.sin(beta);
}
// Add this collision record to collision engine
// Damage type: blunt at start, and then : cutting front
DamageType dmgType = DamageType.BLUNT;
if (attente < 6) {
dmgType = DamageType.CUTTING_FRONT;
}
Collision c = new Collision((int) cx, (int) cy, rayon, Angle.NORD, this, dmgType, null);
EngineZildo.collideManagement.addCollision(c);
}
}
// /////////////////////////////////////////////////////////////////////////////////////
// beingWounded
// /////////////////////////////////////////////////////////////////////////////////////
// IN : cx,cy : enemy's position
// /////////////////////////////////////////////////////////////////////////////////////
// Invoked when Zildo got wounded by any enemy.
// /////////////////////////////////////////////////////////////////////////////////////
@Override
public void beingWounded(float cx, float cy, Perso p_shooter, int p_damage) {
if (mouvement == MouvementZildo.SAUTE ||
mouvement == MouvementZildo.TOMBE || inventoring || underWater ||
isAffectedBy(AffectionKind.INVINCIBILITY)) {
return;
}
// Project Zildo away from the enemy
float diffx = getX() - cx;
float diffy = getY() - cy;
float norme = (float) Math.sqrt((diffx * diffx) + (diffy * diffy));
if (norme == 0.0f) {
norme = 1.0f; // Pour éviter le 'divide by zero'
}
// Et on l'envoie !
setPx(8 * (diffx / norme));
setPy(8 * (diffy / norme));
if (p_shooter != null && p_shooter.getQuel_deplacement().isAlertable()) {
p_shooter.setAlerte(true);
}
if (action != null) {
action = null;
setGhost(false);
setAttente(0);
// If the persoAction is scripted, kill the running scripts
EngineZildo.scriptManagement.stopPersoAction(this);
}
beingWounded(p_shooter, p_damage);
super.beingWounded(cx, cy, p_shooter, p_damage);
}
/**
* @param p_shooter
* @param p_damage HP loss (0 means no sound)
*/
public void beingWounded(Perso p_shooter, int p_damage) {
// If hero is carrying something, let it fall
if (getEn_bras() != null) {
getEn_bras().az = -0.07f;
if (getMouvement() == MouvementZildo.FIERTEOBJET) {
getEn_bras().dying = true;
}
setEn_bras(null);
}
if (p_damage > 0) {
EngineZildo.soundManagement.broadcastSound(BankSound.ZildoTouche, this);
}
setMouvement(MouvementZildo.TOUCHE);
setWounded(true);
pv -= p_damage;
if (guiCircle != null) {
guiCircle.kill();
inventoring = false;
guiCircle = null;
}
if (getDialoguingWith() != null) {
getDialoguingWith().setDialoguingWith(null);
setDialoguingWith(null); // End dialog
EngineZildo.dialogManagement.stopDialog(Server.getClientFromZildo(this), true);
}
}
/**
* Zildo is dead ! Send messages and respawn (in multiplayer deathmatch)
*/
@Override
public void die(boolean p_link, Perso p_shooter) {
affections.clear();
setMouvement(MouvementZildo.TOUCHE);
if (EngineZildo.game.multiPlayer) {
super.die(p_link, p_shooter);
EngineZildo.multiplayerManagement.kill(this, p_shooter);
} else {
// Game over
pos_seqsprite = 0;
EngineZildo.scriptManagement.execute("death", true);
}
}
// /////////////////////////////////////////////////////////////////////////////////////
// stopBeingWounded
// /////////////////////////////////////////////////////////////////////////////////////
@Override
public void stopBeingWounded()
{
setMouvement(MouvementZildo.VIDE);
if (isWounded()) {
setCompte_dialogue(64); // Temps d'invulnerabilité de Zildo
}
setPx(0.0f);
setPy(0.0f);
setSpecialEffect(EngineFX.NO_EFFECT);
super.stopBeingWounded();
}
final int decalxSword[][] = {
{ 0, 0, 0, 0, 0, 0 }, { 0, 2, 3, 2, 1, 1 },
{ 0, 0, 0, 0, 0, 0 }, { 0, -2, -5, -2, -1, -1 } };
final int decalxBow[][] = {
{ -2, -5, -5 }, { 0, 0, 0 }, { 0, 0, 0 }, { -1, -3, -4 }
};
final int decalyBow[][] = {
{ 2, 3, 2 }, { 1, 2, 1 }, { 3, 2, 2 }, { 1, 2, 1 }
};
final int decalboucliery[] = { 0, 2, 2, 1, 1, 1 , 0, 1};
final int decalbouclier2y[] = { 0, 0, 0, 0, -1, -1, 0, 0 };
final int decalbouclier3y[] = { 0, 0, -1, -1, 0, -1, 0, 0 };
// /////////////////////////////////////////////////////////////////////////////////////
// animate
// /////////////////////////////////////////////////////////////////////////////////////
// Manage all things related to Zildo display : shield, shadow, feets, and
// object taken.
// /////////////////////////////////////////////////////////////////////////////////////
@Override
public void animate(int compteur_animation)
{
super.animate(compteur_animation);
// Initialization of convenient variables
bottomZ = getBottomZ();
nature = getCurrentTileNature();
// If zildo's dead, don't display him
if (getPv() <= 0) {
if (EngineZildo.game.multiPlayer) {
setVisible(false);
return;
} else {
Point zPos = getCenteredScreenPosition();
Zildo.pdPlugin.getFilter(CircleFilter.class).setCenter(zPos.x, zPos.y);
}
}
if (getEn_bras() != null && getEn_bras().dying) {
setEn_bras(null);
}
// Affections
affections.render();
if (compte_dialogue != 0) {
compte_dialogue--;
if (compte_dialogue == 0) {
setWounded(false);
}
}
if (mouvement == MouvementZildo.SAUTE) {
moveJump();
}
SpriteEntity pushedEntity = getPushingSprite();
if (px != 0.0f || py != 0.0f) {
// Zildo being hurt !
Pointf p = tryMove(px, py);
px *= 0.8f;
py *= 0.8f;
walkTile(false);
if (Math.abs(px) + Math.abs(py) < 0.2f) {
stopBeingWounded();
}
x = p.x;
y = p.y;
} else if (getMouvement() == MouvementZildo.POUSSE && pushedEntity != null) {
// Zildo est en train de pousser : obstacle bidon ou bloc ?
if (pushedEntity.getEntityType().isElement()) {
Element pushedElement = (Element) pushedEntity;
if (pushedElement.isPushable()) {
pushedElement.moveOnPush(getAngle());
// Break link between Zildo and pushed object
pushSomething(null);
}
}
}
if (quel_deplacement == MouvementPerso.FOLLOW) {
// Not very clean to do such specific thing here
pathFinder.determineDestination();
}
switch (mouvement) {
case ATTAQUE_ARC:
if (attente == 2 * 8) {
EngineZildo.soundManagement.broadcastSound(BankSound.FlecheTir, this);
Element arrow = new ElementArrow(angle, (int) x, (int) y, 0, this);
EngineZildo.spriteManagement.spawnSprite(arrow);
countArrow--;
}
break;
case TOMBE:
z+=vz;
if (z > bottomZ) {
vz+=az;
} else if (az != 0) {
// Fix character on the ground, and cancel movement
land();
}
break;
}
//System.out.println(z);
}
final int[] seqWakeUp = { 0, 1, 0, 1, 2, 2, 3 };
/** Only allowed when player is a squirrel (see {@link ControllablePerso#PRINCESS_BUNNY}) **/
public void jump() {
//TODO: make it homogeneous with PathFinderSquirrel#setTarget
az = -0.1f;
vz = 1.1f; // Adjust speed so as hero can jump to a log from a water mud
mouvement = MouvementZildo.TOMBE;
}
// /////////////////////////////////////////////////////////////////////////////////////
// finaliseComportementPnj
// /////////////////////////////////////////////////////////////////////////////////////
// Manage character's graphic side, depending on the position in the
// animated sequence.
// NOTE: Called even if Zildo is in ghost mode (automatic movement in cinematic).
// /////////////////////////////////////////////////////////////////////////////////////
@Override
public void finaliseComportement(int compteur_animation) {
float xx = x;
float yy = y;
// Default : invisible
shadow.setVisible(false);
shield.setVisible(false);
sword.setVisible(false);
// Wet feet are displayed differently for each appearance
int shiftWetFeet = angle.isVertical() || angle == Angle.OUEST ? 1 : 0;
if (who == ControllablePerso.PRINCESS_BUNNY) {
// Player is controlling princess, so display her
setNSpr(PersoDescription.PRINCESS_BUNNY.nth(0));
int tileBottomZ = getBottomZ();
if (tileBottomZ < z) {
mouvement = MouvementZildo.TOMBE;
az = -0.1f;
}
shadow.setVisible(true);
shadow.setX(x);
shadow.setY(y);
shadow.setZ(tileBottomZ);
Constantes.ZILDO_SPEED = 1f;
int seqPos = 0;
shiftWetFeet = -1 + 3;
switch (angle) {
case NORD:
seqPos = computePosSeqSprite(6);
setNSpr(PersoDescription.PRINCESS_BUNNY.nth(11 + seqPos % 3));
setNBank(SpriteBank.BANK_PNJ3);
reverse = seqPos > 2 ? Reverse.HORIZONTAL : Reverse.NOTHING;
shadow.setX(x-1); // adjust shadow
setVisible(true);
break;
case SUD:
seqPos = computePosSeqSprite(6);
setNSpr(PersoDescription.PRINCESS_BUNNY.nth(3 + seqPos % 3));
setNBank(SpriteBank.BANK_PNJ3);
reverse = seqPos > 2 ? Reverse.HORIZONTAL : Reverse.NOTHING;
shadow.setX(x-1); // adjust shadow
setVisible(true);
break;
case EST:
xx -= 2;
//shiftWetFeet += 2;
case OUEST:
reverse = angle == Angle.OUEST ? Reverse.HORIZONTAL : Reverse.NOTHING;
setNSpr(PersoDescription.PRINCESS_BUNNY.nth(7 + computePosSeqSprite(3)));
setNBank(SpriteBank.BANK_PNJ3);
break;
}
xx -= 7 -3;
yy -= sprModel.getTaille_y()-1; //21;
shadow.setZ(shadow.z - 1); // Display shadow under character => else, this would be weird ;)
setAjustedX((int) xx);
setAjustedY((int) yy);
} else {
// Appearance : Hero
if (isAffectedBy(AffectionKind.FIRE_DAMAGE_REDUCED)) {
if (shieldEffect == null) {
shieldEffect = new ShieldEffect(this, ShieldType.REDBALL);
}
setSpecialEffect(EngineFX.QUAD);
} else if (shieldEffect != null) {
setSpecialEffect(EngineFX.NO_EFFECT);
shieldEffect.kill();
shieldEffect = null;
}
if (isAffectedBy(AffectionKind.INVINCIBILITY)) {
setSpecialEffect(EngineFX.WHITE_HALO);
} else {
setSpecialEffect(EngineFX.NO_EFFECT);
}
// Shield effect animation
if (shieldEffect != null) {
shieldEffect.animate();
}
// Corrections , décalages du sprite
if (angle == Angle.EST) {
xx -= 2;
} else if (angle == Angle.OUEST) {
xx += 2;
}
int v;
switch (mouvement) {
case SOULEVE:
if (angle == Angle.OUEST){
xx-=1;
}
break;
case TIRE:
if (nSpr == 36) {
if (angle == Angle.OUEST){
xx += 1;
} else if (angle == Angle.EST){
xx -= 2;
}
}
break;
case ATTAQUE_EPEE:
shield.setVisible(false);
sword.setVisible(true);
v = pos_seqsprite;
if (v>=0 && v<6) {
xx += decalxSword[angle.value][v];
sword.setSpr(swordSequence.getSpr(angle, v));
Point p = swordSequence.getOffset(angle, v);
sword.setX(xx - 4 + p.x);
sword.setY(yy + 1 - p.y);
}
switch (angle) {
case SUD:
// Sword must be over Zildo
sword.setZ(15);
sword.setY(sword.getY() + 15);
break;
default:
sword.setZ(0);
}
break;
case ATTAQUE_ARC:
v = nSpr - (108 + 3 * angle.value);
if (v>=0 && v<6) {
xx += decalxBow[angle.value][v];
yy += decalyBow[angle.value][v];
}
shield.setVisible(false);
break;
case SAUTE:
// Zildo est en train de sauter, on affiche l'ombre à son arrivée
shadow.setX(posShadowJump.x); // (float) (xx-ax)); //-6;)
shadow.setY(posShadowJump.y); // (float) (yy-ay)-3);
shadow.setZ(0);
shadow.setVisible(true);
shield.setVisible(false);
break;
case FIERTEOBJET:
nSpr = ZildoDescription.ARMSRAISED.ordinal();
yy++;
break;
case TOMBE:
xx=x-6; // Calculate from x, because xx has already been modified
yy=y+8;
if (z != 0) {
shadow.setVisible(true);
shadow.setX(x);
shadow.setY(y);
shadow.setZ(0);
}
break;
case MORT:
xx-=2;
break;
case SLEEPING:
break;
}
// On affiche Zildo
// Ajustemenent
sprModel = EngineZildo.spriteManagement.getSpriteBank(SpriteBank.BANK_ZILDO).get_sprite(nSpr + addSpr);
xx -= 7;
yy -= sprModel.getTaille_y() - 2; //21;
setAjustedX((int) xx);
setAjustedY((int) yy);
if (!askedVisible) {
setVisible(false);
}
//////////////////////////////////////////////////
// End of the part previously in 'animate' method (this was wrong, because this only concerns
// rendering.
//////////////////////////////////////////////////
reverse = Reverse.NOTHING;
switch (getMouvement())
{
case VIDE:
setSpr(ZildoDescription.getMoving(angle, computePosSeqSprite(8)));
// Shield
if (hasItem(ItemKind.SHIELD)) {
shield.setForeground(false);
shield.reverse = Reverse.NOTHING;
switch (angle) {
case NORD:
shield.setX(xx + 2);
shield.setY(yy + 20);
shield.setZ(5 - 1 - decalbouclier3y[nSpr % 8]);
shield.setNSpr(83);
shield.setNBank(SpriteBank.BANK_ZILDO);
break;
case EST:
shield.setX(xx + 14); // PASCAL : +10
shield.setY(yy + 17 + decalbouclier2y[(nSpr - ZildoDescription.RIGHT_FIXED.ordinal()) % 8]);
shield.setZ(0.0f);
shield.setNSpr(84);
shield.setNBank(SpriteBank.BANK_ZILDO);
break;
case SUD:
shield.setX(xx + 13); // PASCAL : -3)
shield.setY(yy + 23+1+ decalboucliery[(nSpr - ZildoDescription.DOWN_FIXED.ordinal()) % 8]);
//System.out.println(yy + " ==> "+(nSpr - ZildoDescription.DOWN_FIXED.ordinal()) % 8+ " = "+decalboucliery[(nSpr - ZildoDescription.DOWN_FIXED.ordinal()) % 6]+" ==> "+shield.y);
shield.setZ(1 + 4);
shield.setNSpr(85);
shield.setNBank(SpriteBank.BANK_ZILDO);
break;
case OUEST:
shield.setX(xx + 3);
shield.setY(yy + 18 - decalbouclier2y[(nSpr - ZildoDescription.RIGHT_FIXED.ordinal()) % 8]);
//System.out.println(yy + " ==> "+(nSpr - ZildoDescription.RIGHT_FIXED.ordinal()) % 8+ " = "+decalbouclier2y[(nSpr - ZildoDescription.RIGHT_FIXED.ordinal()) % 8]+" ==> "+shield.y);
shield.setZ(0.0f);
shield.setNSpr(84);
shield.setForeground(true);
shield.reverse = Reverse.HORIZONTAL;
shield.setNBank(SpriteBank.BANK_ZILDO);
break;
}
shield.setVisible(true);
}
break;
case SAUTE:
setNSpr(angle.value + ZildoDescription.JUMP_UP.getNSpr());
break;
case BRAS_LEVES:
// On affiche ce que Zildo a dans les mains
Element en_bras = getEn_bras();
// Corrections...
if (en_bras != null) {
int objZ = (int) en_bras.getZ();
int variation = seq_1[((getPos_seqsprite() % (4 * Constantes.speed)) / Constantes.speed)];
//en_bras.setX(objX);
//en_bras.setY(objY);
en_bras.setZ(objZ - variation);
// Corrections , décalages du sprite
float xxx = x;
float yyy = y;
if (angle == Angle.EST) {
xxx -= 2;
} else if (angle == Angle.OUEST) {
xxx += 2;
}
en_bras.setX(xxx + 1);
en_bras.setY(yyy); // + 3);
en_bras.setZ(17 - 3 - variation);
}
setSpr(ZildoDescription.getArmraisedMoving(angle, (pos_seqsprite % (8 * Constantes.speed)) / Constantes.speed));
break;
case SOULEVE:
switch (angle) {
case NORD:
setNSpr(ZildoDescription.PULL_UP1.ordinal());
break;
case EST:
setNSpr(ZildoDescription.LIFT_RIGHT.ordinal());
break;
case SUD:
setNSpr(ZildoDescription.PULL_DOWN1.ordinal());
break;
case OUEST:
setNSpr(ZildoDescription.LIFT_LEFT.ordinal());
break;
}
break;
case TIRE:
setSpr(ZildoDescription.getPulling(angle, pos_seqsprite));
break;
case TOUCHE:
setNSpr(ZildoDescription.WOUND_UP.getNSpr() + angle.value);
break;
case POUSSE:
setSpr(ZildoDescription.getPushing(angle, pos_seqsprite/2));
break;
case ATTAQUE_EPEE:
pos_seqsprite = (((6 * 2 - getAttente() - 1) % (6 * 2)) / 2);
setSpr(ZildoDescription.getSwordAttacking(angle, pos_seqsprite));
break;
case ATTAQUE_ROCKBAG:
pos_seqsprite = (((2 * 6 - getAttente() - 1) % (2 * 6)) / 6);
setSpr(ZildoDescription.getSwordAttacking(angle, pos_seqsprite));
break;
case ATTAQUE_ARC:
setSpr(ZildoDescription.getBowAttacking(angle, getAttente()));
break;
case MORT:
setNSpr(ZildoDescription.LAYDOWN);
break;
case TOMBE:
setNSpr(ZildoDescription.FALLING);
break;
case PLAYING_FLUT:
setNSpr(ZildoDescription.ZILDO_FLUT);
break;
case SLEEPING:
setNSpr(ZildoDescription.SLEEPING);
break;
case WAKEUP:
int seqPos = (getPos_seqsprite() / (6 * seqWakeUp.length)) % seqWakeUp.length;
setAddSpr(seqWakeUp[seqPos]);
if (seqPos == seqWakeUp.length -1) {
setPos_seqsprite(pos_seqsprite - 2);
}
setNSpr(ZildoDescription.SLEEPING);
break;
}
if (outfit != null && nBank == SpriteBank.BANK_ZILDO) {
setNBank(outfit.getNBank());
}
// GUI circle
if (guiCircle != null) {
guiCircle.animate();
if (guiCircle.isReduced()) {
inventoring = false;
guiCircle = null;
}
}
}
// End of specific rendering, depending on appearance (hero, or bunny)
// Now, common rendering
if (pv > 0) {
boolean touche = (mouvement == MouvementZildo.TOUCHE || getCompte_dialogue() != 0);
// Zildo blink
touche = (touche && ((compteur_animation >> 1) % 2) == 0);
visible = !touche;
for (Element elem : persoSprites) { // Blink linked elements too
if (elem.isVisible()) {
elem.setVisible(visible);
}
}
} else {
// Zildo should stay focused at die scene
setSpecialEffect(EngineFX.FOCUSED);
}
feet.setVisible(pv > 0 && (inWater || inDirt));
feet.setX(x + shiftWetFeet);
feet.setY(y + 9 + 1);
feet.setZ(3);
feet.setAddSpr((compteur_animation / 6) % 3);
if (inWater) {
feet.setNSpr(ZildoDescription.WATFEET1.getNSpr());
} else if (inDirt) {
feet.setNSpr(ZildoDescription.DIRT1.getNSpr());
feet.setY(feet.getY() - 3);
}
feet.setForeground(false);
}
/**
* Zildo take some goodies. It could be a heart, an arrow, or a weapon...
*
* @param p_element
* (can be null, if p_money is filled)
* @param p_money
* >0 ==> Zildo gets some money
* @return boolean : TRUE=element should disappear / FALSE=element stays
*/
public boolean pickGoodies(Element p_element, int p_value) {
// Effect on perso
if (p_value != 0 && (p_element == null || p_element.getDesc() == ElementDescription.GOLDPURSE1)) {
// Zildo gets/looses some money
setMoney(money + p_value);
if (p_value > 0) {
EngineZildo.soundManagement.broadcastSound(BankSound.ZildoRecupItem, this);
} else {
EngineZildo.soundManagement.broadcastSound(BankSound.ZildoGagneArgent, this);
}
} else {
int elemNSpr=p_element.getNSpr();
ElementDescription d = ElementDescription.fromInt(elemNSpr);
ItemKind kind = d.getItem();
if (kind != null && kind.canBeInInventory()) {
pickItem(kind, p_element);
return false;
} else {
// Automatic behavior (presentation text, ammos adjustments)
EngineZildo.scriptManagement.automaticBehavior(this, null, d);
useItem(d, p_value);
}
}
return true;
}
/** Use an item : either use it when player press the right button, or when he picks it up.
* NOTE: p_value can provide some special values, from element's name. Like a precise number of
* dynamite, arrows ...
*/
private void useItem(ElementDescription d, int p_value) {
BankSound toPlay = null;
switch (d) {
case GOLDCOIN1:
money ++;
break;
case THREEGOLDCOINS1:
money += 3;
break;
case GOLDPURSE1:
money += 20;
break;
case DROP_FLOOR:
case DROP_SMALL:
case DROP_MEDIUM:
if (pv < maxpv) {
pv = Math.min(pv+2, maxpv);
// Blue energy animation
ElementImpact energy = new ElementImpact((int) x, (int) y, ImpactKind.DROP_ENERGY, this);
EngineZildo.spriteManagement.spawnSprite(energy);
toPlay = BankSound.ZildoRecupCoeur;
} else {
toPlay = BankSound.ZildoRecupItem;
}
break;
case ARROW_UP:
countArrow += 5;
break;
case QUAD1:
affections.add(AffectionKind.QUAD_DAMAGE);
EngineZildo.multiplayerManagement.pickUpQuad();
break;
case DYNAMITE:
countBomb ++;
break;
case BOMBS3:
countBomb += p_value == 0 ? 3 : p_value;
break;
case KEY:
countKey++;
break;
}
// Sound
switch (d) {
/*
case GREENMONEY1:
case BLUEMONEY1:
case REDMONEY1:
toPlay = BankSound.ZildoItem;
break;
*/
case QUAD1:
toPlay = BankSound.QuadDamage;
break;
case KEY:
toPlay = BankSound.ZildoKey;
break;
case HEART_FRAGMENT:
toPlay = BankSound.ZildoMoon;
moonHalf++;
break;
case DROP_FLOOR:
case DROP_SMALL:
case DROP_MEDIUM:
break; // Already done
default:
toPlay = BankSound.ZildoRecupItem;
break;
}
if (toPlay != null) { // Isn't it obvious ?
EngineZildo.soundManagement.broadcastSound(toPlay, this);
}
}
/**
* Zildo picks something up (bushes, hen...) Object can be already on the
* map (hen), or we can spawn it there (bushes, jar).
*
* @param objX
* @param objY
* @param d
* sprite's description, in case no object is supplied
* @param object
* the taken element
*/
@Override
public void takeSomething(int objX, int objY, SpriteDescription d, Element object) {
EngineZildo.soundManagement.broadcastSound(BankSound.ZildoRamasse, this);
Element elem = object;
if (object == null) {
elem = new Element();
elem.setNBank(d.getBank());
elem.setNSpr(d.getNSpr());
elem.addShadow(ElementDescription.SHADOW);
}
elem.beingTaken();
elem.setScrX(objX);
elem.setScrY(objY);
elem.setX(objX);
elem.setY(objY);
elem.setZ(4);
elem.setVisible(true);
elem.flying = false;
elem.setForeground(true);
elem.setLinkedPerso(this); // Link to Zildo
if (object == null) {
EngineZildo.spriteManagement.spawnSprite(elem);
}
// On passe en position "soulève", et on attend 20 frames
setMouvement(MouvementZildo.SOULEVE);
setAttente(20);
setEn_bras(elem);
}
/**
* Zildo throws what he got in his raised arms. (enBras)
*/
public void throwSomething() {
// On jette un objet
Element element = getEn_bras();
setMouvement(MouvementZildo.VIDE);
if (element != null) {
setEn_bras(null);
element.beingThrown(x, y, angle, this);
EngineZildo.soundManagement.broadcastSound(BankSound.ZildoLance, this);
}
}
/**
* Called when 'attente' is equals to 0.
*/
public void endMovement() {
switch (mouvement) {
case SOULEVE:
setMouvement(MouvementZildo.BRAS_LEVES);
break;
case FIERTEOBJET:
if (getEn_bras() != null) {
getEn_bras().dying=true;
}
setAngle(Angle.SUD);
case ATTAQUE_EPEE:
case ATTAQUE_ARC:
case ATTAQUE_BOOMERANG:
case ATTAQUE_ROCKBAG:
setMouvement(MouvementZildo.VIDE); // Awaiting for key pressed
break;
}
}
/**
* Display Zildo's inventory around him
*/
public void lookInventory() {
if (inventory.size() == 0) {
// no inventory !
EngineZildo.soundManagement.playSound(BankSound.MenuOutOfOrder, this);
return;
}
Inventory inv = Inventory.fromItems(inventory);
int sel = inv.indexOf(weapon);
if (sel == -1) {
sel = 0;
}
lookItems(inv, sel, this, null);
}
public int getIndexSelection() {
return inventory.indexOf(getWeapon());
}
public void lookItems(Inventory p_items, int p_sel, Perso p_involved, String p_storeName) {
inventoring = true;
guiCircle = new ItemCircle(this);
buying = p_storeName != null;
guiCircle.create(p_items, p_sel, p_involved, buying);
storeDescription = p_storeName;
}
/**
* Zildo buy an item at a store. Check his money, and add item to his
* inventory if he has enough.
*/
public void buyItem() {
StoredItem stItem = guiCircle.getItemSelected();
int remains = money - stItem.price;
Item item = stItem.item;
if (remains < 0) {
// Not enough money
EngineZildo.soundManagement.playSound(BankSound.MenuOutOfOrder, this);
}/* else if (inventory.size() == 8) {
// Too much items
EngineZildo.soundManagement.playSound(BankSound.MenuOutOfOrder, this);
}*/ else {
money -= stItem.price;
SpriteDescription d = item.kind.representation;
if (item.kind.canBeInInventory()) {
if (item.kind.canBeMultiple() || inventory.indexOf(item) == -1) {
inventory.add(item);
}
}
// Be sure that description is instance of ElementDescription, but more for runtime reason
// In fact, that must never happen.
if (d instanceof ElementDescription) {
useItem((ElementDescription) d, 0);
}
guiCircle.decrementSelected();
EngineZildo.scriptManagement.sellItem(storeDescription, item);
EngineZildo.soundManagement.playSound(BankSound.ZildoGagneArgent, this);
}
}
public void closeInventory() {
EngineZildo.soundManagement.playSound(BankSound.MenuIn, this);
guiCircle.close(); // Ask for the circle to close
if (!buying) {
weapon = guiCircle.getItemSelected().item;
Perso perso = getDialoguingWith();
if (perso != null) {
perso.setDialoguingWith(null);
setDialoguingWith(null);
}
}
}
/**
* Directly add an item to the inventory
*
* @param p_item
*/
private void addInventory(Item p_item) {
inventory.add(p_item);
if (getWeapon() == null) {
setWeapon(p_item);
}
}
public boolean isInventoring() {
return inventoring;
}
/**
* Zildo takes an item.
*
* @param p_kind
* @param p_element
* NULL if we have to spawn the element / otherwise, element
* already is on the map.
*/
public void pickItem(ItemKind p_kind, Element p_element) {
if (getEn_bras() == null) { // Doesn't take 2 items at 1 time
addInventory(new Item(p_kind));
attente = 40;
mouvement = MouvementZildo.FIERTEOBJET;
Element elem = p_element;
if (elem == null) {
elem = EngineZildo.spriteManagement.spawnElement(p_kind.representation,
(int) x,
(int) y, 0, Reverse.NOTHING, Rotation.NOTHING);
}
// Place item right above Zildo
elem.x = x + 5;
elem.y = y + 1;
elem.z = 20f;
setEn_bras(elem);
EngineZildo.soundManagement.playSound(BankSound.ZildoTrouve, this);
// Automatic behavior (presentation text, ammos adjustments)
EngineZildo.scriptManagement.automaticBehavior(this, p_kind, null);
// Adventure trigger
if (!EngineZildo.game.multiPlayer) {
TriggerElement trig = TriggerElement.createInventoryTrigger(p_kind);
EngineZildo.scriptManagement.trigger(trig);
}
}
}
/**
* Zildo loose an item from his inventory.
*
* @param p_kind
*/
public void removeItem(ItemKind p_kind) {
int index = 0;
for (Item i : inventory) {
if (i.kind == p_kind) {
if (super.getWeapon() == i) {
setWeapon(null);
}
inventory.remove(index);
return;
}
index++;
}
}
/**
* Reduce item's quantity and focus on another one if necessary.
*/
public void decrementItem(ItemKind p_kind) {
removeItem(p_kind);
setWeapon(null);
for (Item i : inventory) {
if (i.kind == p_kind) {
setWeapon(i);
}
}
}
/**
* Return TRUE if Zildo has an item from given kind.
*
* @param p_kind
* @return boolean
*/
public boolean hasItem(ItemKind p_kind) {
for (Item i : inventory) {
if (i.kind == p_kind) {
return true;
}
}
return false;
}
@Override
public Item getWeapon() {
Item item = super.getWeapon();
if (item == null && !inventory.isEmpty()) {
// No weapon is selected => take the first one, if it exists
// This case occurs only after game has just been loaded
weapon = inventory.get(0);
item = weapon;
}
return item;
}
/**
* Return all Zildo's inventory. Useful for saving a game.
*
* @return List<Item>
*/
public List<Item> getInventory() {
return inventory;
}
/**
* Zildo avance contre un SpriteEntity
*
* @param object
*/
public void pushSomething(Element object) {
if (object == null || object.isPushable()) {
pushingSprite = object;
}
if (object != null && object.getDesc().getBank() == SpriteBank.BANK_GEAR) {
((ElementGear) object).push(this);
}
}
public int getTouch() {
return touch;
}
public void setTouch(int touch) {
this.touch = touch;
}
public boolean isAlive() {
return getPv() > 0;
}
public void setSightAngle(Angle sightAngle) {
this.sightAngle = sightAngle;
}
public int getMoonHalf() {
return moonHalf;
}
public void setMoonHalf(int moonHalf) {
this.moonHalf = moonHalf;
}
int[] accels = new int[] { 0, 1, 1, 1, 2, 2, 3, 6, 8, 10, 10 };
public float getAcceleration() {
return accels[acceleration];
}
public void increaseAcceleration() {
if (acceleration != 10) {
acceleration += 1;
}
}
public void decreaseAcceleration() {
if (acceleration > 1) {
acceleration -= 1;
}
}
/** Hero HP increases, using 2 moon fragments. */
public void gainHPWithNecklace() {
moonHalf -= 2;
maxpv+=2;
pv = maxpv;
}
private int computePosSeqSprite(int speedFactor) {
return pos_seqsprite == -1 ? -1 :
((pos_seqsprite/2) % (speedFactor * Constantes.speed)) / Constantes.speed;
}
public void setAppearance(ControllablePerso who) {
this.who = who;
switch (who) {
case ZILDO:
shadow.setDesc(ElementDescription.SHADOW);
feet.zoom=255;
defaultSize = new Point(8, 4);
break;
case PRINCESS_BUNNY:
shadow.setDesc(ElementDescription.SHADOW_SMALL);
feet.zoom=100;
defaultSize = new Point(2, 2);
break;
}
}
} | lgpl-3.0 |
solvice/jcmpl | src/main/java/jCMPL/CmplInstance.java | 7313 | /* ****************************************************************************
* This code is part of jCMPL
*
* Copyright (C) 2013 Mike Steglich / B. Knie Technical University of Applied
* Sciences Wildau, Germany
*
* jCMPL is a project of the Technical University of Applied Sciences Wildau
* and the Institute for Operations Research and Business Management at the
* Martin Luther University Halle-Wittenberg.
*
* Please visit the project homepage <http://www.coliop.org>
*
* jCMPL 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.
*
* jCMPL 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 jCMPL;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.apache.commons.lang3.StringEscapeUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Handling of the the CmplInstance for jCMPL
*/
public class CmplInstance {
private StringBuilder _instStr;
private HashMap<String, String> _cmplDataList;
/**
* Constructor
*/
protected CmplInstance() {
_instStr = new StringBuilder();
_cmplDataList = new HashMap<String, String>();
}
/**
* Creates a CmplInstance string
*
* @param cmplFileName CMPL file
* @param optList List of the options
* @param dataString CmplData string
* @param jobId JobId
* @return CmplInstance string
* @throws CmplException
*/
protected String cmplInstanceStr(String cmplFileName, HashMap<Integer, String> optList, String dataString, String jobId) throws CmplException {
File cmplFile = new File(cmplFileName);
if (cmplFile.exists()) {
if (!dataString.isEmpty()) {
_cmplDataList.put("__cmplData__" + cmplFile.getName().substring(0, cmplFile.getName().lastIndexOf('.')) + ".cdat", dataString);
}
} else {
throw new CmplException("CMPL file " + cmplFileName + " does not exist.");
}
try {
boolean commentSection = false;
int lineNr = 0;
BufferedReader in = new BufferedReader(new FileReader(cmplFileName));
String tmpName = "";
String tmpName1 = "";
ArrayList<String> lines = new ArrayList<String>();
String tmpLine = "";
while ((tmpLine = in.readLine()) != null) {
lines.add(tmpLine);
}
in.close();
for (String line : lines) {
line = line.trim();
if (line.startsWith("/*")) {
commentSection = true;
line = line.substring(0, line.indexOf("/*") - 1);
}
if (line.contains("*/")) {
commentSection = false;
line = line.substring(line.indexOf("*/") + 1);
}
if (commentSection) {
continue;
}
if (line.startsWith("%data")) {
if (line.contains(":")) {
tmpName = line.substring(5, line.indexOf(":")).trim();
} else {
tmpName = line.substring(5).trim();
}
if (tmpName.isEmpty()) {
if (!dataString.isEmpty()) {
lines.set(lineNr, line.replace("%data", "%data __cmplData__" + cmplFile.getName().substring(0, cmplFile.getName().lastIndexOf('.')) + ".cdat"));
tmpName = "__cmplData__";
} else {
tmpName = cmplFile.getName().substring(0, cmplFile.getName().lastIndexOf('.')) + ".cdat";
}
}
if (!(_cmplDataList.containsKey(tmpName) || tmpName.equals("__cmplData__"))) {
tmpName1 = "";
if (cmplFile.getParent() == null) {
tmpName1 = cmplFile.getName().substring(0, cmplFile.getName().lastIndexOf('.')) + ".cdat";
} else {
tmpName1 = cmplFile.getParent() + File.separator + cmplFile.getName().substring(0, cmplFile.getName().lastIndexOf('.')) + ".cdat";
}
BufferedReader cin = new BufferedReader(new FileReader(tmpName1));
String dline = "";
String tmpString = "";
while ((dline = cin.readLine()) != null) {
tmpString += dline;
}
cin.close();
_cmplDataList.put(tmpName1, tmpString);
}
}
lineNr += 1;
}
_instStr.append("<?xml version = \"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
_instStr.append("<CmplInstance version=\"1.0\">\n");
_instStr.append("<general>\n");
_instStr.append("<name>").append(cmplFile.getName()).append("</name>\n");
_instStr.append("<jobId>").append(jobId).append("</jobId>\n");
_instStr.append("</general>\n");
if (optList.size() > 0) {
_instStr.append("<options>\n");
for (Map.Entry<Integer, String> o : optList.entrySet()) {
_instStr.append("<opt>").append(o.getValue()).append("</opt>\n");
}
_instStr.append("</options>\n");
}
_instStr.append("<problemFiles>\n");
_instStr.append("<file name=\"").append(cmplFile.getName()).append("\" type=\"cmplMain\">\n");
String tmpStr = "";
for (String line : lines) {
tmpStr += line + "\n";
}
_instStr.append(StringEscapeUtils.escapeXml(tmpStr));
_instStr.append("\n");
_instStr.append("</file>\n");
for (Map.Entry<String, String> e : _cmplDataList.entrySet()) {
_instStr.append("<file name=\"").append(e.getKey()).append("\" type=\"cmplData\">\n");
_instStr.append(StringEscapeUtils.escapeXml(e.getValue()));
_instStr.append("\n");
_instStr.append("</file>\n");
}
_instStr.append("</problemFiles>\n");
_instStr.append("</CmplInstance>\n");
}
catch(IOException e
) {
throw new CmplException("IO error : " + e);
}
return _instStr.toString() ;
}
}
| lgpl-3.0 |
airien/workbits | PersonKontroll/app/src/main/java/politiet/no/personkontroll/mvp/PersonkontrollApplication.java | 2185 | package politiet.no.personkontroll.mvp;
import android.app.Application;
import politiet.no.personkontroll.data.source.bruker.BrukerRepositoryComponent;
import politiet.no.personkontroll.data.source.bruker.DaggerBrukerRepositoryComponent;
import politiet.no.personkontroll.data.source.kontroll.DaggerKontrollRepositoryComponent;
import politiet.no.personkontroll.data.source.kontroll.KontrollRepositoryComponent;
import politiet.no.personkontroll.mvp.forside.ForsideComponent;
import politiet.no.personkontroll.mvp.header.HeaderComponent;
/**
* Even though Dagger2 allows annotating a {@link dagger.Component} as a singleton, the code itself
* must ensure only one instance of the class is created. Therefore, we create a custom
* {@link Application} class to store a singleton reference to the {@link
* BrukerRepositoryComponent}.
* <P>
* The application is made of 5 Dagger components, as follows:<BR />
* {@link BrukerRepositoryComponent}: the data (it encapsulates a db and server data)<BR />
* {@link BrukerRepositoryComponent}: showing the list of to do items, including marking them as
* completed<BR />
* {@link ForsideComponent}: First page of the app<BR />
* {@link HeaderComponent}: Felles header i applikasjonen
* completed and deleting it<BR />
*/
public class PersonkontrollApplication extends Application {
private BrukerRepositoryComponent mBrukerRepositoryComponent;
private KontrollRepositoryComponent mKontrollRepositoryComponent;
@Override
public void onCreate() {
super.onCreate();
mBrukerRepositoryComponent = DaggerBrukerRepositoryComponent.builder()
.applicationModule(new ApplicationModule((getApplicationContext())))
.build();
mKontrollRepositoryComponent = DaggerKontrollRepositoryComponent.builder()
.applicationModule(new ApplicationModule((getApplicationContext())))
.build();
}
public BrukerRepositoryComponent getBrukerRepositoryComponent() {
return mBrukerRepositoryComponent;
}
public KontrollRepositoryComponent getKontrollRepositoryComponent() {
return mKontrollRepositoryComponent;
}
}
| lgpl-3.0 |
gmantele/experimental-taplib | uws/uwslib/src/uws/service/request/FormEncodedParser.java | 6172 | package uws.service.request;
/*
* This file is part of UWSLibrary.
*
* UWSLibrary 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.
*
* UWSLibrary 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 UWSLibrary. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2014-2015 - Astronomisches Rechen Institut (ARI)
*/
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import javax.servlet.http.HttpServletRequest;
import uws.UWSException;
/**
* <p>Extract parameters encoded using the HTTP-GET method or the Content-type application/x-www-form-urlencoded
* with the HTTP-POST or HTTP-PUT method in an {@link HttpServletRequest}.</p>
*
* <p>
* By default, this {@link RequestParser} overwrite parameter occurrences in the map: that's to say if a parameter is provided several times,
* only the last value will be kept. This behavior can be changed by overwriting the function {@link #consumeParameter(String, Object, Map)}
* of this class.
* </p>
*
* <p><i>Note:
* When HTTP-POST is used, these parameters are actually already extracted by the server application (like Apache/Tomcat)
* and are available with {@link HttpServletRequest#getParameterMap()}.
* However, when using HTTP-PUT, the parameters are extracted manually from the request content.
* </i></p>
*
* @author Grégory Mantelet (ARI)
* @version 4.2 (07/2015)
* @since 4.1
*/
public class FormEncodedParser implements RequestParser {
/** HTTP content-type for HTTP request formated in url-form-encoded. */
public final static String EXPECTED_CONTENT_TYPE = "application/x-www-form-urlencoded";
@Override
public final Map<String,Object> parse(HttpServletRequest request) throws UWSException{
if (request == null)
return new HashMap<String,Object>();
HashMap<String,Object> params = new HashMap<String,Object>();
// Normal extraction for HTTP-POST and other HTTP methods:
if (request.getMethod() == null || !request.getMethod().equalsIgnoreCase("put")){
Enumeration<String> names = request.getParameterNames();
String paramName;
String[] values;
int i;
while(names.hasMoreElements()){
paramName = names.nextElement();
values = request.getParameterValues(paramName);
// search for the last non-null occurrence:
i = values.length - 1;
while(i >= 0 && values[i] == null)
i--;
// if there is one, keep it:
if (i >= 0)
consumeParameter(paramName, values[i], params);
}
}
/* Parameters are not extracted when using the HTTP-PUT method.
* This block is doing this extraction manually. */
else{
InputStream input = null;
try{
// Get the character encoding:
String charEncoding = request.getCharacterEncoding();
try{
if (charEncoding == null || charEncoding.trim().length() == 0 || Charset.isSupported(charEncoding))
charEncoding = "UTF-8";
}catch(Exception ex){
charEncoding = "UTF-8";
}
// Get a stream on the request content:
input = new BufferedInputStream(request.getInputStream());
// Read the stream by iterating on each parameter pairs:
Scanner scanner = new Scanner(input);
scanner.useDelimiter("&");
String pair;
int indSep;
while(scanner.hasNext()){
// get the pair:
pair = scanner.next();
// split it between the parameter name and value:
indSep = pair.indexOf('=');
try{
if (indSep >= 0)
consumeParameter(URLDecoder.decode(pair.substring(0, indSep), charEncoding), URLDecoder.decode(pair.substring(indSep + 1), charEncoding), params);
else
consumeParameter(URLDecoder.decode(pair, charEncoding), "", params);
}catch(UnsupportedEncodingException uee){
if (indSep >= 0)
consumeParameter(pair.substring(0, indSep), pair.substring(indSep + 1), params);
else
consumeParameter(pair, "", params);
}
}
}catch(IOException ioe){}finally{
if (input != null){
try{
input.close();
}catch(IOException ioe2){}
}
}
}
return params;
}
/**
* <p>Consume the specified parameter: add it inside the given map.</p>
*
* <p>
* By default, this function is just putting the given value inside the map. So, if the parameter already exists in the map,
* its old value will be overwritten by the given one.
* </p>
*
* @param name Name of the parameter to consume.
* @param value Its value.
* @param allParams The list of all parameters read until now.
*/
protected void consumeParameter(final String name, final Object value, final Map<String,Object> allParams){
allParams.put(name, value);
}
/**
* <p>Utility method that determines whether the content of the given request is a application/x-www-form-urlencoded.</p>
*
* <p><i>Important:
* This function just test the content-type of the request. The HTTP method (e.g. GET, POST, ...) is not tested.
* </i></p>
*
* @param request The servlet request to be evaluated. Must be non-null.
*
* @return <i>true</i> if the request is url-form-encoded,
* <i>false</i> otherwise.
*/
public final static boolean isFormEncodedRequest(final HttpServletRequest request){
// Extract the content type and determine if it is a url-form-encoded request:
String contentType = request.getContentType();
if (contentType == null)
return false;
else if (contentType.toLowerCase().startsWith(EXPECTED_CONTENT_TYPE))
return true;
else
return false;
}
}
| lgpl-3.0 |
ujmp/universal-java-matrix-package | ujmp-core/src/main/java/org/ujmp/core/calculation/CanUseMultipleThreads.java | 1121 | /*
* Copyright (C) 2008-2015 by Holger Arndt
*
* This file is part of the Universal Java Matrix Package (UJMP).
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* UJMP 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
* of the License, or (at your option) any later version.
*
* UJMP 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 UJMP; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package org.ujmp.core.calculation;
public interface CanUseMultipleThreads {
public Calculation useThreads(int threadCount);
}
| lgpl-3.0 |
XPModder/XPAdditions | src/main/java/com/xpmodder/xpadditions/client/render/items/itemRenderRegister.java | 858 | package com.xpmodder.xpadditions.client.render.items;
import com.xpmodder.xpadditions.init.ModItems;
import com.xpmodder.xpadditions.reference.Reference;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
public class itemRenderRegister {
public static void registerItemRenderer() {
reg(ModItems.starItem);
reg(ModItems.mediumStarItem);
reg(ModItems.bigStarItem);
reg(ModItems.denseStarItem);
reg(ModItems.xpOrbItem);
reg(ModItems.bookItem);
}
public static void reg(Item item) {
Minecraft.getMinecraft().getRenderItem().getItemModelMesher()
.register(item, 0, new ModelResourceLocation(Reference.MOD_ID + ":" + item.getUnlocalizedName().substring(5), "inventory"));
}
}
| lgpl-3.0 |
nightscape/JMathLib | src/jmathlibtests/toolbox/string/testStrcmpi.java | 1235 | package jmathlibtests.toolbox.string;
import jmathlib.tools.junit.framework.JMathLibTestCase;
import junit.framework.Test;
import junit.framework.TestSuite;
public class testStrcmpi extends JMathLibTestCase {
public testStrcmpi(String name) {
super(name);
}
public static void main (String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(testStrcmpi.class);
}
public void testStrcmpi01() {
assertEvalScalarEquals("a=strcmpi('abcd','abcd');", "a", 1);
}
public void testStrcmpi02() {
assertEvalScalarEquals("a=strcmpi('abcd','ABCD');", "a", 1);
}
public void testStrcmpi03() {
assertEvalScalarEquals("a=strcmpi('abcd','AbCd');", "a", 1);
}
public void testStrcmpi04() {
assertEvalScalarEquals("a=strcmpi('abcd','ABCd');", "a", 1);
}
public void testStrcmpi05() {
assertEvalScalarEquals("a=strcmpi('aBCd','abcd');", "a", 1);
}
public void testStrcmpi06() {
assertEvalScalarEquals("a=strcmpi('aBCd','axcd');", "a", 0);
}
public void testStrcmpi07() {
assertEvalScalarEquals("a=strcmpi('abcd','abcde');", "a", 0);
}
}
| lgpl-3.0 |
DaveVoorhis/JRM | JRM/src/org/reldb/jrm/iterate_and_store/Relation.java | 763 | package org.reldb.jrm.iterate_and_store;
import java.util.Collection;
import java.util.HashSet;
import org.reldb.jrm.Tuple;
public class Relation {
private Collection<Tuple> store = new HashSet<Tuple>();
// used to build relation
protected void add(Tuple t) {
store.add(t);
}
// used by relvar to build relation
protected void add(Collection<Tuple> store) {
this.store = store;
}
// return UNION of this Relation and r
public Relation union(Relation r) {
Relation result = new Relation();
for (Tuple t: store)
result.add(t);
for (Tuple t: r.store)
result.add(t);
return result;
}
public Collection<Tuple> getTuples() {
return store;
}
}
| unlicense |
WALDOISCOMING/Java_Study | Java_BP/src/Chap09/StringBuilderExample4.java | 427 | package Chap09;
/*
* ÀÛ¼ºÀÏÀÚ:2017_03_13
* ÀÛ¼ºÀÚ:±æ°æ¿Ï
* StringBuilder °´Ã¼ÀÇ ¹öÆÛ Å©±â¸¦ ¹®ÀÚ¿¿¡ ¸Â°Ô ÁÙÀÌ´Â ÇÁ·Î±×·¥
* ¿¹Á¦ 9-9
*/
public class StringBuilderExample4 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(100);
sb.append("ÀÚ¹Ù");
System.out.println(sb+":"+sb.capacity());
sb.trimToSize();
System.out.println(sb+":"+sb.capacity());
}
}
| unlicense |
JFixby/jfixby-Fields | battlefields-terrain-p18-api/src/com/jfixby/util/p18t/api/P18LandscapeBrush.java | 384 | package com.jfixby.util.p18t.api;
import com.jfixby.r3.ext.api.patch18.palette.Fabric;
import com.jfixby.scarabei.api.floatn.ReadOnlyFloat3;
public interface P18LandscapeBrush {
void setFabric(Fabric fabric);
P18LandscapePointer pointAt(double terrain_x, double terrain_y,
double terrain_z);
P18LandscapePointer pointAt(ReadOnlyFloat3 terrain_xyz);
void applyPaint();
}
| unlicense |
bodydomelight/tij-problems | src/inner/classes/pkg02/Selector.java | 248 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package inner.classes.pkg02;
/**
*
* @author aamelin
*/
public interface Selector {
boolean end();
Object current();
void next();
}
| unlicense |
UweTrottmann/thetvdb-java | src/main/java/com/uwetrottmann/thetvdb/internal/EverythingIsNullable.java | 669 | package com.uwetrottmann.thetvdb.internal;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.annotation.Nullable;
import javax.annotation.meta.TypeQualifierDefault;
/**
* Extends {@code ParametersAreNullableByDefault} to also apply to method results and fields.
*
* @see javax.annotation.ParametersAreNullableByDefault
*/
@Documented
@Nullable
@TypeQualifierDefault({
ElementType.FIELD,
ElementType.METHOD,
ElementType.PARAMETER
})
@Retention(RetentionPolicy.RUNTIME)
public @interface EverythingIsNullable {
}
| unlicense |
MaciejSzaflik/MedicalAwesomeness | EdgeDetectionAlgorithms/src/nobody/gui/DisplayFrame.java | 3513 | package nobody.gui;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JButton;
import nobody.algorithms.*;
import nobody.util.EdgeDetector;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import javax.swing.JComboBox;
public class DisplayFrame extends JFrame {
public void PaintCurrentState() {
// TODO Auto-generated method stub
}
private int sizeOfFrameX = 1086;
private int sizeOfFrameY = 660;
private int sizeOfDisplay = 540;
private final Display beforeImagePanel;
private final Display afterImagePanel;
private final JComboBox<EdgeDetector.Algorithms> comboBox;
private EdgeDetector edgeDetector;
public DisplayFrame() {
edgeDetector = new EdgeDetector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 0, sizeOfFrameX, sizeOfFrameY);
beforeImagePanel = createDisplayPanel(0,0,false);
afterImagePanel = createDisplayPanel(sizeOfDisplay,0,false);
getContentPane().setLayout(null);
getContentPane().add(beforeImagePanel);
getContentPane().add(afterImagePanel);
JButton btnBlur = new JButton("Detect");
btnBlur.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
AddEffectAndSwap();
}
});
btnBlur.setBounds(12, 570, 117, 25);
getContentPane().add(btnBlur);
JButton btnFile = new JButton("Choose file");
btnFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
beforeImagePanel.openFileChooser();
}
});
btnFile.setBounds(12, 545, 117, 25);
getContentPane().add(btnFile);
btnBlur.setBounds(12, 570, 117, 25);
getContentPane().add(btnBlur);
comboBox = new JComboBox<EdgeDetector.Algorithms>();
comboBox.setBounds(142, 570, 241, 24);
getContentPane().add(comboBox);
JButton button = new JButton("Diff");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(beforeImagePanel.getImageLoaded() == null)
{
beforeImagePanel.openFileChooser();
}
else
{
Diff diff = new Diff(beforeImagePanel.getImageLoaded());
diff.setVisible(true);
}
}
});
button.setBounds(554, 545, 117, 25);
getContentPane().add(button);
JButton btnShowAll = new JButton("Show All");
btnShowAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(beforeImagePanel.getImageLoaded() == null)
{
beforeImagePanel.openFileChooser();
}
else
{
ShowAllAlgorithmsFrame all = new ShowAllAlgorithmsFrame();
all.setVisible(true);
all.Init(beforeImagePanel.getImageLoaded());
}
}
});
btnShowAll.setBounds(554, 570, 117, 25);
getContentPane().add(btnShowAll);
for (EdgeDetector.Algorithms alg : EdgeDetector.Algorithms.values()) {
comboBox.addItem(alg);
}
}
private Display createDisplayPanel(int x,int y,boolean visibleButton)
{
Display newDisplay = new Display(sizeOfDisplay,visibleButton);
newDisplay.setBounds(x,y, sizeOfDisplay, sizeOfDisplay);
newDisplay.setBackground(new Color(200,200,200));
return newDisplay;
}
private EdgeDetector.Algorithms getSelected()
{
return (EdgeDetector.Algorithms)comboBox.getSelectedItem();
}
private void AddEffectAndSwap()
{
BufferedImage image = beforeImagePanel.getImageLoaded();
afterImagePanel.scaleAndSetImage(edgeDetector.DoAlgorithm(getSelected(),image),getSelected().toString());
}
}
| unlicense |
codeApeFromChina/resource | frame_packages/java_libs/hibernate-distribution-3.6.10.Final/project/hibernate-testsuite/src/test/java/org/hibernate/test/optlock/OptimisticLockTest.java | 6692 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.test.optlock;
import junit.framework.Test;
import org.hibernate.JDBCException;
import org.hibernate.Session;
import org.hibernate.StaleObjectStateException;
import org.hibernate.StaleStateException;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.testing.junit.functional.FunctionalTestCase;
import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite;
/**
* Tests relating to the optimistic-lock mapping option.
*
* @author Gavin King
* @author Steve Ebersole
*/
public class OptimisticLockTest extends FunctionalTestCase {
public OptimisticLockTest(String str) {
super(str);
}
public String[] getMappings() {
return new String[] { "optlock/Document.hbm.xml" };
}
public static Test suite() {
return new FunctionalTestClassTestSuite( OptimisticLockTest.class );
}
public void testOptimisticLockDirty() {
testUpdateOptimisticLockFailure( "LockDirty" );
}
public void testOptimisticLockAll() {
testUpdateOptimisticLockFailure( "LockAll" );
}
public void testOptimisticLockDirtyDelete() {
testDeleteOptimisticLockFailure( "LockDirty" );
}
public void testOptimisticLockAllDelete() {
testDeleteOptimisticLockFailure( "LockAll" );
}
private void testUpdateOptimisticLockFailure(String entityName) {
if ( getDialect().doesRepeatableReadCauseReadersToBlockWriters() ) {
reportSkip( "deadlock", "update optimistic locking" );
return;
}
Session mainSession = openSession();
mainSession.beginTransaction();
Document doc = new Document();
doc.setTitle( "Hibernate in Action" );
doc.setAuthor( "Bauer et al" );
doc.setSummary( "Very boring book about persistence" );
doc.setText( "blah blah yada yada yada" );
doc.setPubDate( new PublicationDate( 2004 ) );
mainSession.save( entityName, doc );
mainSession.getTransaction().commit();
mainSession.close();
mainSession = openSession();
mainSession.beginTransaction();
doc = ( Document ) mainSession.get( entityName, doc.getId() );
Session otherSession = getSessions().openSession();
otherSession.beginTransaction();
Document otherDoc = ( Document ) otherSession.get( entityName, doc.getId() );
otherDoc.setSummary( "A modern classic" );
otherSession.getTransaction().commit();
otherSession.close();
try {
doc.setSummary( "A machiavellian achievement of epic proportions" );
mainSession.flush();
fail( "expecting opt lock failure" );
}
catch ( StaleObjectStateException expected ) {
// expected result...
}
catch( StaleStateException expected ) {
// expected result (if using versioned batching)...
}
catch( JDBCException e ) {
// SQLServer will report this condition via a SQLException
// when using its SNAPSHOT transaction isolation...
if ( ! ( getDialect() instanceof SQLServerDialect && e.getErrorCode() == 3960 ) ) {
throw e;
}
else {
// it seems to "lose track" of the transaction as well...
mainSession.getTransaction().rollback();
mainSession.beginTransaction();
}
}
mainSession.clear();
mainSession.getTransaction().commit();
mainSession.close();
mainSession = openSession();
mainSession.beginTransaction();
doc = ( Document ) mainSession.load( entityName, doc.getId() );
mainSession.delete( entityName, doc );
mainSession.getTransaction().commit();
mainSession.close();
}
@SuppressWarnings({ "UnnecessaryBoxing" })
private void testDeleteOptimisticLockFailure(String entityName) {
if ( getDialect().doesRepeatableReadCauseReadersToBlockWriters() ) {
reportSkip( "deadlock", "delete optimistic locking" );
return;
}
Session mainSession = openSession();
mainSession.beginTransaction();
Document doc = new Document();
doc.setTitle( "Hibernate in Action" );
doc.setAuthor( "Bauer et al" );
doc.setSummary( "Very boring book about persistence" );
doc.setText( "blah blah yada yada yada" );
doc.setPubDate( new PublicationDate( 2004 ) );
mainSession.save( entityName, doc );
mainSession.flush();
doc.setSummary( "A modern classic" );
mainSession.flush();
doc.getPubDate().setMonth( Integer.valueOf( 3 ) );
mainSession.flush();
mainSession.getTransaction().commit();
mainSession.close();
mainSession = openSession();
mainSession.beginTransaction();
doc = ( Document ) mainSession.get( entityName, doc.getId() );
Session otherSession = openSession();
otherSession.beginTransaction();
Document otherDoc = ( Document ) otherSession.get( entityName, doc.getId() );
otherDoc.setSummary( "my other summary" );
otherSession.flush();
otherSession.getTransaction().commit();
otherSession.close();
try {
mainSession.delete( doc );
mainSession.flush();
fail( "expecting opt lock failure" );
}
catch ( StaleObjectStateException e ) {
// expected
}
catch( StaleStateException expected ) {
// expected result (if using versioned batching)...
}
catch( JDBCException e ) {
// SQLServer will report this condition via a SQLException
// when using its SNAPSHOT transaction isolation...
if ( ! ( getDialect() instanceof SQLServerDialect && e.getErrorCode() == 3960 ) ) {
throw e;
}
else {
// it seems to "lose track" of the transaction as well...
mainSession.getTransaction().rollback();
mainSession.beginTransaction();
}
}
mainSession.clear();
mainSession.getTransaction().commit();
mainSession.close();
mainSession = openSession();
mainSession.beginTransaction();
doc = ( Document ) mainSession.load( entityName, doc.getId() );
mainSession.delete( entityName, doc );
mainSession.getTransaction().commit();
mainSession.close();
}
}
| unlicense |
zahansafallwa/AlarmClock | AlarmClock/src/com/trigg/alarmclock/AlarmService.java | 716 | package com.trigg.alarmclock;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class AlarmService extends Service {
public static String TAG = AlarmService.class.getSimpleName();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent!=null){
Intent alarmIntent = new Intent(getBaseContext(), AlarmScreen.class);
alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
alarmIntent.putExtras(intent);
getApplication().startActivity(alarmIntent);
AlarmManagerHelper.setAlarms(this);
}
return super.onStartCommand(intent, flags, startId);
}
}
| unlicense |
ecornell/moonscript-idea | src/com/eightbitmage/moonscript/lang/psi/controlFlow/ControlFlowUtil.java | 6200 | /*
* Copyright 2011 Jon S Akhtar (Sylvanaar)
*
* 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.eightbitmage.moonscript.lang.psi.controlFlow;
import com.intellij.openapi.diagnostic.Logger;
import gnu.trove.TIntHashSet;
import gnu.trove.TObjectIntHashMap;
import java.util.ArrayList;
import java.util.List;
public class ControlFlowUtil {
private static final Logger LOG = Logger.getInstance("Lua.ControlFlowUtil");
public static int[] postorder(Instruction[] flow) {
int[] result = new int[flow.length];
boolean[] visited = new boolean[flow.length];
for (int i = 0; i < result.length; i++)
visited[i] = false;
int N = flow.length;
for (int i = 0; i < flow.length; i++) { //graph might not be connected
if (!visited[i])
N = doVisitForPostorder(flow[i], N, result, visited);
}
LOG.assertTrue(N == 0);
return result;
}
private static int doVisitForPostorder(Instruction curr, int currN, int[] postorder, boolean[] visited) {
visited[curr.num()] = true;
for (Instruction succ : curr.allSucc()) {
if (!visited[succ.num()]) {
currN = doVisitForPostorder(succ, currN, postorder, visited);
}
}
postorder[curr.num()] = --currN;
return currN;
}
public static ReadWriteVariableInstruction[] getReadsWithoutPriorWrites(Instruction[] flow) {
List<ReadWriteVariableInstruction> result = new ArrayList<ReadWriteVariableInstruction>();
TObjectIntHashMap<String> namesIndex = buildNamesIndex(flow);
TIntHashSet[] definitelyAssigned = new TIntHashSet[flow.length];
int[] postorder = postorder(flow);
int[] invpostorder = invPostorder(postorder);
findReadsBeforeWrites(flow, definitelyAssigned, result, namesIndex, postorder, invpostorder);
return result.toArray(new ReadWriteVariableInstruction[result.size()]);
}
private static int[] invPostorder(int[] postorder) {
int[] result = new int[postorder.length];
for (int i = 0; i < postorder.length; i++) {
result[postorder[i]] = i;
}
return result;
}
private static TObjectIntHashMap<String> buildNamesIndex(Instruction[] flow) {
TObjectIntHashMap<String> namesIndex = new TObjectIntHashMap<String>();
int idx = 0;
for (Instruction instruction : flow) {
if (instruction instanceof ReadWriteVariableInstruction) {
String name = ((ReadWriteVariableInstruction) instruction).getVariableName();
if (!namesIndex.contains(name)) {
namesIndex.put(name, idx++);
}
}
}
return namesIndex;
}
private static void findReadsBeforeWrites(Instruction[] flow,
TIntHashSet[] definitelyAssigned,
List<ReadWriteVariableInstruction> result,
TObjectIntHashMap<String> namesIndex,
int[] postorder,
int[] invpostorder) {
//skip instructions that are not reachable from the start
int start = 0;
while (invpostorder[start] != 0)
start++;
for (int i = start; i < flow.length; i++) {
int j = invpostorder[i];
Instruction curr = flow[j];
if (curr instanceof ReadWriteVariableInstruction) {
ReadWriteVariableInstruction readWriteInsn = (ReadWriteVariableInstruction) curr;
int idx = namesIndex.get(readWriteInsn.getVariableName());
TIntHashSet vars = definitelyAssigned[j];
if (readWriteInsn.isGlobal()) {
if (!readWriteInsn.isWrite()) {
if (vars == null || !vars.contains(idx)) {
result.add(readWriteInsn);
}
} else {
if (vars == null) {
vars = new TIntHashSet();
definitelyAssigned[j] = vars;
}
vars.add(idx);
}
}
}
for (Instruction succ : curr.allSucc()) {
if (postorder[succ.num()] > postorder[curr.num()]) {
TIntHashSet currDefinitelyAssigned = definitelyAssigned[curr.num()];
TIntHashSet succDefinitelyAssigned = definitelyAssigned[succ.num()];
if (currDefinitelyAssigned != null) {
int[] currArray = currDefinitelyAssigned.toArray();
if (succDefinitelyAssigned == null) {
succDefinitelyAssigned = new TIntHashSet();
succDefinitelyAssigned.addAll(currArray);
definitelyAssigned[succ.num()] = succDefinitelyAssigned;
} else {
succDefinitelyAssigned.retainAll(currArray);
}
} else {
if (succDefinitelyAssigned != null) {
succDefinitelyAssigned.clear();
} else {
succDefinitelyAssigned = new TIntHashSet();
definitelyAssigned[succ.num()] = succDefinitelyAssigned;
}
}
}
}
}
}
}
| unlicense |
yangjun2/android | Lonely/src/lmc/lonely/sys/SysServ.java | 1052 | package lmc.lonely.sys;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import lmc.lonely.R;
public class SysServ extends Activity implements OnClickListener {
private Button serv_start = null;
private Button serv_end = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.sys_serv);
serv_start = (Button) super.findViewById(R.id.serv_start);
serv_end = (Button) super.findViewById(R.id.serv_end);
serv_start.setOnClickListener(this);
serv_end.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.serv_start){
Intent it = new Intent();
it.setClass(this,SysServMgr.class);
this.startService(it);
}else if(v.getId()==R.id.serv_end){
Intent it = new Intent();
it.setClass(this,SysServMgr.class);
this.stopService(it);
}
}
} | unlicense |
lucasPereira/estruturados | java/br/dominioL/estruturados/testes/TesteBooleano.java | 2450 | package br.dominioL.estruturados.testes;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import br.dominioL.estruturados.elemento.primitivos.Booleano;
public class TesteBooleano {
private Booleano verdadeiro;
private Booleano falso;
@Before
public void criarFigurantes() {
verdadeiro = Booleano.verdadeiro();
falso = Booleano.falso();
}
@Test
public void igualdadeDoJava() {
assertThat(verdadeiro, is(equalTo(Booleano.verdadeiro())));
assertThat(verdadeiro, is(not(equalTo(Booleano.falso()))));
assertThat(verdadeiro, is(not(equalTo(null))));
assertThat(falso, is(not(equalTo(Booleano.verdadeiro()))));
assertThat(falso, is(equalTo(Booleano.falso())));
assertThat(falso, is(not(equalTo(null))));
}
@Test
public void igualdadeDoEstruturados() {
assertTrue(verdadeiro.igual(Booleano.verdadeiro()).avaliar());
assertFalse(verdadeiro.igual(Booleano.falso()).avaliar());
assertFalse(falso.igual(Booleano.verdadeiro()).avaliar());
assertTrue(falso.igual(Booleano.falso()).avaliar());
assertFalse(verdadeiro.igual(null).avaliar());
assertFalse(falso.igual(null).avaliar());
}
@Test
public void e() {
assertThat(verdadeiro.e(falso), is(equalTo(Booleano.falso())));
assertThat(verdadeiro, is(equalTo(Booleano.verdadeiro())));
assertThat(verdadeiro.e(verdadeiro), is(equalTo(Booleano.verdadeiro())));
assertThat(verdadeiro, is(equalTo(Booleano.verdadeiro())));
}
@Test
public void ou() {
assertThat(falso.ou(verdadeiro), is(equalTo(Booleano.verdadeiro())));
assertThat(falso, is(equalTo(Booleano.falso())));
assertThat(falso.ou(falso), is(equalTo(Booleano.falso())));
assertThat(falso, is(equalTo(Booleano.falso())));
}
@Test
public void nao() {
assertThat(verdadeiro.negar(), is(equalTo(Booleano.falso())));
assertThat(verdadeiro, is(equalTo(Booleano.verdadeiro())));
assertThat(falso.negar(), is(equalTo(Booleano.verdadeiro())));
assertThat(falso, is(equalTo(Booleano.falso())));
}
@Test(expected = NullPointerException.class)
public void eVerdadeiroComNulo() {
verdadeiro.e(null);
}
@Test(expected = NullPointerException.class)
public void eFalsoComNulo() {
falso.e(null);
}
@Test(expected = NullPointerException.class)
public void ouVerdadeiroComNulo() {
verdadeiro.ou(null);
}
@Test(expected = NullPointerException.class)
public void ouFalsoComNulo() {
falso.ou(null);
}
}
| unlicense |
gushakov/nw-jsf-showcase | tmp~sflight~web/src/ch/unil/sflight/web/jsf/validator/FormEntryValidator.java | 2430 | package ch.unil.sflight.web.jsf.validator;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import ch.unil.sflight.web.jsf.utils.Utils;
import com.sap.tc.logging.Location;
import com.sap.tc.logging.Severity;
import com.sap.tc.logging.SimpleLogger;
public class FormEntryValidator implements Validator {
private static final Location loc = Location
.getLocation(FormEntryValidator.class);
// airline ID pattern: two to three letters
private static final Pattern airlineIdPattern = Pattern.compile("^[a-z]{2,3}$", Pattern.CASE_INSENSITIVE);
// customer ID pattern: digits only
private static final Pattern digitsPattern = Pattern.compile("^\\d+$");
@Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
// airlineId
if (component.getId().equalsIgnoreCase("airlineId")) {
if (value != null) {
SimpleLogger.trace(Severity.DEBUG, loc, "Validating airline ID value {0}", value);
Matcher matcher = airlineIdPattern.matcher((String) value);
if (!matcher.matches()) {
throw new ValidatorException(Utils.makeFacesMessage(
FacesMessage.SEVERITY_ERROR, "error",
"airline_id_invalid"));
}
}
}
//customerId, connectId, counter
else if (component.getId().equalsIgnoreCase("customerId")
|| component.getId().equalsIgnoreCase("connectId")
|| component.getId().equalsIgnoreCase("counter")) {
if (value != null) {
SimpleLogger.trace(Severity.DEBUG, loc, "Validating numeric value {0}", value);
Matcher matcher = digitsPattern.matcher((String) value);
if (!matcher.matches()) {
throw new ValidatorException(Utils.makeFacesMessage(
FacesMessage.SEVERITY_ERROR, "error",
"not_digits"));
}
}
}
//flightDate
else if (component.getId().equalsIgnoreCase("flightDate")) {
if (value != null) {
SimpleLogger.trace(Severity.DEBUG, loc, "Validating flight date value {0}", value);
Date date = (Date) value;
if ( date.before(new Date()) ){
throw new ValidatorException(Utils.makeFacesMessage(
FacesMessage.SEVERITY_ERROR, "error",
"past_date"));
}
}
}
}
}
| unlicense |
jdasher/mancala | Mancala-v0.3/src/mancala/textview/Panel.java | 3197 | package mancala.textview;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import mancala.controller.Controller;
public class Panel extends JPanel {
private static final long serialVersionUID = -5931426239657239552L;
private GridBagConstraints gridCon = new GridBagConstraints();
// Buttons to represent game board
private JButton pit1 = new JButton("4");
private JButton pit2 = new JButton("4");
private JButton pit3 = new JButton("4");
private JButton pit4 = new JButton("4");
private JButton pit5 = new JButton("4");
private JButton pit6 = new JButton("4");
private JButton pit7 = new JButton("4");
private JButton pit8 = new JButton("4");
private JButton pit9 = new JButton("4");
private JButton pit10 = new JButton("4");
private JButton pit11 = new JButton("4");
private JButton pit12 = new JButton("4");
// Buttons for player values
private JLabel player1Score = new JLabel("0");
private JLabel player2Score = new JLabel("0");
// Labels for player scores
private JLabel player1Label = new JLabel("Player 1");
private JLabel player2Label = new JLabel("Player 2");
public Panel() {
this.setLayout(new GridBagLayout());
// Buttons 1-12
gridCon.gridx = 1;
gridCon.gridy = 1;
gridCon.insets = new Insets(10,10,10,10);
this.add(pit12,gridCon);
gridCon.gridx = 2;
gridCon.gridy = 1;
gridCon.insets = new Insets(10,10,10,10);
this.add(pit11,gridCon);
gridCon.gridx = 3;
gridCon.gridy = 1;
gridCon.insets = new Insets(10,10,10,10);
this.add(pit10,gridCon);
gridCon.gridx = 4;
gridCon.gridy = 1;
gridCon.insets = new Insets(10,10,10,10);
this.add(pit9,gridCon);
gridCon.gridx = 5;
gridCon.gridy = 1;
gridCon.insets = new Insets(10,10,10,10);
this.add(pit8,gridCon);
gridCon.gridx = 6;
gridCon.gridy = 1;
gridCon.insets = new Insets(10,10,10,10);
this.add(pit7,gridCon);
gridCon.gridx = 1;
gridCon.gridy = 4;
gridCon.insets = new Insets(10,10,10,10);
this.add(pit1,gridCon);
gridCon.gridx = 2;
gridCon.gridy = 4;
gridCon.insets = new Insets(10,10,10,10);
this.add(pit2,gridCon);
gridCon.gridx = 3;
gridCon.gridy = 4;
gridCon.insets = new Insets(10,10,10,10);
this.add(pit3,gridCon);
gridCon.gridx = 4;
gridCon.gridy = 4;
gridCon.insets = new Insets(10,10,10,10);
this.add(pit4,gridCon);
gridCon.gridx = 5;
gridCon.gridy = 4;
gridCon.insets = new Insets(10,10,10,10);
this.add(pit5,gridCon);
gridCon.gridx = 6;
gridCon.gridy = 4;
gridCon.insets = new Insets(10,10,10,10);
this.add(pit6,gridCon);
// Player pit scores
gridCon.gridx = 0;
gridCon.gridy = 2;
gridCon.insets = new Insets(10,10,10,10);
this.add(player2Score, gridCon);
gridCon.gridx = 7;
gridCon.gridy = 2;
gridCon.insets = new Insets(10,10,10,10);
this.add(player1Score, gridCon);
// Player pit labels
gridCon.gridx = 0;
gridCon.gridy = 3;
gridCon.insets = new Insets(10,10,10,10);
this.add(player2Label, gridCon);
gridCon.gridx = 7;
gridCon.gridy = 3;
gridCon.insets = new Insets(10,10,10,10);
this.add(player1Label, gridCon);
}
} | unlicense |
h4h13/Windy | app/src/main/java/com/sharebuttons/weather/ui/TextLight.java | 813 | package com.sharebuttons.weather.ui;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by Monkey D Luffy on 7/17/2015.
*/
public class TextLight extends TextView {
public TextLight(Context context) {
super(context);
setTypeFace();
}
public TextLight(Context context, AttributeSet attrs) {
super(context, attrs);
setTypeFace();
}
public TextLight(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setTypeFace();
}
private void setTypeFace() {
Typeface typeface = Typeface.createFromAsset(getResources().getAssets(), "fonts/WorkSans-Thin.ttf");
setTypeface(typeface);
}
}
| unlicense |
eocrawford/UW-CS-materials | CS_211/DoubleStack.java | 9099 |
import java.util.EmptyStackException;
/******************************************************************************
* A <CODE>DoubleStack</CODE> is a stack of double values.
*
* <dl><dt><b>Limitations:</b>
* <dd>
* (1) The capacity of one of these stacks can change after it's created, but
* the maximum capacity is limited by the amount of free memory on the
* machine. The constructor, <CODE>ensureCapacity</CODE>, <CODE>push</CODE>,
* and <CODE>trimToSize</CODE> will result in an
* <CODE>OutOfMemoryError</CODE> when free memory is exhausted.
* <dd>
* (2) A stack's capacity cannot exceed the maximum integer 2,147,483,647
* (<CODE>Integer.MAX_VALUE</CODE>). Any attempt to create a larger capacity
* results in a failure due to an arithmetic overflow.
* </dl>
*
* <dt><b>Java Source Code for this class:</b><dd>
* <A HREF="../../../../edu/colorado/collections/DoubleStack.java">
* http://www.cs.colorado.edu/~main/edu/colorado/collections/DoubleStack.java
* </A>
*
* @author Michael Main
* <A HREF="mailto:main@colorado.edu"> (main@colorado.edu) </A>
*
* @version
* Jun 12, 1998
*
* @see DoubleLinkedStack
* @see ObjectStack
* @see BooleanStack
* @see ByteStack
* @see CharStack
* @see FloatStack
* @see IntStack
* @see LongStack
* @see ShortStack
******************************************************************************/
public class DoubleStack implements Cloneable
{
// Invariant of the DoubleStack class:
// 1. The number of items in the stack is in the instance variable manyItems.
// 2. For an empty stack, we do not care what is stored in any of data; for a
// non-empty stack, the items in the stack are stored in a partially-filled array called
// data, with the bottom of the stack at data[0], the next item at data[1], and so on
// to the top of the stack at data[manyItems-1].
private double[ ] data;
private int manyItems;
/**
* Initialize an empty stack with an initial capacity of 10. Note that the
* <CODE>push</CODE> method works efficiently (without needing more
* memory) until this capacity is reached.
* @param - none
* <dt><b>Postcondition:</b><dd>
* This stack is empty and has an initial capacity of 10.
* @exception OutOfMemoryError
* Indicates insufficient memory for:
* <CODE>new double[10]</CODE>.
**/
public DoubleStack( )
{
final int INITIAL_CAPACITY = 10;
manyItems = 0;
data = new double[INITIAL_CAPACITY];
}
/**
* Initialize an empty stack with a specified initial capacity. Note that the
* <CODE>push</CODE> method works efficiently (without needing more
* memory) until this capacity is reached.
* @param <CODE>initialCapacity</CODE>
* the initial capacity of this stack
* <dt><b>Precondition:</b><dd>
* <CODE>initialCapacity</CODE> is non-negative.
* <dt><b>Postcondition:</b><dd>
* This stack is empty and has the given initial capacity.
* @exception IllegalArgumentException
* Indicates that initialCapacity is negative.
* @exception OutOfMemoryError
* Indicates insufficient memory for:
* <CODE>new double[initialCapacity]</CODE>.
**/
public DoubleStack(int initialCapacity)
{
if (initialCapacity < 0)
throw new IllegalArgumentException
("initialCapacity too small " + initialCapacity);
manyItems = 0;
data = new double[initialCapacity];
}
/**
* Generate a copy of this stack.
* @param - none
* @return
* The return value is a copy of this stack. Subsequent changes to the
* copy will not affect the original, nor vice versa. Note that the return
* value must be type cast to a <CODE>DoubleStack</CODE> before it can be used.
* @exception OutOfMemoryError
* Indicates insufficient memory for creating the clone.
**/
public Object clone( )
{ // Clone a DoubleStack.
DoubleStack answer;
try
{
answer = (DoubleStack) super.clone( );
}
catch (CloneNotSupportedException e)
{
// This exception should not occur. But if it does, it would probably indicate a
// programming error that made super.clone unavailable. The most comon error
// The most common error would be forgetting the "Implements Cloneable"
// clause at the start of this class.
throw new RuntimeException
("This class does not implement Cloneable");
}
answer.data = (double [ ]) data.clone( );
return answer;
}
/**
* Change the current capacity of this stack.
* @param - none
* @param <CODE>minimumCapacity</CODE>
* the new capacity for this stack
* <dt><b>Postcondition:</b><dd>
* This stack's capacity has been changed to at least <CODE>minimumCapacity</CODE>.
* If the capacity was already at or greater than <CODE>minimumCapacity</CODE>,
* then the capacity is left unchanged.
* @exception OutOfMemoryError
* Indicates insufficient memory for: <CODE>new double[minimumCapacity]</CODE>.
**/
public void ensureCapacity(int minimumCapacity)
{
double biggerArray[ ];
if (data.length < minimumCapacity)
{
biggerArray = new double[minimumCapacity];
System.arraycopy(data, 0, biggerArray, 0, manyItems);
data = biggerArray;
}
}
/**
* Accessor method to get the current capacity of this stack.
* The <CODE>push</CODE> method works efficiently (without needing
* more memory) until this capacity is reached.
* @param - none
* @return
* the current capacity of this stack
**/
public int getCapacity( )
{
return data.length;
}
/**
* Determine whether this stack is empty.
* @param - none
* @return
* <CODE>true</CODE> if this stack is empty;
* <CODE>false</CODE> otherwise.
**/
public boolean isEmpty( )
{
return (manyItems == 0);
}
/**
* Get the top item of this stack, without removing the item.
* @param - none
* <dt><b>Precondition:</b><dd>
* This stack is not empty.
* @return
* the top item of the stack
* @exception EmptyStackException
* Indicates that this stack is empty.
**/
public double peek( )
{
if (manyItems == 0)
// EmptyStackException is from java.util and its constructor has no argument.
throw new EmptyStackException( );
return data[manyItems-1];
}
/**
* Get the top item, removing it from this stack.
* @param - none
* <dt><b>Precondition:</b><dd>
* This stack is not empty.
* <dt><b>Postcondition:</b><dd>
* The return value is the top item of this stack, and the item has
* been removed.
* @exception EmptyStackException
* Indicates that this stack is empty.
**/
public double pop( )
{
if (manyItems == 0)
// EmptyStackException is from java.util and its constructor has no argument.
throw new EmptyStackException( );
return data[--manyItems];
}
/**
* Push a new item onto this stack. If the addition
* would take this stack beyond its current capacity, then the capacity is
* increased before adding the new item. The new item may be the null
* reference.
* @param <CODE>item</CODE>
* the item to be pushed onto this stack
* <dt><b>Postcondition:</b><dd>
* The item has been pushed onto this stack.
* @exception OutOfMemoryError
* Indicates insufficient memory for increasing the stack's capacity.
* <dt><b>Note:</b><dd>
* An attempt to increase the capacity beyond
* <CODE>Integer.MAX_VALUE</CODE> will cause the stack to fail with an
* arithmetic overflow.
**/
public void push(double item)
{
if (manyItems == data.length)
{
// Double the capacity and add 1; this works even if manyItems is 0. However, in
// case that manyItems*2 + 1 is beyond Integer.MAX_VALUE, there will be an
// arithmetic overflow and the bag will fail.
ensureCapacity(manyItems*2 + 1);
}
data[manyItems] = item;
manyItems++;
}
/**
* Accessor method to determine the number of items in this stack.
* @param - none
* @return
* the number of items in this stack
**/
public int size( )
{
return manyItems;
}
/**
* Reduce the current capacity of this stack to its actual size (i.e., the
* number of items it contains).
* @param - none
* <dt><b>Postcondition:</b><dd>
* This stack's capacity has been changed to its current size.
* @exception OutOfMemoryError
* Indicates insufficient memory for altering the capacity.
**/
public void trimToSize( )
{
double trimmedArray[ ];
if (data.length != manyItems)
{
trimmedArray = new double[manyItems];
System.arraycopy(data, 0, trimmedArray, 0, manyItems);
data = trimmedArray;
}
}
}
| unlicense |
bpmartins/sgcm | src/main/java/model/relatorios/EmprestimoVO.java | 1440 | package model.relatorios;
import java.io.Serializable;
public class EmprestimoVO implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String id;
private String aluno;
private String codAluno;
private String codInstrumento;
private String instrumento;
private String dataInicio;
private String dataFim;
private String observacoes;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAluno() {
return aluno;
}
public void setAluno(String aluno) {
this.aluno = aluno;
}
public String getInstrumento() {
return instrumento;
}
public void setInstrumento(String instrumento) {
this.instrumento = instrumento;
}
public String getDataInicio() {
return dataInicio;
}
public void setDataInicio(String dataInicio) {
this.dataInicio = dataInicio;
}
public String getDataFim() {
return dataFim;
}
public void setDataFim(String dataFim) {
this.dataFim = dataFim;
}
public String getCodAluno() {
return codAluno;
}
public void setCodAluno(String codAluno) {
this.codAluno = codAluno;
}
public String getCodInstrumento() {
return codInstrumento;
}
public void setCodInstrumento(String codInstrumento) {
this.codInstrumento = codInstrumento;
}
public String getObservacoes() {
return observacoes;
}
public void setObservacoes(String observacoes) {
this.observacoes = observacoes;
}
}
| unlicense |
D-Inc/EnderIO | src/main/java/crazypants/enderio/conduit/IConduitItem.java | 389 | package crazypants.enderio.conduit;
import javax.annotation.Nonnull;
import crazypants.enderio.api.tool.IHideFacades;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
public interface IConduitItem extends IHideFacades {
@Nonnull
Class<? extends IConduit> getBaseConduitType();
IConduit createConduit(ItemStack item, EntityPlayer player);
}
| unlicense |
codeApeFromChina/resource | frame_packages/java_libs/spring-2.5.6-src/src/org/springframework/beans/factory/parsing/CompositeComponentDefinition.java | 2418 | /*
* Copyright 2002-2006 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 org.springframework.beans.factory.parsing;
import java.util.LinkedList;
import java.util.List;
import org.springframework.util.Assert;
/**
* {@link ComponentDefinition} implementation that holds one or more nested
* {@link ComponentDefinition} instances, aggregating them into a named group
* of components.
*
* @author Juergen Hoeller
* @since 2.0.1
* @see #getNestedComponents()
*/
public class CompositeComponentDefinition extends AbstractComponentDefinition {
private final String name;
private final Object source;
private final List nestedComponents = new LinkedList();
/**
* Create a new CompositeComponentDefinition.
* @param name the name of the composite component
* @param source the source element that defines the root of the composite component
*/
public CompositeComponentDefinition(String name, Object source) {
Assert.notNull(name, "Name must not be null");
this.name = name;
this.source = source;
}
public String getName() {
return this.name;
}
public Object getSource() {
return this.source;
}
/**
* Add the given component as nested element of this composite component.
* @param component the nested component to add
*/
public void addNestedComponent(ComponentDefinition component) {
Assert.notNull(component, "ComponentDefinition must not be null");
this.nestedComponents.add(component);
}
/**
* Return the nested components that this composite component holds.
* @return the array of nested components, or an empty array if none
*/
public ComponentDefinition[] getNestedComponents() {
return (ComponentDefinition[])
this.nestedComponents.toArray(new ComponentDefinition[this.nestedComponents.size()]);
}
}
| unlicense |
Sequoza/Java-Patterns | Java-Patterns/Strategy/Strategy_1.java | 163 | package Strategy;
public class Strategy_1 implements Strategy {
@Override
public void print(String string) {
System.out.println(string);
}
}
| unlicense |
bigono/lexer | Context.java | 1138 | package task12;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* To be shared amongst various compiler parts.
* Holds all the identifiers and constants we've encountered.
* Lexer pushes them here, then other parts enhance them with more information
*/
class Context {
public final Map<String, Integer> idMap = new HashMap<String, Integer>();
public final List<Constant> constList= new ArrayList<Constant>();
@Override
public String toString() {
return "Context [idMap=" + idMap + ", constList=" + constList + "]";
}
public Context() {
for (String s : Lexer.reservedKeywords) {
enumerateId(s);
}
}
public int enumerateId(String s) {
int n = idMap.size();
idMap.put(s, n);
return n;
}
/*
* TODO
* The method detecting repeating constants would save some data segment space.
* The present implementation doesn't do it.
*/
public int enumerateConstant(Constant c) {
int n = constList.size();
constList.add(c);
return n;
}
}
| unlicense |
marc-portier/mfjcs | mfjcs-rest/src/main/java/org/mfjcs/api/MFJCSException.java | 419 | package org.mfjcs.api;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
public abstract class MFJCSException extends Exception {
public MFJCSException(Throwable cause) {
super(cause);
}
@JsonProperty
public abstract String getErrorCode();
@JsonProperty
@JsonInclude(JsonInclude.Include.NON_NULL)
public Object[] getParams() {
return null;
}
}
| unlicense |
bdinaburg/organizer | src/test/java/mongodbtester/Test3.java | 8371 | package mongodbtester;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.HashSet;
import java.util.Properties;
import org.json.JSONObject;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import transientPojos.ExifData;
import util.ExifUtils;
import util.JSONBuilder;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test3 {
public static void main(String[] args) {
ExifData exifData = ExifUtils.getExifData("c:\\development\\pic.jpg");
System.out.println(exifData);
//ExifUtils.showMetaData(strPathToFile, exifData)
/* showMetaData();
String test = getUrlContents("http://nominatim.openstreetmap.org/reverse?format=json&lat=39.936230555555554&lon=-74.07645277777777&zoom=18&addressdetails=1");
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(test);
String prettyJsonString = gson.toJson(je);
JSONObject jsonObj = new JSONObject(prettyJsonString);
String strStreetAddress = jsonObj.getString("display_name");
System.out.println(prettyJsonString);*/
/* String test = "[GPS] - GPS Latitude = 39° 56' 10.43";
if(test.toUpperCase().indexOf("GPS L") > 0 && test.indexOf(" = ") > 0)
{
System.out.println("yea!!");
}*/
/*DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
Calendar cal = Calendar.getInstance();
String strDate = dateFormat.format(cal.getTime());
System.out.println(strDate);*/
//Test2 tst2 = new Test2();
//System.out.println(tst2.getFile());
//testDates();
//writePropertiesFile();
//checkPath();
}
public static void checkPath()
{
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current absolute path is: " + s);
}
public static void testDates()
{
HashSet<String> testRoles = new HashSet<String>();
testRoles.add("role1");
testRoles.add("role2");
String test = JSONBuilder.buildCreateUserJSON("boris", "password", testRoles);
System.out.println(test);
}
public static void writePropertiesFile() {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("configuration.properties");
// set the properties value
prop.setProperty("hostname", "chaglei.com");
prop.setProperty("port", "27017");
prop.setProperty("schema", "admin");
prop.setProperty("username", "admin");
prop.setProperty("password", "PA$$Word12345");
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private String getFile()
{
ClassLoader classLoader = getClass().getClassLoader();
return classLoader.getResource(".").toString();
}
public static void showMetaData() {
final String alphabet = "+-.1234567890";
File file = new File("c:\\development\\pic.jpg");
Metadata metadata = null;
try {
metadata = ImageMetadataReader.readMetadata(file);
} catch (ImageProcessingException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Directory directory : metadata.getDirectories()) {
for (Tag tag : directory.getTags()) {
String strDescription = tag.getDescription();
String strTagName = tag.getTagName();
strDescription = String.format("[%s] - %s = %s", directory.getName(), strTagName, strDescription);
//System.out.format("[%s] - %s = %s", directory.getName(), strTagName, strDescription);
//strDescription += directory.getName() + strTagName + strDescription;
System.out.println(strDescription);
if(strDescription.toUpperCase().indexOf("GPS L") > 0 && strDescription.toUpperCase().indexOf("REF") < 0)
{
int position = strDescription.indexOf(" = ");
position += 3; //this should put the positioning marker right before
// the first number which should be days
String strDays = "";
String strHours = "";
String strMinutes = "";
boolean boolExit = false;
while(position < strDescription.length() - 1 && boolExit != true)
{
if(alphabet.contains(new Character(strDescription.charAt(position)).toString()))
{
strDays += new Character(strDescription.charAt(position)).toString();
position++;
}
else
{
boolExit = true;
}
}
/**
* continue moving, we just got first number, keep going through garbage
* characters until we encounter a number again
*/
boolExit = false;
while(position < strDescription.length() - 1 && boolExit != true)
{
if(alphabet.contains(new Character(strDescription.charAt(position)).toString()) == false)
{
position++;
}
else
{
boolExit = true;
}
}
/**
* We should be at the start of a second number at this point, get the minutes
*/
boolExit = false;
while(position < strDescription.length() - 1 && boolExit != true)
{
if(alphabet.contains(new Character(strDescription.charAt(position)).toString()))
{
strHours += new Character(strDescription.charAt(position)).toString();
position++;
}
else
{
boolExit = true;
}
}
/**
* continue moving, we just got first number, keep going through garbage
* characters until we encounter a number again //looking for last number now
*/
boolExit = false;
while(position < strDescription.length() - 1 && boolExit != true)
{
if(alphabet.contains(new Character(strDescription.charAt(position)).toString()) == false)
{
position++;
}
else
{
boolExit = true;
}
}
/**
* We should be at the start of a third number at this point, get the hours
*/
boolExit = false;
while(position < strDescription.length() - 1 && boolExit != true)
{
if(alphabet.contains(new Character(strDescription.charAt(position)).toString()))
{
strMinutes += new Character(strDescription.charAt(position)).toString();
position++;
}
else
{
boolExit = true;
}
}
System.out.println("DAYS: " + strDays);
System.out.println("HOURS: " + strHours);
System.out.println("MINUTES: " + strMinutes);
Double dd = Math.signum(Double.parseDouble(strDays)) * (Math.abs(Double.parseDouble(strDays)) + (Double.parseDouble(strHours) / 60.0) + (Double.parseDouble(strMinutes) / 3600.0));
System.out.println("DECIMAL DEGREES:" + dd);
}
}
if (directory.hasErrors()) {
for (String error : directory.getErrors()) {
System.err.format("ERROR: %s", error);
}
}
}
}
private static String getUrlContents(String theUrl) {
StringBuilder content = new StringBuilder();
// many of these calls can throw exceptions, so i've just
// wrapped them all in one try/catch statement.
try {
// create a url object
URL url = new URL(theUrl);
// create a urlconnection object
URLConnection urlConnection = url.openConnection();
// wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
// read from the urlconnection via the bufferedreader
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}
| unlicense |
freshleaf/DutyApp_Android | src/com/g200001/dutyapp/droid/view/vo/IncidentVo.java | 8491 | package com.g200001.dutyapp.droid.view.vo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.text.TextUtils;
import com.g200001.dutyapp.droid.rest.model.Incident;
import com.g200001.dutyapp.droid.rest.model.PolicyRule;
import com.g200001.dutyapp.droid.rest.model.UserInfo;
import com.g200001.dutyapp.droid.util.DutyTextUtils;
public class IncidentVo implements Serializable {
private static final long serialVersionUID = -2315726295241132713L;
public static final int STATE_TRIGGERED = 0;
public static final int STATE_ACKNOWLEDGED = 1;
public static final int STATE_RESOLVED = 2;
public static final int STATE_REASSIGNED = 3;
public static final int STATE_AUTO_RESOLVED = 4;
private String id;
private int state;
private String createTime;
private String acknowledgedTime;
private String resolvedTime;
private String updateTime;
private String subject;
private String details;
private String serviceName;
private List<UserVo> assignedUsers;
private long incidentNo;
private UserVo acknowledgedUser;
private UserVo reassignedUser;
private UserVo resolvedUser;
public static IncidentVo createFromIncidentObj(Incident incidentObj) {
if (incidentObj == null) {
return null;
}
IncidentVo incidentVo = new IncidentVo();
incidentVo.id = incidentObj.getId();
incidentVo.state = incidentObj.getState();
incidentVo.createTime = DutyTextUtils
.getFormattedTimeString(incidentObj.getCreate_time());
// XXX
incidentVo.updateTime = incidentVo.createTime;
if (incidentVo.state == STATE_ACKNOWLEDGED) {
incidentVo.updateTime = DutyTextUtils
.getFormattedTimeString(incidentObj.getAck_time());
}
if (incidentVo.state == STATE_RESOLVED) {
incidentVo.updateTime = DutyTextUtils
.getFormattedTimeString(incidentObj.getResolve_time());
}
incidentVo.subject = incidentObj.getDescription();
incidentVo.details = incidentObj.getDetail();
String serviceName = "";
if (incidentObj.getService() != null) {
serviceName = incidentObj.getService().getService_name();
}
incidentVo.serviceName = serviceName;
incidentVo.incidentNo = incidentObj.getIncident_no();
if (incidentObj.getAck_user() != null) {
incidentVo.acknowledgedUser = new UserVo();
incidentVo.acknowledgedUser.setUserId(incidentObj.getAck_user()
.getId());
incidentVo.acknowledgedUser.setUserName(incidentObj.getAck_user()
.getDisplayName());
}
if (!TextUtils.isEmpty(incidentObj.getAck_time())) {
incidentVo.acknowledgedTime = DutyTextUtils
.getFormattedTimeString(incidentObj.getAck_time());
}
if (incidentObj.getAssign_user() != null) {
incidentVo.reassignedUser = new UserVo();
incidentVo.reassignedUser.setUserId(incidentObj.getAssign_user()
.getId());
incidentVo.reassignedUser.setUserName(incidentObj.getAssign_user()
.getDisplayName());
}
if (incidentObj.getResolve_user() != null) {
incidentVo.resolvedUser = new UserVo();
incidentVo.resolvedUser.setUserId(incidentObj.getResolve_user()
.getId());
incidentVo.resolvedUser.setUserName(incidentObj.getResolve_user()
.getDisplayName());
}
if (!TextUtils.isEmpty(incidentObj.getResolve_time())) {
incidentVo.resolvedTime = DutyTextUtils
.getFormattedTimeString(incidentObj.getResolve_time());
}
if (incidentObj.getService() != null
&& incidentObj.getService().getEscalationPolicy() != null) {
List<PolicyRule> policyRules = incidentObj.getService()
.getEscalationPolicy().getPolicyRules();
if (policyRules != null && policyRules.size() > 0) {
incidentVo.assignedUsers = new ArrayList<UserVo>();
List<UserInfo> uniqueUserInfoList = new ArrayList<UserInfo>();
Iterator<PolicyRule> policyRuleIterator = policyRules
.iterator();
while (policyRuleIterator.hasNext()) {
PolicyRule rule = policyRuleIterator.next();
List<UserInfo> users = rule.getUsers();
if (users == null) {
continue;
}
Iterator<UserInfo> userInfoIterator = users.iterator();
while (userInfoIterator.hasNext()) {
UserInfo tmp = userInfoIterator.next();
Iterator<UserInfo> tmpIterator = uniqueUserInfoList
.iterator();
boolean found = false;
while (tmpIterator.hasNext()) {
if (tmp.equals(tmpIterator.next())) {
found = true;
break;
}
}
if (!found) {
uniqueUserInfoList.add(tmp);
}
}
}
Iterator<UserInfo> uniqueUserInfoIterator = uniqueUserInfoList
.iterator();
while (uniqueUserInfoIterator.hasNext()) {
UserInfo userInfo = uniqueUserInfoIterator.next();
UserVo userVo = new UserVo();
userVo.setUserName(userInfo.getDisplayName());
userVo.setUserId(userInfo.getId());
incidentVo.assignedUsers.add(userVo);
}
}
}
return incidentVo;
}
public boolean isAssignedToUser(String userId) {
if (assignedUsers == null) {
return false;
}
if (userId == null) {
return false;
}
Iterator<UserVo> iterator = assignedUsers.iterator();
while (iterator.hasNext()) {
UserVo userVo = iterator.next();
if (userId.equals(userVo.getUserId())) {
return true;
}
}
return false;
}
public List<IncidentTimelineVo> getTimeline() {
List<IncidentTimelineVo> timelineList = new ArrayList<IncidentTimelineVo>();
IncidentTimelineVo tmp = new IncidentTimelineVo();
tmp.setState(IncidentTimelineVo.STATE_TRIGGERED);
tmp.setTime(createTime);
tmp.setEvent("创建事件");
timelineList.add(tmp);
if (acknowledgedUser != null) {
tmp = new IncidentTimelineVo();
tmp.setState(IncidentTimelineVo.STATE_ACKNOWLEDGED);
tmp.setTime(acknowledgedTime);
tmp.setEvent(acknowledgedUser.getUserName() + " 接受了事件");
timelineList.add(tmp);
}
if (resolvedUser != null) {
tmp = new IncidentTimelineVo();
tmp.setState(IncidentTimelineVo.STATE_RESOLVED);
tmp.setTime(resolvedTime);
tmp.setEvent(resolvedUser.getUserName() + " 解决了事件");
timelineList.add(tmp);
}
return timelineList;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public long getIncidentNo() {
return incidentNo;
}
public void setIncidentNo(long incidentNo) {
this.incidentNo = incidentNo;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public List<UserVo> getAssignedUsers() {
return assignedUsers;
}
public void setAssignedUsers(List<UserVo> assignedUsers) {
this.assignedUsers = assignedUsers;
}
public String getAssignedUserName() {
if (assignedUsers == null) {
return "";
}
Iterator<UserVo> iterator = assignedUsers.iterator();
StringBuffer buff = new StringBuffer();
while (iterator.hasNext()) {
UserVo user = iterator.next();
buff.append(user.getUserName());
if (iterator.hasNext()) {
buff.append(", ");
}
}
return buff.toString();
}
public UserVo getAcknowledgedUser() {
return acknowledgedUser;
}
public void setAcknowledgedUser(UserVo acknowledgedUser) {
this.acknowledgedUser = acknowledgedUser;
}
public UserVo getReassignedUser() {
return reassignedUser;
}
public void setReassignedUser(UserVo reassignedUser) {
this.reassignedUser = reassignedUser;
}
public UserVo getResolvedUser() {
return resolvedUser;
}
public void setResolvedUser(UserVo resolvedUser) {
this.resolvedUser = resolvedUser;
}
public String getAcknowledgedTime() {
return acknowledgedTime;
}
public void setAcknowledgedTime(String acknowledgedTime) {
this.acknowledgedTime = acknowledgedTime;
}
public String getResolvedTime() {
return resolvedTime;
}
public void setResolvedTime(String resolvedTime) {
this.resolvedTime = resolvedTime;
}
}
| apache-2.0 |
gijsleussink/ceylon | runtime/testsuite/src/test/java/org/jboss/ceylon/test/modules/smoke/test/SmokeTestCase.java | 3380 | /*
* Copyright 2011 Red Hat inc. and third party contributors as noted
* by the author tags.
*
* 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 org.jboss.ceylon.test.modules.smoke.test;
import org.jboss.acme.$module_;
import org.jboss.acme.run_;
import org.jboss.ceylon.test.modules.ModulesTest;
import org.jboss.filtered.api.SomeAPI;
import org.jboss.filtered.impl.SomeImpl;
import org.jboss.filtered.spi.SomeSPI;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
/**
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class SmokeTestCase extends ModulesTest {
@Test
public void singleModule() throws Throwable {
JavaArchive module = ShrinkWrap.create(JavaArchive.class, "org.jboss.acme-1.0.0.CR1.car");
module.addClasses($module_.class, run_.class);
testArchive(module);
}
@Test
public void swingModule() throws Throwable {
JavaArchive module = ShrinkWrap.create(JavaArchive.class, "org.jboss.swing-1.0.0.CR1.car");
module.addClasses(org.jboss.swing.$module_.class, org.jboss.swing.run_.class);
testArchive(module);
}
@Test
public void filteredAndCycleModule() throws Throwable {
JavaArchive module = ShrinkWrap.create(JavaArchive.class, "eu.cloud.clazz-1.0.0.GA.car");
module.addClasses(eu.cloud.clazz.$module_.class, eu.cloud.clazz.run_.class);
JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "org.jboss.filtered-1.0.0.Alpha1.car");
lib.addClass(org.jboss.filtered.$module_.class);
lib.addClass(SomeSPI.class);
lib.addClass(SomeAPI.class);
lib.addClass(SomeImpl.class);
testArchive(module, lib);
}
@Test
public void transitiveModule() throws Throwable {
JavaArchive module = ShrinkWrap.create(JavaArchive.class, "cz.brno.as8-8.0.0.Alpha1.car");
module.addClasses(cz.brno.as8.$module_.class, cz.brno.as8.run_.class);
JavaArchive lib1 = ShrinkWrap.create(JavaArchive.class, "com.foobar.qwert-1.0.0.GA.car");
lib1.addClasses(com.foobar.qwert.$module_.class, com.foobar.qwert.run_.class);
JavaArchive lib2 = ShrinkWrap.create(JavaArchive.class, "org.jboss.acme-1.0.0.CR1.car");
lib2.addClasses($module_.class, run_.class);
JavaArchive lib3 = ShrinkWrap.create(JavaArchive.class, "eu.cloud.clazz-1.0.0.GA.car");
lib3.addClasses(eu.cloud.clazz.$module_.class, eu.cloud.clazz.run_.class);
JavaArchive lib4 = ShrinkWrap.create(JavaArchive.class, "org.jboss.filtered-1.0.0.Alpha1.car");
lib4.addClass(org.jboss.filtered.$module_.class);
lib4.addClass(SomeSPI.class);
lib4.addClass(SomeAPI.class);
lib4.addClass(SomeImpl.class);
testArchive(module, lib1, lib2, lib3, lib4);
}
}
| apache-2.0 |
thunderSummer/pobooks | app/src/main/java/com/oureda/thunder/pobooks/activity/main/MainActivity.java | 11009 | package com.oureda.thunder.pobooks.activity.main;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.oureda.thunder.pobooks.CustomView.CombineFAB;
import com.oureda.thunder.pobooks.CustomView.FlowLayout;
import com.oureda.thunder.pobooks.Data.BookInfo;
import com.oureda.thunder.pobooks.Data.Books;
import com.oureda.thunder.pobooks.Data.ChapterInfo;
import com.oureda.thunder.pobooks.Data.TitleInfo;
import com.oureda.thunder.pobooks.R;
import com.oureda.thunder.pobooks.activity.adapter.BookAdapter;
import com.oureda.thunder.pobooks.base.BaseActivity;
import com.oureda.thunder.pobooks.baseInterface.AdapterChangedListener;
import com.oureda.thunder.pobooks.utils.FileUtil;
import com.oureda.thunder.pobooks.utils.LogUtil;
import com.oureda.thunder.pobooks.utils.ToastUtil;
import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends BaseActivity {
FlowLayout flowLayout;
@BindView(R.id.toolbar_main)
Toolbar toolbarMain;
@BindView(R.id.book_list_main)
RecyclerView bookListMain;
@BindView(R.id.swift_refresh)
LinearLayout swiftRefresh;
@BindView(R.id.combine_main)
CombineFAB combineMain;
@BindView(R.id.check_all_main)
CheckBox checkAllMain;
@BindView(R.id.share_main)
ImageView shareMain;
@BindView(R.id.delete_main)
ImageView deleteMain;
@BindView(R.id.bottom_main)
LinearLayout bottomMain;
@BindView(R.id.drawerLayout_main)
DrawerLayout drawerLayoutMain;
@BindView(R.id.search_main_layout)
LinearLayout searchMainLayout;
private BookAdapter bookAdapter;
private List<Books> booksList;
private boolean normal=true;
private void cancelChooseAllBook() {
HashSet localHashSet = new HashSet();
Iterator localIterator = this.booksList.iterator();
while (localIterator.hasNext()) {
((Books) localIterator.next()).setIsCheck(false);
}
this.bookAdapter = new BookAdapter(false, this.booksList, new MyAdapterChangedListener());
this.bookAdapter.setChooseAll(true);
this.bookAdapter.setChooseSet(localHashSet);
this.bookListMain.setAdapter(this.bookAdapter);
}
private void chooseAllBook() {
normal=true;
HashSet localHashSet = new HashSet();
Iterator localIterator = this.booksList.iterator();
while (localIterator.hasNext()) {
Books localBooks = (Books) localIterator.next();
localBooks.setIsCheck(true);
localHashSet.add(localBooks.getBookId());
}
this.bookAdapter = new BookAdapter(false, this.booksList, new MyAdapterChangedListener());
this.bookAdapter.setChooseAll(true);
this.bookAdapter.setChooseSet(localHashSet);
this.bookListMain.setAdapter(this.bookAdapter);
invalidateOptionsMenu();
}
private void delete() {
Iterator localIterator = this.bookAdapter.getChooseSet().iterator();
while (localIterator.hasNext()) {
String str = (String) localIterator.next();
LogUtil.d("dd", "" + str);
DataSupport.deleteAll(Books.class, new String[]{"BookId = ?", str});
DataSupport.deleteAll(TitleInfo.class, new String[]{"path = ?", str});
DataSupport.deleteAll(ChapterInfo.class,"bookId = ?",str);
try {
FileUtil.deleteFile(FileUtil.getBookDir(str));
} catch (IOException e) {
e.printStackTrace();
}
}
getBookList();
this.bookAdapter.clearChooseSet();
this.bookAdapter.setChooseAll(false);
initRecycleView();
this.combineMain.setVisibility(View.GONE);
this.bottomMain.setVisibility(View.VISIBLE);
}
private void getBookList() {
this.booksList = DataSupport.where("isTemp =?","0").find(Books.class);
LogUtil.d(TAG, "the book amount == " + this.booksList.size() + ""+DataSupport.findAll(Books.class).size());
DataSupport.deleteAll(Books.class,"isTemp = ?","1");
DataSupport.deleteAll(ChapterInfo.class,"isTemp = ?","1");
}
private void initRecycleView() {
GridLayoutManager localGridLayoutManager = new GridLayoutManager(this, 3);
this.bookListMain.setLayoutManager(localGridLayoutManager);
this.bookAdapter = new BookAdapter(false, this.booksList, new MyAdapterChangedListener());
this.bookListMain.setAdapter(this.bookAdapter);
}
private void virturlData() {
Books localBooks1 = new Books("5", "真武世界");
localBooks1.setImageId(R.drawable.book);
localBooks1.setAuthor("蚕茧里的牛");
localBooks1.setFromSd(false);
localBooks1.setHasRead(false);
localBooks1.save();
Books localBooks2 = new Books("2", "武极天下");
localBooks2.setImageId(R.drawable.book);
localBooks1.setAuthor("参见里的牛");
localBooks2.setFromSd(false);
localBooks1.setHasRead(false);
localBooks2.save();
localBooks2 = new Books("3", "邪气凛然");
localBooks2.setImageId(R.drawable.book);
localBooks2.setFromSd(false);
localBooks1.setHasRead(false);
localBooks2.save();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Connector.getDatabase();
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},2);
LogUtil.d("ssss","hshs");
}else{
LogUtil.d("ssss","ssss");
}
// virturlData();
initTool();
checkAllMain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
chooseAllBook();
} else {
cancelChooseAllBook();
}
}
});
}
private void initTool(){
setSupportActionBar(toolbarMain);
ActionBar actionBar = getSupportActionBar();
if(actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
}
actionBar.setTitle("阅读");
}
@OnClick({R.id.share_main, R.id.delete_main, R.id.bottom_main})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.share_main:
break;
case R.id.delete_main:
delete();
break;
case R.id.bottom_main:
break;
}
}
private class MyAdapterChangedListener
implements AdapterChangedListener {
private MyAdapterChangedListener() {
}
public void OnAdapterRefresh(boolean isChooseAll) {
bookAdapter.notifyDataSetChanged();
if(isChooseAll){
normal=false;
invalidateOptionsMenu();
combineMain.setVisibility(View.GONE);
bottomMain.setVisibility(View.VISIBLE);
}else{
normal=true;
invalidateOptionsMenu();
visible(combineMain);
gone(bottomMain);
}
}
}
@Override
protected void onResume() {
super.onResume();
getBookList();
bookListMain= (RecyclerView) findViewById(R.id.book_list_main);
initRecycleView();
drawerLayoutMain.closeDrawer(Gravity.START);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
drawerLayoutMain.openDrawer(GravityCompat.START);
break;
case R.id.search_main:
visible(searchMainLayout);
gone(swiftRefresh);
break;
case R.id.cancel_main:
normal=true;
invalidateOptionsMenu();
visible(combineMain);
gone(bottomMain);
initRecycleView();
break;
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(normal){
menu.findItem(R.id.search_main).setVisible(true);
menu.findItem(R.id.cancel_main).setVisible(false);
}else{
menu.findItem(R.id.search_main).setVisible(false);
menu.findItem(R.id.cancel_main).setVisible(true);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public void onBackPressed() {
if(searchMainLayout.getVisibility()==View.VISIBLE){
visible(swiftRefresh);
gone(searchMainLayout);
}
if(normal){
finish();
}else{
normal=true;
invalidateOptionsMenu();
visible(combineMain);
gone(bottomMain);
initRecycleView();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 2:
if(grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
ToastUtil.showToast("授权成功");
}else{
ToastUtil.showToast("拒绝权限无法使用此功能");
finish();
}
break;
}
}
private void request(){
}
}
| apache-2.0 |
Piasy/QQTang | src/qqtang_client/src/com/example/client/view/myView/RegActivity.java | 5492 | package com.example.client.view.myView;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.client.R;
import com.example.client.R.id;
import com.example.client.R.layout;
import com.example.client.R.menu;
import com.example.client.R.string;
import com.example.client.controller.Controller;
import com.example.client.view.others.Constant;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**.
*The activity of register
*includes painting of register,
* inform the controller of user information
* and transfer between the activities.
*/
public class RegActivity extends Activity {
EditText name, nickname, password, repassword;
Button register, regreturn;
Controller controller;
String username, nicknametxt, pass, repass;
/**.
* »æÖÆ×¢²áÒ³Ãæ£¬ÉèÖÃÎı¾ÐÅÏ¢
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg);
name = (EditText) findViewById(R.id.reg_username);
nickname = (EditText) findViewById(R.id.nickname);
password = (EditText) findViewById(R.id.reg_password);
repassword = (EditText) findViewById(R.id.reg_repassword);
register = (Button) findViewById(R.id.reg_button);
regreturn = (Button) findViewById(R.id.reg_return);
controller = Controller.getController();
controller.setHandler(regHandler);
register.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
username = name.getText().toString();
nicknametxt = nickname.getText().toString();
pass = password.getText().toString();
repass = repassword.getText().toString();
controller.signup(username,
pass, repass, nicknametxt);
}
}
);
regreturn.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
gotoMainAct();
}
}
);
}
/**.
* תµ½´óÌü½çÃæ
*/
public void gotoChooseView() {
Intent intent = new Intent();
intent.setClass(RegActivity.this, HallActivity.class);
finish();
startActivity(intent);
}
public void gotoMainAct(){
Intent intent = new Intent();
intent.setClass(RegActivity.this, MainActivity.class);
finish();
startActivity(intent);
}
/**.
* ¿ØÖÆÓÎÏ·½çÃæ²Ëµ¥
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.login, menu);
return true;
}
/**.
* ×¢²áºóµÇÈëÓÎÏ·
*/
public void signin() {
Log.v("myinfo2", "ok0");
controller.signin(username, pass, "hall-server1");
}
/**.
* ÉèÖýÓÊÕÏûÏ¢Handler
*/
Handler regHandler = new Handler() {
@SuppressLint("HandlerLeak")
public void handleMessage(Message msg) {
Log.v("myinfo2", (String)msg.obj);
JSONObject signupStatus = null;
try {
signupStatus = new JSONObject((String) msg.obj);
if (signupStatus.getString("type").equals("signup")) {
String status = "";
Log.v("myinfo2", "signup");
if (signupStatus.has("status")) {
status =
signupStatus.getString("status");
}
if (status != null
&& status.equals("success")) {
Log.v("myinfo2", "ok");
Toast.makeText(
RegActivity.this,
status,
Toast.LENGTH_SHORT
).show();
Log.v("myinfo2", "okk");
signin();
Log.v("myinfo2", "okkk");
} else {
Toast.makeText(RegActivity.this, status, Toast.LENGTH_SHORT).show();
}
}
if (signupStatus.getString("type").equals("signin")) {
String status = "";
if (signupStatus.has("status")) {
status = signupStatus.getString("status");
}
if (status != null && status.equals("Success")) {
Toast.makeText(RegActivity.this,
status,
Toast.LENGTH_SHORT
).show();
gotoChooseView();
}
else{
Toast.makeText(
RegActivity.this,
status,
Toast.LENGTH_SHORT
).show();
}
}
}
catch(JSONException e)
{
Toast.makeText(RegActivity.this, "execption", Toast.LENGTH_SHORT).show();
}
}
};
DialogInterface.OnClickListener listener =
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case AlertDialog.BUTTON_POSITIVE:// "È·ÈÏ"°´Å¥Í˳ö³ÌÐò
System.exit(0);
break;
case AlertDialog.BUTTON_NEGATIVE:// "È¡Ïû"µÚ¶þ¸ö°´Å¥È¡Ïû¶Ô»°¿ò
break;
default:
break;
}
}
};
}
| apache-2.0 |
LMAX-Exchange/disruptor | src/main/java/com/lmax/disruptor/SleepingWaitStrategy.java | 3224 | /*
* Copyright 2011 LMAX Ltd.
*
* 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.lmax.disruptor;
import java.util.concurrent.locks.LockSupport;
/**
* Sleeping strategy that initially spins, then uses a Thread.yield(), and
* eventually sleep (<code>LockSupport.parkNanos(n)</code>) for the minimum
* number of nanos the OS and JVM will allow while the
* {@link com.lmax.disruptor.EventProcessor}s are waiting on a barrier.
*
* <p>This strategy is a good compromise between performance and CPU resource.
* Latency spikes can occur after quiet periods. It will also reduce the impact
* on the producing thread as it will not need signal any conditional variables
* to wake up the event handling thread.
*/
public final class SleepingWaitStrategy implements WaitStrategy
{
private static final int SPIN_THRESHOLD = 100;
private static final int DEFAULT_RETRIES = 200;
private static final long DEFAULT_SLEEP = 100;
private final int retries;
private final long sleepTimeNs;
/**
* Provides a sleeping wait strategy with the default retry and sleep settings
*/
public SleepingWaitStrategy()
{
this(DEFAULT_RETRIES, DEFAULT_SLEEP);
}
/**
* @param retries How many times the strategy should retry before sleeping
*/
public SleepingWaitStrategy(final int retries)
{
this(retries, DEFAULT_SLEEP);
}
/**
* @param retries How many times the strategy should retry before sleeping
* @param sleepTimeNs How long the strategy should sleep, in nanoseconds
*/
public SleepingWaitStrategy(final int retries, final long sleepTimeNs)
{
this.retries = retries;
this.sleepTimeNs = sleepTimeNs;
}
@Override
public long waitFor(
final long sequence, final Sequence cursor, final Sequence dependentSequence, final SequenceBarrier barrier)
throws AlertException
{
long availableSequence;
int counter = retries;
while ((availableSequence = dependentSequence.get()) < sequence)
{
counter = applyWaitMethod(barrier, counter);
}
return availableSequence;
}
@Override
public void signalAllWhenBlocking()
{
}
private int applyWaitMethod(final SequenceBarrier barrier, final int counter)
throws AlertException
{
barrier.checkAlert();
if (counter > SPIN_THRESHOLD)
{
return counter - 1;
}
else if (counter > 0)
{
Thread.yield();
return counter - 1;
}
else
{
LockSupport.parkNanos(sleepTimeNs);
}
return counter;
}
}
| apache-2.0 |
krraghavan/mongodb-aggregate-query-support | mongodb-aggregate-query-support-reactive/src/test/java/com/github/krr/mongodb/aggregate/support/beans/TestValidDocumentAnnotationBean.java | 371 | package com.github.krr.mongodb.aggregate.support.beans;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* Created by anu
* 5/19/17.
*/
@Document(collection = "#{T(com.github.krr.mongodb.aggregate.support.fixtures.DocumentAnnotationFixture).RANDOM_COLLECTION}")
public class TestValidDocumentAnnotationBean extends AbstractTestAggregateBean{
}
| apache-2.0 |
brendandouglas/intellij | base/src/com/google/idea/blaze/base/run/testmap/TestTargetFilterImpl.java | 2867 | /*
* Copyright 2016 The Bazel Authors. All rights reserved.
*
* 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.google.idea.blaze.base.run.testmap;
import static com.google.idea.common.guava.GuavaHelper.toImmutableList;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.idea.blaze.base.dependencies.TargetInfo;
import com.google.idea.blaze.base.ideinfo.TargetIdeInfo;
import com.google.idea.blaze.base.ideinfo.TargetMap;
import com.google.idea.blaze.base.model.BlazeProjectData;
import com.google.idea.blaze.base.model.primitives.Kind;
import com.google.idea.blaze.base.run.TestTargetFinder;
import com.google.idea.blaze.base.sync.SyncCache;
import com.google.idea.blaze.base.sync.workspace.ArtifactLocationDecoder;
import com.intellij.openapi.project.Project;
import java.io.File;
import java.util.Collection;
import javax.annotation.Nullable;
/**
* Used to locate tests from source files for things like right-clicks.
*
* <p>It's essentially a map from source file -> reachable test rules.
*/
public class TestTargetFilterImpl implements TestTargetFinder {
private final Project project;
public TestTargetFilterImpl(Project project) {
this.project = project;
}
@Override
public Collection<TargetInfo> testTargetsForSourceFile(File sourceFile) {
FilteredTargetMap testMap =
SyncCache.getInstance(project)
.get(TestTargetFilterImpl.class, TestTargetFilterImpl::computeTestMap);
if (testMap == null) {
return ImmutableList.of();
}
return testMap
.targetsForSourceFile(sourceFile)
.stream()
.map(TargetIdeInfo::toTargetInfo)
.collect(toImmutableList());
}
private static FilteredTargetMap computeTestMap(Project project, BlazeProjectData projectData) {
return computeTestMap(project, projectData.artifactLocationDecoder, projectData.targetMap);
}
@VisibleForTesting
static FilteredTargetMap computeTestMap(
Project project, ArtifactLocationDecoder decoder, TargetMap targetMap) {
return new FilteredTargetMap(project, decoder, targetMap, TestTargetFilterImpl::isTestTarget);
}
private static boolean isTestTarget(@Nullable TargetIdeInfo target) {
return target != null && target.kind != null && Kind.isTestRule(target.kind.toString());
}
}
| apache-2.0 |
kayasoftware/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/PedanticPluginManagementOrderEnforcerTest.java | 3395 | /*
* Copyright (c) 2012 - 2015 by Stefan Ferstl <st.ferstl@gmail.com>
*
* 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.github.ferstl.maven.pomenforcers;
import org.apache.maven.model.Plugin;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* JUnit tests for {@link PedanticPluginManagementOrderEnforcer}.
*/
public class PedanticPluginManagementOrderEnforcerTest extends AbstractPedanticEnforcerTest<PedanticPluginManagementOrderEnforcer> {
@Override
PedanticPluginManagementOrderEnforcer createRule() {
return new PedanticPluginManagementOrderEnforcer();
}
@Test
@Override
public void getDescription() {
assertThat(this.testRule.getDescription(), equalTo(PedanticEnforcerRule.PLUGIN_MANAGEMENT_ORDER));
}
@Test
@Override
public void accept() {
PedanticEnforcerVisitor visitor = mock(PedanticEnforcerVisitor.class);
this.testRule.accept(visitor);
verify(visitor).visit(this.testRule);
}
@Test
public void defaultSettingsCorrect() {
addManagedPlugin("a.b.c", "a");
addManagedPlugin("a.b.c", "b");
executeRuleAndCheckReport(false);
}
@Test
public void defaultSettingsWrongGroupIdOrder() {
addManagedPlugin("d.e.f", "a");
addManagedPlugin("a.b.c", "a");
executeRuleAndCheckReport(true);
}
@Test
public void defaultSettingsWrongArtifactIdOrder() {
addManagedPlugin("a.b.c", "b");
addManagedPlugin("a.b.c", "a");
executeRuleAndCheckReport(true);
}
@Test
public void groupIdPriorities() {
this.testRule.setGroupIdPriorities("x.y.z,u.v.w");
addManagedPlugin("x.y.z", "a");
addManagedPlugin("u.v.w", "a");
addManagedPlugin("a.b.c", "a");
executeRuleAndCheckReport(false);
}
@Test
public void artifactIdPriorities() {
this.testRule.setArtifactIdPriorities("z,y");
addManagedPlugin("a.b.c", "z");
addManagedPlugin("a.b.c", "y");
addManagedPlugin("a.b.c", "a");
executeRuleAndCheckReport(false);
}
@Test
public void orderBy() {
this.testRule.setOrderBy("artifactId,groupId");
addManagedPlugin("x.y.z", "a");
addManagedPlugin("a.b.c", "b");
executeRuleAndCheckReport(false);
}
private void addManagedPlugin(String groupId, String artifactId) {
String defaultVersion = "1.0";
PluginModel pluginModel = new PluginModel(groupId, artifactId, defaultVersion);
Plugin mavenPlugin = new Plugin();
mavenPlugin.setGroupId(groupId);
mavenPlugin.setArtifactId(artifactId);
mavenPlugin.setVersion(defaultVersion);
this.projectModel.getManagedPlugins().add(pluginModel);
this.mockMavenProject.getPluginManagement().getPlugins().add(mavenPlugin);
}
}
| apache-2.0 |
sschwebach/Enlights | app/src/main/java/edu/wisc/enlight/enlights/LightActivity.java | 17243 | package edu.wisc.enlight.enlights;
import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.larswerkman.holocolorpicker.ColorPicker;
import com.larswerkman.holocolorpicker.OpacityBar;
import com.larswerkman.holocolorpicker.SVBar;
import com.larswerkman.holocolorpicker.SaturationBar;
import com.larswerkman.holocolorpicker.ValueBar;
import java.util.Timer;
import java.util.TimerTask;
public class LightActivity extends Activity {
private final static String TAG = LightActivity.class.getSimpleName();
private BluetoothGattCharacteristic characteristicTx = null;
private RBLService mBluetoothLeService;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothDevice mDevice = null;
private String mDeviceAddress;
private boolean flag = true;
private boolean connState = false;
private boolean scanFlag = false;
private byte[] data = new byte[3];
private static final int REQUEST_ENABLE_BT = 1;
private static final long SCAN_PERIOD = 2000;
private final int REFRESHTIME = 200;
private LinearLayout buttonLayout;
private LayoutInflater inflater;
private Button connectButton;
private Timer sendTimer;
private ProgressBar connectProgress;
private ColorPicker picker;
private SVBar svBar;
private OpacityBar opacityBar;
private SaturationBar saturationBar;
private ValueBar valueBar;
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName,
IBinder service) {
mBluetoothLeService = ((RBLService.LocalBinder) service)
.getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_light);
this.setTitle("Control the Lights!");
connectProgress = (ProgressBar) findViewById(R.id.progress_connect);
buttonLayout = (LinearLayout) findViewById(R.id.layout_buttons);
inflater = (LayoutInflater.from(this));
picker = (ColorPicker) findViewById(R.id.picker);
svBar = (SVBar) findViewById(R.id.svbar);
picker.addSVBar(svBar);
picker.setShowOldCenterColor(false);
picker.setOnColorChangedListener(new ColorPicker.OnColorChangedListener() {
@Override
public void onColorChanged(int i) {
//change the color of all active buttons
for (int j = 0; j < 6; j++) {
View currView = buttonLayout.getChildAt(j);
ToggleButton button = (ToggleButton) currView.findViewById(R.id.button_toggle);
if (button.isChecked()) {
long color = (long) picker.getColor();
long redColor = color & 0x00FF0000;
redColor = 0x00FF0000 - redColor;
long blueColor = color & 0x000000FF;
blueColor = 0x000000FF - blueColor;
long greenColor = color & 0x0000FF00;
greenColor = 0x0000FF00 - greenColor;
button.setTextColor((int) (0xFF000000 + redColor + greenColor + blueColor));
button.setBackgroundColor(picker.getColor());
}
}
}
});
connectButton = (Button) findViewById(R.id.button_connect);
connectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (scanFlag == false) {
connectProgress.setVisibility(View.VISIBLE);
connectButton.setVisibility(View.INVISIBLE);
scanLeDevice();
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
if (mDevice != null) {
mDeviceAddress = mDevice.getAddress();
mBluetoothLeService.connect(mDeviceAddress);
scanFlag = true;
} else {
runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast
.makeText(
LightActivity.this,
"No device found!",
Toast.LENGTH_SHORT);
toast.setGravity(0, 0, Gravity.CENTER);
toast.show();
}
});
}
}
}, SCAN_PERIOD);
}
System.out.println(connState);
if (connState == false) {
mBluetoothLeService.connect(mDeviceAddress);
} else {
connectProgress.setVisibility(View.VISIBLE);
connectButton.setVisibility(View.INVISIBLE);
mBluetoothLeService.disconnect();
mBluetoothLeService.close();
setButtonDisable();
}
}
});
for (int i = 0; i < 6; i++) {
final View view = inflater.inflate(R.layout.button_light, null);
final ToggleButton button = (ToggleButton) view.findViewById(R.id.button_toggle);
final RelativeLayout borderView = (RelativeLayout) view.findViewById(R.id.button_background);
final int buttonNum = i + 1;
view.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f));
button.setBackgroundColor(picker.getColor());
button.setChecked(true);
button.setText("" + (i + 1));
button.setTextColor(0xFF000000);
button.setBackgroundColor(picker.getColor());
borderView.setBackgroundColor(0xFF000000);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (button.isChecked()) {
button.setText("" + (buttonNum));
long color = (long) picker.getColor();
long redColor = color & 0x00FF0000;
redColor = 0x00FF0000 - redColor;
long blueColor = color & 0x000000FF;
blueColor = 0x000000FF - blueColor;
long greenColor = color & 0x0000FF00;
greenColor = 0x0000FF00 - greenColor;
button.setTextColor((int) (0xFF000000 + redColor + greenColor + blueColor));
button.setBackgroundColor(picker.getColor());
borderView.setBackgroundColor(0xFF000000);
} else {
button.setText("" + (buttonNum));
borderView.setBackgroundColor(0x00000000);
}
}
});
buttonLayout.addView(view);
}
final BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Ble not supported", Toast.LENGTH_SHORT)
.show();
finish();
return;
}
Intent gattServiceIntent = new Intent(this,
RBLService.class);
if (!bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE))
Log.e("Connection", "Binding service failed!");
}
private void TimerMethod(){
this.runOnUiThread(new Runnable() {
@Override
public void run() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm.isScreenOn()){
if (connState){
String sendString = "";
for (int i = 0; i < 6; i++) {
ToggleButton currButton = (ToggleButton) buttonLayout.getChildAt(i).findViewById(R.id.button_toggle);
long color = ((ColorDrawable) currButton.getBackground()).getColor();
long redColor = color & 0x00FF0000;
redColor = redColor / 0x00010000;
long blueColor = color & 0x000000FF;
long greenColor = color & 0x0000FF00;
greenColor = greenColor / 0x00000100;
if (redColor > 255){
redColor = 255;
}
if (greenColor > 255){
greenColor = 255;
}
if (blueColor > 255){
blueColor = 255;
}
//Log.e("Color", "color is " + redColor + " " + greenColor + " " + blueColor);
sendString = (i + 1) + "|" + redColor + "|" + greenColor + "|" + blueColor + "^";
byte[] buf = sendString.getBytes();
if (characteristicTx != null) {
characteristicTx.setValue(buf);
mBluetoothLeService.writeCharacteristic(characteristicTx);
}
}
}
}
}
});
}
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (RBLService.ACTION_GATT_DISCONNECTED.equals(action)) {
Toast.makeText(getApplicationContext(), "Disconnected",
Toast.LENGTH_SHORT).show();
setButtonDisable();
} else if (RBLService.ACTION_GATT_SERVICES_DISCOVERED
.equals(action)) {
Toast.makeText(getApplicationContext(), "Connected",
Toast.LENGTH_SHORT).show();
connectButton.setVisibility(View.VISIBLE);
connectProgress.setVisibility(View.INVISIBLE);
getGattService(mBluetoothLeService.getSupportedGattService());
} else if (RBLService.ACTION_DATA_AVAILABLE.equals(action)) {
data = intent.getByteArrayExtra(RBLService.EXTRA_DATA);
//readAnalogInValue(data);
} else if (RBLService.ACTION_GATT_RSSI.equals(action)) {
//displayData(intent.getStringExtra(RBLService.EXTRA_DATA));
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_light, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
this.sendTimer = new Timer();
this.sendTimer.schedule(new TimerTask(){
@Override
public void run(){
TimerMethod();
}
}, 0, REFRESHTIME);
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
}
private void getGattService(BluetoothGattService gattService) {
if (gattService == null)
return;
setButtonEnable();
characteristicTx = gattService
.getCharacteristic(RBLService.UUID_BLE_SHIELD_TX);
BluetoothGattCharacteristic characteristicRx = gattService
.getCharacteristic(RBLService.UUID_BLE_SHIELD_RX);
mBluetoothLeService.setCharacteristicNotification(characteristicRx,
true);
mBluetoothLeService.readCharacteristic(characteristicRx);
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(RBLService.ACTION_GATT_CONNECTED);
intentFilter.addAction(RBLService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(RBLService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(RBLService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(RBLService.ACTION_GATT_RSSI);
return intentFilter;
}
private void scanLeDevice() {
new Thread() {
@Override
public void run() {
mBluetoothAdapter.startLeScan(mLeScanCallback);
try {
Thread.sleep(SCAN_PERIOD);
} catch (InterruptedException e) {
e.printStackTrace();
}
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}.start();
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi,
byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (device != null) {
mDevice = device;
}
}
});
}
};
@Override
protected void onStop() {
super.onStop();
flag = false;
unregisterReceiver(mGattUpdateReceiver);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mServiceConnection != null)
try {
unbindService(mServiceConnection);
}catch(IllegalArgumentException e){
Log.e(TAG, "Receiver never registered");
}
}
@Override
protected void onPause(){
super.onPause();
this.sendTimer.cancel();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT
&& resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
private void setButtonEnable() {
flag = true;
connState = true;
connectButton.setText("Disconnect");
}
private void setButtonDisable() {
flag = false;
connState = false;
connectButton.setVisibility(View.VISIBLE);
connectProgress.setVisibility(View.INVISIBLE);
connectButton.setText("Connect");
}
}
| apache-2.0 |
freeVM/freeVM | enhanced/archive/classlib/modules/crypto2/test/ar/org/fitc/test/crypto/cipher/TestCipherAndCertificateAll.java | 2110 | package ar.org.fitc.test.crypto.cipher;
import java.lang.reflect.Method;
import java.security.InvalidKeyException;
import java.security.cert.Certificate;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import ar.org.fitc.test.util.IteratorCertificate;
public class TestCipherAndCertificateAll extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(TestCipherAndCertificateAll.suite());
}
public static Test suite () {
TestSuite test = new TestSuite();
IteratorCertificate cg = new IteratorCertificate();
while(cg.hasNext()) {
Class c = TestCipherAndCertificate.class;
Method[] ms = c.getMethods();
Certificate cert = cg.next();
for (int i=0; i < ms.length; i++) {
String name = ms[i].getName();
if (name.startsWith("test")) {
if (name.endsWith("1") || name.endsWith("6")) {
if (cg.isCriticalkeyusage() && !cg.isKeyEnciphermentOn()) {
//|| ((cg.uses & KeyUsage.cRLSign) == KeyUsage.cRLSign))) {
test.addTest(new TestCipherAndCertificate(name, cert, cg.keyUses2String(), InvalidKeyException.class));
continue;
}
} else if(name.endsWith("4") || name.endsWith("9")) {
if (cg.isCriticalkeyusage() && !cg.isDataEnciphermentOn()) {
//|| ((cg.uses & KeyUsage.cRLSign) == KeyUsage.cRLSign))) {
test.addTest(new TestCipherAndCertificate(name, cert, cg.keyUses2String(), InvalidKeyException.class));
continue;
}
}
test.addTest(new TestCipherAndCertificate(name, cert, cg.keyUses2String()));
}
}
}
return test;
}
}
| apache-2.0 |
Phoenix616/PermissionsEx | permissionsex-core/src/test/java/ninja/leaping/permissionsex/backend/file/SchemaMigrationsTest.java | 4599 | /**
* PermissionsEx
* Copyright (C) zml and PermissionsEx contributors
*
* 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 ninja.leaping.permissionsex.backend.file;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.gson.GsonConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import ninja.leaping.configurate.yaml.YAMLConfigurationLoader;
import ninja.leaping.permissionsex.logging.TranslatableLogger;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.DumperOptions;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.*;
public class SchemaMigrationsTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void testThreeToFour() throws IOException {
final File testFile = tempFolder.newFile();
ConfigurationLoader<ConfigurationNode> jsonLoader = GsonConfigurationLoader.builder()
.setSource(Resources.asCharSource(getClass().getResource("test3to4.pre.json"), StandardCharsets.UTF_8))
.setSink(Files.asCharSink(testFile, StandardCharsets.UTF_8))
.build();
ConfigurationNode node = jsonLoader.load();
SchemaMigrations.threeToFour().apply(node);
jsonLoader.save(node);
assertEquals(Resources.toString(getClass().getResource("test3to4.post.json"), StandardCharsets.UTF_8), Files.toString(testFile, StandardCharsets.UTF_8));
}
@Test
public void testTwoToThree() throws IOException {
final File testFile = tempFolder.newFile();
ConfigurationLoader<ConfigurationNode> jsonLoader = GsonConfigurationLoader.builder()
.setSource(Resources.asCharSource(getClass().getResource("test2to3.pre.json"), StandardCharsets.UTF_8))
.setSink(Files.asCharSink(testFile, StandardCharsets.UTF_8))
.build();
ConfigurationNode node = jsonLoader.load();
SchemaMigrations.twoTo3().apply(node);
jsonLoader.save(node);
assertEquals(Resources.toString(getClass().getResource("test2to3.post.json"), StandardCharsets.UTF_8), Files.toString(testFile, StandardCharsets.UTF_8));
}
@Test
public void testOneToTwo() throws IOException {
final File testFile = tempFolder.newFile();
ConfigurationLoader<ConfigurationNode> yamlLoader = YAMLConfigurationLoader.builder()
.setSource(Resources.asCharSource(getClass().getResource("test1to2.pre.yml"), StandardCharsets.UTF_8))
.build();
ConfigurationLoader<ConfigurationNode> jsonSaver = GsonConfigurationLoader.builder()
.setFile(testFile)
.build();
ConfigurationNode node = yamlLoader.load();
SchemaMigrations.oneTo2(TranslatableLogger.forLogger(LoggerFactory.getLogger(getClass()))).apply(node);
jsonSaver.save(node);
assertEquals(Resources.toString(getClass().getResource("test1to2.post.json"), StandardCharsets.UTF_8), Files.toString(testFile, StandardCharsets.UTF_8));
}
@Test
public void testInitialToOne() throws IOException {
final File testFile = tempFolder.newFile();
ConfigurationLoader<ConfigurationNode> yamlLoader = YAMLConfigurationLoader.builder()
.setSource(Resources.asCharSource(getClass().getResource("test0to1.pre.yml"), StandardCharsets.UTF_8))
.setSink(Files.asCharSink(testFile, StandardCharsets.UTF_8))
.setFlowStyle(DumperOptions.FlowStyle.BLOCK)
.build();
ConfigurationNode node = yamlLoader.load();
SchemaMigrations.initialTo1().apply(node);
yamlLoader.save(node);
assertEquals(Resources.toString(getClass().getResource("test0to1.post.yml"), StandardCharsets.UTF_8), Files.toString(testFile, StandardCharsets.UTF_8));
}
}
| apache-2.0 |
DOREMUS-ANR/knowledge-base | linked-data/Terminology-and-conceptual-alignments-master/Scripts/Alignement_Script/attributes.java | 530 | public class Concert {
private String uri = "" ;
private String name = "" ;
private String date = "" ;
public Concert(String u, String n, String d)
{
this.uri = u ;
this.name = n ;
this.date = d ;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
| apache-2.0 |
DSInnovators/authorization_service | src/main/java/com/dsi/authorization/service/impl/UserServiceImpl.java | 15768 | package com.dsi.authorization.service.impl;
import com.dsi.authorization.dao.RoleDao;
import com.dsi.authorization.dao.UserDao;
import com.dsi.authorization.dao.UserRoleDao;
import com.dsi.authorization.dao.impl.RoleDaoImpl;
import com.dsi.authorization.dao.impl.UserDaoImpl;
import com.dsi.authorization.dao.impl.UserRoleDaoImpl;
import com.dsi.authorization.dto.UserContextDto;
import com.dsi.authorization.dto.UserDto;
import com.dsi.authorization.exception.CustomException;
import com.dsi.authorization.exception.ErrorContext;
import com.dsi.authorization.exception.ErrorMessage;
import com.dsi.authorization.model.*;
import com.dsi.authorization.model.System;
import com.dsi.authorization.service.UserService;
import com.dsi.authorization.util.Constants;
import com.dsi.authorization.util.Utility;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.hibernate.Session;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sabbir on 6/24/16.
*/
public class UserServiceImpl extends CommonService implements UserService {
private static final Logger logger = Logger.getLogger(UserServiceImpl.class);
private static final UserDao userDao = new UserDaoImpl();
private static final RoleDao roleDao = new RoleDaoImpl();
private static final UserRoleDao userRoleDao = new UserRoleDaoImpl();
@Override
public UserRole saveUser(User user) throws CustomException {
Session session = getSession();
userDao.setSession(session);
roleDao.setSession(session);
userRoleDao.setSession(session);
User currentUser = userDao.getUserByID(user.getCreateBy());
user.setTenantId(currentUser.getTenantId());
if(user.getTenantId() == null){
close(session);
ErrorContext errorContext = new ErrorContext(null, "User", "TenantID not defined.");
ErrorMessage errorMessage = new ErrorMessage(Constants.AUTHORIZATION_SERVICE_0001,
Constants.AUTHORIZATION_SERVICE_0001_DESCRIPTION, errorContext);
throw new CustomException(errorMessage);
}
if(userDao.getUserByEmail(user.getEmail()) != null){
close(session);
ErrorContext errorContext = new ErrorContext(null, "User", "User already exist.");
ErrorMessage errorMessage = new ErrorMessage(Constants.AUTHORIZATION_SERVICE_0002,
Constants.AUTHORIZATION_SERVICE_0002_DESCRIPTION, errorContext);
throw new CustomException(errorMessage);
}
user.setCreatedDate(Utility.today());
user.setModifiedDate(Utility.today());
userDao.saveUser(user);
logger.info("User create successfully.");
UserRole userRole = new UserRole();
userRole.setUser(user);
userRole.setRole(roleDao.getRoleByID(user.getRoleId()));
userRole.setSystem(userDao.getSystemByUserID(user.getCreateBy()));
userRole.setCreateBy(user.getCreateBy());
userRole.setModifiedBy(user.getModifiedBy());
userRole.setCreatedDate(Utility.today());
userRole.setModifiedDate(Utility.today());
userRole.setActive(true);
userRole.setVersion(1);
userRoleDao.saveUserRole(userRole);
logger.info("User role create successfully.");
close(session);
return userRole;
}
@Override
public void updateUser(User user) throws CustomException {
Session session = getSession();
roleDao.setSession(session);
userDao.setSession(session);
userRoleDao.setSession(session);
User existUser = userDao.getUserByID(user.getUserId());
if(existUser != null) {
existUser.setFirstName(user.getFirstName());
existUser.setLastName(user.getLastName());
existUser.setGender(user.getGender());
existUser.setPhone(user.getPhone());
existUser.setModifiedBy(user.getModifiedBy());
existUser.setModifiedDate(Utility.today());
userDao.updateUser(existUser);
logger.info("User update success.");
if(user.getRoleId() != null) {
UserRole existRole = userRoleDao.getUserRoleByUserID(user.getUserId());
if (existRole != null) {
existRole.setModifiedBy(user.getModifiedBy());
existRole.setModifiedDate(Utility.today());
existRole.setRole(roleDao.getRoleByID(user.getRoleId()));
userRoleDao.updateUserRole(existRole);
logger.info("User role update success.");
}
}
}
close(session);
}
@Override
public void deleteUser(String userID) throws CustomException {
Session session = getSession();
userDao.setSession(session);
User user = userDao.getUserByID(userID);
if(user != null) {
userDao.deleteUserContext(user.getUserId());
userDao.deleteUserSession(user.getUserId());
userDao.deleteUserRole(user.getUserId());
userDao.deleteUser(user);
}
close(session);
}
@Override
public UserDto getUserByID(String userID) throws CustomException {
Session session = getSession();
userRoleDao.setSession(session);
UserRole userRole = userRoleDao.getUserRoleByUserID(userID);
if (userRole == null) {
close(session);
ErrorContext errorContext = new ErrorContext(userID, "UserRole",
"UserRole not found by userID: " + userID);
ErrorMessage errorMessage = new ErrorMessage(Constants.AUTHORIZATION_SERVICE_0005,
Constants.AUTHORIZATION_SERVICE_0005_DESCRIPTION, errorContext);
throw new CustomException(errorMessage);
}
UserDto user = new UserDto();
user.setUserId(userID);
user.setFirstName(userRole.getUser().getFirstName());
user.setLastName(userRole.getUser().getLastName());
user.setRoleId(userRole.getRole().getRoleId());
user.setRoleName(userRole.getRole().getName());
user.setMessage("User role info.");
close(session);
return user;
}
@Override
public List<UserDto> getAllUserByRole(String roleType) throws CustomException {
Session session = getSession();
userRoleDao.setSession(session);
List<UserRole> userRoleList = userRoleDao.getAllUserByRole(roleType);
if(userRoleList == null){
close(session);
ErrorContext errorContext = new ErrorContext(null, "UserRole", "User role list not found by roleType: " + roleType);
ErrorMessage errorMessage = new ErrorMessage(Constants.AUTHORIZATION_SERVICE_0005,
Constants.AUTHORIZATION_SERVICE_0005_DESCRIPTION, errorContext);
throw new CustomException(errorMessage);
}
logger.info("User role list size: " + userRoleList.size());
List<UserDto> userDtoList = new ArrayList<>();
for(UserRole userRole : userRoleList){
UserDto userDto = new UserDto();
userDto.setUserId(userRole.getUser().getUserId());
userDto.setFirstName(userRole.getUser().getFirstName());
userDto.setLastName(userRole.getUser().getLastName());
userDtoList.add(userDto);
}
close(session);
return userDtoList;
}
@Override
public String getUsersByRoleType() throws CustomException {
Session session = getSession();
userRoleDao.setSession(session);
JSONObject roleObj = new JSONObject();
JSONArray emailArray;
try {
List<UserRole> userRoleList = userRoleDao.getAllUserByRoleType(RoleName.HR.getValue());
if (userRoleList == null) {
close(session);
ErrorContext errorContext = new ErrorContext(null, null,
"User role list not found by HR RoleType");
ErrorMessage errorMessage = new ErrorMessage(Constants.AUTHORIZATION_SERVICE_0005,
Constants.AUTHORIZATION_SERVICE_0005_DESCRIPTION, errorContext);
throw new CustomException(errorMessage);
}
logger.info("HR role list size: " + userRoleList.size());
emailArray = new JSONArray();
for (UserRole userRole : userRoleList) {
emailArray.put(userRole.getUser().getEmail());
}
roleObj.put(RoleName.HR.getValue(), emailArray);
userRoleList = userRoleDao.getAllUserByRoleType(RoleName.MANAGER.getValue());
if (userRoleList == null) {
close(session);
ErrorContext errorContext = new ErrorContext(null, null,
"User role list not found by Manager RoleType");
ErrorMessage errorMessage = new ErrorMessage(Constants.AUTHORIZATION_SERVICE_0005,
Constants.AUTHORIZATION_SERVICE_0005_DESCRIPTION, errorContext);
throw new CustomException(errorMessage);
}
logger.info("Manager role list size: " + userRoleList.size());
emailArray = new JSONArray();
for(UserRole userRole : userRoleList){
emailArray.put(userRole.getUser().getEmail());
}
roleObj.put(RoleName.MANAGER.getValue(), emailArray);
close(session);
return roleObj.toString();
} catch (JSONException je){
close(session);
ErrorContext errorContext = new ErrorContext(null, null, je.getMessage());
ErrorMessage errorMessage = new ErrorMessage(Constants.AUTHORIZATION_SERVICE_0009,
Constants.AUTHORIZATION_SERVICE_0009_DESCRIPTION, errorContext);
throw new CustomException(errorMessage);
}
}
@Override
public void saveOrUpdateUserContext(List<UserContextDto> userContextDtoList) throws CustomException {
if(Utility.isNullOrEmpty(userContextDtoList)){
ErrorContext errorContext = new ErrorContext(null, "UserContext", "User Context list is empty.");
ErrorMessage errorMessage = new ErrorMessage(Constants.AUTHORIZATION_SERVICE_0001,
Constants.AUTHORIZATION_SERVICE_0001_DESCRIPTION, errorContext);
throw new CustomException(errorMessage);
}
Session session = getSession();
userDao.setSession(session);
UserContext userContext;
try {
for (UserContextDto userContextDto : userContextDtoList) {
userContext = new UserContext();
User user = userDao.getUserByID(userContextDto.getUserId());
UserContext existContext = userDao.getUserContextByUserId(userContextDto.getUserId());
if (userContextDto.getActivity() == 1) {
if (existContext == null) {
userContext.setContext(getContextObjForEmployee(userContextDto));
userContext.setUser(user);
userContext.setVersion(1);
userDao.saveUserContext(userContext);
logger.info("User context save success.");
} else {
logger.info("User context already exist.");
if(userContextDto.getTeamId() != null) {
existContext.setContext(getContextObjFromExist(userContextDto.getTeamId(),
existContext.getContext()));
userDao.updateUserContext(existContext);
logger.info("User context update success.");
}
}
} else if (userContextDto.getActivity() == 2) {
if(existContext != null){
String context = getContextObjAfterRemove(existContext.getContext(),
userContextDto.getTeamId());
existContext.setContext(context);
userDao.updateUserContext(existContext);
logger.info("Update user context.");
}
}
}
close(session);
} catch (JSONException je){
close(session);
ErrorContext errorContext = new ErrorContext(null, null, je.getMessage());
ErrorMessage errorMessage = new ErrorMessage(Constants.AUTHORIZATION_SERVICE_0009,
Constants.AUTHORIZATION_SERVICE_0009_DESCRIPTION, errorContext);
throw new CustomException(errorMessage);
}
}
@Override
public UserContext getUserContextByUserId(String userId) {
logger.info("Read user context by user id: " + userId);
UserContext userContext;
Session session = getSession();
userDao.setSession(session);
userRoleDao.setSession(session);
UserRole userRole = userRoleDao.getUserRoleByUserID(userId);
if(userRole.getRole().getName().equals(RoleName.MEMBER.getValue())
|| userRole.getRole().getName().equals(RoleName.LEAD.getValue())){
userContext = userDao.getUserContextByUserId(userId);
if(userContext != null){
close(session);
return userContext;
}
}
close(session);
return null;
}
@Override
public System getSystemByUserID(String userID) throws CustomException {
Session session = getSession();
userDao.setSession(session);
System system = userDao.getSystemByUserID(userID);
if (system == null) {
close(session);
ErrorContext errorContext = new ErrorContext(userID, "System", "System not found by userID: " + userID);
ErrorMessage errorMessage = new ErrorMessage(Constants.AUTHORIZATION_SERVICE_0005,
Constants.AUTHORIZATION_SERVICE_0005_DESCRIPTION, errorContext);
throw new CustomException(errorMessage);
}
close(session);
return system;
}
private String getContextObjForEmployee(UserContextDto contextDto) throws JSONException {
JSONArray contextArray = new JSONArray();
JSONObject contextObj = new JSONObject();
if(contextDto.getEmployeeId() != null){
contextArray.put(contextDto.getEmployeeId());
contextObj.put("employeeId", contextArray);
}
return contextObj.toString();
}
private String getContextObjFromExist(String teamId, String context) throws JSONException {
JSONObject existContextObj = new JSONObject(context);
if(existContextObj.has("teamId")) {
JSONArray existContextArray = existContextObj.getJSONArray("teamId");
existContextArray.put(teamId);
} else {
JSONArray contextArray = new JSONArray();
contextArray.put(teamId);
existContextObj.put("teamId", contextArray);
}
return existContextObj.toString();
}
private String getContextObjAfterRemove(String context, String teamId) throws JSONException {
JSONObject existContextObj = new JSONObject(context);
JSONArray existContextArray = existContextObj.getJSONArray("teamId");
existContextArray.remove(teamId);
if(existContextArray.length() <= 0){
existContextObj.remove("teamId");
}
return existContextObj.toString();
}
}
| apache-2.0 |
cwpenhale/red5-mobileconsole | red5_server/src/main/java/org/red5/server/net/rtmp/RTMPHandler.java | 21013 | /*
* RED5 Open Source Flash Server - http://code.google.com/p/red5/
*
* Copyright 2006-2012 by respective authors (see below). All rights reserved.
*
* 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 org.red5.server.net.rtmp;
import java.util.HashMap;
import java.util.Map;
import org.red5.logging.Red5LoggerFactory;
import org.red5.server.api.IConnection.Encoding;
import org.red5.server.api.IContext;
import org.red5.server.api.IServer;
import org.red5.server.api.Red5;
import org.red5.server.api.scope.IBroadcastScope;
import org.red5.server.api.scope.IGlobalScope;
import org.red5.server.api.scope.IScope;
import org.red5.server.api.scope.IScopeHandler;
import org.red5.server.api.service.IPendingServiceCall;
import org.red5.server.api.service.IServiceCall;
import org.red5.server.api.so.ISharedObject;
import org.red5.server.api.so.ISharedObjectSecurity;
import org.red5.server.api.so.ISharedObjectSecurityService;
import org.red5.server.api.so.ISharedObjectService;
import org.red5.server.api.stream.IClientBroadcastStream;
import org.red5.server.api.stream.IClientStream;
import org.red5.server.api.stream.IStreamService;
import org.red5.server.exception.ClientRejectedException;
import org.red5.server.exception.ScopeNotFoundException;
import org.red5.server.exception.ScopeShuttingDownException;
import org.red5.server.messaging.IConsumer;
import org.red5.server.messaging.OOBControlMessage;
import org.red5.server.net.rtmp.codec.RTMP;
import org.red5.server.net.rtmp.event.ChunkSize;
import org.red5.server.net.rtmp.event.Invoke;
import org.red5.server.net.rtmp.event.Notify;
import org.red5.server.net.rtmp.event.Ping;
import org.red5.server.net.rtmp.event.SetBuffer;
import org.red5.server.net.rtmp.message.Header;
import org.red5.server.net.rtmp.message.StreamAction;
import org.red5.server.net.rtmp.status.Status;
import org.red5.server.net.rtmp.status.StatusObject;
import org.red5.server.net.rtmp.status.StatusObjectService;
import org.red5.server.service.Call;
import org.red5.server.so.ISharedObjectEvent;
import org.red5.server.so.SharedObjectEvent;
import org.red5.server.so.SharedObjectMessage;
import org.red5.server.so.SharedObjectService;
import org.red5.server.stream.StreamService;
import org.red5.server.util.ScopeUtils;
import org.slf4j.Logger;
/**
* RTMP events handler.
*/
public class RTMPHandler extends BaseRTMPHandler {
protected static Logger log = Red5LoggerFactory.getLogger(RTMPHandler.class);
/**
* Status object service.
*/
protected StatusObjectService statusObjectService;
/**
* Red5 server instance.
*/
protected IServer server;
/**
* Whether or not global scope connections are allowed.
*/
private boolean globalScopeConnectionAllowed = false;
/**
* Setter for server object.
*
* @param server Red5 server instance
*/
public void setServer(IServer server) {
this.server = server;
}
/**
* Setter for status object service.
*
* @param statusObjectService Status object service.
*/
public void setStatusObjectService(StatusObjectService statusObjectService) {
this.statusObjectService = statusObjectService;
}
public boolean isGlobalScopeConnectionAllowed() {
return globalScopeConnectionAllowed;
}
public void setGlobalScopeConnectionAllowed(boolean globalScopeConnectionAllowed) {
this.globalScopeConnectionAllowed = globalScopeConnectionAllowed;
}
/** {@inheritDoc} */
@Override
protected void onChunkSize(RTMPConnection conn, Channel channel, Header source, ChunkSize chunkSize) {
for (IClientStream stream : conn.getStreams()) {
if (stream instanceof IClientBroadcastStream) {
IClientBroadcastStream bs = (IClientBroadcastStream) stream;
IBroadcastScope scope = bs.getScope().getBroadcastScope(bs.getPublishedName());
if (scope == null) {
continue;
}
OOBControlMessage setChunkSize = new OOBControlMessage();
setChunkSize.setTarget("ClientBroadcastStream");
setChunkSize.setServiceName("chunkSize");
if (setChunkSize.getServiceParamMap() == null) {
setChunkSize.setServiceParamMap(new HashMap<String, Object>());
}
setChunkSize.getServiceParamMap().put("chunkSize", chunkSize.getSize());
scope.sendOOBControlMessage((IConsumer) null, setChunkSize);
log.debug("Sending chunksize {} to {}", chunkSize, bs.getProvider());
}
}
}
/**
* Remoting call invocation handler.
*
* @param conn RTMP connection
* @param call Service call
*/
protected void invokeCall(RTMPConnection conn, IServiceCall call) {
final IScope scope = conn.getScope();
if (scope.hasHandler()) {
final IScopeHandler handler = scope.getHandler();
log.debug("Scope: {} handler: {}", scope, handler);
if (!handler.serviceCall(conn, call)) {
// XXX: What to do here? Return an error?
return;
}
}
final IContext context = scope.getContext();
log.debug("Context: {}", context);
context.getServiceInvoker().invoke(call, scope);
}
/**
* Remoting call invocation handler.
*
* @param conn
* RTMP connection
* @param call
* Service call
* @param service
* Server-side service object
* @return <code>true</code> if the call was performed, otherwise
* <code>false</code>
*/
private boolean invokeCall(RTMPConnection conn, IServiceCall call, Object service) {
final IScope scope = conn.getScope();
final IContext context = scope.getContext();
log.debug("Scope: {} Context: {}", scope, context);
log.debug("Service: {}", service);
return context.getServiceInvoker().invoke(call, service);
}
/** {@inheritDoc} */
@SuppressWarnings({ "unchecked" })
@Override
protected void onInvoke(RTMPConnection conn, Channel channel, Header source, Notify invoke, RTMP rtmp) {
log.debug("Invoke: {}", invoke);
// Get call
final IServiceCall call = invoke.getCall();
//log.debug("Call: {}", call);
// method name
final String action = call.getServiceMethodName();
// If it's a callback for server remote call then pass it over to callbacks handler and return
if ("_result".equals(action) || "_error".equals(action)) {
handlePendingCallResult(conn, invoke);
return;
}
boolean disconnectOnReturn = false;
// If this is not a service call then handle connection...
if (call.getServiceName() == null) {
log.debug("call: {}", call);
if (!conn.isConnected() && StreamAction.CONNECT.equals(action)) {
// Handle connection
log.debug("connect");
// Get parameters passed from client to
// NetConnection#connection
final Map<String, Object> params = invoke.getConnectionParams();
// Get hostname
String host = getHostname((String) params.get("tcUrl"));
// App name as path, but without query string if there is
// one
String path = (String) params.get("app");
if (path.indexOf("?") != -1) {
int idx = path.indexOf("?");
params.put("queryString", path.substring(idx));
path = path.substring(0, idx);
}
params.put("path", path);
final String sessionId = null;
conn.setup(host, path, sessionId, params);
try {
// Lookup server scope when connected
// Use host and application name
IGlobalScope global = server.lookupGlobal(host, path);
log.trace("Global lookup result: {}", global);
if (global != null) {
final IContext context = global.getContext();
IScope scope = null;
try {
scope = context.resolveScope(global, path);
//if global scope connection is not allowed, reject
if (scope.getDepth() < 1 && !globalScopeConnectionAllowed) {
call.setStatus(Call.STATUS_ACCESS_DENIED);
if (call instanceof IPendingServiceCall) {
IPendingServiceCall pc = (IPendingServiceCall) call;
StatusObject status = getStatus(NC_CONNECT_REJECTED);
status.setDescription("Global scope connection disallowed on this server.");
pc.setResult(status);
}
disconnectOnReturn = true;
}
} catch (ScopeNotFoundException err) {
call.setStatus(Call.STATUS_SERVICE_NOT_FOUND);
if (call instanceof IPendingServiceCall) {
StatusObject status = getStatus(NC_CONNECT_REJECTED);
status.setDescription(String.format("No scope '%s' on this server.", path));
((IPendingServiceCall) call).setResult(status);
}
log.info("Scope {} not found on {}", path, host);
disconnectOnReturn = true;
} catch (ScopeShuttingDownException err) {
call.setStatus(Call.STATUS_APP_SHUTTING_DOWN);
if (call instanceof IPendingServiceCall) {
StatusObject status = getStatus(NC_CONNECT_APPSHUTDOWN);
status.setDescription(String.format("Application at '%s' is currently shutting down.", path));
((IPendingServiceCall) call).setResult(status);
}
log.info("Application at {} currently shutting down on {}", path, host);
disconnectOnReturn = true;
}
if (scope != null) {
log.info("Connecting to: {}", scope);
boolean okayToConnect;
try {
log.debug("Conn {}, scope {}, call {}", new Object[] { conn, scope, call });
log.debug("Call args {}", call.getArguments());
if (call.getArguments() != null) {
okayToConnect = conn.connect(scope, call.getArguments());
} else {
okayToConnect = conn.connect(scope);
}
if (okayToConnect) {
log.debug("Connected - Client: {}", conn.getClient());
call.setStatus(Call.STATUS_SUCCESS_RESULT);
if (call instanceof IPendingServiceCall) {
IPendingServiceCall pc = (IPendingServiceCall) call;
//send fmsver and capabilities
StatusObject result = getStatus(NC_CONNECT_SUCCESS);
result.setAdditional("fmsVer", Red5.getFMSVersion());
result.setAdditional("capabilities", Integer.valueOf(31));
result.setAdditional("mode", Integer.valueOf(1));
result.setAdditional("data", Red5.getDataVersion());
pc.setResult(result);
}
// Measure initial roundtrip time after connecting
conn.ping(new Ping(Ping.STREAM_BEGIN, 0, -1));
conn.startRoundTripMeasurement();
} else {
log.debug("Connect failed");
call.setStatus(Call.STATUS_ACCESS_DENIED);
if (call instanceof IPendingServiceCall) {
IPendingServiceCall pc = (IPendingServiceCall) call;
pc.setResult(getStatus(NC_CONNECT_REJECTED));
}
disconnectOnReturn = true;
}
} catch (ClientRejectedException rejected) {
log.debug("Connect rejected");
call.setStatus(Call.STATUS_ACCESS_DENIED);
if (call instanceof IPendingServiceCall) {
IPendingServiceCall pc = (IPendingServiceCall) call;
StatusObject status = getStatus(NC_CONNECT_REJECTED);
Object reason = rejected.getReason();
if (reason != null) {
status.setApplication(reason);
//should we set description?
status.setDescription(reason.toString());
}
pc.setResult(status);
}
disconnectOnReturn = true;
}
}
} else {
call.setStatus(Call.STATUS_SERVICE_NOT_FOUND);
if (call instanceof IPendingServiceCall) {
StatusObject status = getStatus(NC_CONNECT_INVALID_APPLICATION);
status.setDescription(String.format("No scope '%s' on this server.", path));
((IPendingServiceCall) call).setResult(status);
}
log.info("No application scope found for {} on host {}", path, host);
disconnectOnReturn = true;
}
} catch (RuntimeException e) {
call.setStatus(Call.STATUS_GENERAL_EXCEPTION);
if (call instanceof IPendingServiceCall) {
IPendingServiceCall pc = (IPendingServiceCall) call;
pc.setResult(getStatus(NC_CONNECT_FAILED));
}
log.error("Error connecting {}", e);
disconnectOnReturn = true;
}
// Evaluate request for AMF3 encoding
if (Integer.valueOf(3).equals(params.get("objectEncoding"))) {
if (call instanceof IPendingServiceCall) {
Object pcResult = ((IPendingServiceCall) call).getResult();
Map<String, Object> result;
if (pcResult instanceof Map) {
result = (Map<String, Object>) pcResult;
result.put("objectEncoding", 3);
} else if (pcResult instanceof StatusObject) {
result = new HashMap<String, Object>();
StatusObject status = (StatusObject) pcResult;
result.put("code", status.getCode());
result.put("description", status.getDescription());
result.put("application", status.getApplication());
result.put("level", status.getLevel());
result.put("objectEncoding", 3);
((IPendingServiceCall) call).setResult(result);
}
}
rtmp.setEncoding(Encoding.AMF3);
}
} else {
//log.debug("Enum value of: {}", StreamAction.getEnum(action));
StreamAction streamAction = StreamAction.getEnum(action);
//if the "stream" action is not predefined a custom type will be returned
switch (streamAction) {
case DISCONNECT:
conn.close();
break;
case CREATE_STREAM:
case INIT_STREAM:
case CLOSE_STREAM:
case RELEASE_STREAM:
case DELETE_STREAM:
case PUBLISH:
case PLAY:
case PLAY2:
case SEEK:
case PAUSE:
case PAUSE_RAW:
case RECEIVE_VIDEO:
case RECEIVE_AUDIO:
IStreamService streamService = (IStreamService) ScopeUtils.getScopeService(conn.getScope(), IStreamService.class, StreamService.class);
Status status = null;
try {
log.debug("Invoking {} from {} with service: {}", new Object[] { call, conn, streamService });
if (!invokeCall(conn, call, streamService)) {
status = getStatus(NS_INVALID_ARGUMENT).asStatus();
status.setDescription(String.format("Failed to %s (stream id: %d)", action, source.getStreamId()));
}
} catch (Throwable err) {
log.error("Error while invoking {} on stream service. {}", action, err);
status = getStatus(NS_FAILED).asStatus();
status.setDescription(String.format("Error while invoking %s (stream id: %d)", action, source.getStreamId()));
status.setDetails(err.getMessage());
}
if (status != null) {
channel.sendStatus(status);
}
break;
default:
invokeCall(conn, call);
}
}
} else if (conn.isConnected()) {
// Service calls, must be connected.
invokeCall(conn, call);
} else {
// Warn user attempts to call service without being connected
log.warn("Not connected, closing connection");
conn.close();
}
if (invoke instanceof Invoke) {
if ((source.getStreamId() != 0) && (call.getStatus() == Call.STATUS_SUCCESS_VOID || call.getStatus() == Call.STATUS_SUCCESS_NULL)) {
// This fixes a bug in the FP on Intel Macs.
log.debug("Method does not have return value, do not reply");
return;
}
boolean sendResult = true;
if (call instanceof IPendingServiceCall) {
IPendingServiceCall psc = (IPendingServiceCall) call;
Object result = psc.getResult();
if (result instanceof DeferredResult) {
// Remember the deferred result to be sent later
DeferredResult dr = (DeferredResult) result;
dr.setServiceCall(psc);
dr.setChannel(channel);
dr.setInvokeId(invoke.getInvokeId());
conn.registerDeferredResult(dr);
sendResult = false;
}
}
if (sendResult) {
// The client expects a result for the method call.
Invoke reply = new Invoke();
reply.setCall(call);
reply.setInvokeId(invoke.getInvokeId());
channel.write(reply);
if (disconnectOnReturn) {
conn.close();
}
}
}
}
public StatusObject getStatus(String code) {
return statusObjectService.getStatusObject(code);
}
/** {@inheritDoc} */
@Override
protected void onPing(RTMPConnection conn, Channel channel, Header source, Ping ping) {
switch (ping.getEventType()) {
case Ping.CLIENT_BUFFER:
SetBuffer setBuffer = (SetBuffer) ping;
// get the stream id
int streamId = setBuffer.getStreamId();
// get requested buffer size in milliseconds
int buffer = setBuffer.getBufferLength();
log.debug("Client sent a buffer size: {} ms for stream id: {}", buffer, streamId);
IClientStream stream = null;
if (streamId != 0) {
// The client wants to set the buffer time
stream = conn.getStreamById(streamId);
if (stream != null) {
stream.setClientBufferDuration(buffer);
log.trace("Stream type: {}", stream.getClass().getName());
}
}
//catch-all to make sure buffer size is set
if (stream == null) {
// Remember buffer time until stream is created
conn.rememberStreamBufferDuration(streamId, buffer);
log.info("Remembering client buffer on stream: {}", buffer);
}
break;
case Ping.PONG_SERVER:
// This is the response to an IConnection.ping request
conn.pingReceived(ping);
break;
default:
log.warn("Unhandled ping: {}", ping);
}
}
/**
* Create and send SO message stating that a SO could not be created.
*
* @param conn
* @param name
* @param persistent
*/
private void sendSOCreationFailed(RTMPConnection conn, String name, boolean persistent) {
log.warn("sendSOCreationFailed - name: {} persistent: {} conn: {}", new Object[] { name, persistent, conn });
SharedObjectMessage msg = new SharedObjectMessage(name, 0, persistent);
msg.addEvent(new SharedObjectEvent(ISharedObjectEvent.Type.CLIENT_STATUS, "error", SO_CREATION_FAILED));
conn.getChannel(3).write(msg);
}
/** {@inheritDoc} */
@Override
protected void onSharedObject(RTMPConnection conn, Channel channel, Header source, SharedObjectMessage object) {
log.debug("onSharedObject: {}", object);
// so name
String name = object.getName();
// whether or not the incoming so is persistent
boolean persistent = object.isPersistent();
log.debug("Incoming shared object - name: {} persistence: {}", name, persistent);
final IScope scope = conn.getScope();
if (scope != null) {
ISharedObjectService sharedObjectService = (ISharedObjectService) ScopeUtils.getScopeService(scope, ISharedObjectService.class, SharedObjectService.class, false);
if (!sharedObjectService.hasSharedObject(scope, name)) {
log.debug("Shared object service doesnt have requested object, creation will be attempted");
ISharedObjectSecurityService security = (ISharedObjectSecurityService) ScopeUtils.getScopeService(scope, ISharedObjectSecurityService.class);
if (security != null) {
// Check handlers to see if creation is allowed
for (ISharedObjectSecurity handler : security.getSharedObjectSecurity()) {
if (!handler.isCreationAllowed(scope, name, persistent)) {
log.debug("Shared object create failed, creation is not allowed");
sendSOCreationFailed(conn, name, persistent);
return;
}
}
}
if (!sharedObjectService.createSharedObject(scope, name, persistent)) {
log.debug("Shared object create failed");
sendSOCreationFailed(conn, name, persistent);
return;
}
}
ISharedObject so = sharedObjectService.getSharedObject(scope, name);
so.dispatchEvent(object);
if (so.isPersistent() != persistent) {
log.warn("Shared object persistence mismatch - current: {} incoming: {}", so.isPersistent(), persistent);
/* Sending the following message seems to screw up follow-on handling of SO events
SharedObjectMessage msg = new SharedObjectMessage(name, 0, persistent);
msg.addEvent(new SharedObjectEvent(ISharedObjectEvent.Type.CLIENT_STATUS, "error", SO_PERSISTENCE_MISMATCH));
conn.getChannel(3).write(msg);
*/
}
} else {
// The scope already has been deleted
log.debug("Shared object scope was not found");
sendSOCreationFailed(conn, name, persistent);
return;
}
}
protected void onBWDone() {
log.debug("onBWDone");
}
}
| apache-2.0 |
ontopia/ontopia | ontopia-engine/src/main/java/net/ontopia/topicmaps/query/impl/rdbms/RulePredicate.java | 3023 | /*
* #!
* Ontopia Engine
* #-
* Copyright (C) 2001 - 2013 The Ontopia 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 net.ontopia.topicmaps.query.impl.rdbms;
import java.util.Iterator;
import java.util.List;
import net.ontopia.topicmaps.query.core.InvalidQueryException;
import net.ontopia.topicmaps.query.parser.AbstractClause;
import net.ontopia.topicmaps.query.parser.NotClause;
import net.ontopia.topicmaps.query.parser.OrClause;
import net.ontopia.topicmaps.query.parser.ParsedRule;
import net.ontopia.topicmaps.query.parser.PredicateClause;
/**
* INTERNAL: Implements rule predicates.
*/
public class RulePredicate
extends net.ontopia.topicmaps.query.impl.basic.RulePredicate
implements JDOPredicateIF {
public RulePredicate(ParsedRule rule) {
super(rule);
}
// --- JDOPredicateIF implementation
@Override
public boolean isRecursive() {
return true;
}
@Override
public void prescan(QueryBuilder builder, List arguments) {
// no-op
}
@Override
public boolean buildQuery(QueryBuilder builder, List expressions, List arguments)
throws InvalidQueryException {
// TODO: Rule predicates does not yet support JDO expressions.
return false;
}
// --- Misc.
public boolean isSelfRecursive() {
return isRecursive(rule.getClauses(), this);
}
protected boolean isRecursive(List clauses, RulePredicate relative_to) {
Iterator iter = clauses.iterator();
while (iter.hasNext()) {
AbstractClause clause = (AbstractClause)iter.next();
if (clause instanceof PredicateClause) {
PredicateClause _clause = (PredicateClause)clause;
JDOPredicateIF pred = (JDOPredicateIF)_clause.getPredicate();
if (pred instanceof RulePredicate) {
// Check to see if rule predicate is recursive
RulePredicate rule_pred = (RulePredicate)pred;
if (rule_pred.equals(relative_to) ||
rule_pred.isRecursive(rule_pred.getClauses(), relative_to))
return true;
}
} else if (clause instanceof OrClause) {
Iterator iter2 = ((OrClause)clause).getAlternatives().iterator();
while (iter2.hasNext())
if (isRecursive((List)iter2.next(), relative_to))
return true;
} else if (clause instanceof NotClause) {
if (isRecursive(((NotClause)clause).getClauses(), relative_to))
return true;
}
}
return false;
}
}
| apache-2.0 |
hcoles/pitest | pitest/src/main/java/org/pitest/coverage/execute/CoverageMinion.java | 6975 | /*
* Copyright 2010 Henry Coles
*
* 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 org.pitest.coverage.execute;
import org.pitest.boot.HotSwapAgent;
import org.pitest.classinfo.ClassName;
import org.pitest.classpath.ClassPathByteArraySource;
import org.pitest.classpath.ClassloaderByteArraySource;
import org.pitest.coverage.CoverageTransformer;
import org.pitest.dependency.DependencyExtractor;
import org.pitest.functional.prelude.Prelude;
import org.pitest.help.PitHelpError;
import org.pitest.mutationtest.config.ClientPluginServices;
import org.pitest.mutationtest.config.MinionSettings;
import org.pitest.mutationtest.mocksupport.BendJavassistToMyWillTransformer;
import org.pitest.mutationtest.mocksupport.JavassistInputStreamInterceptorAdapater;
import org.pitest.testapi.Configuration;
import org.pitest.testapi.TestUnit;
import org.pitest.testapi.execute.FindTestUnits;
import org.pitest.util.ExitCode;
import org.pitest.util.Glob;
import org.pitest.util.Log;
import org.pitest.util.SafeDataInputStream;
import sun.pitest.CodeCoverageStore;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import static org.pitest.util.Unchecked.translateCheckedException;
public class CoverageMinion {
private static final Logger LOG = Log.getLogger();
public static void main(final String[] args) {
enablePowerMockSupport();
ExitCode exitCode = ExitCode.OK;
Socket s = null;
CoveragePipe invokeQueue = null;
try {
final int port = Integer.parseInt(args[0]);
s = new Socket("localhost", port);
final SafeDataInputStream dis = new SafeDataInputStream(
s.getInputStream());
final CoverageOptions paramsFromParent = dis.read(CoverageOptions.class);
configureVerbosity(paramsFromParent);
invokeQueue = new CoveragePipe(new BufferedOutputStream(
s.getOutputStream()));
CodeCoverageStore.init(invokeQueue);
HotSwapAgent.addTransformer(new CoverageTransformer(
convertToJVMClassFilter(paramsFromParent.getFilter())));
final List<TestUnit> tus = getTestsFromParent(dis, paramsFromParent);
LOG.info(() -> tus.size() + " tests received");
final CoverageWorker worker = new CoverageWorker(invokeQueue, tus);
worker.run();
} catch (final PitHelpError phe) {
LOG.log(Level.SEVERE, phe.getMessage());
exitCode = ExitCode.JUNIT_ISSUE;
} catch (final Throwable ex) {
ex.printStackTrace(System.out);
LOG.log(Level.SEVERE, "Error calculating coverage. Process will exit.",
ex);
exitCode = ExitCode.UNKNOWN_ERROR;
} finally {
if (invokeQueue != null) {
invokeQueue.end(exitCode);
}
try {
if (s != null) {
s.close();
}
} catch (final IOException e) {
throw translateCheckedException(e);
}
}
System.exit(exitCode.getCode());
}
private static void enablePowerMockSupport() {
// Bwahahahahahahaha
HotSwapAgent.addTransformer(new BendJavassistToMyWillTransformer(Prelude
.or(new Glob("javassist/*")),
JavassistInputStreamInterceptorAdapater.inputStreamAdapterSupplier(JavassistCoverageInterceptor.class)));
}
private static Predicate<String> convertToJVMClassFilter(
final Predicate<String> child) {
return a -> child.test(a.replace("/", "."));
}
private static List<TestUnit> getTestsFromParent(
final SafeDataInputStream dis, final CoverageOptions paramsFromParent) {
final List<ClassName> classes = receiveTestClassesFromParent(dis);
Collections.sort(classes); // ensure classes loaded in a consistent order
final Configuration testPlugin = createTestPlugin(paramsFromParent);
verifyEnvironment(testPlugin);
final List<TestUnit> tus = discoverTests(testPlugin, classes);
if (tus.isEmpty()) {
LOG.warning("No executable tests were found after examining the " + classes.size()
+ " test classes supplied. This may indicate an issue with the classpath or a missing test plugin (e.g for JUnit 5).");
}
final DependencyFilter filter = new DependencyFilter(
new DependencyExtractor(new ClassPathByteArraySource(),
paramsFromParent.getDependencyAnalysisMaxDistance()),
paramsFromParent.getFilter());
final List<TestUnit> filteredTus = filter
.filterTestsByDependencyAnalysis(tus);
LOG.info(() -> "Dependency analysis reduced number of potential tests by "
+ (tus.size() - filteredTus.size()));
return filteredTus;
}
private static List<TestUnit> discoverTests(final Configuration testPlugin,
final List<ClassName> classes) {
final FindTestUnits finder = new FindTestUnits(testPlugin);
final List<TestUnit> tus = finder
.findTestUnitsForAllSuppliedClasses(classes.stream().flatMap(ClassName.nameToClass()).collect(Collectors.toList()));
LOG.info(() -> "Found " + tus.size() + " tests");
return tus;
}
private static Configuration createTestPlugin(
final CoverageOptions paramsFromParent) {
final ClientPluginServices plugins = ClientPluginServices.makeForContextLoader();
final MinionSettings factory = new MinionSettings(plugins);
return factory.getTestFrameworkPlugin(paramsFromParent.getPitConfig(), ClassloaderByteArraySource.fromContext());
}
private static void verifyEnvironment(Configuration config) {
LOG.info(() -> "Checking environment");
if (config.verifyEnvironment().isPresent()) {
throw config.verifyEnvironment().get();
}
}
private static List<ClassName> receiveTestClassesFromParent(
final SafeDataInputStream dis) {
final int count = dis.readInt();
LOG.fine(() -> "Expecting " + count + " tests classes from parent");
final List<ClassName> classes = new ArrayList<>(count);
for (int i = 0; i != count; i++) {
classes.add(ClassName.fromString(dis.readString()));
}
LOG.fine(() -> "Tests classes received");
return classes;
}
private static void configureVerbosity(CoverageOptions paramsFromParent) {
Log.setVerbose(paramsFromParent.verbosity());
if (!paramsFromParent.verbosity().showMinionOutput()) {
Log.disable();
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/transform/DeploymentMarshaller.java | 2874 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.apigateway.model.transform;
import java.util.Map;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.apigateway.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeploymentMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeploymentMarshaller {
private static final MarshallingInfo<String> ID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("id").build();
private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("description").build();
private static final MarshallingInfo<java.util.Date> CREATEDDATE_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("createdDate").timestampFormat("unixTimestamp").build();
private static final MarshallingInfo<Map> APISUMMARY_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("apiSummary").build();
private static final DeploymentMarshaller instance = new DeploymentMarshaller();
public static DeploymentMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(Deployment deployment, ProtocolMarshaller protocolMarshaller) {
if (deployment == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deployment.getId(), ID_BINDING);
protocolMarshaller.marshall(deployment.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(deployment.getCreatedDate(), CREATEDDATE_BINDING);
protocolMarshaller.marshall(deployment.getApiSummary(), APISUMMARY_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
sshikov/ldpath | ldpath-template/src/main/java/at/newmedialab/ldpath/template/engine/NamespaceDirective.java | 4398 | /*
* Copyright (c) 2011 Salzburg Research.
*
* 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 at.newmedialab.ldpath.template.engine;
import at.newmedialab.ldpath.template.model.freemarker.TemplateWrapperModel;
import freemarker.core.Environment;
import freemarker.template.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Add file description here!
* <p/>
* Author: Sebastian Schaffert
*/
public class NamespaceDirective implements TemplateDirectiveModel {
public NamespaceDirective() {
}
/**
* Executes this user-defined directive; called by FreeMarker when the user-defined
* directive is called in the template.
*
* @param env the current processing environment. Note that you can access
* the output {@link java.io.Writer Writer} by {@link freemarker.core.Environment#getOut()}.
* @param params the parameters (if any) passed to the directive as a
* map of key/value pairs where the keys are {@link String}-s and the
* values are {@link freemarker.template.TemplateModel} instances. This is never
* <code>null</code>. If you need to convert the template models to POJOs,
* you can use the utility methods in the {@link freemarker.template.utility.DeepUnwrap} class.
* @param loopVars an array that corresponds to the "loop variables", in
* the order as they appear in the directive call. ("Loop variables" are out-parameters
* that are available to the nested body of the directive; see in the Manual.)
* You set the loop variables by writing this array. The length of the array gives the
* number of loop-variables that the caller has specified.
* Never <code>null</code>, but can be a zero-length array.
* @param body an object that can be used to render the nested content (body) of
* the directive call. If the directive call has no nested content (i.e., it is like
* [@myDirective /] or [@myDirective][/@myDirective]), then this will be
* <code>null</code>.
* @throws freemarker.template.TemplateException
*
* @throws java.io.IOException
*/
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
TemplateWrapperModel<Map<String,String>> namespacesWrapped = (TemplateWrapperModel<Map<String,String>>)env.getGlobalVariable("namespaces");
Map<String,String> namespaces;
if(namespacesWrapped == null) {
namespaces = new HashMap<String, String>();
namespacesWrapped = new TemplateWrapperModel<Map<String, String>>(namespaces);
env.setGlobalVariable("namespaces",namespacesWrapped);
} else {
namespaces = namespacesWrapped.getAdaptedObject(Map.class);
}
Iterator paramIter = params.entrySet().iterator();
while (paramIter.hasNext()) {
Map.Entry ent = (Map.Entry) paramIter.next();
String paramName = (String) ent.getKey();
TemplateModel paramValue = (TemplateModel) ent.getValue();
if(paramValue instanceof TemplateScalarModel) {
String uri = ((TemplateScalarModel)paramValue).getAsString();
try {
URI test = new URI(uri);
namespaces.put(paramName,test.toString());
} catch (URISyntaxException e) {
throw new TemplateModelException("invalid namespace URI '"+uri+"'",e);
}
}
}
}
}
| apache-2.0 |
Gamma-Associates-Ltd/highchart-java-api | src/main/java/nl/pvanassen/highchart/api/Axis.java | 9938 | package nl.pvanassen.highchart.api;
import java.awt.Color;
import nl.pvanassen.highchart.api.axis.AxisLabels;
import nl.pvanassen.highchart.api.axis.AxisPlotLines;
import nl.pvanassen.highchart.api.base.BaseObject;
import nl.pvanassen.highchart.api.format.DateTimeLabelFormats;
import nl.pvanassen.highchart.api.shared.DashStyleType;
import nl.pvanassen.highchart.api.shared.EnumString;
import nl.pvanassen.highchart.api.shared.HexColor;
import nl.pvanassen.highchart.api.shared.Styleable;
import nl.pvanassen.highchart.api.utils.ArrayString;
import nl.pvanassen.highchart.api.utils.JsonArray;
import nl.pvanassen.highchart.api.utils.Utils;
public class Axis
extends BaseObject
implements Styleable<Axis> {
public enum Type {
LINEAR,
LOGARITHMIC,
DATETIME,
CATEGORY
}
private ArrayString categories;
private DateTimeLabelFormats dateTimeLabelFormats;
private String gridLineColor;
private String gridLineDashStyle;
private Integer gridLineWidth;
private AxisLabels labels;
private String lineColor;
private Integer lineWidth;
private Double max;
private Double min;
private String minorGridLineColor;
private String minorGridLineDashStyle;
private Integer minorGridLineWidth;
private Boolean opposite;
private JsonArray<AxisPlotLines> plotLines;
private Boolean reversed;
private Boolean showEmpty;
private Boolean showFirstLabel;
private Boolean showLastLabel;
private Boolean startOnTick;
private Double tickInterval;
private Title title;
private String type;
public Axis() { }
@Override
public Axis style(
final Axis src) {
if(src == null) {
return this;
}
Utils.stylePrimitiveArray(this.categories, src.categories);
Utils.style(this.dateTimeLabelFormats, src.dateTimeLabelFormats);
this.gridLineColor = src.gridLineColor;
this.gridLineDashStyle = src.gridLineDashStyle;
this.gridLineWidth = src.gridLineWidth;
Utils.style(this.labels, src.labels);
this.lineColor = src.lineColor;
this.lineWidth = src.lineWidth;
this.max = src.max;
this.min = src.min;
this.minorGridLineColor = src.minorGridLineColor;
this.minorGridLineDashStyle = src.minorGridLineDashStyle;
this.minorGridLineWidth = src.minorGridLineWidth;
this.opposite = src.opposite;
this.plotLines = src.plotLines;
this.reversed = src.reversed;
this.showEmpty = src.showEmpty;
this.showFirstLabel = src.showFirstLabel;
this.showLastLabel = src.showLastLabel;
this.startOnTick = src.startOnTick;
this.tickInterval = src.tickInterval;
Utils.style(this.title, src.title);
this.type = src.type;
return this;
}
public ArrayString getCategories() {
if (categories == null) {
categories = new ArrayString();
}
return categories;
}
public int getCategoriesLength() {
return categories != null ? categories.size() : 0;
}
public DateTimeLabelFormats getDateTimeLabelFormats() {
if (dateTimeLabelFormats == null) {
dateTimeLabelFormats = new DateTimeLabelFormats();
}
return dateTimeLabelFormats;
}
public AxisLabels getLabels() {
if (labels == null) {
labels = new AxisLabels();
}
return labels;
}
public Double getMax() {
return max;
}
public Double getMin() {
return min;
}
public JsonArray<AxisPlotLines> getPlotLines() {
if(this.plotLines == null) {
this.plotLines = new JsonArray<AxisPlotLines>();
}
return plotLines;
}
public Double getTickInterval() {
return tickInterval;
}
public Title getTitle() {
if (title == null) {
title = new Title();
}
return title;
}
public String getType() {
return type;
}
public Axis setMax(Double max) {
this.max = max;
return this;
}
public Axis setMin(Double min) {
this.min = min;
return this;
}
public Axis setTickInterval(Double tickInterval) {
this.tickInterval = tickInterval;
return this;
}
public Axis setType(Type type) {
this.type = EnumString.toString(type);
return this;
}
/**
* @return the gridLineColor
*/
public String getGridLineColor() {
return gridLineColor;
}
/**
* @param gridLineColor the gridLineColor to set
* @return
*/
public Axis setGridLineColor(Color gridLineColor) {
this.gridLineColor = HexColor.toString(gridLineColor);
return this;
}
/**
* @return the gridLineDashStyle
*/
public String getGridLineDashStyle() {
return gridLineDashStyle;
}
/**
* @param gridLineDashStyle the gridLineDashStyle to set
* @return
*/
public Axis setGridLineDashStyle(DashStyleType gridLineDashStyle) {
this.gridLineDashStyle = EnumString.toString(gridLineDashStyle);
return this;
}
/**
* @return the gridLineWidth
*/
public Integer getGridLineWidth() {
return gridLineWidth;
}
/**
* @param gridLineWidth the gridLineWidth to set
* @return
*/
public Axis setGridLineWidth(Integer gridLineWidth) {
this.gridLineWidth = gridLineWidth;
return this;
}
/**
* @return the lineColor
*/
public String getLineColor() {
return lineColor;
}
/**
* @param lineColor the lineColor to set
* @return
*/
public Axis setLineColor(Color lineColor) {
this.lineColor = HexColor.toString(lineColor);
return this;
}
/**
* @return the lineWidth
*/
public Integer getLineWidth() {
return lineWidth;
}
/**
* @param lineWidth the lineWidth to set
* @return
*/
public Axis setLineWidth(Integer lineWidth) {
this.lineWidth = lineWidth;
return this;
}
/**
* @return the minorGridLineColor
*/
public String getMinorGridLineColor() {
return minorGridLineColor;
}
/**
* @param minorGridLineColor the minorGridLineColor to set
* @return
*/
public Axis setMinorGridLineColor(Color minorGridLineColor) {
this.minorGridLineColor = HexColor.toString(minorGridLineColor);
return this;
}
/**
* @return the minorGridLineDashStyle
*/
public String getMinorGridLineDashStyle() {
return minorGridLineDashStyle;
}
/**
* @param minorGridLineDashStyle the minorGridLineDashStyle to set
* @return
*/
public Axis setMinorGridLineDashStyle(
final DashStyleType minorGridLineDashStyle) {
this.minorGridLineDashStyle =
EnumString.toString(
minorGridLineDashStyle);
return this;
}
/**
* @return the minorGridLineWidth
*/
public Integer getMinorGridLineWidth() {
return minorGridLineWidth;
}
/**
* @param minorGridLineWidth the minorGridLineWidth to set
* @return
*/
public Axis setMinorGridLineWidth(Integer minorGridLineWidth) {
this.minorGridLineWidth = minorGridLineWidth;
return this;
}
/**
* @return the opposite
*/
public Boolean getOpposite() {
return opposite;
}
/**
* @param opposite the opposite to set
* @return
*/
public Axis setOpposite(Boolean opposite) {
this.opposite = opposite;
return this;
}
/**
* @return the reversed
*/
public Boolean getReversed() {
return reversed;
}
/**
* @param reversed the reversed to set
* @return
*/
public Axis setReversed(Boolean reversed) {
this.reversed = reversed;
return this;
}
/**
* @return the showEmpty
*/
public Boolean getShowEmpty() {
return showEmpty;
}
/**
* @param showEmpty the showEmpty to set
* @return
*/
public Axis setShowEmpty(Boolean showEmpty) {
this.showEmpty = showEmpty;
return this;
}
/**
* @return the showFirstLabel
*/
public Boolean getShowFirstLabel() {
return showFirstLabel;
}
/**
* @param showFirstLabel the showFirstLabel to set
* @return
*/
public Axis setShowFirstLabel(Boolean showFirstLabel) {
this.showFirstLabel = showFirstLabel;
return this;
}
/**
* @return the showLastLabel
*/
public Boolean getShowLastLabel() {
return showLastLabel;
}
/**
* @param showLastLabel the showLastLabel to set
* @return
*/
public Axis setShowLastLabel(Boolean showLastLabel) {
this.showLastLabel = showLastLabel;
return this;
}
/**
* @return the startOnTick
*/
public Boolean getStartOnTick() {
return startOnTick;
}
/**
* @param startOnTick the startOnTick to set
* @return
*/
public Axis setStartOnTick(Boolean startOnTick) {
this.startOnTick = startOnTick;
return this;
}
}
| apache-2.0 |
raqs31/PW_JOURNAL_SYSTEM | PwJournalSystem/src/pw/mario/faces/articles/model/tabs/PrinterTab.java | 1352 | package pw.mario.faces.articles.model.tabs;
import java.io.Serializable;
import javax.enterprise.context.Dependent;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import lombok.Getter;
import pw.mario.faces.articles.co.ArticleDetailsController;
import pw.mario.journal.model.article.Article;
import pw.mario.journal.qualifiers.ArticleManagement;
import pw.mario.journal.qualifiers.ArticleTab;
import pw.mario.journal.qualifiers.enums.ArticleManager;
import pw.mario.journal.service.article.ArticleService;
@Named
@ArticleTab
@Dependent
public class PrinterTab extends AbstractArticleTab implements Serializable {
private static final long serialVersionUID = 1L;
private static final String TITTLE = "Artykuły do druku";
@Inject @ArticleManagement(ArticleManager.PRINTER) private ArticleService articleService;
@Getter private final String id = "Zprinter";
@Override
public String getTittle() {
return TITTLE;
}
@Override
public String onEdit(Article a) {
FacesContext.getCurrentInstance()
.getExternalContext()
.getFlash()
.put(ArticleDetailsController.PARAM_ARTICLE_ID, a);
return "articleDetails?faces-redirect=true";
}
@Override
protected ArticleService getArticleService() {
return articleService;
}
}
| apache-2.0 |
jasonchaffee/undertow | servlet/src/test/java/io/undertow/servlet/test/upgrade/SimpleUpgradeTestCase.java | 3496 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 io.undertow.servlet.test.upgrade;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import javax.servlet.ServletException;
import io.undertow.servlet.api.ServletInfo;
import io.undertow.servlet.test.util.DeploymentUtils;
import io.undertow.testutils.DefaultServer;
import io.undertow.testutils.HttpOneOnly;
import io.undertow.testutils.TestHttpClient;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Stuart Douglas
*/
@HttpOneOnly
@RunWith(DefaultServer.class)
public class SimpleUpgradeTestCase {
@BeforeClass
public static void setup() throws ServletException {
DeploymentUtils.setupServlet(
new ServletInfo("upgradeServlet", UpgradeServlet.class)
.addMapping("/upgrade"),
new ServletInfo("upgradeAsyncServlet", AsyncUpgradeServlet.class)
.addMapping("/asyncupgrade"));
}
@Test
public void testBlockingUpgrade() throws IOException {
runTest("/servletContext/upgrade");
}
@Test
public void testAsyncUpgrade() throws IOException {
runTest("/servletContext/asyncupgrade");
}
public void runTest(final String url) throws IOException {
TestHttpClient client = new TestHttpClient();
try {
final Socket socket = new Socket(DefaultServer.getHostAddress("default"), DefaultServer.getHostPort("default"));
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(("GET " + url + " HTTP/1.1\r\nConnection: upgrade\r\nUpgrade: servlet\r\n\r\n").getBytes());
out.flush();
Assert.assertTrue(readBytes(in).startsWith("HTTP/1.1 101 Switching Protocols\r\n"));
out.write("Echo Messages\r\n\r\n".getBytes());
out.flush();
Assert.assertEquals("Echo Messages\r\n\r\n", readBytes(in));
out.write("Echo Messages2\r\n\r\n".getBytes());
out.flush();
Assert.assertEquals("Echo Messages2\r\n\r\n", readBytes(in));
out.write("exit\r\n\r\n".getBytes());
out.flush();
out.close();
} finally {
client.getConnectionManager().shutdown();
}
}
private String readBytes(final InputStream in) throws IOException {
final StringBuilder builder = new StringBuilder();
byte[] buf = new byte[100];
int read;
while (!builder.toString().contains("\r\n\r\n") && (read = in.read(buf)) != -1) { //awesome hack
builder.append(new String(buf, 0, read));
}
return builder.toString();
}
}
| apache-2.0 |
Mogztter/jinjava | src/main/java/com/hubspot/jinjava/el/ext/AbstractCallableMethod.java | 2465 | package com.hubspot.jinjava.el.ext;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.google.common.base.Throwables;
/**
* Defines a function which will be called in the context of an interpreter instance. Supports named params with default values, as well as var args.
*
* @author jstehler
*
*/
public abstract class AbstractCallableMethod {
public static final Method EVAL_METHOD;
static {
try {
EVAL_METHOD = AbstractCallableMethod.class.getMethod("evaluate", Object[].class);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
private final String name;
private final LinkedHashMap<String, Object> argNamesWithDefaults;
public AbstractCallableMethod(String name, LinkedHashMap<String, Object> argNamesWithDefaults) {
this.name = name;
this.argNamesWithDefaults = argNamesWithDefaults;
}
public Object evaluate(Object... args) {
Map<String, Object> argMap = new LinkedHashMap<>(argNamesWithDefaults);
Map<String, Object> kwargMap = new LinkedHashMap<>();
List<Object> varArgs = new ArrayList<>();
int argPos = 0;
for (Map.Entry<String, Object> argEntry : argMap.entrySet()) {
if (argPos < args.length) {
Object arg = args[argPos++];
// once we hit the first named parameter, the rest must be named parameters...
if (arg instanceof NamedParameter) {
argPos--;
break;
}
argEntry.setValue(arg);
} else {
break;
}
}
// consumeth thyne named params
for (int i = argPos; i < args.length; i++) {
Object arg = args[i];
if (arg instanceof NamedParameter) {
NamedParameter param = (NamedParameter) arg;
if (argMap.containsKey(param.getName())) {
argMap.put(param.getName(), param.getValue());
} else {
kwargMap.put(param.getName(), param.getValue());
}
} else {
varArgs.add(arg);
}
}
return doEvaluate(argMap, kwargMap, varArgs);
}
public abstract Object doEvaluate(Map<String, Object> argMap, Map<String, Object> kwargMap, List<Object> varArgs);
public String getName() {
return name;
}
public List<String> getArguments() {
return new ArrayList<>(argNamesWithDefaults.keySet());
}
public Map<String, Object> getDefaults() {
return argNamesWithDefaults;
}
}
| apache-2.0 |
nik1202/EduProject | chapter_001/src/test/java/ru/arrays/DeleteTest.java | 620 | package ru.arrays;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Delete duplicates Array.
*
* @author nik1202
* @version $Id$
* @since 0.1
*/
public class DeleteTest {
/**
* Test delete duplicates array.
*/
@Test
public void whenArrayLengthIsSixThenDelete() {
String[] expect = new String[] {"Hello", "world", "qwe"};
String[] result = new String[] {"Hello", "world", "world", "Hello", "qwe", "Hello"};
Delete d = new Delete();
String[] s = d.del(result);
assertThat(s, is(expect));
}
} | apache-2.0 |
cuongvanhd/wallride | src/main/java/org/wallride/core/repository/ArticleRepositoryImpl.java | 6285 | /*
* Copyright 2014 Tagbangers, Inc.
*
* 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 org.wallride.core.repository;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.util.Version;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.hibernate.search.jpa.Search;
import org.hibernate.search.query.dsl.BooleanJunction;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.wallride.core.domain.Article;
import org.wallride.core.service.ArticleSearchRequest;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
public class ArticleRepositoryImpl implements ArticleRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public Page<Article> search(ArticleSearchRequest request) {
return search(request, null);
}
@Override
public Page<Article> search(ArticleSearchRequest request, Pageable pageable) {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
QueryBuilder qb = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder()
.forEntity(Article.class)
.get();
@SuppressWarnings("rawtypes")
BooleanJunction<BooleanJunction> junction = qb.bool();
junction.must(qb.all().createQuery());
junction.must(qb.keyword().onField("drafted").ignoreAnalyzer().matching("_null_").createQuery());
if (StringUtils.hasText(request.getKeyword())) {
Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms");
String[] fields = new String[] {
"title", "body",
"categories.name", "tags.name",
};
MultiFieldQueryParser parser = new MultiFieldQueryParser(Version.LATEST, fields, analyzer);
parser.setDefaultOperator(QueryParser.Operator.AND);
Query query = null;
try {
query = parser.parse(request.getKeyword());
}
catch (ParseException e1) {
try {
query = parser.parse(QueryParser.escape(request.getKeyword()));
}
catch (ParseException e2) {
throw new RuntimeException(e2);
}
}
junction.must(query);
}
if (request.getStatus() != null) {
junction.must(qb.keyword().onField("status").matching(request.getStatus()).createQuery());
}
if (StringUtils.hasText(request.getLanguage())) {
junction.must(qb.keyword().onField("language").matching(request.getLanguage()).createQuery());
}
if (request.getDateFrom() != null) {
junction.must(qb.range().onField("date").above(request.getDateFrom()).createQuery());
}
if (request.getDateTo() != null) {
junction.must(qb.range().onField("date").below(request.getDateTo()).createQuery());
}
if (!CollectionUtils.isEmpty(request.getCategoryIds())) {
BooleanJunction<BooleanJunction> subJunction = qb.bool();
for (long categoryId : request.getCategoryIds()) {
subJunction.should(qb.keyword().onField("categories.id").matching(categoryId).createQuery());
}
junction.must(subJunction.createQuery());
}
if (!CollectionUtils.isEmpty(request.getCategoryCodes())) {
BooleanJunction<BooleanJunction> subJunction = qb.bool();
for (String categoryCode : request.getCategoryCodes()) {
subJunction.should(qb.keyword().onField("categories.code").matching(categoryCode).createQuery());
}
junction.must(subJunction.createQuery());
}
if (!CollectionUtils.isEmpty(request.getTagIds())) {
BooleanJunction<BooleanJunction> subJunction = qb.bool();
for (long tagId : request.getTagIds()) {
subJunction.should(qb.keyword().onField("tags.id").matching(tagId).createQuery());
}
junction.must(subJunction.createQuery());
}
if (!CollectionUtils.isEmpty(request.getTagNames())) {
BooleanJunction<BooleanJunction> subJunction = qb.bool();
for (String tagName : request.getTagNames()) {
subJunction.should(qb.phrase().onField("tags.name").sentence(tagName).createQuery());
}
junction.must(subJunction.createQuery());
}
if (request.getAuthorId() != null) {
junction.must(qb.keyword().onField("author.id").matching(request.getAuthorId()).createQuery());
}
Query searchQuery = junction.createQuery();
Session session = (Session) entityManager.getDelegate();
Criteria criteria = session.createCriteria(Article.class)
.setFetchMode("cover", FetchMode.JOIN)
.setFetchMode("user", FetchMode.JOIN)
.setFetchMode("categories", FetchMode.JOIN);
// .setFetchMode("tags", FetchMode.JOIN);
Sort sort = new Sort(
new SortField("date", SortField.Type.STRING, true),
new SortField("id", SortField.Type.LONG, true));
FullTextQuery persistenceQuery = fullTextEntityManager
.createFullTextQuery(searchQuery, Article.class)
.setCriteriaQuery(criteria)
.setSort(sort);
if (pageable != null) {
persistenceQuery.setFirstResult(pageable.getOffset());
persistenceQuery.setMaxResults(pageable.getPageSize());
}
int resultSize = persistenceQuery.getResultSize();
@SuppressWarnings("unchecked")
List<Article> results = persistenceQuery.getResultList();
return new PageImpl<>(results, pageable, resultSize);
}
}
| apache-2.0 |
Athou/commafeed | src/main/java/com/commafeed/backend/HttpGetter.java | 7588 | package com.commafeed.backend;
import java.io.IOException;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.commafeed.CommaFeedConfiguration;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nl.altindag.ssl.SSLFactory;
/**
* Smart HTTP getter: handles gzip, ssl, last modified and etag headers
*
*/
@Singleton
public class HttpGetter {
private static final String ACCEPT_LANGUAGE = "en";
private static final String PRAGMA_NO_CACHE = "No-cache";
private static final String CACHE_CONTROL_NO_CACHE = "no-cache";
private static final HttpResponseInterceptor REMOVE_INCORRECT_CONTENT_ENCODING = new ContentEncodingInterceptor();
private static final SSLFactory SSL_FACTORY = SSLFactory.builder().withUnsafeTrustMaterial().withUnsafeHostnameVerifier().build();
private String userAgent;
@Inject
public HttpGetter(CommaFeedConfiguration config) {
this.userAgent = config.getApplicationSettings().getUserAgent();
if (this.userAgent == null) {
this.userAgent = String.format("CommaFeed/%s (https://github.com/Athou/commafeed)", config.getVersion());
}
}
public HttpResult getBinary(String url, int timeout) throws ClientProtocolException, IOException, NotModifiedException {
return getBinary(url, null, null, timeout);
}
/**
*
* @param url
* the url to retrive
* @param lastModified
* header we got last time we queried that url, or null
* @param eTag
* header we got last time we queried that url, or null
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws NotModifiedException
* if the url hasn't changed since we asked for it last time
*/
public HttpResult getBinary(String url, String lastModified, String eTag, int timeout)
throws ClientProtocolException, IOException, NotModifiedException {
HttpResult result = null;
long start = System.currentTimeMillis();
CloseableHttpClient client = newClient(timeout);
CloseableHttpResponse response = null;
try {
HttpGet httpget = new HttpGet(url);
HttpClientContext context = HttpClientContext.create();
httpget.addHeader(HttpHeaders.ACCEPT_LANGUAGE, ACCEPT_LANGUAGE);
httpget.addHeader(HttpHeaders.PRAGMA, PRAGMA_NO_CACHE);
httpget.addHeader(HttpHeaders.CACHE_CONTROL, CACHE_CONTROL_NO_CACHE);
httpget.addHeader(HttpHeaders.USER_AGENT, userAgent);
if (lastModified != null) {
httpget.addHeader(HttpHeaders.IF_MODIFIED_SINCE, lastModified);
}
if (eTag != null) {
httpget.addHeader(HttpHeaders.IF_NONE_MATCH, eTag);
}
try {
response = client.execute(httpget, context);
int code = response.getStatusLine().getStatusCode();
if (code == HttpStatus.SC_NOT_MODIFIED) {
throw new NotModifiedException("'304 - not modified' http code received");
} else if (code >= 300) {
throw new HttpResponseException(code, "Server returned HTTP error code " + code);
}
} catch (HttpResponseException e) {
if (e.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
throw new NotModifiedException("'304 - not modified' http code received");
} else {
throw e;
}
}
Header lastModifiedHeader = response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
String lastModifiedHeaderValue = lastModifiedHeader == null ? null : StringUtils.trimToNull(lastModifiedHeader.getValue());
if (lastModifiedHeaderValue != null && StringUtils.equals(lastModified, lastModifiedHeaderValue)) {
throw new NotModifiedException("lastModifiedHeader is the same");
}
Header eTagHeader = response.getFirstHeader(HttpHeaders.ETAG);
String eTagHeaderValue = eTagHeader == null ? null : StringUtils.trimToNull(eTagHeader.getValue());
if (eTag != null && StringUtils.equals(eTag, eTagHeaderValue)) {
throw new NotModifiedException("eTagHeader is the same");
}
HttpEntity entity = response.getEntity();
byte[] content = null;
String contentType = null;
if (entity != null) {
content = EntityUtils.toByteArray(entity);
if (entity.getContentType() != null) {
contentType = entity.getContentType().getValue();
}
}
String urlAfterRedirect = url;
if (context.getRequest() instanceof HttpUriRequest) {
HttpUriRequest req = (HttpUriRequest) context.getRequest();
HttpHost host = context.getTargetHost();
urlAfterRedirect = req.getURI().isAbsolute() ? req.getURI().toString() : host.toURI() + req.getURI();
}
long duration = System.currentTimeMillis() - start;
result = new HttpResult(content, contentType, lastModifiedHeaderValue, eTagHeaderValue, duration, urlAfterRedirect);
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(client);
}
return result;
}
public static CloseableHttpClient newClient(int timeout) {
HttpClientBuilder builder = HttpClients.custom();
builder.useSystemProperties();
builder.addInterceptorFirst(REMOVE_INCORRECT_CONTENT_ENCODING);
builder.disableAutomaticRetries();
builder.setSSLContext(SSL_FACTORY.getSslContext());
builder.setSSLHostnameVerifier(SSL_FACTORY.getHostnameVerifier());
RequestConfig.Builder configBuilder = RequestConfig.custom();
configBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
configBuilder.setSocketTimeout(timeout);
configBuilder.setConnectTimeout(timeout);
configBuilder.setConnectionRequestTimeout(timeout);
builder.setDefaultRequestConfig(configBuilder.build());
builder.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Consts.ISO_8859_1).build());
return builder.build();
}
public static void main(String[] args) throws Exception {
CommaFeedConfiguration config = new CommaFeedConfiguration();
HttpGetter getter = new HttpGetter(config);
HttpResult result = getter.getBinary("https://sourceforge.net/projects/mpv-player-windows/rss", 30000);
System.out.println(new String(result.content));
}
public static class NotModifiedException extends Exception {
private static final long serialVersionUID = 1L;
public NotModifiedException(String message) {
super(message);
}
}
@Getter
@RequiredArgsConstructor
public static class HttpResult {
private final byte[] content;
private final String contentType;
private final String lastModifiedSince;
private final String eTag;
private final long duration;
private final String urlAfterRedirect;
}
}
| apache-2.0 |
yelhouti/springfox | springfox-swagger1/src/main/java/springfox/documentation/swagger1/dto/DataType.java | 3780 | /*
*
* Copyright 2015 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 springfox.documentation.swagger1.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//CHECKSTYLE:OFF CyclomaticComplexityCheck
public class DataType implements SwaggerDataType {
private static final Pattern containerPattern = Pattern.compile("([a-zA-Z]+)\\[([_a-zA-Z\\.\\-]+)\\]");
@JsonUnwrapped
@JsonProperty
private SwaggerDataType dataType;
public DataType(String initialType) {
this.dataType = typeFromDataType(initialType);
}
public SwaggerDataType typeFromDataType(String initialType) {
if (isOfType(initialType.toLowerCase(), "void")) {
return new PrimitiveDataType("void");
}
if (isOfType(initialType, "int")) {
return new PrimitiveFormatDataType("integer", "int32");
}
if (isOfType(initialType, "long")) {
return new PrimitiveFormatDataType("integer", "int64");
}
if (isOfType(initialType, "float")) {
return new PrimitiveFormatDataType("number", "float");
}
if (isOfType(initialType, "double")) {
return new PrimitiveFormatDataType("number", "double");
}
if (isOfType(initialType, "string")) {
return new PrimitiveDataType("string");
}
if (isOfType(initialType, "byte")) {
return new PrimitiveFormatDataType("string", "byte");
}
if (isOfType(initialType, "boolean")) {
return new PrimitiveDataType("boolean");
}
if (isOfType(initialType, "Date") || isOfType(initialType, "DateTime")) {
return new PrimitiveFormatDataType("string", "date-time");
}
if (isOfType(initialType, "bigdecimal")) {
return new PrimitiveDataType("number");
}
if (isOfType(initialType, "biginteger")) {
return new PrimitiveDataType("integer");
}
if (isOfType(initialType, "UUID")) {
return new PrimitiveFormatDataType("string", "uuid");
}
if (isOfType(initialType, "date")) {
return new PrimitiveFormatDataType("string", "date");
}
if (isOfType(initialType, "date-time")) {
return new PrimitiveFormatDataType("string", "date-time");
}
if (isOfType(initialType, "__file")) {
return new PrimitiveDataType("File");
}
Matcher matcher = containerPattern.matcher(initialType);
if (matcher.matches()) {
String containerInnerType = matcher.group(2);
if ("__file".equals(containerInnerType)) {
containerInnerType = "File";
}
if (isUniqueContainerType(matcher.group(1))) {
return new ContainerDataType(containerInnerType, true);
} else {
return new ContainerDataType(containerInnerType, false);
}
}
return new ReferenceDataType(initialType);
}
private boolean isUniqueContainerType(String containerInnerType) {
return null != containerInnerType && containerInnerType.equalsIgnoreCase("Set");
}
private boolean isOfType(String initialType, String ofType) {
return initialType.equals(ofType);
}
@Override
public String getAbsoluteType() {
return dataType.getAbsoluteType();
}
}
//CHECKSTYLE:ON | apache-2.0 |
dropwizard/dropwizard-java8 | dropwizard-java8/src/test/java/io/dropwizard/java8/jersey/params/YearParamTest.java | 382 | package io.dropwizard.java8.jersey.params;
import org.junit.Test;
import java.time.Year;
import static org.assertj.core.api.Assertions.assertThat;
public class YearParamTest {
@Test
public void parsesDateTimes() throws Exception {
final YearParam param = new YearParam("2012");
assertThat(param.get())
.isEqualTo(Year.of(2012));
}
}
| apache-2.0 |
ttddyy/spring-social-evernote | src/main/java/org/springframework/social/evernote/api/impl/ThriftNullSafeCollectionInterceptor.java | 2390 | package org.springframework.social.evernote.api.impl;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Tadaya Tsuyukubo
*/
public class ThriftNullSafeCollectionInterceptor implements MethodInterceptor {
private Set<Field> initiallyNullListFields = new HashSet<Field>();
private Set<Field> initiallyNullSetFields = new HashSet<Field>();
private Set<Field> initiallyNullMapFields = new HashSet<Field>();
public ThriftNullSafeCollectionInterceptor() {
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
final Method method = invocation.getMethod();
final Object invoked = invocation.getThis();
if (isThriftWriteMethod(method)) {
// when collection was initially null and still is an empty collection, then set back to null
// to omit thrift transmission.
for (Field field : initiallyNullListFields) {
if (((List) ReflectionUtils.getField(field, invoked)).size() == 0) {
ReflectionUtils.setField(field, invoked, null);
}
}
for (Field field : initiallyNullSetFields) {
if (((Set) ReflectionUtils.getField(field, invoked)).size() == 0) {
ReflectionUtils.setField(field, invoked, null);
}
}
for (Field field : initiallyNullMapFields) {
if (((Map) ReflectionUtils.getField(field, invoked)).size() == 0) {
ReflectionUtils.setField(field, invoked, null);
}
}
}
return invocation.proceed();
}
private static boolean isThriftWriteMethod(Method method) {
// to work with in-lined thrift classes (com.evernote.thrift), and regular thrift generated classes in unittest
// compare by method name and parameter name.
if ("write".equals(method.getName())) {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length == 1 && "TProtocol".equals(paramTypes[0].getSimpleName())) {
return true;
}
}
return false;
}
public Set<Field> getInitiallyNullListFields() {
return initiallyNullListFields;
}
public Set<Field> getInitiallyNullSetFields() {
return initiallyNullSetFields;
}
public Set<Field> getInitiallyNullMapFields() {
return initiallyNullMapFields;
}
}
| apache-2.0 |
GoldenGnu/eve-esi | src/main/java/net/troja/eve/esi/model/CharacterFitting.java | 4500 | /*
* EVE Swagger Interface
* An OpenAPI for EVE Online
*
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package net.troja.eve.esi.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import net.troja.eve.esi.model.FittingItem;
import java.io.Serializable;
/**
* fitting object
*/
@ApiModel(description = "fitting object")
public class CharacterFitting implements Serializable {
private static final long serialVersionUID = 1L;
@JsonProperty("description")
private String description = null;
@JsonProperty("items")
private List<FittingItem> items = new ArrayList<FittingItem>();
@JsonProperty("name")
private String name = null;
@JsonProperty("ship_type_id")
private Integer shipTypeId = null;
public CharacterFitting description(String description) {
this.description = description;
return this;
}
/**
* description string
*
* @return description
**/
@ApiModelProperty(example = "null", required = true, value = "description string")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public CharacterFitting items(List<FittingItem> items) {
this.items = items;
return this;
}
public CharacterFitting addItemsItem(FittingItem itemsItem) {
this.items.add(itemsItem);
return this;
}
/**
* items array
*
* @return items
**/
@ApiModelProperty(example = "null", required = true, value = "items array")
public List<FittingItem> getItems() {
return items;
}
public void setItems(List<FittingItem> items) {
this.items = items;
}
public CharacterFitting name(String name) {
this.name = name;
return this;
}
/**
* name string
*
* @return name
**/
@ApiModelProperty(example = "null", required = true, value = "name string")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CharacterFitting shipTypeId(Integer shipTypeId) {
this.shipTypeId = shipTypeId;
return this;
}
/**
* ship_type_id integer
*
* @return shipTypeId
**/
@ApiModelProperty(example = "null", required = true, value = "ship_type_id integer")
public Integer getShipTypeId() {
return shipTypeId;
}
public void setShipTypeId(Integer shipTypeId) {
this.shipTypeId = shipTypeId;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CharacterFitting characterFitting = (CharacterFitting) o;
return Objects.equals(this.description, characterFitting.description)
&& Objects.equals(this.items, characterFitting.items)
&& Objects.equals(this.name, characterFitting.name)
&& Objects.equals(this.shipTypeId, characterFitting.shipTypeId);
}
@Override
public int hashCode() {
return Objects.hash(description, items, name, shipTypeId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CharacterFitting {\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" items: ").append(toIndentedString(items)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" shipTypeId: ").append(toIndentedString(shipTypeId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| apache-2.0 |
sghill/gocd | common/src/com/thoughtworks/go/remote/work/RemoteConsoleAppender.java | 1954 | /*
* Copyright 2017 ThoughtWorks, Inc.
*
* 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.thoughtworks.go.remote.work;
import com.thoughtworks.go.util.HttpService;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.Charset;
public class RemoteConsoleAppender implements ConsoleAppender {
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteConsoleAppender.class);
private String consoleUri;
private HttpService httpService;
public RemoteConsoleAppender(String consoleUri, HttpService httpService) {
this.consoleUri = consoleUri;
this.httpService = httpService;
}
public void append(String content) throws IOException {
HttpPut putMethod = new HttpPut(consoleUri);
try {
LOGGER.debug("Appending console to URL -> {}", consoleUri);
putMethod.setEntity(new StringEntity(content, Charset.defaultCharset()));
HttpService.setSizeHeader(putMethod, content.getBytes().length);
CloseableHttpResponse response = httpService.execute(putMethod);
LOGGER.debug("Got {}", response.getStatusLine().getStatusCode());
} finally {
putMethod.releaseConnection();
}
}
}
| apache-2.0 |
zoneXcoding/Mineworld | src/main/java/org/terasology/rendering/gui/dialogs/UIDialogCreateNewWorld.java | 13239 | /*
* Copyright 2012 Benjamin Glatzel <benjamin.glatzel@me.com>
*
* 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 org.terasology.rendering.gui.dialogs;
import org.newdawn.slick.Color;
import org.terasology.config.Config;
import org.terasology.config.ModConfig;
import org.terasology.game.CoreRegistry;
import org.terasology.game.GameEngine;
import org.terasology.game.modes.StateLoading;
import org.terasology.game.types.FreeStyleType;
import org.terasology.game.types.GameType;
import org.terasology.game.types.SurvivalType;
import org.terasology.logic.manager.PathManager;
import org.terasology.rendering.gui.framework.UIDisplayContainer;
import org.terasology.rendering.gui.framework.UIDisplayElement;
import org.terasology.rendering.gui.framework.events.ClickListener;
import org.terasology.rendering.gui.widgets.UIButton;
import org.terasology.rendering.gui.widgets.UIComboBox;
import org.terasology.rendering.gui.widgets.UIDialog;
import org.terasology.rendering.gui.widgets.UILabel;
import org.terasology.rendering.gui.widgets.UIListItem;
import org.terasology.rendering.gui.widgets.UIText;
import org.terasology.rendering.gui.windows.UIMenuSingleplayer;
import org.terasology.utilities.FastRandom;
import org.terasology.world.WorldInfo;
import org.terasology.world.generator.core.*;
import org.terasology.world.liquid.LiquidsGenerator;
import javax.vecmath.Vector2f;
import javax.vecmath.Vector4f;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/*
* Dialog for generate new world
*
* @author Anton Kireev <adeon.k87@gmail.com>
* @version 0.1
*/
public class UIDialogCreateNewWorld extends UIDialog {
private UIButton okButton;
private UIButton cancelButton;
private UILabel inputSeedLabel;
private UIText inputSeed;
private UILabel inputWorldTitleLabel;
private UIText inputWorldTitle;
private UILabel chunkGeneratorLabel;
private UIComboBox chunkGenerator;
private UIComboBox typeOfGame;
private UILabel typeOfGameLabel;
private ModConfig modConfig;
public UIDialogCreateNewWorld() {
super(new Vector2f(512f, 380f));
setTitle("Create new world");
modConfig = new ModConfig();
modConfig.copy(CoreRegistry.get(Config.class).getDefaultModSelection());
}
@Override
protected void createDialogArea(UIDisplayContainer parent) {
inputSeed = new UIText();
inputSeed.setSize(new Vector2f(256f, 30f));
//inputSeed.setBackgroundImage("engine:gui_menu", new Vector2f(0f, 90f), new Vector2f(256f, 30f));
inputSeed.setVisible(true);
inputWorldTitle = new UIText();
inputWorldTitle.setSize(new Vector2f(256f, 30f));
//inputWorldTitle.setBackgroundImage("engine:gui_menu", new Vector2f(0f, 90f), new Vector2f(256f, 30f));
inputWorldTitle.setText(getWorldName());
inputWorldTitle.setVisible(true);
inputSeedLabel = new UILabel("Enter a seed (optional):");
inputSeedLabel.setColor(Color.darkGray);
inputSeedLabel.setSize(new Vector2f(0f, 16f));
inputSeedLabel.setVisible(true);
inputWorldTitleLabel = new UILabel("Enter a world name:");
inputWorldTitleLabel.setColor(Color.darkGray);
inputWorldTitleLabel.setSize(new Vector2f(0f, 16f));
inputWorldTitleLabel.setVisible(true);
typeOfGameLabel = new UILabel("Choose type of game:");
typeOfGameLabel.setColor(Color.darkGray);
typeOfGameLabel.setSize(new Vector2f(0f, 16f));
typeOfGameLabel.setVisible(true);
typeOfGame = new UIComboBox(new Vector2f(176f, 22f), new Vector2f(176f, 50f));
UIListItem item = new UIListItem(new SurvivalType().getName(), new SurvivalType());
item.setTextColor(Color.black);
item.setPadding(new Vector4f(5f, 5f, 5f, 5f));
typeOfGame.addItem(item);
item = new UIListItem(new FreeStyleType().getName(), new FreeStyleType());
item.setTextColor(Color.black);
item.setPadding(new Vector4f(5f, 5f, 5f, 5f));
typeOfGame.addItem(item);
typeOfGame.select(0);
typeOfGame.setVisible(true);
chunkGeneratorLabel = new UILabel("Choose Chunk Generator:");
chunkGeneratorLabel.setColor(Color.darkGray);
chunkGeneratorLabel.setSize(new Vector2f(0f, 16f));
chunkGeneratorLabel.setVisible(true);
chunkGenerator = new UIComboBox(new Vector2f(176f, 22f), new Vector2f(176f, 48f));
item = new UIListItem("Perlin", new Integer(0));
item.setTextColor(Color.black);
item.setPadding(new Vector4f(5f, 5f, 5f, 5f));
chunkGenerator.addItem(item);
item = new UIListItem("Flat", new Integer(1));
item.setTextColor(Color.black);
item.setPadding(new Vector4f(5f, 5f, 5f, 5f));
chunkGenerator.addItem(item);
item = new UIListItem("Multi", new Integer(2));
item.setTextColor(Color.cyan);
item.setPadding(new Vector4f(5f, 5f, 5f, 5f));
chunkGenerator.addItem(item);
item = new UIListItem("Heigthmap Generator", new Integer(3));
item.setTextColor(Color.black);
item.setPadding(new Vector4f(5f, 5f, 5f, 5f));
chunkGenerator.addItem(item);
chunkGenerator.select(0);
chunkGenerator.setVisible(true);
inputWorldTitleLabel.setPosition(new Vector2f(15f, 32f));
inputWorldTitle.setPosition(new Vector2f(inputWorldTitleLabel.getPosition().x, inputWorldTitleLabel.getPosition().y + inputWorldTitleLabel.getSize().y + 8f));
inputSeedLabel.setPosition(new Vector2f(inputWorldTitle.getPosition().x, inputWorldTitle.getPosition().y + inputWorldTitle.getSize().y + 16f));
inputSeed.setPosition(new Vector2f(inputSeedLabel.getPosition().x, inputSeedLabel.getPosition().y + inputSeedLabel.getSize().y + 8f));
typeOfGameLabel.setPosition(new Vector2f(inputSeed.getPosition().x, inputSeed.getPosition().y + inputSeed.getSize().y + 16f));
typeOfGame.setPosition(new Vector2f(typeOfGameLabel.getPosition().x, typeOfGameLabel.getPosition().y + typeOfGameLabel.getSize().y + 8f));
chunkGeneratorLabel.setPosition(new Vector2f(typeOfGame.getPosition().x, typeOfGame.getPosition().y + typeOfGame.getSize().y + 16f));
chunkGenerator.setPosition(new Vector2f(chunkGeneratorLabel.getPosition().x, chunkGeneratorLabel.getPosition().y + chunkGeneratorLabel.getSize().y + 8f));
UIButton modButton = new UIButton(new Vector2f(80, 30), UIButton.ButtonType.NORMAL);
modButton.setPosition(new Vector2f(chunkGenerator.getPosition().x, chunkGenerator.getPosition().y + chunkGenerator.getSize().y + 58f));
modButton.setVisible(true);
modButton.getLabel().setText("Mods...");
modButton.addClickListener(new ClickListener() {
@Override
public void click(UIDisplayElement element, int button) {
UIDialogMods dialog = new UIDialogMods(modConfig);
dialog.open();
}
});
parent.addDisplayElement(inputWorldTitleLabel);
parent.addDisplayElement(inputWorldTitle);
parent.addDisplayElement(inputSeedLabel);
parent.addDisplayElement(inputSeed);
parent.addDisplayElement(chunkGeneratorLabel);
parent.addDisplayElement(chunkGenerator);
parent.addDisplayElement(typeOfGame);
parent.addDisplayElement(typeOfGameLabel);
parent.addDisplayElement(modButton);
parent.layout();
}
@Override
protected void createButtons(UIDisplayContainer parent) {
okButton = new UIButton(new Vector2f(128f, 32f), UIButton.ButtonType.NORMAL);
okButton.getLabel().setText("Play");
okButton.setPosition(new Vector2f(getSize().x / 2 - okButton.getSize().x - 16f, getSize().y - okButton.getSize().y - 10));
okButton.setVisible(true);
okButton.addClickListener(new ClickListener() {
@Override
public void click(UIDisplayElement element, int button) {
Config config = CoreRegistry.get(Config.class);
//validation of the input
if (inputWorldTitle.getText().isEmpty()) {
getGUIManager().showMessage("Error", "Please enter a world name");
return;
} else if ((new File(PathManager.getInstance().getWorldSavePath(inputWorldTitle.getText()), WorldInfo.DEFAULT_FILE_NAME)).exists()) {
getGUIManager().showMessage("Error", "A World with this name already exists");
return;
}
CoreRegistry.put(GameType.class, (GameType) typeOfGame.getSelection().getValue());
//set the world settings
if (inputSeed.getText().length() > 0) {
config.getWorldGeneration().setDefaultSeed(inputSeed.getText());
} else {
FastRandom random = new FastRandom();
config.getWorldGeneration().setDefaultSeed(random.randomCharacterString(32));
}
if (inputWorldTitle.getText().length() > 0) {
config.getWorldGeneration().setWorldTitle(inputWorldTitle.getText());
} else {
config.getWorldGeneration().setWorldTitle(getWorldName());
}
List<String> chunkList = new ArrayList<String>();
switch (chunkGenerator.getSelectionIndex()) {
case 1: //flat
chunkList.add(FlatTerrainGenerator.class.getName());
//if (checkboxFlora == selected) ... (pseudo code)
//chunkList.add(FloraGenerator.class.getName());
chunkList.add(OreGenerator.class.getName());
chunkList.add(LiquidsGenerator.class.getName());
chunkList.add(ForestGenerator.class.getName());
break;
case 2: //multiworld
chunkList.add(MultiTerrainGenerator.class.getName());
//chunkList.add(FloraGenerator.class.getName());
chunkList.add(OreGenerator.class.getName());
chunkList.add(LiquidsGenerator.class.getName());
chunkList.add(ForestGenerator.class.getName());
break;
case 3: //Nym
chunkList.add(BasicHMTerrainGenerator.class.getName());
//chunkList.add(FloraGenerator.class.getName());
chunkList.add(OreGenerator.class.getName());
chunkList.add(LiquidsGenerator.class.getName());
chunkList.add(ForestGenerator.class.getName());
break;
default: //normal
chunkList.add(PerlinTerrainGenerator.class.getName());
//chunkList.add(FloraGenerator.class.getName());
chunkList.add(OreGenerator.class.getName());
chunkList.add(LiquidsGenerator.class.getName());
chunkList.add(ForestGenerator.class.getName());
break;
}
String[] chunksListArr = chunkList.toArray(new String[chunkList.size()]);
CoreRegistry.get(Config.class).getDefaultModSelection().copy(modConfig);
CoreRegistry.get(Config.class).save();
CoreRegistry.get(GameEngine.class).changeState(new StateLoading(new WorldInfo(config.getWorldGeneration().getWorldTitle(), config.getWorldGeneration().getDefaultSeed(), config.getSystem().getDayNightLengthInMs() / 4, chunksListArr, CoreRegistry.get(GameType.class).getClass().toString(), modConfig)));
}
});
cancelButton = new UIButton(new Vector2f(128f, 32f), UIButton.ButtonType.NORMAL);
cancelButton.setPosition(new Vector2f(okButton.getPosition().x + okButton.getSize().x + 16f, okButton.getPosition().y));
cancelButton.getLabel().setText("Cancel");
cancelButton.setVisible(true);
cancelButton.addClickListener(new ClickListener() {
@Override
public void click(UIDisplayElement element, int button) {
close();
}
});
parent.addDisplayElement(okButton);
parent.addDisplayElement(cancelButton);
}
private String getWorldName() {
UIMenuSingleplayer menu = (UIMenuSingleplayer) getGUIManager().getWindowById("singleplayer");
return "World" + (menu.getWorldCount() + 1);
}
}
| apache-2.0 |
PubFlow/Workflow-Provider | src/main/java/de/pfWorkflowWS/restConnection/resourceController/WorkflowServiceController.java | 4510 | /**
* Copyright (C) 2016 Marc Adolf, Arnd Plumhoff
*
* 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 de.pfWorkflowWS.restConnection.resourceController;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import de.pfWorkflowWS.authentication.PubflowJiraRestTemplate;
import de.pfWorkflowWS.restConnection.restMessages.WorkflowReceiveMessage;
import de.pfWorkflowWS.workflow.jbpm.WorkflowJBPMThread;
import de.pfWorkflowWS.workflow.jbpm.availableWorkflows.CVOOJBPMWorkflow;
import de.pfWorkflowWS.workflow.jbpm.availableWorkflows.EPrintsJBPMWorkflow;
import de.pfWorkflowWS.workflow.jbpm.availableWorkflows.JBPMWorkflow;
import de.pfWorkflowWS.workflow.jbpm.availableWorkflows.OCNJBPMWorkflow;
/**
* Accepts the incoming request for new Workflow executions. The incoming
* message is represented by {@link WorkflowReceiveMessage}. Does not wait for
* the result of the Workflow execution.
*
* @author Marc Adolf
*
*/
@RestController
@RequestMapping("/workflow")
public class WorkflowServiceController {
@Autowired
private PubflowJiraRestTemplate oAuthRestTemplate;
@RequestMapping(value = "/OCNWorkflow", method = RequestMethod.POST)
public ResponseEntity<String> executeOCNWorkflow(@RequestBody WorkflowReceiveMessage msg) {
/*
* OCN
*/
return handleJBPMWorkflow(OCNJBPMWorkflow.getInstance(), msg);
}
@RequestMapping(value = "/EPrintsWorkflow", method = RequestMethod.POST)
public ResponseEntity<String> executeEPrintsWorkflow(@RequestBody WorkflowReceiveMessage msg) {
/*
* EPrints
*/
return handleJBPMWorkflow(EPrintsJBPMWorkflow.getInstance(), msg);
}
@RequestMapping(value = "/CVOOWorkflow", method = RequestMethod.POST)
public ResponseEntity<String> executeCVOOWorkflow(@RequestBody WorkflowReceiveMessage msg) {
/*
* CVOO
*/
return handleJBPMWorkflow(CVOOJBPMWorkflow.getInstance(), msg);
}
@RequestMapping(value = "/TestWorkflow", method = RequestMethod.GET)
public void executeTestWorkflow() throws URISyntaxException {
/*
* Test
*/
// WorkflowReceiveMessage msg = new WorkflowReceiveMessage();
// msg.setId("testId");
// msg.setCallbackAddress("http://www.example.de");
System.out.println(this.oAuthRestTemplate.getForObject(new URI("http://riemann:2990/jira/rest/api/latest/issue/PUB-1"), String.class));
}
/*
* Often JBPM Workflows share the same code. This class validates the
* message, initializes the JBPM Workflow with its Knowledgebase and starts
* a new Thread to execute the Workflow. Responses are generated.
* representing the success. Does not wait for the execution to finish.
*/
private ResponseEntity<String> handleJBPMWorkflow(JBPMWorkflow offeredWorkflow, WorkflowReceiveMessage msg) {
Logger myLogger = LoggerFactory.getLogger(getClass());
myLogger.debug("Message id: " + msg.getId());
myLogger.debug("Message Callback Address:" + msg.getCallbackAddress());
myLogger.debug("Message is valid?: " + msg.isValid());
if (!msg.isValid()) {
return new ResponseEntity<String>(
"Message is not valid: it needs an id and a field for the callbackAddress", HttpStatus.BAD_REQUEST);
}
try {
offeredWorkflow.init();
WorkflowJBPMThread worker = new WorkflowJBPMThread(msg, offeredWorkflow);
worker.start();
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<String>("Workflow could not be loaded", HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<String>("received", HttpStatus.ACCEPTED);
}
}
| apache-2.0 |
davidsoergel/dsutils | src/main/java/com/davidsoergel/dsutils/range/EnumSetRange.java | 1514 | /*
* Copyright (c) 2001-2013 David Soergel <dev@davidsoergel.com>
* Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
package com.davidsoergel.dsutils.range;
import com.davidsoergel.dsutils.EnumValue;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.HashSet;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* @version $Id: BooleanSetRange.java 690 2009-07-31 21:17:50Z soergel $
*/
public class EnumSetRange extends AbstractSetRange<EnumValue>
{
/* public EnumSetRange(final Collection<EnumValue> values)
{
super(values);
}*/
// for Hessian
protected EnumSetRange()
{
}
public EnumSetRange(@NotNull final Collection enumValues)
{
super(new HashSet<EnumValue>());
for (@NotNull Object s : enumValues)
{
if (s instanceof String)
{
values.add(new EnumValue((String) s));
}
else if (s instanceof EnumValue)
{
values.add((EnumValue) s);
}
else
{
throw new RangeRuntimeException(
"EnumSetRange must be initialized with EnumValues or Strings, not " + s.getClass());
}
}
}
@NotNull
protected EnumSetRange create(@NotNull final Collection<EnumValue> values)
{
return new EnumSetRange(values);
}
@NotNull
public SortedSet<String> getStringValues()
{
@NotNull SortedSet<String> result = new TreeSet<String>();
for (@NotNull EnumValue value : values)
{
result.add(value.toString());
}
return result;
}
}
| apache-2.0 |