List of usage examples for java.lang String join
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
From source file:com.github.cc007.headsplacer.commands.HeadsPlacerCommand.java
private boolean searchAtIndex(Player player, String[] args) { if (args.length < 2) { player.sendMessage(ChatColor.RED + "You need to specify an index and a head! Use: /heads (search|searchfirst|searchatindex <index>) <head name>"); return false; }/*from ww w .ja v a2 s .c o m*/ if (!HeadsPlacerCommand.isInteger(args[1])) { player.sendMessage(ChatColor.RED + "You need to specify an index! Use: /heads (search|searchfirst|searchatindex <index>) <head name>"); return false; } if (args.length < 3) { player.sendMessage(ChatColor.RED + "You need to specify a head! Use: /heads (search|searchfirst|searchatindex <index>) <head name>"); return false; } String[] searchArgs = new String[args.length - 2]; System.arraycopy(args, 2, searchArgs, 0, searchArgs.length); player.sendMessage(ChatColor.GREEN + "Placing head..."); try { ItemStack head = HeadCreator.getItemStack( plugin.getHeadsUtils().getHead(String.join(" ", searchArgs), Integer.parseInt(args[1]))); placeHeadAndGetInv(head, player, 0); player.sendMessage(ChatColor.GREEN + "Head placed."); return true; } catch (NullPointerException ex) { player.sendMessage(ChatColor.RED + "No heads found!"); return false; } }
From source file:alluxio.cli.fs.command.SetFaclCommand.java
@Override protected void runPlainPath(AlluxioURI path, CommandLine cl) throws AlluxioException, IOException { SetAclOptions options = SetAclOptions.defaults().setRecursive(false); if (cl.hasOption(RECURSIVE_OPTION.getOpt())) { options.setRecursive(true);// ww w. j a v a2 s.c om } List<AclEntry> entries = Collections.emptyList(); SetAclAction action = SetAclAction.REPLACE; List<String> specifiedActions = new ArrayList<>(1); if (cl.hasOption(SET_OPTION.getLongOpt())) { specifiedActions.add(SET_OPTION.getLongOpt()); action = SetAclAction.REPLACE; String aclList = cl.getOptionValue(SET_OPTION.getLongOpt()); if (cl.hasOption(DEFAULT_OPTION.getOpt())) { entries = Arrays.stream(aclList.split(",")).map(AclEntry::toDefault).map(AclEntry::fromCliString) .collect(Collectors.toList()); } else { entries = Arrays.stream(aclList.split(",")).map(AclEntry::fromCliString) .collect(Collectors.toList()); } } if (cl.hasOption(MODIFY_OPTION.getOpt())) { specifiedActions.add(MODIFY_OPTION.getOpt()); action = SetAclAction.MODIFY; String aclList = cl.getOptionValue(MODIFY_OPTION.getOpt()); if (cl.hasOption(DEFAULT_OPTION.getOpt())) { entries = Arrays.stream(aclList.split(",")).map(AclEntry::toDefault).map(AclEntry::fromCliString) .collect(Collectors.toList()); } else { entries = Arrays.stream(aclList.split(",")).map(AclEntry::fromCliString) .collect(Collectors.toList()); } } if (cl.hasOption(REMOVE_OPTION.getOpt())) { specifiedActions.add(REMOVE_OPTION.getOpt()); action = SetAclAction.REMOVE; String aclList = cl.getOptionValue(REMOVE_OPTION.getOpt()); if (cl.hasOption(DEFAULT_OPTION.getOpt())) { entries = Arrays.stream(aclList.split(",")).map(AclEntry::toDefault) .map(AclEntry::fromCliStringWithoutPermissions).collect(Collectors.toList()); } else { entries = Arrays.stream(aclList.split(",")).map(AclEntry::fromCliStringWithoutPermissions) .collect(Collectors.toList()); } } if (cl.hasOption(REMOVE_ALL_OPTION.getOpt())) { specifiedActions.add(REMOVE_ALL_OPTION.getOpt()); action = SetAclAction.REMOVE_ALL; } if (cl.hasOption(REMOVE_DEFAULT_OPTION.getOpt())) { specifiedActions.add(REMOVE_DEFAULT_OPTION.getOpt()); action = SetAclAction.REMOVE_DEFAULT; } if (specifiedActions.isEmpty()) { throw new IllegalArgumentException("No actions specified."); } else if (specifiedActions.size() > 1) { throw new IllegalArgumentException( "Only 1 action can be specified: " + String.join(", ", specifiedActions)); } mFileSystem.setAcl(path, action, entries, options); }
From source file:com.kalessil.phpStorm.phpInspectionsEA.inspectors.apiUsage.UnSafeIsSetOverArrayInspector.java
@Override @NotNull/*from ww w.j a v a2 s .c o m*/ public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new BasePhpElementVisitor() { @Override public void visitPhpIsset(@NotNull PhpIsset issetExpression) { /* * if no parameters, we don't check; * if multiple parameters, perhaps if-inspection fulfilled and isset's were merged * * TODO: still needs analysis regarding concatenations in indexes */ final PhpExpression[] arguments = issetExpression.getVariables(); if (arguments.length != 1) { return; } /* gather context information */ PsiElement issetParent = issetExpression.getParent(); boolean issetInverted = false; if (issetParent instanceof UnaryExpression) { final PsiElement operator = ((UnaryExpression) issetParent).getOperation(); if (OpenapiTypesUtil.is(operator, PhpTokenTypes.opNOT)) { issetInverted = true; issetParent = issetParent.getParent(); } } boolean isResultStored = (issetParent instanceof AssignmentExpression || issetParent instanceof PhpReturn); /* false-positives: ternaries using isset-or-null semantics, there array_key_exist can introduce bugs */ final PsiElement conditionCandidate = issetInverted ? issetExpression.getParent() : issetExpression; boolean isTernaryCondition = issetParent instanceof TernaryExpression && conditionCandidate == ((TernaryExpression) issetParent).getCondition(); if (isTernaryCondition) { final TernaryExpression ternary = (TernaryExpression) issetParent; final PsiElement nullCandidate = issetInverted ? ternary.getTrueVariant() : ternary.getFalseVariant(); if (PhpLanguageUtil.isNull(nullCandidate)) { return; } } /* do analyze */ final PsiElement argument = ExpressionSemanticUtil.getExpressionTroughParenthesis(arguments[0]); if (argument == null) { return; } /* false positives: variables in template/global context - too unreliable */ if (argument instanceof Variable && ExpressionSemanticUtil.getBlockScope(argument) == null) { return; } if (!(argument instanceof ArrayAccessExpression)) { if (argument instanceof FieldReference) { /* if field is not resolved, it's probably dynamic and isset has a purpose */ final PsiReference referencedField = argument.getReference(); final PsiElement resolvedField = referencedField == null ? null : OpenapiResolveUtil.resolveReference(referencedField); if (resolvedField == null || !(ExpressionSemanticUtil.getBlockScope(resolvedField) instanceof PhpClass)) { return; } } if (SUGGEST_TO_USE_NULL_COMPARISON) { /* false-positives: finally, perhaps fallback to initialization in try */ if (PsiTreeUtil.getParentOfType(issetExpression, Finally.class) == null) { final List<String> fragments = Arrays.asList(argument.getText(), issetInverted ? "===" : "!==", "null"); if (!ComparisonStyle.isRegular()) { Collections.reverse(fragments); } final String replacement = String.join(" ", fragments); holder.registerProblem(issetInverted ? issetExpression.getParent() : issetExpression, String.format(patternUseNullComparison, replacement), ProblemHighlightType.WEAK_WARNING, new CompareToNullFix(replacement)); } } return; } /* TODO: has method/function reference as index */ if (REPORT_CONCATENATION_IN_INDEXES && !isResultStored && this.hasConcatenationAsIndex((ArrayAccessExpression) argument)) { holder.registerProblem(argument, messageConcatenationInIndex); return; } if (SUGGEST_TO_USE_ARRAY_KEY_EXISTS && !isArrayAccess((ArrayAccessExpression) argument)) { holder.registerProblem(argument, messageUseArrayKeyExists, ProblemHighlightType.WEAK_WARNING); } } /* checks if any of indexes is concatenation expression */ /* TODO: iterator for array access expression */ private boolean hasConcatenationAsIndex(@NotNull ArrayAccessExpression expression) { PsiElement expressionToInspect = expression; while (expressionToInspect instanceof ArrayAccessExpression) { final ArrayIndex index = ((ArrayAccessExpression) expressionToInspect).getIndex(); if (index != null && index.getValue() instanceof BinaryExpression) { final PsiElement operation = ((BinaryExpression) index.getValue()).getOperation(); if (operation != null && operation.getNode().getElementType() == PhpTokenTypes.opCONCAT) { return true; } } expressionToInspect = expressionToInspect.getParent(); } return false; } // TODO: partially duplicates semanticalAnalysis.OffsetOperationsInspector.isContainerSupportsArrayAccess() private boolean isArrayAccess(@NotNull ArrayAccessExpression expression) { /* ok JB parses `$var[]= ...` always as array, lets make it working properly and report them later */ final PsiElement container = expression.getValue(); if (!(container instanceof PhpTypedElement)) { return false; } final Set<String> containerTypes = new HashSet<>(); final PhpType resolved = OpenapiResolveUtil.resolveType((PhpTypedElement) container, container.getProject()); if (resolved != null) { resolved.filterUnknown().getTypes().forEach(t -> containerTypes.add(Types.getType(t))); } /* failed to resolve, don't try to guess anything */ if (containerTypes.isEmpty()) { return false; } boolean supportsOffsets = false; for (final String typeToCheck : containerTypes) { /* assume is just null-ble declaration or we shall just rust to mixed */ if (typeToCheck.equals(Types.strNull)) { continue; } if (typeToCheck.equals(Types.strMixed)) { supportsOffsets = true; continue; } /* some of possible types are scalars, what's wrong */ if (!StringUtils.isEmpty(typeToCheck) && typeToCheck.charAt(0) != '\\') { supportsOffsets = false; break; } /* assume class has what is needed, OffsetOperationsInspector should report if not */ supportsOffsets = true; } containerTypes.clear(); return supportsOffsets; } }; }
From source file:net.minecraftforge.fml.common.network.internal.FMLNetworkHandler.java
/** * @param listData map of modId string to version string, represents the mods available on the given side * @param side the side that listData is coming from, either client or server * @return null if everything is fine, returns a string error message if there are mod rejections *///from www . j a v a 2s .c o m @Nullable public static String checkModList(Map<String, String> listData, Side side) { List<Pair<ModContainer, String>> rejects = NetworkRegistry.INSTANCE.registry().entrySet().stream() .map(entry -> Pair.of(entry.getKey(), entry.getValue().checkCompatible(listData, side))) .filter(pair -> pair.getValue() != null).sorted(Comparator.comparing(o -> o.getKey().getName())) .collect(Collectors.toList()); if (rejects.isEmpty()) { return null; } else { List<String> rejectStrings = new ArrayList<>(); for (Pair<ModContainer, String> reject : rejects) { ModContainer modContainer = reject.getKey(); rejectStrings.add(modContainer.getName() + ": " + reject.getValue()); } String rejectString = String.join("\n", rejectStrings); FMLLog.log.info("Rejecting connection {}: {}", side, rejectString); return String.format("Server Mod rejections:\n%s", rejectString); } }
From source file:com.bbva.arq.devops.ae.mirrorgate.collectors.jira.config.Config.java
@Bean(JIRA_TYPES) public String getJiraTypes() { Set<String> all = new HashSet<>(); all.addAll(bugTypes.stream().filter((s) -> s.length() > 0).collect(Collectors.toList())); all.addAll(featureTypes.stream().filter((s) -> s.length() > 0).collect(Collectors.toList())); all.addAll(storyTypes.stream().filter((s) -> s.length() > 0).collect(Collectors.toList())); all.addAll(taskTypes.stream().filter((s) -> s.length() > 0).collect(Collectors.toList())); all.addAll(epicTypes.stream().filter((s) -> s.length() > 0).collect(Collectors.toList())); return String.join(",", all); }
From source file:cop.raml.utils.Utils.java
public static String offs(String str, int offs, boolean strict) { if (StringUtils.isBlank(str) || offs < 0) return str; String tmp = StringUtils.repeat(StringUtils.SPACE, offs); String[] lines = Arrays.stream(splitLine(str)).map(line -> tmp + (strict ? line : line.trim())) .map(line -> StringUtils.isBlank(line) ? StringUtils.EMPTY : line).toArray(String[]::new); return String.join("\n", lines); }
From source file:com.vmware.admiral.compute.container.ShellContainerExecutorService.java
private void executeCommand(ContainerState container, ShellContainerExecutorState execState, Operation op) { AdapterRequest adapterRequest = new AdapterRequest(); // task callback not needed in case of exec, as it is direct, but needed for validation. adapterRequest.serviceTaskCallback = ServiceTaskCallback .create(UriUtils.buildUri(getHost(), SELF_LINK).toString()); adapterRequest.resourceReference = UriUtils.buildUri(getHost(), container.documentSelfLink); adapterRequest.operationTypeId = ContainerOperationType.EXEC.id; adapterRequest.customProperties = new HashMap<>(); String command = String.join(COMMAND_ARGUMENTS_SEPARATOR, execState.command); adapterRequest.customProperties.put(COMMAND_KEY, command); if (execState.attachStdErr != null) { adapterRequest.customProperties.put("AttachStderr", execState.attachStdErr.toString()); }/* w ww. ja va 2s .c o m*/ if (execState.attachStdOut != null) { adapterRequest.customProperties.put("AttachStdout", execState.attachStdOut.toString()); } String host = container.adapterManagementReference.getHost(); String targetPath = null; if (StringUtils.isBlank(host)) { targetPath = container.adapterManagementReference.toString(); } else { targetPath = container.adapterManagementReference.getPath(); } sendRequest(Operation.createPatch(getHost(), targetPath).setBody(adapterRequest).setCompletion((o, e) -> { if (e != null) { op.fail(e); return; } op.setBody(o.getBody(String.class)); op.setContentType(Operation.MEDIA_TYPE_TEXT_PLAIN); op.complete(); })); }
From source file:net.sf.jabref.importer.fileformat.JSONEntryParser.java
/** * Convert a JSONObject obtained from http://api.springer.com/metadata/json to a BibEntry * * @param springerJsonEntry the JSONObject from search results * @return the converted BibEntry/*from w ww .j a v a 2 s. co m*/ */ public static BibEntry parseSpringerJSONtoBibtex(JSONObject springerJsonEntry) { // Fields that are directly accessible at the top level Json object String[] singleFieldStrings = { FieldName.ISSN, FieldName.VOLUME, FieldName.ABSTRACT, FieldName.DOI, FieldName.TITLE, FieldName.NUMBER, FieldName.PUBLISHER }; BibEntry entry = new BibEntry(); String nametype; // Guess publication type String isbn = springerJsonEntry.optString("isbn"); if (com.google.common.base.Strings.isNullOrEmpty(isbn)) { // Probably article entry.setType("article"); nametype = FieldName.JOURNAL; } else { // Probably book chapter or from proceeding, go for book chapter entry.setType("incollection"); nametype = "booktitle"; entry.setField(FieldName.ISBN, isbn); } // Authors if (springerJsonEntry.has("creators")) { JSONArray authors = springerJsonEntry.getJSONArray("creators"); List<String> authorList = new ArrayList<>(); for (int i = 0; i < authors.length(); i++) { if (authors.getJSONObject(i).has("creator")) { authorList.add(authors.getJSONObject(i).getString("creator")); } else { LOGGER.info("Empty author name."); } } entry.setField(FieldName.AUTHOR, String.join(" and ", authorList)); } else { LOGGER.info("No author found."); } // Direct accessible fields for (String field : singleFieldStrings) { if (springerJsonEntry.has(field)) { String text = springerJsonEntry.getString(field); if (!text.isEmpty()) { entry.setField(field, text); } } } // Page numbers if (springerJsonEntry.has("startingPage") && !(springerJsonEntry.getString("startingPage").isEmpty())) { if (springerJsonEntry.has("endPage") && !(springerJsonEntry.getString("endPage").isEmpty())) { entry.setField(FieldName.PAGES, springerJsonEntry.getString("startingPage") + "--" + springerJsonEntry.getString("endPage")); } else { entry.setField(FieldName.PAGES, springerJsonEntry.getString("startingPage")); } } // Journal if (springerJsonEntry.has("publicationName")) { entry.setField(nametype, springerJsonEntry.getString("publicationName")); } // URL if (springerJsonEntry.has("url")) { JSONArray urlarray = springerJsonEntry.optJSONArray("url"); if (urlarray == null) { entry.setField(FieldName.URL, springerJsonEntry.optString("url")); } else { entry.setField(FieldName.URL, urlarray.getJSONObject(0).optString("value")); } } // Date if (springerJsonEntry.has("publicationDate")) { String date = springerJsonEntry.getString("publicationDate"); entry.setField(FieldName.DATE, date); // For BibLatex String[] dateparts = date.split("-"); entry.setField(FieldName.YEAR, dateparts[0]); entry.setField(FieldName.MONTH, MonthUtil.getMonthByNumber(Integer.parseInt(dateparts[1])).bibtexFormat); } // Clean up abstract (often starting with Abstract) entry.getFieldOptional(FieldName.ABSTRACT).ifPresent(abstractContents -> { if (abstractContents.startsWith("Abstract")) { entry.setField(FieldName.ABSTRACT, abstractContents.substring(8)); } }); return entry; }
From source file:net.fabricmc.loader.FabricLoader.java
public void load(Collection<File> modFiles) { if (modsLoaded) { throw new RuntimeException("FabricLoader has already had mods loaded!"); }/*from w w w. j ava 2 s . com*/ List<Pair<ModInfo, File>> existingMods = new ArrayList<>(); int classpathModsCount = 0; if (Boolean.parseBoolean(System.getProperty("fabric.development", "false"))) { List<Pair<ModInfo, File>> classpathMods = getClasspathMods(); existingMods.addAll(classpathMods); classpathModsCount = classpathMods.size(); LOGGER.debug("Found %d classpath mods", classpathModsCount); } for (File f : modFiles) { if (f.isDirectory()) { continue; } if (!f.getPath().endsWith(".jar")) { continue; } ModInfo[] fileMods = getJarMods(f); if (Launch.classLoader != null && fileMods.length != 0) { try { Launch.classLoader.addURL(f.toURI().toURL()); } catch (MalformedURLException e) { LOGGER.error("Unable to load mod from %s", f.getName()); e.printStackTrace(); continue; } } for (ModInfo info : fileMods) { existingMods.add(Pair.of(info, f)); } } LOGGER.debug("Found %d JAR mods", existingMods.size() - classpathModsCount); mods: for (Pair<ModInfo, File> pair : existingMods) { ModInfo mod = pair.getLeft(); /* if (mod.isLazilyLoaded()) { innerMods: for (Pair<ModInfo, File> pair2 : existingMods) { ModInfo mod2 = pair2.getLeft(); if (mod == mod2) { continue innerMods; } for (Map.Entry<String, ModInfo.Dependency> entry : mod2.getRequires().entrySet()) { String depId = entry.getKey(); ModInfo.Dependency dep = entry.getValue(); if (depId.equalsIgnoreCase(mod.getId()) && dep.satisfiedBy(mod)) { addMod(mod, pair.getRight(), loaderInitializesMods()); } } } continue mods; } */ addMod(mod, pair.getRight(), loaderInitializesMods()); } String modText; switch (mods.size()) { case 0: modText = "Loading %d mods"; break; case 1: modText = "Loading %d mod: %s"; break; default: modText = "Loading %d mods: %s"; break; } LOGGER.info(modText, mods.size(), String.join(", ", mods.stream().map(ModContainer::getInfo).map(ModInfo::getId).collect(Collectors.toList()))); modsLoaded = true; onModsPopulated(); }
From source file:com.oneops.inductor.ProcessRunner.java
/** * Creates a process and logs the output * * @param cmd//from w ww .j a v a 2s .c o m * @param logKey * @param result */ private void executeProcess(String[] cmd, String logKey, ProcessResult result) { Map<String, String> env = getEnvVars(logKey, cmd); logger.info(logKey + " Cmd: " + String.join(" ", cmd) + ", Env: " + env); // run the cmd try { CommandLine cmdLine = new CommandLine(cmd[0]); // add rest of cmd string[] as arguments for (int i = 1; i < cmd.length; i++) { // needs the quote handling=false or else doesn't work // http://www.techques.com/question/1-5080109/How-to-execute--bin-sh-with-commons-exec? cmdLine.addArgument(cmd[i], false); } DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setWatchdog(new ExecuteWatchdog(timeoutInSeconds * 1000)); executor.setStreamHandler(new OutputHandler(logger, logKey, result)); result.setResultCode(executor.execute(cmdLine, env)); // set fault to last error if fault map is empty if (result.getResultCode() != 0 && result.getFaultMap().keySet().size() < 1) { result.getFaultMap().put("ERROR", result.getLastError()); } } catch (ExecuteException ee) { logger.error(logKey + ee); result.setResultCode(ee.getExitValue()); } catch (IOException e) { logger.error(e); result.setResultCode(1); } }