Java Code Examples for java.util.StringJoiner

The following are top voted examples for showing how to use java.util.StringJoiner. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: n4js   File: ClassifierReference.java   View source code 7 votes vote down vote up
/**
 * Creates a resolved classifier reference. This means a classifier with a valid uri of its declaration.
 *
 * @param qualifiedName
 *            QualifiedName of the classifier
 * @param uri
 *            Platform uri of the classifier declaration
 */
public ClassifierReference(QualifiedName qualifiedName, URI uri) {
	this.classifierName = qualifiedName.getLastSegment();
	List<String> frontSegments = qualifiedName.getSegments();
	if (frontSegments.size() > 0) {
		StringJoiner joiner = new StringJoiner(N4JSQualifiedNameConverter.DELIMITER);
		for (String segment : frontSegments.subList(0, frontSegments.size() - 1)) {
			joiner.add(segment);
		}
		this.classifierModuleSpecifier = joiner.toString();
	} else {
		this.classifierModuleSpecifier = "";
	}
	this.uri = uri;

}
 
Example 2
Project: n4js   File: StackGraphFactory.java   View source code 6 votes vote down vote up
private static void collectData(DataSeries parentSeries, StackNode parentNode, float baseHeight, float baseWidth,
		StringJoiner sj, IndentLevel indent) {

	if (parentSeries.hasNoChildren())
		return;

	indent.increase();

	Long siblingSum = parentSeries.getChildren().map(s -> s.sum).max(Long::compare).get();
	parentSeries.getChildren().forEach(series -> {
		sj.add(indent.get() + SimpleTimeFormat.convert(series.sum) + " - " + series.name);
		float parentScale = (float) series.sum / parentSeries.sum;
		float siblingScale = (float) series.sum / siblingSum;
		StackNode node = new StackNode(series.name,
				series.name + " took " + SimpleTimeFormat.convert(series.sum),
				parentNode.width * parentScale, baseHeight, parentScale, siblingScale);

		parentNode.addChild(node);
		collectData(series, node, baseHeight, baseWidth, sj, indent);
	});

	indent.decrease();
}
 
Example 3
Project: uppercore   File: ScriptListCommand.java   View source code 6 votes vote down vote up
@WithCommand
public void run(CommandSender sender, @WithName("plugin") @WithOptional Plugin plugin) {
    Collection<String> scriptNames;
    if (plugin != null) {
        ScriptRegistry reg = (ScriptRegistry) scripts().get(plugin);
        scriptNames = reg.getEntries().keySet();
    } else
        scriptNames = scripts().getEntries().keySet();
    StringJoiner str = new StringJoiner(GRAY + ", ");
    for (String name : scriptNames)
        str.add(AQUA + name);
    if (scriptNames.size() > 0)
        sender.sendMessage(GOLD + "Showing " + scriptNames.size() + " scripts: " + str.toString());
    else
        sender.sendMessage(RED + "No script found.");
}
 
Example 4
Project: openjdk-jdk10   File: StringJoinerTest.java   View source code 6 votes vote down vote up
public void addAlladdAll() {
    StringJoiner sj = new StringJoiner(DASH, "{", "}");
    ArrayList<String> firstOne = new ArrayList<>();
    firstOne.add(ONE);
    firstOne.add(TWO);
    firstOne.add(THREE);
    firstOne.stream().forEachOrdered(sj::add);

    ArrayList<String> nextOne = new ArrayList<>();
    nextOne.add(FOUR);
    nextOne.add(FIVE);
    nextOne.stream().forEachOrdered(sj::add);

    String expected = "{"+ONE+DASH+TWO+DASH+THREE+DASH+FOUR+DASH+FIVE+"}";
    assertEquals(sj.toString(), expected);
}
 
Example 5
Project: qpp-conversion-tool   File: ConversionEntry.java   View source code 6 votes vote down vote up
/**
 * extractDir parses the input path for wild card characters.
 *
 * @param path String folder path to search
 * @return String up to the wild card character
 */
static String extractDir(String path) {
	String[] parts = path.split(DIR_EXTRACTION);

	StringJoiner dirPath = new StringJoiner(fileSystem.getSeparator());
	for (String part : parts) {
		// append until a wild card
		if (part.contains("*")) { // append until a wild card
			break;
		}
		dirPath.add(part);
	}
	if (dirPath.length() == 0) { // if no path then use the current dir
		return ".";
	}

	return dirPath.toString();
}
 
Example 6
Project: lttng-scope   File: LamiProcess.java   View source code 6 votes vote down vote up
private String generateString() {
    Long pid = fPid;
    Long tid = fTid;

    StringBuilder sb = new StringBuilder();
    if (fName != null) {
        sb.append(fName);
    }

    if (pid != null || tid != null) {
        sb.append(' ');
        StringJoiner sj = new StringJoiner(", ", "(", ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        if (pid != null) {
            sj.add("pid=" + pid.toString()); //$NON-NLS-1$
        }
        if (tid != null) {
            sj.add("tid=" + tid.toString()); //$NON-NLS-1$
        }
        sb.append(sj.toString());
    }

    return sb.toString();
}
 
Example 7
Project: processing-idea   File: ProcessingSketchRootSelectStep.java   View source code 6 votes vote down vote up
private void refreshPdeFileImportPreview() {
    if (! getParameters().importablePdeFiles.isEmpty()) {
        filesDetectedLabel.setForeground(JBColor.BLACK);
        filesDetectedLabel.setText(getParameters().importablePdeFiles.size() + " PDE files");

        StringJoiner importablePdeFilePaths = new StringJoiner("\n");

        for (VirtualFile importablePdeFile : getParameters().importablePdeFiles) {
            importablePdeFilePaths.add(importablePdeFile.getPath());
        }

        importableClassesListTextArea.setText(importablePdeFilePaths.toString());
    } else {
        importableClassesListTextArea.setText("No sketch classes were found at this root directory.");
        filesDetectedLabel.setText("0 PDE files");
        filesDetectedLabel.setForeground(JBColor.RED);
    }
}
 
Example 8
Project: AthenaX   File: WebServer.java   View source code 6 votes vote down vote up
public WebServer(URI endpoint) throws IOException {
  this.server = GrizzlyServerFactory.createHttpServer(endpoint, new HttpHandler() {

    @Override
    public void service(Request rqst, Response rspns) throws Exception {
      rspns.setStatus(HttpStatus.NOT_FOUND_404.getStatusCode(), "Not found");
      rspns.getWriter().write("404: not found");
    }
  });

  WebappContext context = new WebappContext("WebappContext", BASE_PATH);
  ServletRegistration registration = context.addServlet("ServletContainer", ServletContainer.class);
  registration.setInitParameter(ServletContainer.RESOURCE_CONFIG_CLASS,
      PackagesResourceConfig.class.getName());

  StringJoiner sj = new StringJoiner(",");
  for (String s : PACKAGES) {
    sj.add(s);
  }

  registration.setInitParameter(PackagesResourceConfig.PROPERTY_PACKAGES, sj.toString());
  registration.addMapping(BASE_PATH);
  context.deploy(server);
}
 
Example 9
Project: alfresco-repository   File: TransformerDebugTest.java   View source code 6 votes vote down vote up
private String[] unnumbered(String actual[])
{
    for (int i = actual.length-1; i >= 0; i--)
    {
        StringJoiner sj = new StringJoiner("\n");
        String[] bits = actual[i].split("\n");
        for (String bit: bits)
        {
            Pattern p = Pattern.compile("^[0-9.]*");
            Matcher m = p.matcher(bit);
            bit = m.replaceFirst("0");
            sj.add(bit);
        }
        actual[i] = sj.toString();
    }
    return actual;
}
 
Example 10
Project: tdb3   File: Opts.java   View source code 6 votes vote down vote up
public static void print(Map<String,Method> methods) throws Exception {
    methods.forEach((n,m)->{
        
        Class<?> returnType = m.getReturnType();
        Class<?>[] params = m.getParameterTypes();
        System.out.printf("%-40s ", m.getName());

        // Only string, boolean, long, int double
        //if ( returnType )

        System.out.print(returnType.getSimpleName());

        System.out.print(" <- ");
        StringJoiner sj = new StringJoiner(" ,", "(",")");
        for (Class<?>p : params ) {
            sj.add(p.getSimpleName());
        }
        System.out.print(sj.toString());
        System.out.println();
    });
}
 
Example 11
Project: ValueClassGenerator   File: Constructor.java   View source code 6 votes vote down vote up
private String getConstructorLine() {
    StringBuilder resultBuilder = new StringBuilder();
    resultBuilder
            .append("public ")
            .append(sourceClass.getName())
            .append("(");
    StringJoiner constructorParams = new StringJoiner(", ");
    variables.stream().forEach(variable -> {
        String name = variable.getName().getValue();
        constructorParams.add(determinClassName(variable) + " " + name);
    });
    resultBuilder.append(constructorParams.toString());
    resultBuilder.append(
            ") {");
    return resultBuilder.toString();
}
 
Example 12
Project: TreeFlood   File: RobotNodeStringifier.java   View source code 6 votes vote down vote up
/**
 * Returns a text containing all robots currently located in the given node.
 */
@Override
public String nodeToString(final ITreeNode node) {
	ITreeNode nodeToStringify = node;
	// Use an alias if set
	if (this.mOriginalToAlias != null) {
		final ITreeNode alias = this.mOriginalToAlias.get(node);
		if (alias != null) {
			nodeToStringify = alias;
		}
	}

	final StringJoiner joiner = new StringJoiner(", ", "{", "}");
	final SortedSet<Robot> robotsAtNode = this.mNodeToRobots.get(nodeToStringify);
	if (robotsAtNode != null) {
		for (final Robot robot : robotsAtNode) {
			joiner.add(Integer.toString(robot.getId()));
		}
	}
	return joiner.toString();
}
 
Example 13
Project: scanning   File: ScanAtomAssembler.java   View source code 6 votes vote down vote up
@Override
public void setBeanName(ScanAtom bean) {
	StringJoiner name = new StringJoiner(" ");
	name.add("Scan of");

	ScanRequest<?> scanReq = bean.getScanReq();
	StringJoiner paths = new StringJoiner(", ");
	for (Object pathModel : scanReq.getCompoundModel().getModels()) {
		for (String pathName : pathAssemblerRegister.keySet()) {
			if (pathModel.getClass().getSimpleName().toLowerCase().startsWith(pathName)) {
				paths.add(pathAssemblerRegister.get(pathName).getString(pathModel));
			}
		}
	}
	name.add(paths.toString());
	name.add("collecting data with");
	name.add(scanReq.getDetectors().keySet().stream().map(detName -> "'"+detName+"'").collect(Collectors.joining(", ")));
	name.add("detector(s)");

	bean.setName(name.toString());
}
 
Example 14
Project: omero-ms-queue   File: Caches.java   View source code 6 votes vote down vote up
/**
 * Sets headers so that the response is never cached.
 * @param response the response on which to set the headers.
 * @throws NullPointerException if the argument is {@code null}. 
 */
public static void doNotCache(HttpServletResponse response) {
    requireNonNull(response, "response");
    
    response.setHeader(CacheControl, new StringJoiner(", ")
                                    .add(NoStore)
                                    .add(NoCache)
                                    .add(MustRevalidate)
                                    .toString());
    response.setHeader(Pragma, NoCache);
    response.setIntHeader(Expires, 0);
}
 
Example 15
Project: mot-automated-testsuite   File: DataServerManager.java   View source code 6 votes vote down vote up
/**
 * Calculates the server classpath, which is a colon-delimited string of directories and .jar files.
 * @param baseLibDir    The base directory of server libs and classes
 * @return The classpath
 */
private static String calculateServerClasspath(String baseLibDir) {
    try {
        Path baseLibPath = Paths.get(baseLibDir).toAbsolutePath().normalize();
        Stream<Path> jars = Files.find(baseLibPath, 1, (path, attrs) -> path.toString().endsWith(".jar"));
        StringJoiner joiner = new StringJoiner(":");

        // server libs directory (containing the server Java classes)
        joiner.add(baseLibPath.toString());

        // all .jar files in the same directory
        jars.forEach((path) -> joiner.add(path.toString()));

        return joiner.toString();

    } catch (IOException ex) {
        String message = "Error resolving server base lib dir: " + ex.getMessage();
        logger.error(message, ex);
        throw new IllegalArgumentException(message, ex);
    }
}
 
Example 16
Project: shuffleboard   File: NetworkTableSourceEntry.java   View source code 6 votes vote down vote up
private static String displayStringForValue(Object value) {
  if (value == null) {
    return "";
  }
  if (value instanceof double[]) {
    return Arrays.toString((double[]) value);
  }
  if (value instanceof String[]) {
    return Arrays.toString((String[]) value);
  }
  if (value instanceof boolean[]) {
    return Arrays.toString((boolean[]) value);
  }
  if (value instanceof byte[]) {
    StringJoiner joiner = new StringJoiner(", ", "[", "]");
    for (byte raw : (byte[]) value) {
      // Display as unsigned hexadecimal strings, eg 15 -> 0x0F
      joiner.add(String.format("0x%02X", 0xFF & raw));
    }
    return joiner.toString();
  }
  return value.toString();
}
 
Example 17
Project: openjdk-jdk10   File: MergeTest.java   View source code 6 votes vote down vote up
public void testEmptyBoth() {
    fixesStream().forEach(fixes -> {
        StringJoiner sj = new StringJoiner(",", fixes.pre0, fixes.suf0);
        StringJoiner other = new StringJoiner(":", fixes.pre1, fixes.suf1);

        sj.merge(other);
        assertEquals(sj.toString(), fixes.pre0 + fixes.suf0);

        other.setEmptyValue("NOTHING");
        sj.merge(other);
        assertEquals(sj.toString(), fixes.pre0 + fixes.suf0);

        sj = new StringJoiner(",", fixes.pre0, fixes.suf0).setEmptyValue("EMPTY");
        assertEquals(sj.toString(), "EMPTY");
        sj.merge(other);
        assertEquals(sj.toString(), "EMPTY");
    });
}
 
Example 18
Project: saluki   File: ConsulService.java   View source code 6 votes vote down vote up
String toConsulRegistrationJson() {
    final StringBuilder builder = new StringBuilder();
    builder.append("{");
    append(builder, "ID", id);
    builder.append(",");
    append(builder, "Name", name);
    builder.append(",");
    if (!tags.isEmpty()) {
        builder.append("\"Tags\":[");
        StringJoiner joiner = new StringJoiner(",");
        tags.stream().map(t -> "\"" + t + "\"").forEach(joiner::add);
        builder.append(joiner.toString());
        builder.append("],");
    }
    if (address != null) {
        append(builder, "Address", address);
        builder.append(",");
    }
    append(builder, "Port", port);
    builder.append(",");
    builder.append("\"Check\":{");
    append(builder, "Interval", interval);
    builder.append("}");
    builder.append("}");
    return builder.toString();
}
 
Example 19
Project: L2J-Global   File: AdminEditChar.java   View source code 6 votes vote down vote up
/**
 * @param activeChar
 * @param characterName
 * @throws IllegalArgumentException
 */
private void findCharactersPerAccount(L2PcInstance activeChar, String characterName) throws IllegalArgumentException
{
	final L2PcInstance player = L2World.getInstance().getPlayer(characterName);
	if (player == null)
	{
		throw new IllegalArgumentException("Player doesn't exist");
	}
	
	final Map<Integer, String> chars = player.getAccountChars();
	final StringJoiner replyMSG = new StringJoiner("<br1>");
	chars.values().stream().forEachOrdered(replyMSG::add);
	
	final NpcHtmlMessage adminReply = new NpcHtmlMessage(0, 1);
	adminReply.setFile(activeChar.getHtmlPrefix(), "data/html/admin/accountinfo.htm");
	adminReply.replace("%account%", player.getAccountName());
	adminReply.replace("%player%", characterName);
	adminReply.replace("%characters%", replyMSG.toString());
	activeChar.sendPacket(adminReply);
}
 
Example 20
Project: openjdk-jdk10   File: SocketPermission.java   View source code 6 votes vote down vote up
/**
 * Returns the "canonical string representation" of the actions in the
 * specified mask.
 * Always returns present actions in the following order:
 * connect, listen, accept, resolve.
 *
 * @param mask a specific integer action mask to translate into a string
 * @return the canonical string representation of the actions
 */
private static String getActions(int mask) {
    StringJoiner sj = new StringJoiner(",");
    if ((mask & CONNECT) == CONNECT) {
        sj.add("connect");
    }
    if ((mask & LISTEN) == LISTEN) {
        sj.add("listen");
    }
    if ((mask & ACCEPT) == ACCEPT) {
        sj.add("accept");
    }
    if ((mask & RESOLVE) == RESOLVE) {
        sj.add("resolve");
    }
    return sj.toString();
}
 
Example 21
Project: openNaEF   File: Notifier.java   View source code 6 votes vote down vote up
/**
 * 設定ファイルを元に NaEF Restful API の DtoChanges 取得 API の URL を生成する
 * <p>
 * http://{naef-addr}:{naef-rest-api-port}/api/{naef-rest-api-version}/dto-changes?version={tx}&time={time}
 *
 * @param tx   ターゲットとなるトランザクション ID
 * @param time ターゲットとなる時間
 * @return NaEF Restful API DtoChanges URL
 */
public static URL getDtoChangesUri(TransactionId.W tx, DateTime time) throws IOException {
    NotifierConfig conf = NotifierConfig.instance();
    String urlStr = new Formatter().format(
            "http://%s:%s/api/%s/dto-changes",
            conf.naefAddr(),
            conf.naefRestApiPort(),
            conf.naefRestApiVersion())
            .toString();

    StringJoiner queries = new StringJoiner("&");
    if (tx != null) {
        queries.add("version=" + tx.toString());
    }
    if (time != null) {
        queries.add("time=" + time.getValue());
    }

    if (queries.length() > 0) {
        urlStr += "?" + queries.toString();
    }

    return new URL(urlStr);
}
 
Example 22
Project: uroborosql   File: SqlContextFactoryImpl.java   View source code 6 votes vote down vote up
/**
 * classファイルから対象パッケージ以下のEnumクラスを取得
 *
 * @param packageName ルートパッケージ名
 * @param dir 対象ディレクトリ
 * @return クラスリスト
 * @throws ClassNotFoundException エラー
 * @throws IOException
 */
private static Set<Class<?>> findEnumClassesWithFile(final String packageName, final Path dir) {
	Set<Class<?>> classes = new HashSet<>();
	try (Stream<Path> stream = Files.walk(dir)) {
		stream.filter(entry -> entry.getFileName().toString().endsWith(".class")).forEach(file -> {
			StringJoiner joiner = new StringJoiner(".", packageName + ".", "");
			dir.relativize(file).forEach(p -> joiner.add(p.toString()));
			String className = joiner.toString().replaceAll(".class$", "");
			loadEnum(className).ifPresent(classes::add);
		});
	} catch (IOException e) {
		LOG.error(e.getMessage(), e);
	}

	return classes;
}
 
Example 23
Project: africastalking-java   File: SmsService.java   View source code 6 votes vote down vote up
private String formatRecipients(String[] recipients) {

        if (recipients == null){
            return null;
        }

        if (recipients.length == 1) {
            return recipients[0];
        }

        StringJoiner joiner = new StringJoiner(",");
        for (CharSequence cs: recipients) {
            joiner.add(cs);
        }
        return joiner.toString();
    }
 
Example 24
Project: presto-manager   File: LogFilter.java   View source code 6 votes vote down vote up
/**
 * @return true if the line addition succeeded
 */
private boolean addNewEntry(String line)
{
    if (entries.size() >= maxEntries) {
        if (keepFirst) {
            return false;
        }
        else if (maxEntries == 0) {
            return true;
        }
        entries.removeFirst();
    }
    StringJoiner joiner = new StringJoiner(lineSeparator);
    joiner.add(line);
    entries.addLast(joiner);
    return true;
}
 
Example 25
Project: spanner-jdbc   File: CloudSpannerArray.java   View source code 5 votes vote down vote up
@Override
public String toString()
{
	StringJoiner joiner = new StringJoiner(",", "{", "}");
	if (data != null)
	{
		for (Object o : (Object[]) data)
		{
			joiner.add(o.toString());
		}
	}
	return joiner.toString();
}
 
Example 26
Project: n4js   File: N4jscBase.java   View source code 5 votes vote down vote up
/**
 * Dumps available runners to a stream
 *
 * @param out
 *            stream to print to
 */
private void printAvailableRunners(PrintStream out) {
	if (testerRegistry.getDescriptors().isEmpty())
		out.println("No runners found.");
	else {
		StringJoiner sj = new StringJoiner("\n\t");
		sj.add("Available runners are:");
		testerRegistry.getDescriptors().values().forEach(td -> sj.add(td.getId()));
		out.println(sj);
	}
}
 
Example 27
Project: n4js   File: N4jscBase.java   View source code 5 votes vote down vote up
/**
 * Dumps available testers to a stream
 *
 * @param out
 *            stream to print to
 */
private void printAvailableTesters(PrintStream out) {
	if (testerRegistry.getDescriptors().isEmpty())
		out.println("No testers found.");
	else {
		StringJoiner sj = new StringJoiner("\n\t");
		sj.add("Available testers are:");
		testerRegistry.getDescriptors().values().forEach(td -> sj.add(td.getId()));
		out.println(sj);
	}
}
 
Example 28
Project: openjdk-jdk10   File: Class.java   View source code 5 votes vote down vote up
/**
 * Helper method to get the method name from arguments.
 */
private String methodToString(String name, Class<?>[] argTypes) {
    StringJoiner sj = new StringJoiner(", ", getName() + "." + name + "(", ")");
    if (argTypes != null) {
        for (int i = 0; i < argTypes.length; i++) {
            Class<?> c = argTypes[i];
            sj.add((c == null) ? "null" : c.getName());
        }
    }
    return sj.toString();
}
 
Example 29
Project: openjdk-jdk10   File: Constructor.java   View source code 5 votes vote down vote up
@Override
String toShortString() {
    StringBuilder sb = new StringBuilder("constructor ");
    sb.append(getDeclaringClass().getTypeName());
    sb.append('(');
    StringJoiner sj = new StringJoiner(",");
    for (Class<?> parameterType : getParameterTypes()) {
        sj.add(parameterType.getTypeName());
    }
    sb.append(sj);
    sb.append(')');
    return sb.toString();
}
 
Example 30
Project: openjdk-jdk10   File: RDN.java   View source code 5 votes vote down vote up
public String toRFC1779String(Map<String, String> oidMap) {
    if (assertion.length == 1) {
        return assertion[0].toRFC1779String(oidMap);
    }

    StringJoiner sj = new StringJoiner(" + ");
    for (int i = 0; i < assertion.length; i++) {
        sj.add(assertion[i].toRFC1779String(oidMap));
    }
    return sj.toString();
}
 
Example 31
Project: uppercore   File: InvalidConfigException.java   View source code 5 votes vote down vote up
private String getErrorMessage(String initMsg) {
    List<String> locators = Lists.reverse(getLocators());
    if (locators.size() > 0) {
        initMsg += ": ";
        StringJoiner joiner = new StringJoiner(", ");
        for (String loc : locators) {
            joiner.add(loc);
        }
        initMsg += joiner.toString();
    }
    initMsg += " " + configError;
    return initMsg;
}
 
Example 32
Project: openjdk-jdk10   File: HttpURLConnection.java   View source code 5 votes vote down vote up
/**
 * Returns a filtered version of the given headers value.
 *
 * Note: The implementation currently only filters out HttpOnly cookies
 *       from Set-Cookie and Set-Cookie2 headers.
 */
private String filterHeaderField(String name, String value) {
    if (value == null)
        return null;

    if (SET_COOKIE.equalsIgnoreCase(name) ||
        SET_COOKIE2.equalsIgnoreCase(name)) {

        // Filtering only if there is a cookie handler. [Assumption: the
        // cookie handler will store/retrieve the HttpOnly cookies]
        if (cookieHandler == null || value.length() == 0)
            return value;

        JavaNetHttpCookieAccess access =
                SharedSecrets.getJavaNetHttpCookieAccess();
        StringJoiner retValue = new StringJoiner(",");  // RFC 2965, comma separated
        List<HttpCookie> cookies = access.parse(value);
        for (HttpCookie cookie : cookies) {
            // skip HttpOnly cookies
            if (!cookie.isHttpOnly())
                retValue.add(access.header(cookie));
        }
        return retValue.toString();
    }

    return value;
}
 
Example 33
Project: uppercore   File: ConfigIcon.java   View source code 5 votes vote down vote up
@Override
public String toString() {
    StringJoiner joiner = new StringJoiner(", ");
    joiner.add("permission: " + permission);
    joiner.add("noPermissionError: " + noPermissionError);
    joiner.add("noPermissionSound: " + noPermissionSound);
    joiner.add("cost: " + cost);
    joiner.add("noMoneyError: " + noMoneyError);
    joiner.add("noMoneySound: " + noMoneySound);
    return '{' + joiner.toString() + '}';
}
 
Example 34
Project: incubator-netbeans   File: Feedback.java   View source code 5 votes vote down vote up
private <E extends Enum<E>> void selectorToString(StringBuilder sb, Set<E> c, E[] values) {
    if (!c.containsAll(Arrays.asList(values))) {
        sb.append(c.stream()
                .sorted((x, y) -> x.ordinal() - y.ordinal())
                .map(v -> v.name().toLowerCase(Locale.US))
                .collect(new Collector<CharSequence, StringJoiner, String>() {
                    @Override
                    public BiConsumer<StringJoiner, CharSequence> accumulator() {
                        return StringJoiner::add;
                    }

                    @Override
                    public Supplier<StringJoiner> supplier() {
                        return () -> new StringJoiner(",", (sb.length() == 0)? "" : "-", "")
                                .setEmptyValue("");
                    }

                    @Override
                    public BinaryOperator<StringJoiner> combiner() {
                        return StringJoiner::merge;
                    }

                    @Override
                    public Function<StringJoiner, String> finisher() {
                        return StringJoiner::toString;
                    }

                    @Override
                    public Set<Characteristics> characteristics() {
                        return Collections.emptySet();
                    }
                }));
    }
}
 
Example 35
Project: IdeaCurrency   File: IdeaCurrencyConfig.java   View source code 5 votes vote down vote up
@Transient
public void setSelectedExchangeCurrencyPairs(Set<SelectedExchangeCurrencyPair> selectedExchangeCurrencyPairs) {
    this.selectedExchangeCurrencyPairs = selectedExchangeCurrencyPairs;
    for (SelectedExchangeCurrencyPair selectedExchangeCurrencyPair : selectedExchangeCurrencyPairs) {
        StringJoiner stringJoiner = new StringJoiner(",");
        for (CurrencyPair currencyPair : selectedExchangeCurrencyPair.getCurrencyPairList()) {
            stringJoiner.add(currencyPair.toString());
        }
        if (StringUtils.isNotBlank(stringJoiner.toString())) {
            currencyPairByExchangeMap.put(selectedExchangeCurrencyPair.getExchangeName(), stringJoiner.toString());
        }
    }
}
 
Example 36
Project: trellis   File: UUIDGenerator.java   View source code 5 votes vote down vote up
private static String getId(final String prefix, final Integer hierarchy, final Integer length) {
    final String id = randomUUID().toString();
    final String nodash = id.replaceAll("-", "");
    final StringJoiner joiner = new StringJoiner("/");
    rangeClosed(0, hierarchy - 1).forEach(x -> joiner.add(nodash.substring(x * length, (x + 1) * length)));
    joiner.add(id);

    return prefix + joiner;
}
 
Example 37
Project: elasticsearch_my   File: CustomMustacheFactory.java   View source code 5 votes vote down vote up
@Override
protected Function<String, String> createFunction(Object resolved) {
    return s -> {
        if (s == null) {
            return null;
        } else if (resolved instanceof Iterable) {
            StringJoiner joiner = new StringJoiner(delimiter);
            for (Object o : (Iterable) resolved) {
                joiner.add(oh.stringify(o));
            }
            return joiner.toString();
        }
        return s;
    };
}
 
Example 38
Project: openjdk-jdk10   File: Feedback.java   View source code 5 votes vote down vote up
private <E extends Enum<E>> void selectorToString(StringBuilder sb, Set<E> c, E[] values) {
    if (!c.containsAll(Arrays.asList(values))) {
        sb.append(c.stream()
                .sorted((x, y) -> x.ordinal() - y.ordinal())
                .map(v -> v.name().toLowerCase(Locale.US))
                .collect(new Collector<CharSequence, StringJoiner, String>() {
                    @Override
                    public BiConsumer<StringJoiner, CharSequence> accumulator() {
                        return StringJoiner::add;
                    }

                    @Override
                    public Supplier<StringJoiner> supplier() {
                        return () -> new StringJoiner(",", (sb.length() == 0)? "" : "-", "")
                                .setEmptyValue("");
                    }

                    @Override
                    public BinaryOperator<StringJoiner> combiner() {
                        return StringJoiner::merge;
                    }

                    @Override
                    public Function<StringJoiner, String> finisher() {
                        return StringJoiner::toString;
                    }

                    @Override
                    public Set<Characteristics> characteristics() {
                        return Collections.emptySet();
                    }
                }));
    }
}
 
Example 39
Project: hue   File: JoinDetector.java   View source code 5 votes vote down vote up
private String literalize(List<String> v, int type){
	StringJoiner sj = new StringJoiner(",", "(",")");
	if(type == Types.NUMERIC || type == Types.BIGINT || type == Types.BIT || type == Types.DECIMAL
			|| type == Types.DOUBLE || type == Types.FLOAT || type == Types.INTEGER || type == Types.REAL || type == Types.ROWID
			|| type == Types.SMALLINT || type == Types.TINYINT){


		v.forEach(s -> sj.add(s) );
	}else{
		v.forEach(s -> sj.add("'" + s + "'") );
	}
	return sj.toString();
}
 
Example 40
Project: openjdk-jdk10   File: MergeTest.java   View source code 5 votes vote down vote up
public void testSimple() {
    fixesStream().forEach(fixes -> {
        StringJoiner sj = new StringJoiner(",", fixes.pre0, fixes.suf0);
        StringJoiner other = new StringJoiner(",", fixes.pre1, fixes.suf1);
        Stream.of("a", "b", "c").forEachOrdered(sj::add);
        Stream.of("d", "e", "f").forEachOrdered(other::add);

        sj.merge(other);
        assertEquals(sj.toString(), fixes.pre0 + "a,b,c,d,e,f" + fixes.suf0);
    });
}