List of usage examples for org.apache.commons.lang ArrayUtils indexOf
public static int indexOf(boolean[] array, boolean valueToFind)
Finds the index of the given value in the array.
From source file:fr.inria.atlanmod.neoemf.graph.blueprints.datastore.estores.impl.DirectWriteBlueprintsResourceEStoreImpl.java
@Override public int indexOf(InternalEObject object, EStructuralFeature feature, Object value) { if (feature instanceof EAttribute) { return ArrayUtils.indexOf(toArray(object, feature), value); } else if (feature instanceof EReference) { if (value == null) { return ArrayUtils.INDEX_NOT_FOUND; }//w w w . ja va 2s .c o m Vertex inVertex = graph.getVertex(object); Vertex outVertex = graph.getVertex((EObject) value); Iterator<Edge> iterator = outVertex.getEdges(Direction.IN, feature.getName()).iterator(); while (iterator.hasNext()) { Edge e = iterator.next(); if (e.getVertex(Direction.OUT).equals(inVertex)) { return e.getProperty(POSITION); } } return ArrayUtils.INDEX_NOT_FOUND; } else { throw new IllegalArgumentException(feature.toString()); } }
From source file:gda.util.exafs.Element.java
/** * Checks whether a particular edge exists or not * //from ww w .j av a 2 s . co m * @param edgeName * the selected edge * @return true if edge exists, false if it does not */ private boolean edgeExists(String edgeName) { int index = ArrayUtils.indexOf(edgeNames, edgeName); if (index >= 0) { return edgeExists(index); } return false; }
From source file:fr.inria.atlanmod.neoemf.datastore.estores.impl.ReadOnlyHbaseResourceEStoreImpl.java
@Override public int indexOf(InternalEObject object, EStructuralFeature feature, Object value) { NeoEMFEObject neoEMFEObject = NeoEMFEObjectAdapterFactoryImpl.getAdapter(object, NeoEMFEObject.class); String[] array = (String[]) getFromTableIfNotExisting(neoEMFEObject, feature); if (array == null) { return -1; }/* w w w. j a v a 2s. c o m*/ if (feature instanceof EAttribute) { return ArrayUtils.indexOf(array, serializeValue((EAttribute) feature, value)); } else { NeoEMFEObject childEObject = NeoEMFEObjectAdapterFactoryImpl.getAdapter(value, NeoEMFEObject.class); return ArrayUtils.indexOf(array, childEObject.neoemfId()); } }
From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java
private void collectXmlNodeInfo(XmlNodeInfo xmlNodeInfo, Class<?> type) { XmlNode xmlNode = type.getAnnotation(XmlNode.class); if (xmlNode == null || ArrayUtils.indexOf(type.getDeclaredAnnotations(), xmlNode) < 0) { return;// ww w .ja v a2 s . c om } xmlNodeInfo.addSourceType(type); if (StringUtils.isNotEmpty(xmlNode.nodeName())) { xmlNodeInfo.setNodeName(xmlNode.nodeName()); } if (StringUtils.isNotEmpty(xmlNode.label())) { xmlNodeInfo.setLabel(xmlNode.label()); } if (StringUtils.isNotEmpty(xmlNode.icon())) { xmlNodeInfo.setIcon(xmlNode.icon()); } if (StringUtils.isNotEmpty(xmlNode.definitionType())) { xmlNodeInfo.setDefinitionType(xmlNode.definitionType()); } for (String implType : xmlNode.implTypes()) { if (StringUtils.isNotEmpty(implType)) { xmlNodeInfo.getImplTypes().add(implType); } } if (!xmlNodeInfo.isScopable() && xmlNode.scopable()) { xmlNodeInfo.setScopable(true); } if (!xmlNodeInfo.isInheritable() && xmlNode.inheritable()) { xmlNodeInfo.setInheritable(true); } if (!xmlNode.isPublic()) { xmlNodeInfo.setScope("protected"); } int[] clientTypes = xmlNode.clientTypes(); if (clientTypes != null) { if (clientTypes.length > 0) { xmlNodeInfo.setClientTypes(clientTypes); } } if (!xmlNodeInfo.isDeprecated() && xmlNode.deprecated()) { xmlNodeInfo.setDeprecated(true); } if (StringUtils.isNotEmpty(xmlNode.fixedProperties())) { Map<String, String> fixedProperties = xmlNodeInfo.getFixedProperties(); for (String fixedProperty : StringUtils.split(xmlNode.fixedProperties(), ",;")) { int i = fixedProperty.indexOf('='); if (i > 0) { String property = fixedProperty.substring(0, i); fixedProperties.put(property, fixedProperty.substring(i + 1)); } } } Map<String, XmlProperty> properties = xmlNodeInfo.getProperties(); XmlProperty[] annotationProperties = xmlNode.properties(); boolean hasPropertyAnnotation = false; if (annotationProperties.length == 1) { XmlProperty xmlProperty = annotationProperties[0]; hasPropertyAnnotation = StringUtils.isNotEmpty(xmlProperty.propertyName()) || StringUtils.isNotEmpty(xmlProperty.propertyType()) || StringUtils.isNotEmpty(xmlProperty.parser()); } else if (annotationProperties.length > 1) { hasPropertyAnnotation = true; } if (hasPropertyAnnotation) { for (XmlProperty xmlProperty : annotationProperties) { if (StringUtils.isEmpty(xmlProperty.propertyName())) { throw new IllegalArgumentException( "@XmlProperty.propertyName undefined. [" + type.getName() + "]"); } for (String property : StringUtils.split(xmlProperty.propertyName(), ",;")) { properties.put(property, xmlProperty); } } } Set<XmlSubNode> subNodes = xmlNodeInfo.getSubNodes(); XmlSubNode[] annotationSubNodes = xmlNode.subNodes(); boolean hasSubNodeAnnotation = (annotationSubNodes.length > 0); if (annotationSubNodes.length == 1) { XmlSubNode xmlSubNode = annotationSubNodes[0]; hasSubNodeAnnotation = StringUtils.isNotEmpty(xmlSubNode.propertyName()) || StringUtils.isNotEmpty(xmlSubNode.nodeName()) || StringUtils.isNotEmpty(xmlSubNode.propertyType()); } if (hasSubNodeAnnotation) { for (XmlSubNode xmlSubNode : annotationSubNodes) { if (!(StringUtils.isNotEmpty(xmlSubNode.propertyType()) || (StringUtils.isNotEmpty(xmlSubNode.nodeName()) && StringUtils.isNotEmpty(xmlSubNode.parser())))) { throw new IllegalArgumentException( "Neither @XmlSubNode.propertyType nor @XmlSubNode.nodeName/@XmlSubNode.parser undefined. [" + type.getName() + "]"); } subNodes.add(xmlSubNode); } } }
From source file:gda.util.exafs.Element.java
/** * Gets the energy of the given edge in eV * // w ww . j av a 2 s .c o m * @param edgeName * the edge ("K", "L1" etc) * @return energy value */ public double getEdgeEnergy(String edgeName) { int index = ArrayUtils.indexOf(edgeNames, edgeName); if (index >= 0) { return getEdgeEnergy(index); } return Double.NaN; }
From source file:com.flexive.faces.javascript.yui.YahooResultProvider.java
/** * Renders the response schema needed for the YUI datatable. * * @param result the result to be written * @param writer the JSON output writer * @param firstColumn the first column to be included (1-based) * @throws java.io.IOException on output errors *//* w w w . j a va 2s . co m*/ private static void createResponseSchema(FxResultSet result, JsonWriter writer, int firstColumn) throws IOException { writer.startAttribute("responseSchema"); writer.startMap(); writer.startAttribute("fields"); writer.startArray(); final FxEnvironment environment = CacheAdmin.getEnvironment(); for (int i = firstColumn; i <= result.getColumnCount(); i++) { writer.startMap(); writer.writeAttribute("key", getColumnKey(result, i)); String parser = "string"; // the YUI data parser used for sorting boolean funref = false; // is parser a direct function reference? final String columnName = result.getColumnName(i); try { if ("@pk".equals(columnName)) { // PKs get rendered as <id>.<version> parser = "number"; } else { // set parser according to property type final FxProperty property = environment.getProperty(columnName); final Class valueClass = property.getEmptyValue().getValueClass(); if (Number.class.isAssignableFrom(valueClass) && ArrayUtils.indexOf(RESOLVED_SYSTEM_PROPS, columnName) == -1) { parser = "number"; } } } catch (FxRuntimeException e) { // property not found, use default if (LOG.isDebugEnabled()) { LOG.debug("Property '" + columnName + " not found (ignored): " + e.getMessage(), e); } } writer.writeAttribute("parser", parser, !funref); writer.closeMap(); } // include primary key in attribute pk, if available if (result.getColumnIndex("@pk") != -1) { writeSchemaColumn(writer, "pk"); } if (result.getColumnIndex("@permissions") != -1) { writeSchemaColumn(writer, "permissions"); } if (result.getColumnIndex("typedef") != -1) { writeSchemaColumn(writer, "hasBinary"); } if (result.getColumnIndex("@lock") != -1) { writeSchemaColumn(writer, "locked"); writeSchemaColumn(writer, "lockedBy"); writeSchemaColumn(writer, "lockType"); writeSchemaColumn(writer, "mayLock"); writeSchemaColumn(writer, "mayUnlock"); } writer.closeArray(); writer.closeMap(); }
From source file:com.opengamma.integration.coppclark.CoppClarkHolidayFileReader.java
private void parseCurrencyFile() throws IOException { System.out.println("Parse currencies"); Map<String, HolidayDocument> combinedMap = new HashMap<String, HolidayDocument>(512); for (InputStream stream : getCurrencyStreams()) { Map<String, HolidayDocument> fileMap = new HashMap<String, HolidayDocument>(512); @SuppressWarnings("resource") CSVReader reader = new CSVReader(new InputStreamReader(new BufferedInputStream(stream))); // header String[] row = reader.readNext(); final int ccIdx = ArrayUtils.indexOf(row, "CenterID"); final int isoCountryIdx = ArrayUtils.indexOf(row, "ISOCountryCode"); final int isoCurrencyIdx = ArrayUtils.indexOf(row, "ISOCurrencyCode"); final int eventDateIdx = ArrayUtils.indexOf(row, "EventDate"); // data// w ww. j av a 2s . co m while ((row = reader.readNext()) != null) { String ccId = row[ccIdx].trim(); String countryISO = row[isoCountryIdx].trim(); String currencyISO = row[isoCurrencyIdx].trim(); Currency currency = Currency.of(currencyISO); // validates format String eventDateStr = row[eventDateIdx]; LocalDate eventDate = LocalDate.parse(eventDateStr, DATE_FORMAT); HolidayDocument doc = fileMap.get(ccId); if (doc == null) { currency = fixEuro(currency, countryISO); doc = new HolidayDocument(new ManageableHoliday(currency, EMPTY_DATE_LIST)); doc.setProviderId(ExternalId.of(COPP_CLARK_SCHEME, ccId)); fileMap.put(ccId, doc); } doc.getHoliday().getHolidayDates().add(eventDate); } merge(combinedMap, fileMap); } mergeWithDatabase(combinedMap); }
From source file:com.kalessil.phpStorm.phpInspectionsEA.inspectors.forEach.DisconnectedForeachInstructionInspector.java
@Override @NotNull/*from www . j a v a2 s .c o m*/ public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) { return new BasePhpElementVisitor() { @Override public void visitPhpForeach(@NotNull ForeachStatement foreach) { final GroupStatement foreachBody = ExpressionSemanticUtil.getGroupStatement(foreach); /* ensure foreach structure is ready for inspection */ if (foreachBody != null) { final PsiElement[] statements = foreachBody.getChildren(); if (statements.length > 0 && Stream.of(statements).anyMatch(s -> OpenapiTypesUtil.is(s, PhpElementTypes.HTML))) { return; } /* pre-collect introduced and internally used variables */ final Set<String> allModifiedVariables = this.collectCurrentAndOuterLoopVariables(foreach); final Map<PsiElement, Set<String>> instructionDependencies = new HashMap<>(); /* iteration 1 - investigate what are dependencies and influence */ for (final PsiElement oneInstruction : statements) { if (oneInstruction instanceof PhpPsiElement && !(oneInstruction instanceof PsiComment)) { final Set<String> individualDependencies = new HashSet<>(); instructionDependencies.put(oneInstruction, individualDependencies); investigateInfluence((PhpPsiElement) oneInstruction, individualDependencies, allModifiedVariables); } } /* iteration 2 - analyse dependencies */ for (final PsiElement oneInstruction : statements) { if (oneInstruction instanceof PhpPsiElement && !(oneInstruction instanceof PsiComment)) { boolean isDependOnModified = false; /* check if any dependency is overridden */ final Set<String> individualDependencies = instructionDependencies.get(oneInstruction); if (individualDependencies != null && !individualDependencies.isEmpty()) { isDependOnModified = individualDependencies.stream() .anyMatch(allModifiedVariables::contains); individualDependencies.clear(); } /* verify and report if violation detected */ if (!isDependOnModified) { final ExpressionType target = getExpressionType(oneInstruction); if (ExpressionType.NEW != target && ExpressionType.ASSIGNMENT != target && ExpressionType.CLONE != target && ExpressionType.INCREMENT != target && ExpressionType.DECREMENT != target && ExpressionType.DOM_ELEMENT_CREATE != target && ExpressionType.ACCUMULATE_IN_ARRAY != target && ExpressionType.CONTROL_STATEMENTS != target) { /* loops, ifs, switches, try's needs to be reported on keyword, others - complete */ final PsiElement reportingTarget = oneInstruction instanceof ControlStatement || oneInstruction instanceof Try || oneInstruction instanceof PhpSwitch ? oneInstruction.getFirstChild() : oneInstruction; /* secure exceptions with '<?= ?>' constructions, false-positives with html */ if (!OpenapiTypesUtil.isPhpExpressionImpl(oneInstruction) && oneInstruction.getTextLength() > 0) { /* inner looping termination/continuation should be taken into account */ final PsiElement loopInterrupter = PsiTreeUtil.findChildOfAnyType( oneInstruction, true, PhpBreak.class, PhpContinue.class, PhpThrow.class, PhpReturn.class); /* operating with variables should be taken into account */ final boolean isVariablesUsed = PsiTreeUtil.findChildOfAnyType( oneInstruction, true, (Class) Variable.class) != null; if (null == loopInterrupter && isVariablesUsed) { holder.registerProblem(reportingTarget, messageDisconnected); } } } if (SUGGEST_USING_CLONE && (ExpressionType.DOM_ELEMENT_CREATE == target || ExpressionType.NEW == target)) { holder.registerProblem(oneInstruction, messageUseClone); } } } } /* release containers content */ allModifiedVariables.clear(); instructionDependencies.values().forEach(Set::clear); instructionDependencies.clear(); } } private Set<String> collectCurrentAndOuterLoopVariables(@NotNull ForeachStatement foreach) { final Set<String> variables = new HashSet<>(); PsiElement current = foreach; while (current != null && !(current instanceof Function) && !(current instanceof PsiFile)) { if (current instanceof ForeachStatement) { ((ForeachStatement) current).getVariables().forEach(v -> variables.add(v.getName())); } current = current.getParent(); } return variables; } private void investigateInfluence(@Nullable PhpPsiElement oneInstruction, @NotNull Set<String> individualDependencies, @NotNull Set<String> allModifiedVariables) { for (final PsiElement variable : PsiTreeUtil.findChildrenOfType(oneInstruction, Variable.class)) { final String variableName = ((Variable) variable).getName(); PsiElement valueContainer = variable; PsiElement parent = variable.getParent(); while (parent instanceof FieldReference) { valueContainer = parent; parent = parent.getParent(); } /* a special case: `[] = ` and `array() = ` unboxing */ if (OpenapiTypesUtil.is(parent, PhpElementTypes.ARRAY_VALUE)) { parent = parent.getParent().getParent(); } final PsiElement grandParent = parent.getParent(); /* writing into variable */ if (parent instanceof AssignmentExpression) { /* php-specific `list(...) =` , `[...] =` construction */ if (parent instanceof MultiassignmentExpression) { final MultiassignmentExpression assignment = (MultiassignmentExpression) parent; if (assignment.getValue() != variable) { allModifiedVariables.add(variableName); individualDependencies.add(variableName); continue; } } else { final AssignmentExpression assignment = (AssignmentExpression) parent; if (assignment.getVariable() == valueContainer) { /* we are modifying the variable */ allModifiedVariables.add(variableName); /* self-assignment and field assignment counted as the variable dependent on itself */ if (assignment instanceof SelfAssignmentExpression || valueContainer instanceof FieldReference) { individualDependencies.add(variableName); } /* assignments as call arguments counted as the variable dependent on itself */ if (grandParent instanceof ParameterList) { individualDependencies.add(variableName); } continue; } } } /* adding into an arrays; we both depend and modify the container */ if (parent instanceof ArrayAccessExpression && valueContainer == ((ArrayAccessExpression) parent).getValue()) { allModifiedVariables.add(variableName); individualDependencies.add(variableName); } if (parent instanceof ParameterList) { if (grandParent instanceof MethodReference) { /* an object consumes the variable, perhaps modification takes place */ final MethodReference reference = (MethodReference) grandParent; final PsiElement referenceOperator = OpenapiPsiSearchUtil .findResolutionOperator(reference); if (OpenapiTypesUtil.is(referenceOperator, PhpTokenTypes.ARROW)) { final PsiElement variableCandidate = reference.getFirstPsiChild(); if (variableCandidate instanceof Variable) { allModifiedVariables.add(((Variable) variableCandidate).getName()); continue; } } } else if (OpenapiTypesUtil.isFunctionReference(grandParent)) { /* php will create variable, if it is by reference */ final FunctionReference reference = (FunctionReference) grandParent; final int position = ArrayUtils.indexOf(reference.getParameters(), variable); if (position != -1) { final PsiElement resolved = OpenapiResolveUtil.resolveReference(reference); if (resolved instanceof Function) { final Parameter[] parameters = ((Function) resolved).getParameters(); if (parameters.length > position && parameters[position].isPassByRef()) { allModifiedVariables.add(variableName); individualDependencies.add(variableName); continue; } } } } } /* increment/decrement are also write operations */ final ExpressionType type = this.getExpressionType(parent); if (ExpressionType.INCREMENT == type || ExpressionType.DECREMENT == type) { allModifiedVariables.add(variableName); individualDependencies.add(variableName); continue; } /* TODO: lookup for array access and property access */ individualDependencies.add(variableName); } /* handle compact function usage */ for (final FunctionReference reference : PsiTreeUtil.findChildrenOfType(oneInstruction, FunctionReference.class)) { if (OpenapiTypesUtil.isFunctionReference(reference)) { final String functionName = reference.getName(); if (functionName != null && functionName.equals("compact")) { for (final PsiElement argument : reference.getParameters()) { if (argument instanceof StringLiteralExpression) { final String compactedVariableName = ((StringLiteralExpression) argument) .getContents(); if (!compactedVariableName.isEmpty()) { individualDependencies.add(compactedVariableName); } } } } } } } @NotNull private ExpressionType getExpressionType(@Nullable PsiElement expression) { if (expression instanceof PhpBreak || expression instanceof PhpContinue || expression instanceof PhpReturn) { return ExpressionType.CONTROL_STATEMENTS; } /* regular '...;' statements */ if (OpenapiTypesUtil.isStatementImpl(expression)) { return getExpressionType(((Statement) expression).getFirstPsiChild()); } /* unary operations */ if (expression instanceof UnaryExpression) { final PsiElement operation = ((UnaryExpression) expression).getOperation(); if (OpenapiTypesUtil.is(operation, PhpTokenTypes.opINCREMENT)) { return ExpressionType.INCREMENT; } if (OpenapiTypesUtil.is(operation, PhpTokenTypes.opDECREMENT)) { return ExpressionType.DECREMENT; } } /* different types of assignments */ if (expression instanceof AssignmentExpression) { final AssignmentExpression assignment = (AssignmentExpression) expression; final PsiElement variable = assignment.getVariable(); if (variable instanceof Variable) { final PsiElement value = assignment.getValue(); if (value instanceof NewExpression) { return ExpressionType.NEW; } else if (value instanceof UnaryExpression) { if (OpenapiTypesUtil.is(((UnaryExpression) value).getOperation(), PhpTokenTypes.kwCLONE)) { return ExpressionType.CLONE; } } else if (value instanceof MethodReference) { final MethodReference call = (MethodReference) value; final String methodName = call.getName(); if (methodName != null && methodName.equals("createElement")) { final PsiElement resolved = OpenapiResolveUtil.resolveReference(call); if (resolved instanceof Method && ((Method) resolved).getFQN().equals("\\DOMDocument.createElement")) { return ExpressionType.DOM_ELEMENT_CREATE; } } } /* allow all assignations afterwards */ return ExpressionType.ASSIGNMENT; } /* accumulating something in external container */ if (variable instanceof ArrayAccessExpression) { final ArrayAccessExpression storage = (ArrayAccessExpression) variable; if (null == storage.getIndex() || null == storage.getIndex().getValue()) { return ExpressionType.ACCUMULATE_IN_ARRAY; } } } return ExpressionType.OTHER; } }; }
From source file:com.topsec.tsm.sim.sysconfig.web.SystemConfigController.java
/** * ?/*from w w w . ja va 2 s .co m*/ * @param backupConfig * @param storeConfig * @return * @throws Exception */ private boolean backupPartitionInStorePartition(Config backupConfig, Config storeConfig) throws Exception { if (backupConfig == null) { return false; } Block block = backupConfig.getBlockbyKey("local"); if (block == null || StringUtil.isBlank(block.getItemValue("path"))) { return false; } String backupPath = block.getItemValue("path"); if (StringUtil.isBlank(backupPath)) { return false; } Block storeBlock = storeConfig.getBlockbyKey("archive_path"); String archivePathList = StringUtil.ifBlank(storeBlock.getItemValue("archive_path_list"), storeBlock.getItemValue("archive_path")); String[] storePathList = StringUtil.split(archivePathList, ";"); String[] storePathPartition = new String[storePathList.length]; String backupPartition; if (SystemUtils.IS_OS_WINDOWS) { backupPartition = backupPath.substring(0, backupPath.indexOf(':')); for (int i = 0; i < storePathList.length; i++) { String storePath = storePathList[i]; storePathPartition[i] = storePath.substring(0, storePath.indexOf(':')).toLowerCase();//?? } if (ArrayUtils.indexOf(storePathPartition, backupPartition.toLowerCase()) > -1) { return true; } } else { Node auditorNode = nodeMgrFacade.getKernelAuditor(false); try { //??? String[] params = new String[storePathList.length + 1]; params[0] = backupPath;//? System.arraycopy(storePathList, 0, params, 1, storePathList.length); String[] pathPartition = (String[]) NodeUtil.dispatchCommand(NodeUtil.getRoute(auditorNode), MessageDefinition.CMD_QUERY_PATH_PARTITION, params, 60 * 1000); backupPartition = pathPartition[0]; System.arraycopy(pathPartition, 1, storePathPartition, 0, storePathPartition.length); if (ArrayUtils.indexOf(storePathPartition, backupPartition) > -1) { return true; } } catch (Exception e) { throw e; } } return false; }
From source file:eu.scidipes.toolkits.palibrary.impl.UploadRepInfoLabel.java
private void removeRepInfoHelper(final RepresentationInformation riToRemove, final CoreRIType type) { for (final RepresentationInformation repInfo : repInfoChildren) { if (type.getType().isAssignableFrom(repInfo.getClass()) && repInfo.getRepresentationInformation() != null) { final RepInfoGroup repInfoGroup = (RepInfoGroup) repInfo.getRepresentationInformation(); final RepresentationInformation[] currentGrandChildren = repInfoGroup .getRepresentationInformationChildren(); final int idx = ArrayUtils.indexOf(currentGrandChildren, riToRemove); LOG.debug("Index of riToRemove in currentGrandChildren is: " + idx); if (idx > -1) { repInfoGroup.setRepresentationInformationChildren( (RepresentationInformation[]) ArrayUtils.remove(currentGrandChildren, idx)); LOG.debug(format("riToRemove [%s] at index [%d] was removed from %s core RI", riToRemove, Integer.valueOf(idx), type.toString())); } else { LOG.debug(format("riToRemove [%s] was not found in %s core RI", riToRemove, type.toString())); }// w w w . ja v a 2s .co m } } }