java.util.StringJoiner Java Examples

The following examples show how to use java.util.StringJoiner. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MockUrlLogicServiceImpl.java    From v-mock with MIT License 8 votes vote down vote up
/**
 * 通过url查询logic字符串
 *
 * @param url 路径
 * @return logic字符串
 */
@Override
public String selectLogicStrByUrl(String url) {
    // 拆分为子url
    List<String> subUrls = StrUtil.splitTrim(url, StrUtil.C_SLASH);
    // empty -> put '/'
    if (subUrls.isEmpty()) {
        subUrls.add(StrUtil.SLASH);
    }
    // 查询对应logicId
    List<MockUrlLogic> urlLogics = this.list(Wrappers.<MockUrlLogic>lambdaQuery()
            // in 查询请求的url
            .in(MockUrlLogic::getSubUrl, subUrls));
    // 转为map
    Map<String, Long> subUrlAndLogicId = urlLogics.stream().collect(Collectors.toMap(MockUrlLogic::getSubUrl, MockUrlLogic::getLogicId));
    StringJoiner logicStrJoiner = new StringJoiner(StrUtil.COMMA);
    // 删除空元素,循环拼接
    subUrls.stream().filter(StrUtil::isNotBlank).forEach(item -> {
        // 2.get logicId, ※ 如果是null,那么推测此处用户用了path传参, 则返回占位符!
        Long logicId = subUrlAndLogicId.get(item);
        // 拼接
        logicStrJoiner.add(logicId == null ? CommonConst.PATH_PLACEHOLDER : logicId.toString());
    });
    return logicStrJoiner.toString();
}
 
Example #2
Source File: ODataAtomParser.java    From odata with Apache License 2.0 6 votes vote down vote up
private void ensureNonNullableCollectionArePresent(StructuredType entityType) throws ODataException {
    if (getRequest().getMethod() != ODataRequest.Method.POST) {
        return;
    }
    List<String> missingCollectionPropertyName = new ArrayList<>();

    entityType.getStructuralProperties().stream()
            .filter(property -> (property.isCollection()) &&
                    !(property instanceof NavigationProperty) && (!property.isNullable()))
            .forEach(property -> {
                LOG.debug("Validating non-nullable collection property : {}", property.getName());
                if (!foundCollectionProperties.contains(property.getName())) {
                    missingCollectionPropertyName.add(property.getName());
                }
            });
    if (missingCollectionPropertyName.size() != 0) {
        StringJoiner joiner = new StringJoiner(",");
        missingCollectionPropertyName.forEach(joiner::add);
        LOG.debug("Non-nullable collections of {} are not found in the request" + missingCollectionPropertyName);
        throw new ODataUnmarshallingException("The request does not specify the non-nullable collections: '"
                + joiner.toString() + ".");
    }

}
 
Example #3
Source File: RakNetInterface.java    From Nemisys with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void setName(String name) {
    QueryRegenerateEvent info = this.server.getQueryInformation();

    String[] names = name.split("!@#");
    String motd = Utils.rtrim(names[0].replace(";", "\\;"), '\\');
    String subMotd = names.length > 1 ? Utils.rtrim(names[1].replace(";", "\\;"), '\\') : "";
    StringJoiner joiner = new StringJoiner(";")
            .add("MCPE")
            .add(motd)
            .add(Integer.toString(ProtocolInfo.CURRENT_PROTOCOL))
            .add(ProtocolInfo.MINECRAFT_VERSION_NETWORK)
            .add(Integer.toString(info.getPlayerCount()))
            .add(Integer.toString(info.getMaxPlayerCount()))
            .add(server.getServerUniqueId().toString())
            .add(subMotd)
            .add("Survival")
            .add("1");

    this.handler.sendOption("name", joiner.toString());
}
 
Example #4
Source File: Exercise33_2_Deque.java    From algorithms-sedgewick-wayne with MIT License 6 votes vote down vote up
private void testPopLeft() {
    StdOut.println("\nTest Pop Left");

    Exercise33_2_Deque<String> deque = new Exercise33_2_Deque<>();
    deque.pushRight("a");
    deque.pushRight("b");
    deque.pushRight("c");

    deque.popLeft();
    deque.popLeft();

    StringJoiner dequeItems = new StringJoiner(" ");
    for (String item : deque) {
        dequeItems.add(item);
    }

    StdOut.println("Deque items: " + dequeItems.toString());
    StdOut.println("Expected: c");
}
 
Example #5
Source File: NestedSQLMapper.java    From syncer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String[] join(HashMap<String, Object> map) {
  StringJoiner keys = new StringJoiner(",");
  ParameterizedString parameterizedString = null;
  HashMap<String, String> tmp = new HashMap<>();
  for (Entry<String, Object> entry : map.entrySet()) {
    keys.add(SQLHelper.wrapCol(entry.getKey()));
    Object value = entry.getValue();
    if (value instanceof ParameterizedString && value != parameterizedString) {
      // TODO 18/3/8 multiple query, change to select .. a join b
      // JdbcNestedQueryMapper & ParameterizedString
      parameterizedString = (ParameterizedString) value;
    } else {
      tmp.put(entry.getKey(), SQLHelper.inSQL(value));
    }
  }
  Assert.notNull(parameterizedString, "[Impossible to be null]");
  parameterizedString.nameToAlias(tmp);
  return new String[]{keys.toString(), parameterizedString.getSql()};
}
 
Example #6
Source File: MergeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public void testEmptyBoth() {
    StringJoiner sj = new StringJoiner(",", "{", "}");
    StringJoiner other = new StringJoiner(":", "[", "]");

    sj.merge(other);
    assertEquals(sj.toString(), "{}");

    other.setEmptyValue("NOTHING");
    sj.merge(other);
    assertEquals(sj.toString(), "{}");

    sj = new StringJoiner(",", "{", "}").setEmptyValue("EMPTY");
    assertEquals(sj.toString(), "EMPTY");
    sj.merge(other);
    assertEquals(sj.toString(), "EMPTY");
}
 
Example #7
Source File: DetailItem.java    From logbook-kai with MIT License 6 votes vote down vote up
@Override
public String toString() {
    return new StringJoiner("\t")
            .add(Optional.ofNullable(this.alv.get())
                    .filter(v -> v > 0)
                    .map(v -> Messages.getString("item.alv", v)) //$NON-NLS-1$
                    .orElse(""))
            .add(Optional.ofNullable(this.level.get())
                    .filter(v -> v > 0)
                    .map(v -> Messages.getString("item.level", v)) //$NON-NLS-1$
                    .orElse(""))
            .add(Optional.ofNullable(this.ship.get())
                    .map(Ships::toName)
                    .orElse("未所持"))
            .toString();
}
 
Example #8
Source File: ItemsetResult.java    From macrobase with Apache License 2.0 6 votes vote down vote up
public String prettyPrint() {
    StringJoiner joiner = new StringJoiner("\n");
    items.stream()
            .forEach(i -> joiner.add(String.format("\t%s: %s",
                                                   i.getColumn(),
                                                   i.getValue())));

    return String.format("support: %f\n" +
                         "records: %f\n" +
                         "ratio: %f\n" +
                         "\nColumns:\n%s\n\n",
                         support,
                         numRecords,
                         ratioToInliers,
                         joiner.toString());
}
 
Example #9
Source File: LinxSvDataFile.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
private static String header()
{
    return new StringJoiner(DELIMITER)
            .add("svId")
            .add("clusterId")
            .add("clusterReason")
            .add("fragileSiteStart")
            .add("fragileSiteEnd")
            .add("isFoldback")
            .add("lineTypeStart")
            .add("lineTypeEnd")
            .add("junctionCopyNumberMin")
            .add("junctionCopyNumberMax")
            .add("geneStart")
            .add("geneEnd")
            .add("replicationTimingStart")
            .add("replicationTimingEnd")
            .add("localTopologyIdStart")
            .add("localTopologyIdEnd")
            .add("localTopologyStart")
            .add("localTopologyEnd")
            .add("localTICountStart")
            .add("localTICountEnd")
            .toString();
}
 
Example #10
Source File: ObfuscationReflectionHelper.java    From patchwork-api with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Finds a constructor with the specified parameter types in the given class and makes it accessible.
 * Note: For performance, store the returned value and avoid calling this repeatedly.
 *
 * <p>Throws an exception if the constructor is not found.</p>
 *
 * @param clazz          The class to find the constructor in.
 * @param parameterTypes The parameter types of the constructor.
 * @param <T>            The type.
 * @return The constructor with the specified parameters in the given class.
 * @throws NullPointerException        If {@code clazz} is null.
 * @throws NullPointerException        If {@code parameterTypes} is null.
 * @throws UnknownConstructorException If the constructor could not be found.
 */
@Nonnull
public static <T> Constructor<T> findConstructor(@Nonnull final Class<T> clazz, @Nonnull final Class<?>... parameterTypes) {
	Preconditions.checkNotNull(clazz, "Class to find constructor on cannot be null.");
	Preconditions.checkNotNull(parameterTypes, "Parameter types of constructor to find cannot be null.");

	try {
		Constructor<T> constructor = clazz.getDeclaredConstructor(parameterTypes);
		constructor.setAccessible(true);
		return constructor;
	} catch (final NoSuchMethodException e) {
		final StringBuilder desc = new StringBuilder();
		desc.append(clazz.getSimpleName());

		StringJoiner joiner = new StringJoiner(", ", "(", ")");

		for (Class<?> type : parameterTypes) {
			joiner.add(type.getSimpleName());
		}

		desc.append(joiner);

		throw new UnknownConstructorException("Could not find constructor '" + desc + "' in " + clazz);
	}
}
 
Example #11
Source File: XACMLProperties.java    From XACML with MIT License 6 votes vote down vote up
/**
 * Set the properties to ensure it points to correct referenced policy files. This will overwrite
 * any previous properties set for referenced policies.
 *
 * @param properties Properties object that will get updated with referenced policy details
 * @param referencedPolicies list of Paths to referenced Policies
 * @return Properties object passed in
 */
public static Properties setXacmlReferencedProperties(Properties properties, Path... referencedPolicies) {
    //
    // Clear out the old entries
    //
    clearPolicyProperties(properties, XACMLProperties.PROP_REFERENCEDPOLICIES);
    //
    // Rebuild the list
    //
    int id = 1;
    StringJoiner joiner = new StringJoiner(",");
    for (Path policy : referencedPolicies) {
        String ref = "ref" + id++;
        joiner.add(ref);
        properties.setProperty(ref + FILE_APPEND, policy.toAbsolutePath().toString());
    }
    properties.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, joiner.toString());
    return properties;
}
 
Example #12
Source File: ValueNode.java    From JRediSearch with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private String toStringDefault(ParenMode mode) {
    boolean useParen = mode == ParenMode.ALWAYS;
    if (!useParen) {
        useParen = mode != ParenMode.NEVER && values.length > 1;
    }
    StringBuilder sb = new StringBuilder();
    if (useParen) {
        sb.append('(');
    }
    StringJoiner sj = new StringJoiner(joinString);
    for (Value v : values) {
        sj.add(formatField() + v.toString());
    }
    sb.append(sj.toString());
    if (useParen) {
        sb.append(')');
    }
    return sb.toString();
}
 
Example #13
Source File: PrettyWriter.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private String formatMethod(RecordedMethod m) {
    StringBuilder sb = new StringBuilder();
    sb.append(m.getType().getName());
    sb.append(".");
    sb.append(m.getName());
    sb.append("(");
    StringJoiner sj = new StringJoiner(", ");
    String md = m.getDescriptor().replace("/", ".");
    String parameter = md.substring(1, md.lastIndexOf(")"));
    for (String qualifiedName : decodeDescriptors(parameter, "")) {
        String typeName = qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1);
        sj.add(typeName);
    }
    sb.append(sj);
    sb.append(")");
    return sb.toString();
}
 
Example #14
Source File: SchoolToken.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public String[] unparse(LoadContext context, Spell spell)
{
	Changes<SpellSchool> changes = context.getObjectContext().getListChanges(spell, ListKey.SPELL_SCHOOL);
	if (changes == null || changes.isEmpty())
	{
		return null;
	}
	StringJoiner joiner = new StringJoiner(Constants.PIPE);
	if (changes.includesGlobalClear())
	{
		joiner.add(Constants.LST_DOT_CLEAR);
	}
	if (changes.hasAddedItems())
	{
		changes.getAdded().forEach(added -> joiner.add(added.toString()));
	}
	return new String[]{joiner.toString()};
}
 
Example #15
Source File: SelectionSessionLogger.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a string id that may be used to identify a TextClassifier result.
 */
public static String createId(
        String text, int start, int end, Context context, int modelVersion,
        List<Locale> locales) {
    Preconditions.checkNotNull(text);
    Preconditions.checkNotNull(context);
    Preconditions.checkNotNull(locales);
    final StringJoiner localesJoiner = new StringJoiner(",");
    for (Locale locale : locales) {
        localesJoiner.add(locale.toLanguageTag());
    }
    final String modelName = String.format(Locale.US, "%s_v%d", localesJoiner.toString(),
            modelVersion);
    final int hash = Objects.hash(text, start, end, context.getPackageName());
    return SignatureParser.createSignature(CLASSIFIER_ID, modelName, hash);
}
 
Example #16
Source File: Utils.java    From obfuscator with MIT License 6 votes vote down vote up
public static String modifierToString(int mod) {
    StringJoiner sj = new StringJoiner(" ");

    if ((mod & ACC_BRIDGE) != 0) sj.add("[bridge]");
    if ((mod & ACC_SYNTHETIC) != 0) sj.add("[syntetic]");

    if ((mod & ACC_PUBLIC) != 0) sj.add("public");
    if ((mod & ACC_PROTECTED) != 0) sj.add("protected");
    if ((mod & ACC_PRIVATE) != 0) sj.add("private");

    /* Canonical order */
    if ((mod & ACC_ABSTRACT) != 0) sj.add("abstract");
    if ((mod & ACC_STATIC) != 0) sj.add("static");
    if ((mod & ACC_FINAL) != 0) sj.add("final");
    if ((mod & ACC_TRANSIENT) != 0) sj.add("transient");
    if ((mod & ACC_VOLATILE) != 0) sj.add("volatile");
    if ((mod & ACC_SYNCHRONIZED) != 0) sj.add("synchronized");
    if ((mod & ACC_NATIVE) != 0) sj.add("native");
    if ((mod & ACC_STRICT) != 0) sj.add("strictfp");
    if ((mod & ACC_INTERFACE) != 0) sj.add("interface");

    return sj.toString();
}
 
Example #17
Source File: DescriptorToken.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public String[] unparse(LoadContext context, Spell spell)
{
	Changes<String> changes = context.getObjectContext().getListChanges(spell, ListKey.SPELL_DESCRIPTOR);
	if (changes == null || changes.isEmpty())
	{
		return null;
	}
	StringJoiner joiner = new StringJoiner(Constants.PIPE);
	if (changes.includesGlobalClear())
	{
		joiner.add(Constants.LST_DOT_CLEAR);
	}
	if (changes.hasAddedItems())
	{
		changes.getAdded().forEach(added -> joiner.add(Objects.requireNonNull(added)));
	}
	return new String[]{joiner.toString()};
}
 
Example #18
Source File: DriverCatalogFile.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
private static String toString(@NotNull final DriverCatalog ratio) {
    return new StringJoiner(DELIMITER).add(ratio.chromosome())
            .add(ratio.chromosomeBand())
            .add(ratio.gene())
            .add(String.valueOf(ratio.driver()))
            .add(String.valueOf(ratio.category()))
            .add(String.valueOf(ratio.likelihoodMethod()))
            .add(FORMAT.format(ratio.driverLikelihood()))
            .add(FORMAT.format(ratio.dndsLikelihood()))
            .add(String.valueOf(ratio.missense()))
            .add(String.valueOf(ratio.nonsense()))
            .add(String.valueOf(ratio.splice()))
            .add(String.valueOf(ratio.inframe()))
            .add(String.valueOf(ratio.frameshift()))
            .add(String.valueOf(ratio.biallelic()))
            .add(FORMAT.format(ratio.minCopyNumber()))
            .add(FORMAT.format(ratio.maxCopyNumber()))
            .toString();
}
 
Example #19
Source File: MockUrlServiceImpl.java    From v-mock with MIT License 6 votes vote down vote up
/**
 * 简单处理入参URL
 *
 * @param url
 * @return url
 */
@Override
public String insertUrlLogic(String url) {
    // 处理逻辑 logic 表 url插入
    List<MockUrlLogic> mockUrlLogics = mockUrlLogicService.insertByUrl(url);
    // 转为map <subUrl, logicId>
    Map<String, Long> urlAndId = mockUrlLogics.stream()
            .collect(Collectors.toMap(MockUrlLogic::getSubUrl, MockUrlLogic::getLogicId));
    // 处理logic字段
    StringJoiner logicJoiner = new StringJoiner(COMMA);
    // 根据url 转为对应的logic字符串
    Arrays.stream(url.split("\\/")).filter(StrUtil::isNotBlank).map(i ->
            // if {path} in url, return {path}
            CommonConst.PATH_PLACEHOLDER.equalsIgnoreCase(i) ? CommonConst.PATH_PLACEHOLDER : urlAndId.get(i).toString()
    ).collect(Collectors.toList()).forEach(logicJoiner::add);
    return logicJoiner.toString();
}
 
Example #20
Source File: Exercise22_Proof.java    From algorithms-sedgewick-wayne with MIT License 6 votes vote down vote up
private void printProof(State state) {
    Stack<State> states = new Stack<>();

    states.push(state);
    while (state.previous != null) {
        states.push(state.previous);
        state = state.previous;
    }

    StringJoiner proof = new StringJoiner(" -> ");
    while (!states.isEmpty()) {
        proof.add(String.valueOf(states.pop().id));
    }

    StdOut.println(proof);
}
 
Example #21
Source File: SocketPermission.java    From Bytecoder with Apache License 2.0 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 #22
Source File: Tokens2Conll.java    From biomedicus with Apache License 2.0 6 votes vote down vote up
public String conllString() {
  StringBuilder conllBuilder = new StringBuilder();
  int i = 1;
  for (ParseToken token : tokenLabels) {
    String text = token.getText();
    StringJoiner tokenBuilder = new StringJoiner("\t", "", "\n");
    tokenBuilder.add(Integer.toString((i++))); // sentence position
    tokenBuilder.add(text); // text
    tokenBuilder.add("_"); // LEMMA
    tokenBuilder.add("_"); // UPOSTAG
    tokenBuilder.add("_"); // XPOSTAG
    tokenBuilder.add("_"); // FEATS
    tokenBuilder.add("_"); // HEAD
    tokenBuilder.add("_"); // DEPREL
    tokenBuilder.add("_"); // DEPS
    tokenBuilder
        .add(token.getHasSpaceAfter() ? "_" : "SpaceAfter=No"); // MISC
    conllBuilder.append(tokenBuilder.toString());
  }

  return conllBuilder.toString();
}
 
Example #23
Source File: EquipmentTypeLookupTest.java    From megamek with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void allLookupKeysValid() throws IllegalAccessException {
    // Collect all failed fields so the test results will show which field(s) failed
    final StringJoiner sj = new StringJoiner(", ");

    for (Field field : EquipmentTypeLookup.class.getFields()) {
        if (field.isAnnotationPresent(EquipmentTypeLookup.EquipmentName.class)
                && ((field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)) {
            String eqName = field.get(null).toString();
            if (EquipmentType.get(eqName) == null) {
                sj.add(eqName);
            }
        }
    }

    assertEquals("", sj.toString());
}
 
Example #24
Source File: ValidationError.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    return new StringJoiner(", ", ValidationError.class.getSimpleName() + "[", "]")
        .add("path='" + path + "'")
        .add("message='" + message + "'")
        .add("invalidValue='" + invalidValue + "'")
        .toString();
}
 
Example #25
Source File: StringExamplesTest.java    From java-8-lambdas-exercises with MIT License 5 votes vote down vote up
@Test
public void beatlesExample() {
    StringJoiner joiner = new StringJoiner(", ", "[", "]");
    joiner.add("John");
    joiner.add("Paul");
    joiner.add("Ringo");
    assertEquals("[John, Paul, Ringo]", joiner.toString());
}
 
Example #26
Source File: GDCatalogType.java    From GriefDefender with MIT License 5 votes vote down vote up
@Override
public String toString() {
    return new StringJoiner(", ", GDCatalogType.class.getSimpleName() + "[", "]")
            .add("id=" + getId())
            .add("name=" + getName())
            .toString();
}
 
Example #27
Source File: ConstraintGenerator.java    From FHIR with Apache License 2.0 5 votes vote down vote up
private String generate(List<Node> nodes) {
    StringJoiner joiner = new StringJoiner(" and ");
    for (Node node : nodes) {
        if (isExtensionUrl(node.elementDefinition)) {
            continue;
        }
        if (isOptional(node.elementDefinition)) {
            joiner.add("(" + generate(node) + ")");
        } else {
            joiner.add(generate(node));
        }
    }
    return joiner.toString();
}
 
Example #28
Source File: VeeamClient.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a single command to be passed through SSH
 */
protected String transformPowerShellCommandList(List<String> cmds) {
    StringJoiner joiner = new StringJoiner(";");
    joiner.add("PowerShell Add-PSSnapin VeeamPSSnapin");
    for (String cmd : cmds) {
        joiner.add(cmd);
    }
    return joiner.toString();
}
 
Example #29
Source File: AnnotationsInheritanceOrderRedefinitionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static String toSimpleString(Annotation[] anns) {
    StringJoiner joiner = new StringJoiner(", ");
    for (Annotation ann : anns) {
        joiner.add(toSimpleString(ann));
    }
    return joiner.toString();
}
 
Example #30
Source File: SellingCompletedEventImpl.java    From robozonky with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    return new StringJoiner(", ", SellingCompletedEventImpl.class.getSimpleName() + "[", "]")
        .add("super=" + super.toString())
        .add("portfolioOverview=" + portfolioOverview)
        .toString();
}