Example usage for java.util.stream Collectors joining

List of usage examples for java.util.stream Collectors joining

Introduction

In this page you can find the example usage for java.util.stream Collectors joining.

Prototype

public static Collector<CharSequence, ?, String> joining(CharSequence delimiter) 

Source Link

Document

Returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.

Usage

From source file:com.haulmont.cuba.core.config.AppPropertiesLocator.java

private void setDataType(Method method, AppPropertyEntity entity) {
    Class<?> returnType = method.getReturnType();
    if (returnType.isPrimitive()) {
        if (returnType == boolean.class)
            entity.setDataTypeName(datatypes.getIdByJavaClass(Boolean.class));
        if (returnType == int.class)
            entity.setDataTypeName(datatypes.getIdByJavaClass(Integer.class));
        if (returnType == long.class)
            entity.setDataTypeName(datatypes.getIdByJavaClass(Long.class));
        if (returnType == double.class || returnType == float.class)
            entity.setDataTypeName(datatypes.getIdByJavaClass(Double.class));
    } else if (returnType.isEnum()) {
        entity.setDataTypeName("enum");
        EnumStore enumStoreAnn = method.getAnnotation(EnumStore.class);
        if (enumStoreAnn != null && enumStoreAnn.value() == EnumStoreMode.ID) {
            //noinspection unchecked
            Class<EnumClass> enumeration = (Class<EnumClass>) returnType;
            entity.setEnumValues(Arrays.asList(enumeration.getEnumConstants()).stream()
                    .map(ec -> String.valueOf(ec.getId())).collect(Collectors.joining(",")));
        } else {/*from ww w  .  j a v  a  2 s.  co  m*/
            entity.setEnumValues(Arrays.asList(returnType.getEnumConstants()).stream().map(Object::toString)
                    .collect(Collectors.joining(",")));
        }
    } else {
        Datatype<?> datatype = datatypes.get(returnType);
        if (datatype != null)
            entity.setDataTypeName(datatypes.getId(datatype));
        else
            entity.setDataTypeName(datatypes.getIdByJavaClass(String.class));
    }

    String dataTypeName = entity.getDataTypeName();
    if (!dataTypeName.equals("enum")) {
        Datatype datatype = Datatypes.get(dataTypeName);
        String v = null;
        try {
            v = entity.getDefaultValue();
            datatype.parse(v);
            v = entity.getCurrentValue();
            datatype.parse(v);
        } catch (ParseException e) {
            log.debug("Cannot parse '{}' with {} datatype, using StringDatatype for property {}", v, datatype,
                    entity.getName());
            entity.setDataTypeName(datatypes.getIdByJavaClass(String.class));
        }
    }
}

From source file:org.rakam.client.builder.document.SlateDocumentGenerator.java

private String toExampleJsonParameters(Map<String, Property> properties) {
    return "{" + properties.entrySet().stream()
            .map(e -> "\"" + e.getKey() + "\" : " + getValue(e.getValue()) + "\n")
            .collect(Collectors.joining(", ")) + "}";
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

/**
 * Sharing item.//from  w  ww  .ja v a 2  s. co  m
 * @param owner user name
 * @param folderId folder id (optional)
 * @param itemId item id
 * @param everyone <code>true</code> to share with everyone
 * @param org <code>true</code> to share with group
 * @param groups list of groups to share with
 * @param token token
 * @return share response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public ShareResponse share(String owner, String folderId, String itemId, boolean everyone, boolean org,
        String[] groups, String token) throws URISyntaxException, IOException {
    URIBuilder builder = new URIBuilder(shareUri(owner, folderId, itemId));

    HttpPost req = new HttpPost(builder.build());
    HashMap<String, String> params = new HashMap<>();
    params.put("f", "json");
    params.put("everyone", Boolean.toString(everyone));
    params.put("org", Boolean.toString(org));
    params.put("groups", groups != null ? Arrays.asList(groups).stream().collect(Collectors.joining(",")) : "");
    params.put("token", token);

    req.setEntity(createEntity(params));

    return execute(req, ShareResponse.class);
}

From source file:com.evolveum.midpoint.gui.api.util.WebComponentUtil.java

public static String getReferencedObjectNames(List<ObjectReferenceType> refs, boolean showTypes) {
    return refs.stream()
            .map(ref -> emptyIfNull(getName(ref))
                    + (showTypes ? (" (" + emptyIfNull(getTypeLocalized(ref)) + ")") : ""))
            .collect(Collectors.joining(", "));
}

From source file:io.bitsquare.gui.main.funds.withdrawal.WithdrawalView.java

private void selectForWithdrawal(WithdrawalListItem item, boolean isSelected) {
    if (isSelected)
        selectedItems.add(item);//from   w  w w.  j  a  v a  2 s.c  om
    else
        selectedItems.remove(item);

    fromAddresses = selectedItems.stream().map(WithdrawalListItem::getAddressString)
            .collect(Collectors.toSet());

    if (!selectedItems.isEmpty()) {
        amountOfSelectedItems = Coin
                .valueOf(selectedItems.stream().mapToLong(e -> e.getBalance().getValue()).sum());
        if (amountOfSelectedItems.isPositive()) {
            senderAmountAsCoinProperty.set(amountOfSelectedItems);
            amountTextField.setText(formatter.formatCoin(amountOfSelectedItems));
        } else {
            senderAmountAsCoinProperty.set(Coin.ZERO);
            amountOfSelectedItems = Coin.ZERO;
            amountTextField.setText("");
            withdrawFromTextField.setText("");
        }

        if (selectedItems.size() == 1) {
            withdrawFromTextField
                    .setText(selectedItems.stream().findAny().get().getAddressEntry().getAddressString());
            withdrawFromTextField.setTooltip(null);
        } else {
            String tooltipText = "Withdraw from multiple addresses:\n" + selectedItems.stream()
                    .map(WithdrawalListItem::getAddressString).collect(Collectors.joining(",\n"));
            int abbr = Math.max(10, 66 / selectedItems.size());
            String text = "Withdraw from multiple addresses ("
                    + selectedItems.stream().map(e -> StringUtils.abbreviate(e.getAddressString(), abbr))
                            .collect(Collectors.joining(", "))
                    + ")";
            withdrawFromTextField.setText(text);
            withdrawFromTextField.setTooltip(new Tooltip(tooltipText));
        }
    } else {
        reset();
    }
}

From source file:com.adobe.acs.commons.it.build.ScrMetadataIT.java

private String cleanText(String input) {
    if (input == null) {
        return null;
    }//from  ww w.j a v  a 2  s.  co  m

    String[] parts = StringUtils.split(input, '\n');
    return Arrays.stream(parts).map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.joining("\n"));
}

From source file:com.zero_x_baadf00d.partialize.Partialize.java

/**
 * Build a JSON object from data taken from the scanner and
 * the given class type and instance.//from w  ww . j  a v a  2  s. c  om
 *
 * @param depth         The current depth
 * @param fields        The field names to requests
 * @param clazz         The class of the object to render
 * @param instance      The instance of the object to render
 * @param partialObject The partial JSON document
 * @return A JSON Object
 * @since 16.01.18
 */
private ObjectNode buildPartialObject(final int depth, String fields, final Class<?> clazz,
        final Object instance, final ObjectNode partialObject) {
    if (depth <= this.maximumDepth) {
        if (clazz.isAnnotationPresent(com.zero_x_baadf00d.partialize.annotation.Partialize.class)) {
            final List<String> closedFields = new ArrayList<>();
            List<String> allowedFields = Arrays.asList(clazz
                    .getAnnotation(com.zero_x_baadf00d.partialize.annotation.Partialize.class).allowedFields());
            List<String> defaultFields = Arrays.asList(clazz
                    .getAnnotation(com.zero_x_baadf00d.partialize.annotation.Partialize.class).defaultFields());
            if (allowedFields.isEmpty()) {
                allowedFields = new ArrayList<>();
                for (final Method m : clazz.getDeclaredMethods()) {
                    final String methodName = m.getName();
                    if (methodName.startsWith("get") || methodName.startsWith("has")) {
                        final char[] c = methodName.substring(3).toCharArray();
                        c[0] = Character.toLowerCase(c[0]);
                        allowedFields.add(new String(c));
                    } else if (methodName.startsWith("is")) {
                        final char[] c = methodName.substring(2).toCharArray();
                        c[0] = Character.toLowerCase(c[0]);
                        allowedFields.add(new String(c));
                    }
                }
            }
            if (defaultFields.isEmpty()) {
                defaultFields = allowedFields.stream().map(f -> {
                    if (this.aliases != null && this.aliases.containsValue(f)) {
                        for (Map.Entry<String, String> e : this.aliases.entrySet()) {
                            if (e.getValue().compareToIgnoreCase(f) == 0) {
                                return e.getKey();
                            }
                        }
                    }
                    return f;
                }).collect(Collectors.toList());
            }
            if (fields == null || fields.length() == 0) {
                fields = defaultFields.stream().collect(Collectors.joining(","));
            }
            Scanner scanner = new Scanner(fields);
            scanner.useDelimiter(com.zero_x_baadf00d.partialize.Partialize.SCANNER_DELIMITER);
            while (scanner.hasNext()) {
                String word = scanner.next();
                String args = null;
                if (word.compareTo("*") == 0) {
                    final StringBuilder sb = new StringBuilder();
                    if (scanner.hasNext()) {
                        scanner.useDelimiter("\n");
                        sb.append(",");
                        sb.append(scanner.next());
                    }
                    final Scanner newScanner = new Scanner(
                            allowedFields.stream().filter(f -> !closedFields.contains(f)).map(f -> {
                                if (this.aliases != null && this.aliases.containsValue(f)) {
                                    for (Map.Entry<String, String> e : this.aliases.entrySet()) {
                                        if (e.getValue().compareToIgnoreCase(f) == 0) {
                                            return e.getKey();
                                        }
                                    }
                                }
                                return f;
                            }).collect(Collectors.joining(",")) + sb.toString());
                    newScanner.useDelimiter(com.zero_x_baadf00d.partialize.Partialize.SCANNER_DELIMITER);
                    scanner.close();
                    scanner = newScanner;
                }
                if (word.contains("(")) {
                    while (scanner.hasNext()
                            && (StringUtils.countMatches(word, "(") != StringUtils.countMatches(word, ")"))) {
                        word += "," + scanner.next();
                    }
                    final Matcher m = this.fieldArgsPattern.matcher(word);
                    if (m.find()) {
                        word = m.group(1);
                        args = m.group(2);
                    }
                }
                final String aliasField = word;
                final String field = this.aliases != null && this.aliases.containsKey(aliasField)
                        ? this.aliases.get(aliasField)
                        : aliasField;
                if (allowedFields.stream().anyMatch(
                        f -> f.toLowerCase(Locale.ENGLISH).compareTo(field.toLowerCase(Locale.ENGLISH)) == 0)) {
                    if (this.accessPolicyFunction != null
                            && !this.accessPolicyFunction.apply(new AccessPolicy(clazz, instance, field))) {
                        continue;
                    }
                    closedFields.add(aliasField);
                    try {
                        final Method method = clazz.getMethod("get" + WordUtils.capitalize(field));
                        final Object object = method.invoke(instance);
                        this.internalBuild(depth, aliasField, field, args, partialObject, clazz, object);
                    } catch (IllegalAccessException | InvocationTargetException
                            | NoSuchMethodException ignore) {
                        try {
                            final Method method = clazz.getMethod(field);
                            final Object object = method.invoke(instance);
                            this.internalBuild(depth, aliasField, field, args, partialObject, clazz, object);
                        } catch (IllegalAccessException | InvocationTargetException
                                | NoSuchMethodException ex) {
                            if (this.exceptionConsumer != null) {
                                this.exceptionConsumer.accept(ex);
                            }
                        }
                    }
                }
            }
            return partialObject;
        } else if (instance instanceof Map<?, ?>) {
            if (fields == null || fields.isEmpty() || fields.compareTo("*") == 0) {
                for (Map.Entry<?, ?> e : ((Map<?, ?>) instance).entrySet()) {
                    this.internalBuild(depth, String.valueOf(e.getKey()), String.valueOf(e.getKey()), null,
                            partialObject, e.getValue() == null ? Object.class : e.getValue().getClass(),
                            e.getValue());
                }
            } else {
                final Map<?, ?> tmpMap = (Map<?, ?>) instance;
                for (final String k : fields.split(",")) {
                    if (k.compareTo("*") != 0) {
                        final Object o = tmpMap.get(k);
                        this.internalBuild(depth, k, k, null, partialObject,
                                o == null ? Object.class : o.getClass(), o);
                    } else {
                        for (Map.Entry<?, ?> e : ((Map<?, ?>) instance).entrySet()) {
                            this.internalBuild(depth, String.valueOf(e.getKey()), String.valueOf(e.getKey()),
                                    null, partialObject,
                                    e.getValue() == null ? Object.class : e.getValue().getClass(),
                                    e.getValue());
                        }
                    }
                }
            }
        } else {
            throw new RuntimeException("Can't convert " + clazz.getCanonicalName());
        }
    }
    return partialObject;
}

From source file:com.ikanow.aleph2.management_db.controllers.actors.TestBucketDeletionActor.java

@Test
public void test_bucketDeletionActor_purge_immediate_noStatus() throws Exception {
    final DataBucketBean bucket = createBucketInfrastructure("/test/purge/immediate/nostatus", true);

    storeBucketAndStatus(bucket, false, null);

    final ManagementFuture<Boolean> res = _core_mgmt_db.purgeBucket(bucket, Optional.empty());

    // check result
    assertFalse("Purge called failed: " + res.getManagementResults().get().stream().map(msg -> msg.message())
            .collect(Collectors.joining(";")), res.get());
    assertEquals(3, res.getManagementResults().get().size());
}

From source file:com.evolveum.midpoint.gui.api.util.WebComponentUtil.java

public static String getReferencedObjectDisplayNamesAndNames(List<ObjectReferenceType> refs,
        boolean showTypes) {
    return refs.stream()
            .map(ref -> emptyIfNull(getDisplayNameAndName(ref))
                    + (showTypes ? (" (" + emptyIfNull(getTypeLocalized(ref)) + ")") : ""))
            .collect(Collectors.joining(", "));
}

From source file:me.ixfan.wechatkit.user.UserManager.java

/**
 * ??//from   w  w  w. j av a  2s .  co  m
 *
 * @param tagId ID
 * @param openIds ?OpenID?openid?50
 * @throws WeChatApiErrorException API??
 */
public void batchUntaggingUsers(int tagId, List<String> openIds) throws WeChatApiErrorException {
    Args.notNegative(tagId, "Tag ID");
    Args.notEmpty(openIds, "OpenIds");

    final String url = WeChatConstants.WECHAT_POST_BATCH_UNTAGGING.replace("${ACCESS_TOKEN}",
            super.tokenManager.getAccessToken());
    final String jsonData = "{\"openid_list\":[${OPENIDS}],\"tagid\":${TAG_ID}}";
    JsonObject jsonResp;
    try {
        jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(url,
                jsonData.replace("${OPENIDS}", openIds.stream().collect(Collectors.joining(",")))
                        .replace("${TAG_ID}", String.valueOf(tagId)));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (jsonResp.get("errcode").getAsInt() != 0) {
        throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(),
                jsonResp.get("errmsg").getAsString());
    }
}