Example usage for org.apache.commons.lang3 StringUtils join

List of usage examples for org.apache.commons.lang3 StringUtils join

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils join.

Prototype

public static String join(final Iterable<?> iterable, final String separator) 

Source Link

Document

Joins the elements of the provided Iterable into a single String containing the provided elements.

No delimiter is added before or after the list.

Usage

From source file:com.threewks.thundr.bind.TestBindTo.java

public Object methodMap(Map<String, List<String>> argument1) {
    return StringUtils.join(argument1, ":");
}

From source file:de.vandermeer.skb.interfaces.transformers.textformat.Test_Text_To_WrappedFormat.java

@Test
public void test_Simple() {
    String words = new LoremIpsum().getWords(30);
    String text = words;/*from w  w  w . ja  v a 2 s.  c  o  m*/
    text = StringUtils.replace(words, "dolor ", "dolor " + LINEBREAK);
    text = StringUtils.replace(text, "dolore ", "dolore " + LINEBREAK);

    Pair<ArrayList<String>, ArrayList<String>> textPair;

    textPair = Text_To_WrappedFormat.convert(text, 20, null);
    assertEquals(0, textPair.getLeft().size());
    assertEquals(11, textPair.getRight().size());
    assertEquals(words, StringUtils.join(textPair.getRight(), ' '));

    textPair = Text_To_WrappedFormat.convert(text, 30, Pair.of(6, 10));

    System.err.println(words);
    System.err.println(text);
    System.err.println("\n----[ top ]----");
    System.err.println("123456789012345678901234567890");
    for (String s : textPair.getLeft()) {
        System.err.println(s);
    }
    System.err.println("\n----[ bottom ]----");
    System.err.println("123456789012345678901234567890");
    for (String s : textPair.getRight()) {
        System.err.println(s);
    }
}

From source file:co.foxdev.foxbot.commands.CommandGoogle.java

@Override
public void execute(MessageEvent event, String[] args) {
    User sender = event.getUser();//from ww  w .j a  v  a 2 s . c om
    Channel channel = event.getChannel();

    if (args.length != 0) {
        String query = StringUtils.join(args, " ");
        String address = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + query;
        Connection conn = Jsoup.connect(address).ignoreContentType(true).followRedirects(true).timeout(1000);
        JSONObject jsonObject;

        try {
            jsonObject = new JSONObject(conn.get().text());
        } catch (IOException ex) {
            foxbot.getLogger().error("Error occurred while performing Google search", ex);
            channel.send().message(Utils
                    .colourise(String.format("(%s) &cSomething went wrong...", Utils.munge(sender.getNick()))));
            return;
        }

        JSONArray jsonArray = jsonObject.getJSONObject("responseData").getJSONArray("results");

        if (jsonArray.length() == 0) {
            channel.send().message(
                    Utils.colourise(String.format("(%s) &cNo results found!", Utils.munge(sender.getNick()))));
            return;
        }

        JSONObject result = jsonArray.getJSONObject(0);
        String resultCount = jsonObject.getJSONObject("responseData").getJSONObject("cursor")
                .getString("resultCount");
        String title = result.getString("titleNoFormatting");
        String url = result.getString("unescapedUrl");
        channel.send().message(Utils.colourise(String.format(
                "(%s's Google Search) &2Title: &r%s &2URL: &r%s &2Results: &r%s", Utils.munge(sender.getNick()),
                StringEscapeUtils.unescapeHtml4(title), url, resultCount)));
        return;
    }

    sender.send().notice(
            String.format("Wrong number of args! Use %sgoogle <query>", foxbot.getConfig().getCommandPrefix()));
}

From source file:annis.sqlgen.SubQueryCorpusSelectionStrategy.java

public String buildSubQuery(List<Long> corpusList, List<QueryAnnotation> metaData) {
    StringBuffer sb = new StringBuffer();

    sb.append("SELECT DISTINCT c1.id FROM corpus AS c1");

    if (!corpusList.isEmpty()) {
        sb.append(", ");
        sb.append("corpus AS c2");
    }/*from  w  w w .j a va2s.  c om*/

    for (int i = 1; i <= metaData.size(); ++i) {
        sb.append(", ");
        sb.append("corpus_annotation AS corpus_annotation");
        sb.append(i);
    }

    if (hasCorpusSelection(corpusList, metaData))
        sb.append(" WHERE ");

    List<String> conditions = new ArrayList<String>();

    if (!corpusList.isEmpty()) {
        conditions.add("c1.pre >= c2.pre");
        conditions.add("c1.post <= c2.post");
        conditions.add("c2.id IN ( :corpusList )".replace(":corpusList", StringUtils.join(corpusList, ", ")));
    }

    for (int i = 1; i <= metaData.size(); ++i) {
        QueryAnnotation annotation = metaData.get(i - 1);
        if (annotation.getNamespace() != null)
            conditions.add("corpus_annotation" + i + ".namespace = '" + annotation.getNamespace() + "'");
        conditions.add("corpus_annotation" + i + ".name = '" + annotation.getName() + "'");
        if (annotation.getValue() != null) {
            String value = annotation.getValue();
            if (annotation.getTextMatching() == QueryNode.TextMatching.REGEXP_EQUAL
                    || annotation.getTextMatching() == QueryNode.TextMatching.REGEXP_NOT_EQUAL) {
                value = "^" + value + "$";
            }
            conditions.add("corpus_annotation" + i + ".value " + annotation.getTextMatching().sqlOperator()
                    + " '" + value + "'");
        }
        conditions.add("corpus_annotation" + i + ".corpus_ref = c1.id");
    }

    sb.append(StringUtils.join(conditions, " AND "));

    return sb.toString();
}

From source file:ca.uhn.fhir.rest.method.HttpGetClientInvocation.java

public HttpGetClientInvocation(FhirContext theContext, Map<String, List<String>> theParameters,
        String... theUrlFragments) {
    super(theContext);
    myParameters = theParameters;/*from  ww w .j  av  a2 s. c  om*/
    myUrlPath = StringUtils.join(theUrlFragments, '/');
}

From source file:com.ctrip.infosec.rule.executor.PostRulesExecutorService.java

/**
 * //from   ww  w .j  av  a  2  s.co m
 */
void execute(RiskFact fact, boolean isAsync) {

    // matchRules      
    List<PostRule> matchedRules = Configs.matchPostRules(fact, isAsync);
    List<String> scriptRulePackageNames = Collections3.extractToList(matchedRules, "ruleNo");
    logger.debug(
            Contexts.getLogPrefix() + "matched post rules: " + StringUtils.join(scriptRulePackageNames, ", "));
    TraceLogger.traceLog("? " + matchedRules.size() + " ??? ...");

    StatelessPostRuleEngine statelessPostRuleEngine = SpringContextHolder
            .getBean(StatelessPostRuleEngine.class);
    for (PostRule rule : matchedRules) {
        RuleMonitorHelper.newTrans(fact, RuleMonitorType.POST_RULE, rule.getRuleNo());
        TraceLogger.beginNestedTrans(fact.eventId);
        TraceLogger.setNestedLogPrefix("[" + rule.getRuleNo() + "]");
        Contexts.setPolicyOrRuleNo(rule.getRuleNo());
        try {
            long start = System.currentTimeMillis();

            // add current execute ruleNo and logPrefix before execution
            fact.ext.put(Constants.key_ruleNo, rule.getRuleNo());
            fact.ext.put(Constants.key_isAsync, isAsync);

            statelessPostRuleEngine.execute(rule.getRuleNo(), fact);

            // remove current execute ruleNo when finished execution.
            fact.ext.remove(Constants.key_ruleNo);
            fact.ext.remove(Constants.key_isAsync);

            long handlingTime = System.currentTimeMillis() - start;
            if (handlingTime > 100) {
                logger.info(Contexts.getLogPrefix() + "postRule: " + rule.getRuleNo() + ", usage: "
                        + handlingTime + "ms");
            }
            TraceLogger.traceLog("[" + rule.getRuleNo() + "] usage: " + handlingTime + "ms");

        } catch (Throwable ex) {
            logger.warn(Contexts.getLogPrefix() + "??. postRule: " + rule.getRuleNo(),
                    ex);
            TraceLogger.traceLog("[" + rule.getRuleNo() + "] EXCEPTION: " + ex.toString());
        } finally {
            TraceLogger.commitNestedTrans();
            RuleMonitorHelper.commitTrans(fact);
            Contexts.clearLogPrefix();
        }
    }

}

From source file:com.datumbox.framework.applications.nlp.CETRTest.java

/**
 * Test of extract method, of class CETR.
 *//*from w  w  w  .  ja v a  2  s .c o m*/
@Test
public void testExtract() {
    logger.info("extract");

    Configuration conf = Configuration.getConfiguration();

    String dbName = this.getClass().getSimpleName();

    String text;
    try {
        List<String> lines = Files.readAllLines(
                Paths.get(this.getClass().getClassLoader().getResource("datasets/example.com.html").toURI()),
                StandardCharsets.UTF_8);
        text = StringUtils.join(lines, "\r\n");
    } catch (IOException | URISyntaxException ex) {
        throw new RuntimeException(ex);
    }

    CETR.Parameters parameters = new CETR.Parameters();
    parameters.setNumberOfClusters(2);
    parameters.setAlphaWindowSizeFor2DModel(3);
    parameters.setSmoothingAverageRadius(2);
    CETR instance = new CETR(dbName, conf);
    String expResult = "This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.";
    String result = instance.extract(text, parameters);
    assertEquals(expResult, result);
}

From source file:com.springstudy.utils.email.SimpleMailService.java

/**
 * ??.//from w  w w . j ava  2 s.c o m
 */
public boolean sendNotificationMail(com.gmk.framework.common.utils.email.Email email) {
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setFrom(Global.getConfig("mailFrom"));
    msg.setTo(email.getAddress());
    if (StringUtils.isNotEmpty(email.getCc())) {
        String cc[] = email.getCc().split(";");
        msg.setCc(cc);//?
    }
    msg.setSubject(email.getSubject());

    // ????
    //      String content = String.format(textTemplate, userName, new Date());
    String content = email.getContent();
    msg.setText(content);
    try {
        mailSender.send(msg);
        if (logger.isInfoEnabled()) {
            logger.info("??{}", StringUtils.join(msg.getTo(), ","));
        }
        return true;
    } catch (Exception e) {
        logger.error(email.getAddressee() + "-" + email.getSubject() + "-" + "??", e);
    }
    return false;
}

From source file:com.microsoft.azure.shortcuts.resources.samples.AvailabilitySetSample.java

public static void test(Subscription subscription) throws Exception {
    String newAvailabilitySetName = "marcinsas";
    AvailabilitySet availabilitySet;/*  ww w  .  j ava  2s.com*/

    // Create a new availability set in a new default group
    availabilitySet = subscription.availabilitySets().define(newAvailabilitySetName).withRegion(Region.US_WEST)
            .withNewResourceGroup().create();

    // Get info about a specific availability set using its group and name
    availabilitySet = subscription.availabilitySets(availabilitySet.id());
    printAvailabilitySet(availabilitySet);

    // Listing availability sets in a specific resource group
    Map<String, AvailabilitySet> availabilitySets = subscription.availabilitySets()
            .asMap(availabilitySet.resourceGroup());
    System.out.println(String.format("Availability set ids in group '%s': \n\t%s",
            availabilitySet.resourceGroup(), StringUtils.join(availabilitySets.keySet(), ",\n\t")));

    // Delete availability set
    availabilitySet.delete();

    // Delete its group
    subscription.resourceGroups().delete(availabilitySet.resourceGroup());

    // Create a new group
    ResourceGroup group = subscription.resourceGroups().define("marcinstestgroup").withRegion(Region.US_WEST)
            .create();

    // Create an availability set in an existing group
    availabilitySet = subscription.availabilitySets().define(newAvailabilitySetName + "2")
            .withRegion(Region.US_WEST).withExistingResourceGroup(group).withTag("hello", "world")
            .withoutTag("hello").create();

    // Get an existing availability set based onb group and name
    availabilitySet = subscription.availabilitySets(availabilitySet.resourceGroup(), availabilitySet.name());
    printAvailabilitySet(availabilitySet);

    // Delete the entire group
    subscription.resourceGroups().delete(group.id());
}

From source file:de.dhbw.vetaraus.NetFactory.java

/**
 * Create a new Netica net from an existing CSV file. Cases are learned through gradient descent learning algorithm.
 *
 * @param path/*from w w w . j a  v a  2  s .c  o m*/
 *         Filepath of the CSV file
 * @return A Netica net.
 * @throws NeticaException
 *         Netica problems.
 * @throws IOException
 *         I/O problems.
 */
public static Net fromCases(String path) throws NeticaException, IOException {
    List<Case> cases = SanitizeUtils.sanitizeCases(CSV.parse(path));

    Set<String> ageGroupSet = new TreeSet<>();
    Set<String> degreeSet = new TreeSet<>();
    Set<String> occupationSet = new TreeSet<>();
    Set<String> incomeSet = new TreeSet<>();
    Set<String> tariffSet = new TreeSet<>();

    // Find all states
    for (Case c : cases) {
        ageGroupSet.add(c.getAge());
        degreeSet.add(c.getDegree());
        occupationSet.add(c.getOccupation());
        incomeSet.add(c.getIncome());
        tariffSet.add(c.getTariff());
    }

    Net net = new Net(NeticaUtils.getEnvironment());

    Caseset caseset = getCaseset(cases);

    // Create nodes in net:
    NodeList nodeList = new NodeList(net);
    Node ageGroupNode = new Node(Constants.NODE_AGE, StringUtils.join(ageGroupSet, ','), net);
    Node genderNode = new Node(Constants.NODE_GENDER, "m,w", net);
    Node marriedNode = new Node(Constants.NODE_MARRIED, "ja,nein", net);
    Node childCountNode = new Node(Constants.NODE_CHILDCOUNT, "_0,_1,_2,_3,_4", net);
    Node degreeNode = new Node(Constants.NODE_DEGREE, StringUtils.join(degreeSet, ','), net);
    Node occupationNode = new Node(Constants.NODE_OCCUPATION, StringUtils.join(occupationSet, ','), net);
    Node incomeNode = new Node(Constants.NODE_INCOME, StringUtils.join(incomeSet, ','), net);
    Node tariffNode = new Node(Constants.NODE_INSURANCE, StringUtils.join(tariffSet, ','), net);

    // Link nodes:
    tariffNode.addLink(ageGroupNode);
    tariffNode.addLink(genderNode);
    tariffNode.addLink(marriedNode);
    tariffNode.addLink(childCountNode);
    tariffNode.addLink(incomeNode);
    incomeNode.addLink(occupationNode);
    occupationNode.addLink(degreeNode);

    nodeList.add(ageGroupNode);
    nodeList.add(genderNode);
    nodeList.add(marriedNode);
    nodeList.add(childCountNode);
    nodeList.add(degreeNode);
    nodeList.add(occupationNode);
    nodeList.add(incomeNode);
    nodeList.add(tariffNode);

    Learner learner = new Learner(Learner.GRADIENT_DESCENT_LEARNING);
    learner.learnCPTs(nodeList, caseset, 1.0);

    return net;
}