List of usage examples for org.apache.commons.lang ArrayUtils contains
public static boolean contains(boolean[] array, boolean valueToFind)
Checks if the value is in the given array.
From source file:gda.device.enumpositioner.EpicsSimpleBinary.java
@Override public String checkPositionValid(Object position) { if (!(position instanceof String) && !(position instanceof PyString)) { return "position not a string"; }//ww w . jav a 2 s . c o m if (!ArrayUtils.contains(positions, position)) { return position.toString() + "not in array of acceptable strings"; } return null; }
From source file:com.blockwithme.hacktors.Chunk.java
/** Adds an item, using local coordinates. */ public void addItemLocal(final int x, final int y, final Item item) { if (item == null) { throw new IllegalArgumentException("item is null"); }//from ww w. j ava 2 s . co m final int index = index(x, y); if (!ArrayUtils.contains(items[index], item)) { items[index] = (Item[]) ArrayUtils.add(items[index], item); } }
From source file:gov.nih.nci.caarray.magetab.idf.IdfDocument.java
private void handleLine(List<String> lineContents, boolean processingTermSources) { if (!isEmpty(lineContents)) { EntryHeading heading = createHeading(lineContents.get(0)); IdfRow idfRow = new IdfRow(heading, IdfRowType.get(heading.getTypeName())); if (ArrayUtils.contains(IdfRowType.TERM_SOURCE_TYPES, idfRow.getType()) != processingTermSources) { return; }/*from w w w . j a v a 2 s .co m*/ validateColumnValues(idfRow, lineContents); for (int columnIndex = 1; columnIndex < lineContents.size(); columnIndex++) { currentColumnNumber = columnIndex + 1; int valueIndex = columnIndex - 1; String value = StringUtils.trim(lineContents.get(columnIndex)); if (!StringUtils.isEmpty(value)) { value = NCICommonsUtils.performXSSFilter(value, true, true); handleValue(idfRow, value, valueIndex); } } } }
From source file:gov.nih.nci.cabig.caaers.service.workflow.WorkflowServiceImpl.java
/** * This method, return the list of possible transitions available at a given time on a specific workflow process instance */// w ww . j a v a 2 s . c o m public List<Transition> nextTransitions(Integer workflowId, String loginId) { ProcessInstance processInstance = fetchProcessInstance(workflowId.longValue()); String workflowDefinitionName = processInstance.getProcessDefinition().getName(); WorkflowConfig wfConfig = workflowConfigDao.getByWorkflowDefinitionName(workflowDefinitionName); List<Transition> possibleTransitions = possibleTransitionsResolver.fetchNextTransitions(wfConfig, processInstance); //now filter based on login roles String taskNodeName = processInstance.getRootToken().getNode().getName(); TaskConfig taskConfig = wfConfig.findTaskConfig(taskNodeName); if (taskConfig == null) return possibleTransitions; // task is not configured List<UserGroupType> userGroupTypes = userRepository.getUserByLoginName(loginId).getUserGroupTypes(); //CAAERS-4586 Map<String, Transition> filteredTransitionMap = new HashMap<String, Transition>(); for (Transition transition : possibleTransitions) { TransitionConfig transitionConfig = taskConfig.findTransitionConfig(transition.getName()); if (transitionConfig == null) continue; //transition is not configured so no body can move it expect sysadmin List<TransitionOwner> owners = transitionConfig.getOwners(); if (owners == null) continue; //no body owns the transition for (TransitionOwner owner : owners) { if (owner.isPerson()) { PersonTransitionOwner personOwner = (PersonTransitionOwner) owner; if (StringUtils.equals(personOwner.getPerson().getLoginId(), loginId)) { if (!filteredTransitionMap.containsKey(transition.getName())) { filteredTransitionMap.put(transition.getName(), transition); } } } else { RoleTransitionOwner roleOwner = (RoleTransitionOwner) owner; PersonRole ownerRole = roleOwner.getUserRole(); UserGroupType[] ownerGroupTypes = ownerRole.getUserGroups(); for (UserGroupType userGroupType : userGroupTypes) { if (ArrayUtils.contains(ownerGroupTypes, userGroupType)) { if (!filteredTransitionMap.containsKey(transition.getName())) { filteredTransitionMap.put(transition.getName(), transition); } break; } } } } } return new ArrayList<Transition>(filteredTransitionMap.values()); }
From source file:net.sourceforge.atunes.kernel.modules.player.PlayerHandler.java
/** * Gets the single instance of PlayerHandler. This method returns player * engine configured by user or default if it's available on the system * /* w ww . j a va2s.com*/ * @return single instance of PlayerHandler */ public static final synchronized PlayerHandler getInstance() { if (instance == null) { instance = new PlayerHandler(); // Get engines list List<PlayerEngine> engines = getEngines(); // Remove unsupported engines Iterator<PlayerEngine> it = engines.iterator(); while (it.hasNext()) { if (!it.next().isEngineAvailable()) { it.remove(); } } // Update engine names engineNames = new String[engines.size()]; for (int i = 0; i < engines.size(); i++) { engineNames[i] = engines.get(i).getEngineName(); } Arrays.sort(engineNames); getLogger().info(LogCategories.PLAYER, "List of availables engines : " + ArrayUtils.toString(engineNames)); if (engines.isEmpty()) { handlePlayerError(new IllegalStateException(LanguageTool.getString("NO_PLAYER_ENGINE"))); } else { // Get engine of application state (default or selected by user) String selectedEngine = ApplicationState.getInstance().getPlayerEngine(); // If selected engine is not available then try default engine or another one if (!ArrayUtils.contains(engineNames, selectedEngine)) { getLogger().info(LogCategories.PLAYER, selectedEngine + " is not availaible"); if (ArrayUtils.contains(engineNames, DEFAULT_ENGINE)) { selectedEngine = DEFAULT_ENGINE; } else { // If default engine is not available, then get the first engine of map returned selectedEngine = engines.iterator().next().getEngineName(); } // Update application state with this engine ApplicationState.getInstance().setPlayerEngine(selectedEngine); } for (PlayerEngine engine : engines) { if (engine.getEngineName().equals(selectedEngine)) { instance.playerEngine = engine; getLogger().info(LogCategories.PLAYER, "Engine initialized : " + selectedEngine); } } if (instance.playerEngine == null) { handlePlayerError(new IllegalStateException(LanguageTool.getString("NO_PLAYER_ENGINE"))); } // Init engine instance.playerEngine.initializePlayerEngine(); Kernel.getInstance().addFinishListener(instance); // Add core playback listeners instance.playerEngine.addPlaybackStateListener(instance.playerEngine); instance.playerEngine.addPlaybackStateListener(VisualHandler.getInstance()); instance.playerEngine.addPlaybackStateListener(NotifyHandler.getInstance()); } // Add a shutdown hook to perform some actions before killing the JVM Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { getLogger().debug(LogCategories.SHUTDOWN_HOOK, "Final check for Zombie player engines"); instance.playerEngine.killPlayer(); getLogger().debug(LogCategories.SHUTDOWN_HOOK, "Closing player ..."); } })); } return instance; }
From source file:com.atolcd.pentaho.di.trans.steps.gisgeoprocessing.GisGeoprocessing.java
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (GisGeoprocessingMeta) smi;/* w ww . j a v a2s . c o m*/ data = (GisGeoprocessingData) sdi; Geometry geoprocessingResult; Object[] r = getRow(); if (r == null) { setOutputDone(); return false; } if (first) { first = false; data.outputRowMeta = (RowMetaInterface) getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); operator = meta.getOperator(); returnType = meta.getReturnType(); // Rcupration des indexes des colonnes contenant les gomrtries // d'entre firstGeometryFieldIndex = getInputRowMeta().indexOfValue(meta.getFirstGeometryFieldName()); // Besoin de 2 gomtries if (ArrayUtils.contains(meta.getTwoGeometriesOperators(), operator)) { withSecondGeometry = true; secondGeometryFieldIndex = getInputRowMeta().indexOfValue(meta.getSecondGeometryFieldName()); } else { withSecondGeometry = false; } // Posibilits d'extraction de gomtries if (ArrayUtils.contains(meta.getWithExtractTypeOperators(), operator)) { withExtractType = true; extractType = meta.getExtractType(); } else { withExtractType = false; } // Besoin de distance if (ArrayUtils.contains(meta.getWithDistanceOperators(), operator)) { withDistance = true; if (meta.isDynamicDistance()) { distanceFieldIndex = getInputRowMeta().indexOfValue(meta.getDistanceFieldName()); } else { try { distanceValue = Double.parseDouble(environmentSubstitute(meta.getDistanceValue())); } catch (Exception e) { throw new KettleException("Distance is not valid"); } } } else { withDistance = false; } // Rcupration de l'index de la colonne contenant le rsultat outputFieldIndex = data.outputRowMeta.indexOfValue(meta.getOutputFieldName()); // Exploser les gomtries; if (operator.equalsIgnoreCase("EXPLODE")) { withExplode = true; } else { withExplode = false; } // Si buffer tendu if (operator.equalsIgnoreCase("EXTENDED_BUFFER")) { bufferSegmentsCount = meta.getBufferSegmentsCount(); bufferCapStyle = meta.getBufferCapStyle(); bufferJoinStyle = meta.getBufferJoinStyle(); bufferSingleSide = meta.getBufferSingleSide(); } else { bufferSegmentsCount = null; bufferCapStyle = null; bufferJoinStyle = null; bufferSingleSide = null; } logBasic("Initialized successfully"); } Object[] currenRow = RowDataUtil.resizeArray(r, r.length + 1); geoprocessingResult = getGeoprocessingResult(r); Geometry[] resultGeometries = null; if (withExplode && geoprocessingResult != null) { int numGeometries = geoprocessingResult.getNumGeometries(); resultGeometries = new Geometry[numGeometries]; for (int i = 0; i < numGeometries; i++) { Geometry subGeometry = GeometryUtils.getNonEmptyGeometry(geoprocessingResult.getSRID(), geoprocessingResult.getGeometryN(i)); if (subGeometry instanceof LinearRing) { int srid = subGeometry.getSRID(); subGeometry = geometryFactory.createLineString(subGeometry.getCoordinates()); subGeometry.setSRID(srid); } resultGeometries[i] = subGeometry; } } else { resultGeometries = new Geometry[] { geoprocessingResult }; } for (Geometry resultGeometry : resultGeometries) { Object[] outputRow = currenRow.clone(); if (withExtractType && !GeometryUtils.isNullOrEmptyGeometry(resultGeometry)) { if (extractType.equalsIgnoreCase("PUNTAL_ONLY")) { resultGeometry = GeometryUtils.getGeometryFromType(resultGeometry, Puntal.class); } else if (extractType.equalsIgnoreCase("LINEAL_ONLY")) { resultGeometry = GeometryUtils.getGeometryFromType(resultGeometry, Lineal.class); } else if (extractType.equalsIgnoreCase("POLYGONAL_ONLY")) { resultGeometry = GeometryUtils.getGeometryFromType(resultGeometry, Polygonal.class); } } if (returnType.equalsIgnoreCase("ALL")) { outputRow[outputFieldIndex] = resultGeometry; putRow(data.outputRowMeta, outputRow); } else if (returnType.equalsIgnoreCase("NOT_NULL")) { if (!GeometryUtils.isNullOrEmptyGeometry(resultGeometry)) { outputRow[outputFieldIndex] = resultGeometry; putRow(data.outputRowMeta, outputRow); } } } incrementLinesInput(); if (checkFeedback(getLinesRead())) { logBasic("Linenr " + getLinesRead()); } return true; }
From source file:com.pureinfo.srm.reports.table.MyTabeleDataHelper.java
public static Map getRowMap(Class[] _contentClass, String[] _alias, String[] _sToCalculate, SQLCondition _condition, String _sGroupProp, String[] _caredValues) throws PureException { IContentMgr mgr = ArkContentHelper.getContentMgrOf(_contentClass[0]); List params = new ArrayList(); IObjects datas = null;//from w ww .jav a2 s.c o m IStatement query = null; Map row = null; if (_sToCalculate == null) _sToCalculate = new String[] { "count( {this.*} )" }; try { String sCondion = ""; if (_condition != null) sCondion = _condition.toSQL(params); String strSQL = "SELECT "; for (int i = 0; i < _sToCalculate.length; i++) { strSQL += (_sToCalculate[i] + " AS _RESULT" + i + ','); } strSQL += " {this." + _sGroupProp + "} FROM {this}"; for (int i = 1; i < _alias.length; i++) { strSQL += (",{" + _alias[i] + '}'); } strSQL += (sCondion == null || sCondion.trim().length() < 1 ? "" : " WHERE ") + sCondion + " GROUP BY {this." + _sGroupProp + '}'; query = mgr.createQuery(strSQL, 0); for (int i = 1; i < _contentClass.length; i++) { query.registerAlias(_alias[i], _contentClass[i]); } if (!params.isEmpty()) { query.setParameters(0, params); } datas = query.executeQuery(); row = new HashMap(datas.getSize()); do { DolphinObject data = datas.next(); if (data == null) { break; } Object[] result = new Object[_sToCalculate.length]; for (int i = 0; i < result.length; i++) { result[i] = data.getProperty("_RESULT" + i); } row.put(data.getProperty(_sGroupProp), result); } while (true); } finally { params.clear(); DolphinHelper.clear(datas, query); } double[] caredTotal = new double[_sToCalculate.length]; double[] total = new double[_sToCalculate.length]; for (Iterator iter = row.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String sName = (String) entry.getKey(); Object[] num = (Object[]) entry.getValue(); for (int i = 0; i < num.length; i++) { if (num[i] instanceof Number) { if (_caredValues != null) { if (ArrayUtils.contains(_caredValues, sName)) { caredTotal[i] += ((Number) num[i]).doubleValue(); } } caredTotal[i] += ((Number) num[i]).doubleValue(); } } } Object[] oOther = new Object[_sToCalculate.length]; Object[] oTotal = new Object[_sToCalculate.length]; for (int i = 0; i < total.length; i++) { oTotal[i] = new Double(total[i]); oOther[i] = new Double(total[i] - caredTotal[i]); } row.put(OTHER, oOther); row.put(TOTAL, oTotal); return row; }
From source file:edu.cornell.med.icb.clustering.TestQTClusterer.java
@Test public void zeroDistanceCalculator() { final Clusterer clusterer = new QTClusterer(4); final SimilarityDistanceCalculator distanceCalculator = new MaxLinkageDistanceCalculator() { public double distance(final int i, final int j) { return 0; // instances 0-3 belong to the same cluster }//from w ww. j a va 2s.co m }; final List<int[]> clusters = clusterer.cluster(distanceCalculator, 2); assertNotNull(clusters); assertEquals("Expected one cluster", 1, clusters.size()); final int[] cluster = clusters.get(0); assertEquals("First cluster must have size 4", 4, cluster.length); assertTrue("Instance 0 in cluster 0", ArrayUtils.contains(cluster, 0)); assertTrue("Instance 1 in cluster 0", ArrayUtils.contains(cluster, 1)); assertTrue("Instance 2 in cluster 0", ArrayUtils.contains(cluster, 2)); assertTrue("Instance 3 in cluster 0", ArrayUtils.contains(cluster, 3)); }
From source file:eu.dime.ps.dto.Resource.java
protected void addToMap(org.ontoware.rdfreactor.schema.rdfs.Resource resource, Map<URI, String> renamingRules, URI me) {//from www .j a v a 2s .c om this.put("guid", resource.asURI().toString()); ClosableIterator<Statement> it = resource.getModel().findStatements(resource.asResource(), Variable.ANY, Variable.ANY); while (it.hasNext()) { Statement statement = it.next(); URI predicate = statement.getPredicate(); Node object = statement.getObject(); if (ArrayUtils.contains(PROPERTIES_TO_FILTER, predicate)) { continue; } // HACK FOR PoC: the UI expects an attribute 'type' in the JSON // mapped to person, group, etc. // this need to be mapped to rdf:type and the proper URI for the // instance - now hard coded // person|group|livestream|livestreamitem|databox|resource|profile|notification|serviceaccount|situation if (predicate.equals(RDF.type)) { URI type = object.asURI(); if (type.equals(PIMO.Person)) { this.put("type", "person"); } else if (type.equals(PIMO.PersonGroup)) { this.put("type", "group"); } else if (type.equals(NCO.Contact)) { this.put("type", "profile"); } else if (type.equals(DLPO.LivePost)) { this.put("type", "livepost"); } else if (type.equals(DAO.Account)) { this.put("type", "account"); } else if (type.equals(NFO.FileDataObject)) { this.put("type", "resource"); } else if (type.equals(DCON.Situation)) { this.put("type", "situation"); } else if (type.equals(PPO.PrivacyPreference)) { if (resource.getModel().contains(resource.asURI(), RDFS.label, new PlainLiteralImpl("DATABOX"))) { this.put("type", "databox"); } else if (resource.getModel().contains(resource.asURI(), RDFS.label, new PlainLiteralImpl("PROFILECARD"))) { this.put("type", "profile"); } } else if (type.equals(PIMO.SocialEvent)) { this.put("type", "event"); } else if (type.equals(NFO.DataContainer)) { this.put("type", "databox"); } // the rest of the loop is how it should be after PoC continue; } // ------- Object value = null; if (object instanceof DatatypeLiteral) { DatatypeLiteral literal = object.asDatatypeLiteral(); URI type = literal.getDatatype(); if (type.equals(XSD._double) || type.equals(XSD._float) || type.equals(XSD._decimal)) { String number = literal.getValue(); if (number.contains("E")) { // scientific notation value = DECIMAL_FORMAT.format(literal.getValue()); } else { // standard form value = Double.parseDouble(number); } } else if (type.equals(XSD._long) || type.equals(XSD._integer) || type.equals(XSD._int)) { value = Long.parseLong(literal.getValue()); } else { value = literal.getValue(); } } else if (object instanceof Literal) { value = object.asLiteral().getValue(); } else if (object instanceof URI) { URI oUri = object.asURI(); if (renamingRules.containsKey(oUri)) { value = renamingRules.get(oUri); } else { value = collapse(object.asURI().toString()); } } else { // discards blank nodes... continue; } if (ArrayUtils.contains(DATETIME_PROPERTIES, predicate)) { value = new DateTime((String) value).getMillis(); } String key = null; if (renamingRules.containsKey(predicate)) { key = renamingRules.get(predicate); if (key.equals("defProfile") && !value.toString().startsWith("p_")) value = "p_" + value; } else { key = collapse(predicate.toString()); } if (ArrayUtils.contains(DATETIME_PROPERTIES, predicate)) { // datetime properties seem to be unique, so all // are discarded but one. this.put(key, value); } else if (this.containsKey(key)) { Object v = this.get(key); List<Object> values; if (v instanceof List) { values = (List<Object>) v; } else { values = new LinkedList<Object>(); values.add(v); } values.add(value); this.put(key, values); } else { this.put(key, value); } } it.close(); //set userId setUserId(resource, me.toString()); // ensure always 'name' and 'imageUrl' is returned if (!this.containsKey("name")) { this.put("name", this.get("type")); } if (!this.containsKey("imageUrl")) { this.put("imageUrl", ""); } // ensure always 'items' is an array if (this.containsKey("items")) { Object o = this.get("items"); if (!(o instanceof List)) { List<Object> items = new LinkedList<Object>(); items.add(o); this.put("items", items); } } else { List<Object> items = new LinkedList<Object>(); this.put("items", items); } // inject 'downloadUrl' for files if (resource instanceof FileDataObject) { if (said == null) { logger.warn("'downloadUrl' could not be generated, a 'said' must be passed."); } else { // a shared file Node shared = ModelUtils.findObject(resource.getModel(), resource, NSO.sharedBy); if (shared != null) { //get the account fom the NSO.sharedWith Node account = ModelUtils.findObject(resource.getModel(), resource, NSO.sharedWith); if (account != null) { this.put("downloadUrl", "/dime-communications/api/dime/rest/" + said + "/resource/@me/shared/" + shared.asURI().toString() + "/" + account.asURI().toString() + "/" + resource.asURI().toString()); } else { logger.warn( "'downloadUrl' could not be generated, there was no nso.sharedWith associated to the file"); } } //a file from the CMS else { String guid = UriUtil.decodeUri(resource.asURI().toString()); String encodedGuid; try { encodedGuid = URLEncoder.encode(guid, "UTF-8"); this.put("downloadUrl", "/dime-communications/api/dime/rest/" + said + "/resource/filemanager/" + encodedGuid); } catch (UnsupportedEncodingException e) { logger.warn("'downloadUrl' could not be generated well 'said' is wrong."); } } } //TODO add the url from files not shared that are not in the CMS } }
From source file:com.linkedin.pinot.core.predicate.NoDictionaryEqualsPredicateEvaluatorsTest.java
@Test public void testDoublePredicateEvaluators() { double doubleValue = _random.nextDouble(); EqPredicate eqPredicate = new EqPredicate(COLUMN_NAME, Collections.singletonList(Double.toString(doubleValue))); PredicateEvaluator eqPredicateEvaluator = EqualsPredicateEvaluatorFactory .newNoDictionaryBasedEvaluator(eqPredicate, FieldSpec.DataType.DOUBLE); NEqPredicate neqPredicate = new NEqPredicate(COLUMN_NAME, Collections.singletonList(Double.toString(doubleValue))); PredicateEvaluator neqPredicateEvaluator = NotEqualsPredicateEvaluatorFactory .newNoDictionaryBasedEvaluator(neqPredicate, FieldSpec.DataType.DOUBLE); Assert.assertTrue(eqPredicateEvaluator.apply(doubleValue)); Assert.assertFalse(neqPredicateEvaluator.apply(doubleValue)); double[] randomDoubles = new double[NUM_MULTI_VALUES]; PredicateEvaluatorTestUtils.fillRandom(randomDoubles); randomDoubles[_random.nextInt(randomDoubles.length)] = doubleValue; Assert.assertTrue(eqPredicateEvaluator.apply(randomDoubles)); Assert.assertFalse(neqPredicateEvaluator.apply(randomDoubles)); for (int i = 0; i < 100; i++) { double random = _random.nextDouble(); Assert.assertEquals(eqPredicateEvaluator.apply(random), (random == doubleValue)); Assert.assertEquals(neqPredicateEvaluator.apply(random), (random != doubleValue)); PredicateEvaluatorTestUtils.fillRandom(randomDoubles); Assert.assertEquals(eqPredicateEvaluator.apply(randomDoubles), ArrayUtils.contains(randomDoubles, doubleValue)); Assert.assertEquals(neqPredicateEvaluator.apply(randomDoubles), !ArrayUtils.contains(randomDoubles, doubleValue)); }/*from w w w.ja v a 2 s. c o m*/ }