Example usage for java.util StringJoiner StringJoiner

List of usage examples for java.util StringJoiner StringJoiner

Introduction

In this page you can find the example usage for java.util StringJoiner StringJoiner.

Prototype

public StringJoiner(CharSequence delimiter) 

Source Link

Document

Constructs a StringJoiner with no characters in it, with no prefix or suffix , and a copy of the supplied delimiter .

Usage

From source file:org.wso2.identity.integration.test.util.Utils.java

public static List<NameValuePair> getConsentRequiredClaimsFromResponse(HttpResponse response) throws Exception {

    String redirectUrl = Utils.getRedirectUrl(response);
    Map<String, String> queryParams = Utils.getQueryParams(redirectUrl);
    List<NameValuePair> urlParameters = new ArrayList<>();
    String requestedClaims = queryParams.get("requestedClaims");
    String mandatoryClaims = queryParams.get("mandatoryClaims");

    String consentRequiredClaims;

    if (isNotBlank(mandatoryClaims) && isNotBlank(requestedClaims)) {
        StringJoiner joiner = new StringJoiner(",");
        joiner.add(mandatoryClaims);/*  www.ja v  a  2  s.co m*/
        joiner.add(requestedClaims);
        consentRequiredClaims = joiner.toString();
    } else if (isNotBlank(mandatoryClaims)) {
        consentRequiredClaims = mandatoryClaims;
    } else {
        consentRequiredClaims = requestedClaims;
    }

    String[] claims;
    if (isNotBlank(consentRequiredClaims)) {
        claims = consentRequiredClaims.split(",");
    } else {
        claims = new String[0];
    }

    for (String claim : claims) {
        if (isNotBlank(claim)) {
            String[] claimMeta = claim.split("_", 2);
            if (claimMeta.length == 2) {
                urlParameters.add(new BasicNameValuePair("consent_" + claimMeta[0], "on"));
            }
        }
    }
    return urlParameters;
}

From source file:org.ballerinalang.langserver.command.testgen.ValueSpaceGenerator.java

/**
 * Returns value space for a given BType.
 *
 * @param importsAcceptor imports acceptor
 * @param currentPkgId    current package id
 * @param bType           BType to evaluate
 * @param template        templates to be modified
 * @return {@link String}  modified templates
 *//*w w w  .j  a v a 2s. co m*/
public static String[] getValueSpaceByType(BiConsumer<String, String> importsAcceptor, PackageID currentPkgId,
        BType bType, String[] template) {
    if ((bType.tsymbol == null || bType.tsymbol.name.value.isEmpty()) && bType instanceof BArrayType) {
        BArrayType bArrayType = (BArrayType) bType;
        String[] values = getValueSpaceByTypeSymbol(bArrayType.eType.tsymbol,
                createTemplateArray(template.length));
        IntStream.range(0, template.length).forEach(
                index -> template[index] = template[index].replace(PLACE_HOLDER, "[" + values[index] + "]"));
        return template;
    } else if (bType instanceof BFiniteType) {
        // Check for finite set assignment
        BFiniteType bFiniteType = (BFiniteType) bType;
        Set<BLangExpression> valueSpace = bFiniteType.valueSpace;
        if (!valueSpace.isEmpty()) {
            return getValueSpaceByNode(importsAcceptor, currentPkgId, valueSpace.stream().findFirst().get(),
                    template);
        }
    } else if (bType instanceof BMapType && ((BMapType) bType).constraint != null) {
        // Check for constrained map assignment eg. map<Student>
        BType constraintType = ((BMapType) bType).constraint;
        String[] values = getValueSpaceByType(importsAcceptor, currentPkgId, constraintType,
                createTemplateArray(template.length));
        IntStream.range(0, template.length).forEach(index -> {
            template[index] = template[index].replace(PLACE_HOLDER, "{key: " + values[index] + "}");
        });
        return template;
    } else if (bType instanceof BUnionType) {
        // Check for union assignment int|string
        BUnionType bUnionType = (BUnionType) bType;
        Set<BType> memberTypes = bUnionType.getMemberTypes();
        if (!memberTypes.isEmpty()) {
            return getValueSpaceByType(importsAcceptor, currentPkgId, memberTypes.stream().findFirst().get(),
                    template);
        }
    } else if (bType instanceof BTupleType) {
        // Check for tuple assignment (int, string)
        BTupleType bTupleType = (BTupleType) bType;
        List<BType> tupleTypes = bTupleType.tupleTypes;
        String[][] vSpace = new String[template.length][tupleTypes.size()];
        IntStream.range(0, tupleTypes.size()).forEach(j -> {
            BType type = tupleTypes.get(j);
            String[] values = getValueSpaceByType(importsAcceptor, currentPkgId, type,
                    createTemplateArray(template.length));
            IntStream.range(0, values.length).forEach(i -> vSpace[i][j] = values[i]);
        });
        IntStream.range(0, template.length).forEach(index -> {
            template[index] = template[index].replace(PLACE_HOLDER,
                    "(" + String.join(", ", vSpace[index]) + ")");
        });
        return template;
    } else if (bType instanceof BRecordType) {
        BRecordType bRecordType = (BRecordType) bType;
        List<BField> params = bRecordType.fields;
        String[][] list = new String[template.length][params.size()];
        IntStream.range(0, params.size()).forEach(paramIndex -> {
            BField field = params.get(paramIndex);
            String[] values = getValueSpaceByType(importsAcceptor, currentPkgId, field.type,
                    createTemplateArray(template.length));
            IntStream.range(0, values.length).forEach(valIndex -> {
                list[valIndex][paramIndex] = field.name + ": " + values[valIndex];
            });
        });

        IntStream.range(0, template.length).forEach(index -> {
            String paramsStr = String.join(", ", list[index]);
            String newObjStr = "{" + paramsStr + "}";
            template[index] = template[index].replace(PLACE_HOLDER, newObjStr);
        });
        return template;
    } else if (bType instanceof BObjectType && ((BObjectType) bType).tsymbol instanceof BObjectTypeSymbol) {
        BObjectTypeSymbol bStructSymbol = (BObjectTypeSymbol) ((BObjectType) bType).tsymbol;
        List<BVarSymbol> params = bStructSymbol.initializerFunc.symbol.params;
        String[][] list = new String[template.length][params.size()];
        IntStream.range(0, params.size()).forEach(paramIndex -> {
            BVarSymbol param = params.get(paramIndex);
            String[] values = getValueSpaceByType(importsAcceptor, currentPkgId, param.type,
                    createTemplateArray(template.length));
            IntStream.range(0, values.length).forEach(valIndex -> {
                list[valIndex][paramIndex] = values[valIndex];
            });
        });

        IntStream.range(0, template.length).forEach(index -> {
            String pkgPrefix = CommonUtil.getPackagePrefix(importsAcceptor, currentPkgId, bStructSymbol.pkgID);
            String paramsStr = String.join(", ", list[index]);
            String newObjStr = "new " + pkgPrefix + bStructSymbol.name.getValue() + "(" + paramsStr + ")";
            template[index] = template[index].replace(PLACE_HOLDER, newObjStr);
        });
        return template;
    } else if (bType instanceof BInvokableType) {
        BInvokableType invokableType = (BInvokableType) bType;
        TestFunctionGenerator generator = new TestFunctionGenerator(importsAcceptor, currentPkgId,
                invokableType);
        StringJoiner params = new StringJoiner(", ");
        String[][] valueSpace = generator.getValueSpace();
        String[] typeSpace = generator.getTypeSpace();
        String[] nameSpace = generator.getNamesSpace();
        IntStream.range(0, typeSpace.length - 1).forEach(index -> {
            String type = typeSpace[index];
            String name = nameSpace[index];
            params.add(type + " " + name);
        });
        String returnType = "(" + typeSpace[typeSpace.length - 1] + ")";
        IntStream.range(0, template.length).forEach(index -> {
            String functionStr = "function (" + params.toString() + ") returns " + returnType + "{ "
                    + ((valueSpace != null) ? "return " + valueSpace[index][invokableType.paramTypes.size()]
                            : "")
                    + "; }";
            template[index] = template[index].replace(PLACE_HOLDER, functionStr);
        });
        return template;
    }
    return (bType.tsymbol != null) ? getValueSpaceByTypeSymbol(bType.tsymbol, template)
            : (String[]) Stream.of(template).map(s -> s.replace(PLACE_HOLDER, "()")).toArray();
}

From source file:com.hzq.car.CarTest.java

private void sendAndSave(String token, Date date, String url) throws ParseException, IOException {
    Integer pages = getPages(token, date, url);
    for (int i = 0; i <= pages; i++) {
        Map map = getData(token, date, url, i);
        List<Map> o = (List<Map>) ((Map) ((Map) map.get("data")).get("pager")).get("items");

        o.stream().filter(secondCar -> "".equals(secondCar.get("status"))
                && "".equals(secondCar.get("upShelf"))).forEach(data1 -> {
                    SecondCar car = new SecondCar();
                    car.setUserId(-1);//from  w w w .  j a  v  a 2  s .co  m
                    car.setMerchantId(0);
                    car.setIsMerchant(0);
                    //?
                    String brand = (String) data1.get("brand");
                    if (brand != null) {
                        Integer type = getCarType(brand);
                        car.setType(type);
                    }
                    //
                    String model = (String) data1.get("model");
                    car.setTitle(model);
                    // journey
                    String mileage = (String) data1.get("mileage");
                    BigDecimal journey = new BigDecimal(mileage).divide(new BigDecimal(10000), 2,
                            RoundingMode.HALF_UP);
                    car.setJourney(journey);

                    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    SimpleDateFormat fmt2 = new SimpleDateFormat("yyyy-MM-dd");
                    //
                    String firstLicensePlateDate = (String) data1.get("firstLicensePlateDate");
                    try {
                        firstLicensePlateDate = fmt2.format(fmt.parse(firstLicensePlateDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    car.setLicenseTime(firstLicensePlateDate);

                    //
                    car.setBuyTime(firstLicensePlateDate);

                    //
                    String insuranceExpiresDate = (String) data1.get("insuranceExpiresDate");
                    try {
                        if (insuranceExpiresDate != null && !"null".equals(insuranceExpiresDate)) {
                            insuranceExpiresDate = fmt2.format(fmt.parse(insuranceExpiresDate));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    car.setInsuranceDeadtime(insuranceExpiresDate);
                    //??
                    String carDescribe = (String) data1.get("carDescribe");
                    car.setIntroduction(carDescribe);
                    //??? nature
                    Integer usage = 0;
                    String useType = (String) data1.get("useType");
                    if ("??".equals(useType))
                        usage = 1;
                    car.setNature(usage.toString());
                    //? exhaust
                    BigDecimal engineVolume = new BigDecimal((String) data1.get("engineVolume"));
                    car.setExhaust(engineVolume);
                    // carPicture
                    List<String> carPicture = (List<String>) data1.get("carPicture");
                    if (carPicture.size() > 0) {
                        car.setPictue(carPicture.get(0));
                        StringJoiner joiner = new StringJoiner(",");
                        carPicture.forEach(joiner::add);
                        car.setCarPic(joiner.toString());
                    }
                    // salePrice
                    Integer salePrice = Integer.parseInt((String) data1.get("salePrice"));
                    BigDecimal price = new BigDecimal(salePrice).divide(new BigDecimal(10000), 2,
                            RoundingMode.HALF_UP);
                    car.setPrice(price);
                    //?  firstLicensePlateDate
                    Integer year = Integer.parseInt(firstLicensePlateDate.substring(0, 4));
                    Integer toSet = 0;
                    int now = 2017 - year;
                    if (now <= 1)
                        toSet = 0;
                    if (now > 1 && now <= 3)
                        toSet = 1;
                    if (now > 3 && now <= 5)
                        toSet = 3;
                    if (now > 5 && now <= 8)
                        toSet = 4;
                    if (now > 8 && now <= 10)
                        toSet = 5;
                    if (now > 10)
                        toSet = 6;
                    car.setYear(toSet);
                    //
                    String color = (String) data1.get("color");
                    Integer resultColor = 15;
                    if (color != null) {
                        if (color.contains(""))
                            resultColor = 1;
                        if (color.contains(""))
                            resultColor = 2;
                        if (color.contains(""))
                            resultColor = 3;
                        if (color.contains("?"))
                            resultColor = 4;
                        if (color.contains(""))
                            resultColor = 5;
                        if (color.contains("?"))
                            resultColor = 6;
                        if (color.contains(""))
                            resultColor = 7;
                        if (color.contains(""))
                            resultColor = 8;
                        if (color.contains(""))
                            resultColor = 9;
                        if (color.contains(""))
                            resultColor = 10;
                        if (color.contains(""))
                            resultColor = 11;
                        if (color.contains(""))
                            resultColor = 12;
                        if (color.contains(""))
                            resultColor = 13;
                        if (color.contains(""))
                            resultColor = 14;
                    }
                    car.setColor(resultColor);
                    //?,?? contactPerson  phone
                    String contactPerson = (String) data1.get("contactPerson");
                    String phone = (String) data1.get("phone");
                    car.setConcactName(contactPerson);
                    car.setConcactPhone(phone);
                    //
                    Integer transferNumber = (Integer) data1.get("transferNumber");
                    car.setTimes(transferNumber);
                    //
                    try {
                        car.setCreatedAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                .parse((String) data1.get("upShelfDate")));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    try {
                        secondCarMapper.insert(car);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });

    }

}

From source file:ca.osmcanada.osvuploadr.JPMain.java

private String sendForm(String target_url, Map<String, String> arguments, String method,
        List<Cookie> cookielist) {
    try {// w w w.  j a  va 2  s.co  m
        URL url = new URL(target_url);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        //HttpURLConnection http = (HttpURLConnection)con;
        con.setRequestMethod(method); // PUT is another valid option
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        String cookiestr = "";
        if (cookielist != null) {
            if (cookielist.size() > 0) {
                for (Cookie cookie : cookielist) {
                    if (!cookiestr.equals("")) {
                        cookiestr += ";" + cookie.getName() + "=" + cookie.getValue();
                    } else {
                        cookiestr += cookie.getName() + "=" + cookie.getValue();
                    }
                }
                con.setRequestProperty("Cookie", cookiestr);
            }
        }

        con.setReadTimeout(5000);

        StringJoiner sj = new StringJoiner("&");
        for (Map.Entry<String, String> entry : arguments.entrySet())
            sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
                    + URLEncoder.encode(entry.getValue(), "UTF-8"));
        byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
        int length = out.length;

        con.setFixedLengthStreamingMode(length);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        con.setRequestProperty("Accept-Language", "en-us;");
        con.connect();
        try (OutputStream os = con.getOutputStream()) {
            os.write(out);
            os.close();
        }

        boolean redirect = false;
        int status = con.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        if (redirect) {
            String newURL = con.getHeaderField("Location");
            String cookies = con.getHeaderField("Set-Cookie");
            if (cookies == null) {
                cookies = cookiestr;
            }
            con = (HttpURLConnection) new URL(newURL).openConnection();
            con.setRequestProperty("Cookie", cookies);
        }

        InputStream is = con.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int letti;

        while ((letti = is.read(buf)) > 0)
            baos.write(buf, 0, letti);

        String data = new String(baos.toByteArray(), Charset.forName("UTF-8"));
        con.disconnect();

        return data;

    } catch (Exception ex) {
        Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ConsentMgtPostAuthnHandler.java

private String buildConsentClaimString(List<ClaimMetaData> consentClaimsData) {

    StringJoiner joiner = new StringJoiner(CLAIM_SEPARATOR);
    for (ClaimMetaData claimMetaData : consentClaimsData) {
        joiner.add(claimMetaData.getId() + "_" + claimMetaData.getDisplayName());
    }/*  ww w.j  a  v a 2  s  .c o  m*/
    return joiner.toString();
}

From source file:info.archinnov.achilles.internals.metamodel.AbstractEntityProperty.java

public String generateSchema(SchemaContext context) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(format("Generating DDL script for entity of type %s", entityClass.getCanonicalName()));
    }//from www  .j a va2s .c om
    StringJoiner joiner = new StringJoiner("\n\n");
    SchemaCreator.generateTable_And_Indices(context, this).forEach(joiner::add);
    return joiner.toString();
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

private void logKeyStore(KeyStore ks, String ksLocation, char[] ksPwd) {
    if (log.isInfoEnabled()) {
        log.info("Loaded cluster key store from: {}", ksLocation);
        try {//from ww w .  jav  a 2  s  .co m
            for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
                String alias = e.nextElement();
                Key key = ks.getKey(alias, ksPwd);
                Certificate[] certs = ks.getCertificateChain(alias);
                log.debug("{} -> {}", alias, certs);
                final byte[] encodedKey;
                if (certs != null && certs.length > 0) {
                    encodedKey = certs[0].getEncoded();
                } else {
                    log.info("Could not find cert chain for {}, using fingerprint of key instead...", alias);
                    encodedKey = key.getEncoded();
                }
                // Compute the certificate's fingerprint (use the key if certificate cannot be found)
                MessageDigest digest = MessageDigest.getInstance("SHA1");
                digest.update(encodedKey);
                StringJoiner fingerprint = new StringJoiner(":");
                for (byte b : digest.digest()) {
                    fingerprint.add(String.format("%02X", b));
                }
                log.info("{} -> {}", alias, fingerprint);
            }
        } catch (Exception e) {
            log.warn("Unable to print contents of key store: {}", ksLocation, e);
        }
    }
}

From source file:com.oneops.transistor.service.BomManagerImpl.java

private String getNspath(String nsPath, CmsCI plat) {
    StringJoiner nSjoiner = new StringJoiner("/");
    nSjoiner.add(nsPath).add(plat.getCiName()).add(plat.getAttribute("major_version").getDjValue());
    return nSjoiner.toString();
}

From source file:info.archinnov.achilles.internals.codegen.meta.EntityMetaCodeGen.java

private MethodSpec buildPartitionKeys(List<FieldMetaSignature> parsingResults, TypeName rawClassType) {
    StringJoiner joiner = new StringJoiner(",");
    parsingResults.stream().filter(x -> x.context.columnType == ColumnType.PARTITION)
            .map(x -> Tuple2.of(x.context.fieldName, (PartitionKeyInfo) x.context.columnInfo))
            .sorted(PARTITION_KEY_SORTER).map(x -> x._1()).forEach(x -> joiner.add(x));

    return MethodSpec.methodBuilder("getPartitionKeys").addAnnotation(Override.class)
            .addModifiers(Modifier.PROTECTED).returns(propertyListType(rawClassType))
            .addStatement("return $T.asList($L)", ARRAYS, joiner.toString()).build();
}

From source file:info.archinnov.achilles.internals.codegen.meta.EntityMetaCodeGen.java

private MethodSpec buildClusteringColumns(List<FieldMetaSignature> parsingResults, TypeName rawClassType) {
    StringJoiner joiner = new StringJoiner(",");
    parsingResults.stream().filter(x -> x.context.columnType == CLUSTERING)
            .map(x -> Tuple2.of(x.context.fieldName, (ClusteringColumnInfo) x.context.columnInfo))
            .sorted(CLUSTERING_COLUMN_SORTER).map(x -> x._1()).forEach(x -> joiner.add(x));

    return MethodSpec.methodBuilder("getClusteringColumns").addAnnotation(Override.class)
            .addModifiers(Modifier.PROTECTED).returns(propertyListType(rawClassType))
            .addStatement("return $T.asList($L)", ARRAYS, joiner.toString()).build();
}