/** * Start at the given nesting level - read lines until you get to line with equal to or greater * than the current one. */ public static String[] getArtifactLines(Pointer startingIndex, String... lines) { List<String> lineList = new ArrayList<>(); int index = startingIndex.getIndex(); String topLine = lines[index]; lineList.add( topLine); // add the line which defines this object - all others, if they exist, are // children. int nestingLevel = parseNestingLevel(topLine); for (int i = index + 1; i < lines.length; i++) { String line = lines[i]; // we return if the nesting level of the line in question is the same as the "parent" level int childNestingLevel = parseNestingLevel(line); if (childNestingLevel == nestingLevel) { startingIndex.increment(lineList.size()); // return new array of startIndex to i return lineList.toArray(new String[lineList.size()]); } else { lineList.add(line); } } startingIndex.increment(lineList.size()); return lineList.toArray(new String[lineList.size()]); }
public static IdeaPluginDescriptorImpl[] loadDescriptors(@Nullable StartupProgress progress) { if (ClassUtilCore.isLoadingOfExternalPluginsDisabled()) { return IdeaPluginDescriptorImpl.EMPTY_ARRAY; } final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>(); int pluginsCount = countPlugins(PathManager.getPluginsPath()) + countPlugins(PathManager.getPreinstalledPluginsPath()); loadDescriptors(PathManager.getPluginsPath(), result, progress, pluginsCount); Application application = ApplicationManager.getApplication(); boolean fromSources = false; if (application == null || !application.isUnitTestMode()) { int size = result.size(); loadDescriptors(PathManager.getPreinstalledPluginsPath(), result, progress, pluginsCount); fromSources = size == result.size(); } loadDescriptorsFromProperty(result); loadDescriptorsFromClassPath(result, fromSources ? progress : null); IdeaPluginDescriptorImpl[] pluginDescriptors = result.toArray(new IdeaPluginDescriptorImpl[result.size()]); try { Arrays.sort(pluginDescriptors, new PluginDescriptorComparator(pluginDescriptors)); } catch (Exception e) { prepareLoadingPluginsErrorMessage( IdeBundle.message("error.plugins.were.not.loaded", e.getMessage())); getLogger().info(e); return findCorePlugin(pluginDescriptors); } return pluginDescriptors; }
/** * Given a string, return an array of tokens. The separator can be escaped with the '\' character. * The '\' character may also be escaped by the '\' character. * * @param s the string to tokenize. * @param separator the separator char. * @param maxTokens the maxmimum number of tokens returned. If the max is reached, the remaining * part of s is appended to the end of the last token. * @return an array of tokens. */ public static String[] tokenize(String s, char separator, int maxTokens) { List tokens = new ArrayList(); StringBuilder token = new StringBuilder(); boolean prevIsEscapeChar = false; for (int i = 0; i < s.length(); i += Character.charCount(i)) { int currentChar = s.codePointAt(i); if (prevIsEscapeChar) { // Case 1: escaped character token.appendCodePoint(currentChar); prevIsEscapeChar = false; } else if (currentChar == separator && tokens.size() < maxTokens - 1) { // Case 2: separator tokens.add(token.toString()); token = new StringBuilder(); } else if (currentChar == '\\') { // Case 3: escape character prevIsEscapeChar = true; } else { // Case 4: regular character token.appendCodePoint(currentChar); } } if (token.length() > 0) { tokens.add(token.toString()); } return (String[]) tokens.toArray(new String[] {}); }
@Override protected ObjectMapper createMapper( String name, String fullPath, boolean enabled, Nested nested, Dynamic dynamic, ContentPath.Type pathType, Map<String, Mapper> mappers, @Nullable @IndexSettings Settings settings) { assert !nested.isNested(); FormatDateTimeFormatter[] dates = null; if (dynamicDateTimeFormatters == null) { dates = new FormatDateTimeFormatter[0]; } else if (dynamicDateTimeFormatters.isEmpty()) { // add the default one dates = Defaults.DYNAMIC_DATE_TIME_FORMATTERS; } else { dates = dynamicDateTimeFormatters.toArray( new FormatDateTimeFormatter[dynamicDateTimeFormatters.size()]); } return new RootObjectMapper( name, enabled, dynamic, pathType, mappers, dates, dynamicTemplates.toArray(new DynamicTemplate[dynamicTemplates.size()]), dateDetection, numericDetection, settings); }
/** Initialize mappings, during the first request. */ protected void initializeMappings() { String viewMappings = webConfig.getOptionValue(WebContextInitParameter.FaceletsViewMappings); if ((viewMappings != null) && (viewMappings.length() > 0)) { String[] mappingsArray = Util.split(viewMappings, ";"); List<String> extensionsList = new ArrayList<String>(mappingsArray.length); List<String> prefixesList = new ArrayList<String>(mappingsArray.length); for (int i = 0; i < mappingsArray.length; i++) { String mapping = mappingsArray[i].trim(); int mappingLength = mapping.length(); if (mappingLength <= 1) { continue; } if (mapping.charAt(0) == '*') { extensionsList.add(mapping.substring(1)); } else if (mapping.charAt(mappingLength - 1) == '*') { prefixesList.add(mapping.substring(0, mappingLength - 1)); } } extensionsArray = new String[extensionsList.size()]; extensionsList.toArray(extensionsArray); prefixesArray = new String[prefixesList.size()]; prefixesList.toArray(prefixesArray); } }
/** * Creates a new <code>AnnotationDirectoryItem</code> with the given values * * @param dexFile The <code>DexFile</code> that this item belongs to * @param classAnnotations The annotations associated with the overall class * @param fieldAnnotations A list of <code>FieldAnnotation</code> objects that contain the field * annotations for this class * @param methodAnnotations A list of <code>MethodAnnotation</code> objects that contain the * method annotations for this class * @param parameterAnnotations A list of <code>ParameterAnnotation</code> objects that contain the * parameter annotations for the methods in this class */ private AnnotationDirectoryItem( DexFile dexFile, @Nullable AnnotationSetItem classAnnotations, @Nullable List<FieldAnnotation> fieldAnnotations, @Nullable List<MethodAnnotation> methodAnnotations, @Nullable List<ParameterAnnotation> parameterAnnotations) { super(dexFile); this.classAnnotations = classAnnotations; if (fieldAnnotations == null || fieldAnnotations.size() == 0) { this.fieldAnnotations = null; } else { this.fieldAnnotations = new FieldAnnotation[fieldAnnotations.size()]; this.fieldAnnotations = fieldAnnotations.toArray(this.fieldAnnotations); Arrays.sort(this.fieldAnnotations); } if (methodAnnotations == null || methodAnnotations.size() == 0) { this.methodAnnotations = null; } else { this.methodAnnotations = new MethodAnnotation[methodAnnotations.size()]; this.methodAnnotations = methodAnnotations.toArray(this.methodAnnotations); Arrays.sort(this.methodAnnotations); } if (parameterAnnotations == null || parameterAnnotations.size() == 0) { this.parameterAnnotations = null; } else { this.parameterAnnotations = new ParameterAnnotation[parameterAnnotations.size()]; this.parameterAnnotations = parameterAnnotations.toArray(this.parameterAnnotations); Arrays.sort(this.parameterAnnotations); } }
/** * Builds an {@link AFPChain} from already-matched arrays of atoms and residues. * * @param ca1 An array of atoms in the first structure * @param ca2 An array of atoms in the second structure * @param residues1 An array of {@link ResidueNumber ResidueNumbers} in the first structure that * are aligned. Only null ResidueNumbers are considered to be unaligned * @param residues2 An array of {@link ResidueNumber ResidueNumbers} in the second structure that * are aligned. Only null ResidueNumbers are considered to be unaligned * @throws StructureException */ private static AFPChain buildAlignment( Atom[] ca1, Atom[] ca2, ResidueNumber[] residues1, ResidueNumber[] residues2) throws StructureException { // remove any gap // this includes the ones introduced by the nullifying above List<ResidueNumber> alignedResiduesList1 = new ArrayList<ResidueNumber>(); List<ResidueNumber> alignedResiduesList2 = new ArrayList<ResidueNumber>(); for (int i = 0; i < residues1.length; i++) { if (residues1[i] != null && residues2[i] != null) { alignedResiduesList1.add(residues1[i]); alignedResiduesList2.add(residues2[i]); } } ResidueNumber[] alignedResidues1 = alignedResiduesList1.toArray(new ResidueNumber[alignedResiduesList1.size()]); ResidueNumber[] alignedResidues2 = alignedResiduesList2.toArray(new ResidueNumber[alignedResiduesList2.size()]); AFPChain afpChain = AlignmentTools.createAFPChain(ca1, ca2, alignedResidues1, alignedResidues2); afpChain.setAlgorithmName("unknown"); AlignmentTools.updateSuperposition(afpChain, ca1, ca2); afpChain.setBlockSize(new int[] {afpChain.getNrEQR()}); afpChain.setBlockRmsd(new double[] {afpChain.getTotalRmsdOpt()}); afpChain.setBlockGap(new int[] {afpChain.getGapLen()}); return afpChain; }
public static final AccountTypeWS getWS( Integer id, Integer entityId, String invoiceDesign, Date dateCreated, BigDecimal creditNotificationLimit1, BigDecimal creditNotificationLimit2, BigDecimal creditLimit, InvoiceDeliveryMethodDTO invoiceDeliveryMethod, Integer currencyId, Integer languageId, String description, MainSubscriptionWS mainSubscription, Set<AccountInformationTypeDTO> informationTypes, Set<PaymentMethodTypeDTO> paymentMethodTypes, Integer preferredNotificationAitId) { AccountTypeWS ws = new AccountTypeWS(); ws.setId(id); ws.setEntityId(entityId); ws.setInvoiceDesign(invoiceDesign); ws.setDateCreated(dateCreated); ws.setCreditNotificationLimit1( creditNotificationLimit1 != null ? creditNotificationLimit1.toString() : null); ws.setCreditNotificationLimit2( creditNotificationLimit2 != null ? creditNotificationLimit2.toString() : null); ws.setCreditLimit(creditLimit != null ? creditLimit.toString() : null); ws.setInvoiceDeliveryMethodId( invoiceDeliveryMethod != null ? invoiceDeliveryMethod.getId() : null); ws.setCurrencyId(currencyId); ws.setLanguageId(languageId); ws.setMainSubscription(mainSubscription); if (description != null) { ws.setName(description, Constants.LANGUAGE_ENGLISH_ID); } if (null != informationTypes && informationTypes.size() > 0) { List<Integer> informationTypeIds = new ArrayList<Integer>(); for (AccountInformationTypeDTO ait : informationTypes) { informationTypeIds.add(ait.getId()); } if (!informationTypeIds.isEmpty()) { ws.setInformationTypeIds( informationTypeIds.toArray(new Integer[informationTypeIds.size()])); } } if (null != paymentMethodTypes && paymentMethodTypes.size() > 0) { List<Integer> paymentMethodTypeIds = new ArrayList<Integer>(0); for (PaymentMethodTypeDTO paymentMethodType : paymentMethodTypes) { paymentMethodTypeIds.add(paymentMethodType.getId()); } ws.setPaymentMethodTypeIds( paymentMethodTypeIds.toArray(new Integer[paymentMethodTypeIds.size()])); } ws.setpreferredNotificationAitId(preferredNotificationAitId); return ws; }
@org.junit.Test public void testUnmanagedClasspath() { List<Object> list1 = WrapUtil.toList("a", new Object()); assertSame(test, test.unmanagedClasspath(list1.toArray(new Object[list1.size()]))); assertEquals(list1, test.getUnmanagedClasspath()); List list2 = WrapUtil.toList(WrapUtil.toList("b", "c")); test.unmanagedClasspath(list2.toArray(new Object[list2.size()])); assertEquals(GUtil.addLists(list1, GUtil.flatten(list2)), test.getUnmanagedClasspath()); }
public static void main(String[] args) { Random rand = new Random(47); List<Pet> pets = Pets.arrayList(7); print("1: " + pets); Hamster h = new Hamster(); pets.add(h); // Automatically resizes print("2: " + pets); print("3: " + pets.contains(h)); pets.remove(h); // Remove by object Pet p = pets.get(2); print("4: " + p + " " + pets.indexOf(p)); Pet cymric = new Cymric(); print("5: " + pets.indexOf(cymric)); print("6: " + pets.remove(cymric)); // Must be the exact object: print("7: " + pets.remove(p)); print("8: " + pets); pets.add(3, new Mouse()); // Insert at an index print("9: " + pets); List<Pet> sub = pets.subList(1, 4); print("subList: " + sub); print("10: " + pets.containsAll(sub)); Collections.sort(sub); // In-place sort print("sorted subList: " + sub); // Order is not important in containsAll(): print("11: " + pets.containsAll(sub)); Collections.shuffle(sub, rand); // Mix it up print("shuffled subList: " + sub); print("12: " + pets.containsAll(sub)); List<Pet> copy = new ArrayList<Pet>(pets); sub = Arrays.asList(pets.get(1), pets.get(4)); print("sub: " + sub); copy.retainAll(sub); print("13: " + copy); copy = new ArrayList<Pet>(pets); // Get a fresh copy copy.remove(2); // Remove by index print("14: " + copy); copy.removeAll(sub); // Only removes exact objects print("15: " + copy); copy.set(1, new Mouse()); // Replace an element print("16: " + copy); copy.addAll(2, sub); // Insert a list in the middle print("17: " + copy); print("18: " + pets.isEmpty()); pets.clear(); // Remove all elements print("19: " + pets); print("20: " + pets.isEmpty()); pets.addAll(Pets.arrayList(4)); print("21: " + pets); Object[] o = pets.toArray(); print("22: " + o[3]); Pet[] pa = pets.toArray(new Pet[0]); print("23: " + pa[3].id()); }
private static void writeBlocksToNBT( NBTTagCompound tagCompound, BlockMeta[] blocks, String name) { List<Integer> ids = new ArrayList<Integer>(blocks.length); List<Integer> meta = new ArrayList<Integer>(blocks.length); for (BlockMeta t : blocks) { ids.add(Block.blockRegistry.getIDForObject(t.getBlock())); meta.add((int) t.getMeta()); } tagCompound.setIntArray(name, ArrayUtils.toPrimitive(ids.toArray(new Integer[ids.size()]))); tagCompound.setIntArray( name + "_meta", ArrayUtils.toPrimitive(meta.toArray(new Integer[meta.size()]))); }
// implement RelOptRule public void onMatch(RelOptRuleCall call) { CalcRel calcRel = (CalcRel) call.rels[0]; RexProgram program = calcRel.getProgram(); // check the projection List<Integer> projOrdinals = new ArrayList<Integer>(); RelDataType outputRowType = isProjectSimple(calcRel, projOrdinals); if (outputRowType == null) { return; } RexLocalRef condition = program.getCondition(); CompOperatorEnum compOp = CompOperatorEnum.COMP_NOOP; Integer[] filterOrdinals = {}; List<RexLiteral> filterLiterals = new ArrayList<RexLiteral>(); // check the condition if (condition != null) { RexNode filterExprs = program.expandLocalRef(condition); List<Integer> filterList = new ArrayList<Integer>(); List<CompOperatorEnum> op = new ArrayList<CompOperatorEnum>(); if (!isConditionSimple(calcRel, filterExprs, filterList, filterLiterals, op)) { return; } compOp = op.get(0); filterOrdinals = filterList.toArray(new Integer[filterList.size()]); } RelNode fennelInput = mergeTraitsAndConvert( calcRel.getTraits(), FennelRel.FENNEL_EXEC_CONVENTION, calcRel.getChild()); if (fennelInput == null) { return; } Integer[] projection = projOrdinals.toArray(new Integer[projOrdinals.size()]); FennelReshapeRel reshapeRel = new FennelReshapeRel( calcRel.getCluster(), fennelInput, projection, outputRowType, compOp, filterOrdinals, filterLiterals, new FennelRelParamId[] {}, new Integer[] {}, null); call.transformTo(reshapeRel); }
/** Return class names form jet sources in given scope which should be visible as Java classes. */ @NotNull @Override public PsiClass[] getClassesByName( @NotNull @NonNls String name, @NotNull GlobalSearchScope scope) { List<PsiClass> result = new ArrayList<PsiClass>(); IDELightClassGenerationSupport lightClassGenerationSupport = IDELightClassGenerationSupport.getInstanceForIDE(project); MultiMap<String, FqName> packageClasses = lightClassGenerationSupport.getAllPackageClasses(scope); // .namespace classes can not be indexed, since they have no explicit declarations Collection<FqName> fqNames = packageClasses.get(name); if (!fqNames.isEmpty()) { for (FqName fqName : fqNames) { PsiClass psiClass = JavaElementFinder.getInstance(project).findClass(fqName.getFqName(), scope); if (psiClass != null) { result.add(psiClass); } } } // Quick check for classes from getAllClassNames() Collection<JetClassOrObject> classOrObjects = JetShortClassNameIndex.getInstance().get(name, project, scope); if (classOrObjects.isEmpty()) { return result.toArray(new PsiClass[result.size()]); } for (JetClassOrObject classOrObject : classOrObjects) { FqName fqName = JetPsiUtil.getFQName(classOrObject); if (fqName != null) { assert fqName.shortName().getName().equals(name) : "A declaration obtained from index has non-matching name:\n" + "in index: " + name + "\n" + "declared: " + fqName.shortName() + "(" + fqName + ")"; PsiClass psiClass = JavaElementFinder.getInstance(project).findClass(fqName.getFqName(), scope); if (psiClass != null) { result.add(psiClass); } } } return result.toArray(new PsiClass[result.size()]); }
public static Predicate[] networkPermissionsPredicates( CriteriaBuilder cb, Root<?> from, Set<AccessKeyPermission> permissions) { List<Predicate> predicates = new ArrayList<>(); for (AccessKeyBasedFilterForDevices extraFilter : AccessKeyBasedFilterForDevices.createExtraFilters(permissions)) { List<Predicate> filter = new ArrayList<>(); if (extraFilter.getNetworkIds() != null) { filter.add(from.get("id").in(extraFilter.getNetworkIds())); } predicates.add(cb.and(filter.toArray(new Predicate[filter.size()]))); } return predicates.toArray(new Predicate[predicates.size()]); }
private static void processCallerMethod( JavaChangeInfo changeInfo, PsiMethod caller, PsiMethod baseMethod, boolean toInsertParams, boolean toInsertThrows) throws IncorrectOperationException { LOG.assertTrue(toInsertParams || toInsertThrows); if (toInsertParams) { List<PsiParameter> newParameters = new ArrayList<PsiParameter>(); ContainerUtil.addAll(newParameters, caller.getParameterList().getParameters()); final JavaParameterInfo[] primaryNewParms = changeInfo.getNewParameters(); PsiSubstitutor substitutor = baseMethod == null ? PsiSubstitutor.EMPTY : ChangeSignatureProcessor.calculateSubstitutor(caller, baseMethod); for (JavaParameterInfo info : primaryNewParms) { if (info.getOldIndex() < 0) newParameters.add(createNewParameter(changeInfo, info, substitutor)); } PsiParameter[] arrayed = newParameters.toArray(new PsiParameter[newParameters.size()]); boolean[] toRemoveParm = new boolean[arrayed.length]; Arrays.fill(toRemoveParm, false); resolveParameterVsFieldsConflicts(arrayed, caller, caller.getParameterList(), toRemoveParm); } if (toInsertThrows) { List<PsiJavaCodeReferenceElement> newThrowns = new ArrayList<PsiJavaCodeReferenceElement>(); final PsiReferenceList throwsList = caller.getThrowsList(); ContainerUtil.addAll(newThrowns, throwsList.getReferenceElements()); final ThrownExceptionInfo[] primaryNewExns = changeInfo.getNewExceptions(); for (ThrownExceptionInfo thrownExceptionInfo : primaryNewExns) { if (thrownExceptionInfo.getOldIndex() < 0) { final PsiClassType type = (PsiClassType) thrownExceptionInfo.createType(caller, caller.getManager()); final PsiJavaCodeReferenceElement ref = JavaPsiFacade.getInstance(caller.getProject()) .getElementFactory() .createReferenceElementByType(type); newThrowns.add(ref); } } PsiJavaCodeReferenceElement[] arrayed = newThrowns.toArray(new PsiJavaCodeReferenceElement[newThrowns.size()]); boolean[] toRemoveParm = new boolean[arrayed.length]; Arrays.fill(toRemoveParm, false); ChangeSignatureUtil.synchronizeList( throwsList, Arrays.asList(arrayed), ThrowsList.INSTANCE, toRemoveParm); } }
public TreeNode[] findChildrenBySuffix(String suffix) { if (suffix == null) { List<TreeNode> lst = new ArrayList<TreeNode>(); for (List<TreeNodeImpl> lst1 : childs.values()) { lst.addAll(lst1); } return lst.toArray(new TreeNode[lst.size()]); } else { List<TreeNodeImpl> lst = childs.get(suffix); if (lst != null) { return lst.toArray(new TreeNode[lst.size()]); } } return new TreeNode[0]; }
@NotNull public ContextItem[] findCtxItems(String startCtxPath, String name) { String[] path = startCtxPath.split("/"); int startWith = ("/" + path[1]).startsWith(ContextPath.FILE_CTX_PRX) ? 2 : 1; TreeNode cycled = root; for (int i = startWith; i < path.length; i++) { String encodedName = "/" + path[i]; cycled = cycled.findChildByEncodedName(encodedName); if (cycled == null) { return new ContextItem[0]; } } List<ContextItem> out = new ArrayList<ContextItem>(); TreeNode[] children = name == null ? cycled.getChildren().toArray(new TreeNode[0]) : cycled.findChildrenBySuffix(name); for (TreeNode n : children) { // todo -- revise to replace using value directly with a TreeNode instance out.add(new ContextItemImpl(n.getPath(), n.getValue())); } return out.toArray(new ContextItem[out.size()]); }
Field[] keyFields() { Class c = clazz; try { List<Field> fields = new ArrayList<Field>(); while (!c.equals(Object.class)) { for (Field field : c.getDeclaredFields()) { // TODO: add cashe field->isAnnotationPresent if (InternalCache.isEnableAnnotationPresent()) { if (InternalCache.isAnnotationPresent(Id.class, field) || InternalCache.isAnnotationPresent(EmbeddedId.class, field)) { field.setAccessible(true); fields.add(field); } } else { if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(EmbeddedId.class)) { field.setAccessible(true); fields.add(field); } } } c = c.getSuperclass(); } final Field[] f = fields.toArray(new Field[fields.size()]); if (f.length == 0) { throw new UnexpectedException("Cannot get the object @Id for an object of type " + clazz); } return f; } catch (Exception e) { throw new UnexpectedException( "Error while determining the object @Id for an object of type " + clazz); } }
private static PsiAnnotationMemberValue[] readFromClass( @NonNls String attributeName, @NotNull PsiAnnotation magic, PsiType type) { PsiAnnotationMemberValue fromClassAttr = magic.findAttributeValue(attributeName); PsiType fromClassType = fromClassAttr instanceof PsiClassObjectAccessExpression ? ((PsiClassObjectAccessExpression) fromClassAttr).getOperand().getType() : null; PsiClass fromClass = fromClassType instanceof PsiClassType ? ((PsiClassType) fromClassType).resolve() : null; if (fromClass == null) return null; String fqn = fromClass.getQualifiedName(); if (fqn == null) return null; List<PsiAnnotationMemberValue> constants = new ArrayList<PsiAnnotationMemberValue>(); for (PsiField field : fromClass.getFields()) { if (!field.hasModifierProperty(PsiModifier.PUBLIC) || !field.hasModifierProperty(PsiModifier.STATIC) || !field.hasModifierProperty(PsiModifier.FINAL)) continue; PsiType fieldType = field.getType(); if (!Comparing.equal(fieldType, type)) continue; PsiAssignmentExpression e = (PsiAssignmentExpression) JavaPsiFacade.getElementFactory(field.getProject()) .createExpressionFromText("x=" + fqn + "." + field.getName(), field); PsiReferenceExpression refToField = (PsiReferenceExpression) e.getRExpression(); constants.add(refToField); } if (constants.isEmpty()) return null; return constants.toArray(new PsiAnnotationMemberValue[constants.size()]); }
@NotNull public static PsiClassType[] getImplementsListTypes(GrTypeDefinition grType) { Set<PsiClass> visited = new HashSet<PsiClass>(); List<PsiClassType> result = new ArrayList<PsiClassType>(); getImplementListsInner(grType, result, visited); return result.toArray(new PsiClassType[result.size()]); }
@Override public IndexResponse getIndexByColumnNames( RpcController controller, GetIndexByColumnNamesRequest request) throws ServiceException { TableIdentifierProto identifier = request.getTableIdentifier(); String databaseName = identifier.getDatabaseName(); String tableName = identifier.getTableName(); List<String> columnNamesList = request.getColumnNamesList(); String[] columnNames = new String[columnNamesList.size()]; columnNames = columnNamesList.toArray(columnNames); rlock.lock(); try { if (!store.existIndexByColumns(databaseName, tableName, columnNames)) { return IndexResponse.newBuilder() .setState(errUndefinedIndex(tableName, columnNamesList)) .build(); } return IndexResponse.newBuilder() .setState(OK) .setIndexDesc(store.getIndexByColumns(databaseName, tableName, columnNames)) .build(); } catch (Throwable t) { printStackTraceIfError(LOG, t); return IndexResponse.newBuilder().setState(returnError(t)).build(); } finally { rlock.unlock(); } }
public TreeNode[] findNodeInContext(String startCtxPath, @Nullable final String name) { final List<TreeNode> out = new ArrayList<TreeNode>(); root.iterateThruContext( startCtxPath, new TreeNodeRoot.TreeNodeHandler2() { public boolean handleNode(int ctxPathCounter, TreeNode node) { if (name == null || node.getName().equalsIgnoreCase(name)) { out.add(node); } return true; } }); return out.toArray(new TreeNode[out.size()]); /* String[] path = startCtxPath.split("/"); int startWith = ("/" + path[1]).startsWith(ContextPath.FILE_CTX_PRX) ? 2 : 1; TreeNode cycled = root; for (int i = startWith; i < path.length; i++) { String encodedName = "/" + path[i]; cycled = cycled.findChildByEncodedName(encodedName); if (cycled == null) { return new TreeNode[0]; } } return cycled.findChildrenBySuffix(name); */ }
public void init(String[] args) throws UserError { Context.reset(); CommandLineParser globalParser = new GnuParser(); List<String> globalArgs = new ArrayList<String>(); boolean inGlobal = true; for (String arg : args) { if (inGlobal) { if (arg.startsWith("--")) { globalArgs.add(arg); } else { this.command = arg; inGlobal = false; } } else { commandArgs.add(arg); } } try { this.globalArguments = globalParser.parse(globalOptions, globalArgs.toArray(new String[globalArgs.size()])); } catch (ParseException e) { throw new UserError("Error parsing global command line argument: " + e.getMessage()); } }
public static String[] listFiles(File dir, Boolean includeSubDirs) throws IOException { FileFilter fileFilter = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; File[] subFolders = dir.listFiles(fileFilter); List<String> files = new ArrayList<String>(); List<File> fileArray = new ArrayList<File>( FileUtils.listFiles( dir, TrueFileFilter.INSTANCE, includeSubDirs ? TrueFileFilter.INSTANCE : null)); for (File file : fileArray) { if (file.isFile()) { if (includeSubDirs && containsParentFolder(file, subFolders)) { files.add(file.getParentFile().getName() + File.separator + file.getName()); } else { files.add(file.getName()); } } } return (String[]) files.toArray(new String[0]); }
@Override public ReturnState existIndexByColumnNames( RpcController controller, GetIndexByColumnNamesRequest request) throws ServiceException { TableIdentifierProto identifier = request.getTableIdentifier(); String databaseName = identifier.getDatabaseName(); String tableName = identifier.getTableName(); List<String> columnNames = request.getColumnNamesList(); try { // linked meta data do not support index. The request will be failed. if (linkedMetadataManager.existsDatabase(databaseName)) { return errUndefinedIndex(tableName); } } catch (Throwable t) { printStackTraceIfError(LOG, t); return returnError(t); } rlock.lock(); try { return store.existIndexByColumns( databaseName, tableName, columnNames.toArray(new String[columnNames.size()])) ? OK : errUndefinedIndex(tableName, columnNames); } catch (Throwable t) { printStackTraceIfError(LOG, t); return returnError(t); } finally { rlock.unlock(); } }
public static boolean canHarvestBlock(Block block, EntityPlayer player, int metadata) { if (block.blockMaterial.isToolNotRequired()) { return true; } ItemStack stack = player.inventory.getCurrentItem(); if (stack == null) { return player.canHarvestBlock(block); } List info = toolClasses.get(stack.getItem()); if (info == null) { return player.canHarvestBlock(block); } Object[] tmp = info.toArray(); String toolClass = (String) tmp[0]; int harvestLevel = (Integer) tmp[1]; Integer blockHarvestLevel = toolHarvestLevels.get(Arrays.asList(block, metadata, toolClass)); if (blockHarvestLevel == null) { return player.canHarvestBlock(block); } if (blockHarvestLevel > harvestLevel) { return false; } return true; }
@DataProvider(name = "AdaptorGetter") public Object[][] makeActiveRegionCutTests() { final List<Object[]> tests = new LinkedList<Object[]>(); tests.add( new Object[] { new GetAdaptorFunc() { @Override public int getAdaptor(final GATKSAMRecord record) { return ReadUtils.getAdaptorBoundary(record); } } }); tests.add( new Object[] { new GetAdaptorFunc() { @Override public int getAdaptor(final GATKSAMRecord record) { return record.getAdaptorBoundary(); } } }); return tests.toArray(new Object[][] {}); }
// spread expressions public static Object[] despreadList(Object[] args, Object[] spreads, int[] positions) { List ret = new ArrayList(); int argsPos = 0; int spreadPos = 0; for (int pos = 0; pos < positions.length; pos++) { for (; argsPos < positions[pos]; argsPos++) { ret.add(args[argsPos]); } Object value = spreads[spreadPos]; if (value == null) { ret.add(null); } else if (value instanceof List) { ret.addAll((List) value); } else if (value.getClass().isArray()) { ret.addAll(DefaultTypeTransformation.primitiveArrayToList(value)); } else { throw new IllegalArgumentException( "cannot spread the type " + value.getClass().getName() + " with value " + value); } spreadPos++; } for (; argsPos < args.length; argsPos++) { ret.add(args[argsPos]); } return ret.toArray(); }
/** populates a request object (pre-populated with defaults) based on a parser. */ public static void parseRequest(TermVectorRequest termVectorRequest, XContentParser parser) throws IOException { XContentParser.Token token; String currentFieldName = null; List<String> fields = new ArrayList<>(); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (currentFieldName != null) { if (currentFieldName.equals("fields")) { if (token == XContentParser.Token.START_ARRAY) { while (parser.nextToken() != XContentParser.Token.END_ARRAY) { fields.add(parser.text()); } } else { throw new ElasticsearchParseException( "The parameter fields must be given as an array! Use syntax : \"fields\" : [\"field1\", \"field2\",...]"); } } else if (currentFieldName.equals("offsets")) { termVectorRequest.offsets(parser.booleanValue()); } else if (currentFieldName.equals("positions")) { termVectorRequest.positions(parser.booleanValue()); } else if (currentFieldName.equals("payloads")) { termVectorRequest.payloads(parser.booleanValue()); } else if (currentFieldName.equals("term_statistics") || currentFieldName.equals("termStatistics")) { termVectorRequest.termStatistics(parser.booleanValue()); } else if (currentFieldName.equals("field_statistics") || currentFieldName.equals("fieldStatistics")) { termVectorRequest.fieldStatistics(parser.booleanValue()); } else if ("_index" .equals(currentFieldName)) { // the following is important for multi request parsing. termVectorRequest.index = parser.text(); } else if ("_type".equals(currentFieldName)) { termVectorRequest.type = parser.text(); } else if ("_id".equals(currentFieldName)) { if (termVectorRequest.doc != null) { throw new ElasticsearchParseException( "Either \"id\" or \"doc\" can be specified, but not both!"); } termVectorRequest.id = parser.text(); } else if ("doc".equals(currentFieldName)) { if (termVectorRequest.id != null) { throw new ElasticsearchParseException( "Either \"id\" or \"doc\" can be specified, but not both!"); } termVectorRequest.doc(jsonBuilder().copyCurrentStructure(parser)); } else if ("_routing".equals(currentFieldName) || "routing".equals(currentFieldName)) { termVectorRequest.routing = parser.text(); } else { throw new ElasticsearchParseException( "The parameter " + currentFieldName + " is not valid for term vector request!"); } } } if (fields.size() > 0) { String[] fieldsAsArray = new String[fields.size()]; termVectorRequest.selectedFields(fields.toArray(fieldsAsArray)); } }
/** * Returns paths constructed by rewriting pathInfo using rules from the hosted site's mappings. * Paths are ordered from most to least specific match. * * @param site The hosted site. * @param pathInfo Path to be rewritten. * @param queryString * @return The rewritten path. May be either: * <ul> * <li>A path to a file in the Orion workspace, eg. <code>/ProjectA/foo/bar.txt</code> * <li>An absolute URL pointing to another site, eg. <code>http://foo.com/bar.txt</code> * </ul> * * @return The rewritten paths. * @throws URISyntaxException */ private URI[] getMapped(IHostedSite site, IPath pathInfo, String queryString) throws URISyntaxException { final Map<String, List<String>> map = site.getMappings(); final IPath originalPath = pathInfo; IPath path = originalPath.removeTrailingSeparator(); List<URI> uris = new ArrayList<URI>(); String rest = null; final int count = path.segmentCount(); for (int i = 0; i <= count; i++) { List<String> base = map.get(path.toString()); if (base != null) { rest = originalPath.removeFirstSegments(count - i).toString(); for (int j = 0; j < base.size(); j++) { URI uri = rest.equals("") ? new URI(base.get(j)) : URIUtil.append(new URI(base.get(j)), rest); uris.add( new URI( uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), queryString, uri.getFragment())); } } path = path.removeLastSegments(1); } if (uris.size() == 0) // No mapping for / return null; else return uris.toArray(new URI[uris.size()]); }