Example usage for java.lang String join

List of usage examples for java.lang String join

Introduction

In this page you can find the example usage for java.lang String join.

Prototype

public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) 

Source Link

Document

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter .

Usage

From source file:com.formkiq.core.service.workflow.WorkflowEditorServiceImplTest.java

/**
 * testEventStepup02()./*from   w w w.  j  a  v  a 2s. c  o m*/
 * _eventId_stepup up at max size.
 * @throws IOException IOException
 */
@Test
public void testEventStepup02() throws IOException {
    // given
    Workflow wf = expectAction();

    // when
    replayAll();
    this.ws.eventIdstepup(this.flow, this.request, new String[] { "3" });

    // then
    verifyAll();

    assertEquals("1,2,3", String.join(",", wf.getSteps()));
    assertEquals("1,2,3", String.join(",", wf.getPrintsteps()));
}

From source file:org.wallride.service.PageService.java

@CacheEvict(value = WallRideCacheConfiguration.PAGE_CACHE, allEntries = true)
public Page savePage(PageUpdateRequest request, AuthorizedUser authorizedUser) {
    postRepository.lock(request.getId());
    Page page = pageRepository.findOneByIdAndLanguage(request.getId(), request.getLanguage());
    LocalDateTime now = LocalDateTime.now();

    String code = request.getCode();
    if (code == null) {
        try {//w w  w .ja  v a2 s.c  o  m
            code = new CodeFormatter().parse(request.getTitle(), LocaleContextHolder.getLocale());
        } catch (ParseException e) {
            throw new ServiceException(e);
        }
    }
    if (!StringUtils.hasText(code)) {
        if (!page.getStatus().equals(Post.Status.DRAFT)) {
            throw new EmptyCodeException();
        }
    }
    if (!page.getStatus().equals(Post.Status.DRAFT)) {
        Post duplicate = postRepository.findOneByCodeAndLanguage(code, request.getLanguage());
        if (duplicate != null && !duplicate.equals(page)) {
            throw new DuplicateCodeException(code);
        }
    }

    if (!page.getStatus().equals(Post.Status.DRAFT)) {
        page.setCode(code);
        page.setDraftedCode(null);
    } else {
        page.setCode(null);
        page.setDraftedCode(code);
    }

    Page parent = (request.getParentId() != null)
            ? entityManager.getReference(Page.class, request.getParentId())
            : null;
    if (!(page.getParent() == null && parent == null)
            && !ObjectUtils.nullSafeEquals(page.getParent(), parent)) {
        pageRepository.shiftLftRgt(page.getLft(), page.getRgt());
        pageRepository.shiftRgt(page.getRgt());
        pageRepository.shiftLft(page.getRgt());

        int rgt = 0;
        if (parent == null) {
            rgt = pageRepository.findMaxRgt();
            rgt++;
        } else {
            rgt = parent.getRgt();
            pageRepository.unshiftRgt(rgt);
            pageRepository.unshiftLft(rgt);
        }
        page.setLft(rgt);
        page.setRgt(rgt + 1);
    }

    page.setParent(parent);

    Media cover = null;
    if (request.getCoverId() != null) {
        cover = entityManager.getReference(Media.class, request.getCoverId());
    }
    page.setCover(cover);
    page.setTitle(request.getTitle());
    page.setBody(request.getBody());

    //      User author = null;
    //      if (request.getAuthorId() != null) {
    //         author = entityManager.getReference(User.class, request.getAuthorId());
    //      }
    //      page.setAuthor(author);

    LocalDateTime date = request.getDate();
    if (Post.Status.PUBLISHED.equals(page.getStatus())) {
        if (date == null) {
            date = now.truncatedTo(ChronoUnit.HOURS);
        } else if (date.isAfter(now)) {
            page.setStatus(Post.Status.SCHEDULED);
        }
    }
    page.setDate(date);
    page.setLanguage(request.getLanguage());

    page.getCategories().clear();
    SortedSet<Category> categories = new TreeSet<>();
    for (long categoryId : request.getCategoryIds()) {
        categories.add(entityManager.getReference(Category.class, categoryId));
    }
    page.setCategories(categories);

    page.getTags().clear();
    Set<String> tagNames = StringUtils.commaDelimitedListToSet(request.getTags());
    if (!CollectionUtils.isEmpty(tagNames)) {
        for (String tagName : tagNames) {
            Tag tag = tagRepository.findOneForUpdateByNameAndLanguage(tagName, request.getLanguage());
            if (tag == null) {
                tag = new Tag();
                tag.setName(tagName);
                tag.setLanguage(request.getLanguage());
                page.setCreatedAt(now);
                page.setCreatedBy(authorizedUser.toString());
                page.setUpdatedAt(now);
                page.setUpdatedBy(authorizedUser.toString());
                tag = tagRepository.saveAndFlush(tag);
            }
            page.getTags().add(tag);
        }
    }

    page.getRelatedPosts().clear();
    Set<Post> relatedPosts = new HashSet<>();
    for (long relatedId : request.getRelatedPostIds()) {
        relatedPosts.add(entityManager.getReference(Post.class, relatedId));
    }
    page.setRelatedToPosts(relatedPosts);

    Seo seo = new Seo();
    seo.setTitle(request.getSeoTitle());
    seo.setDescription(request.getSeoDescription());
    seo.setKeywords(request.getSeoKeywords());
    page.setSeo(seo);

    List<Media> medias = new ArrayList<>();
    if (StringUtils.hasText(request.getBody())) {
        //         Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
        String mediaUrlPrefix = wallRideProperties.getMediaUrlPrefix();
        Pattern mediaUrlPattern = Pattern.compile(String.format("%s([0-9a-zA-Z\\-]+)", mediaUrlPrefix));
        Matcher mediaUrlMatcher = mediaUrlPattern.matcher(request.getBody());
        while (mediaUrlMatcher.find()) {
            Media media = mediaRepository.findOneById(mediaUrlMatcher.group(1));
            medias.add(media);
        }
    }
    page.setMedias(medias);

    page.setUpdatedAt(now);
    page.setUpdatedBy(authorizedUser.toString());

    SortedSet<CustomFieldValue> fieldValues = new TreeSet<>();
    Map<CustomField, CustomFieldValue> valueMap = new LinkedHashMap<>();
    for (CustomFieldValue value : page.getCustomFieldValues()) {
        valueMap.put(value.getCustomField(), value);
    }

    page.getCustomFieldValues().clear();
    if (!CollectionUtils.isEmpty(request.getCustomFieldValues())) {
        for (CustomFieldValueEditForm valueForm : request.getCustomFieldValues()) {
            CustomField customField = entityManager.getReference(CustomField.class,
                    valueForm.getCustomFieldId());
            CustomFieldValue value = valueMap.get(customField);
            if (value == null) {
                value = new CustomFieldValue();
            }
            value.setCustomField(customField);
            value.setPost(page);
            if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)) {
                if (!ArrayUtils.isEmpty(valueForm.getTextValues())) {
                    value.setTextValue(String.join(",", valueForm.getTextValues()));
                } else {
                    value.setTextValue(null);
                }
            } else {
                value.setTextValue(valueForm.getTextValue());
            }
            value.setStringValue(valueForm.getStringValue());
            value.setNumberValue(valueForm.getNumberValue());
            value.setDateValue(valueForm.getDateValue());
            value.setDatetimeValue(valueForm.getDatetimeValue());
            if (!value.isEmpty()) {
                fieldValues.add(value);
            }
        }
    }
    page.setCustomFieldValues(fieldValues);

    return pageRepository.save(page);
}

From source file:it.unibas.spicy.persistence.relational.DAORelational.java

private void loadPrimaryKeys(IDataSourceProxy dataSource, DatabaseMetaData databaseMetaData, String catalog,
        String schemaName, boolean source, Statement statement, int scenarioNo, boolean web)
        throws SQLException {

    String[] tableTypes = new String[] { "TABLE" };
    ResultSet tableResultSet = databaseMetaData.getTables(catalog, schemaName, null, tableTypes);
    while (tableResultSet.next()) {
        String tableName = tableResultSet.getString("TABLE_NAME");
        if (!this.dataDescription.checkLoadTable(tableName)) {
            logger.debug("Excluding table: " + tableName);
            continue;
        }//  ww  w .  ja  va 2s.  c  om
        if (logger.isDebugEnabled())
            logger.debug("Searching primary keys. ANALYZING TABLE  = " + tableName);
        ResultSet resultSet = databaseMetaData.getPrimaryKeys(catalog, null, tableName);
        List<PathExpression> listOfPath = new ArrayList<PathExpression>();
        List<String> PKcolumnNames = new ArrayList<String>();
        while (resultSet.next()) {
            String columnName = resultSet.getString("COLUMN_NAME");
            if (logger.isDebugEnabled())
                logger.debug("Analyzing primary key: " + columnName);
            if (!this.dataDescription.checkLoadAttribute(tableName, columnName)) {
                continue;
            }
            if (logger.isDebugEnabled())
                logger.debug("Found a Primary Key: " + columnName);
            String keyPrimary = tableName + "." + columnName;
            listOfPath.add(DAORelationalUtility.generatePath(keyPrimary));

            //giannisk alter table, add primary key
            ////un-comment the following if Primary Key Constraints are to be considered
            PKcolumnNames.add("\"" + columnName + "\"");
        }
        if (!web && !PKcolumnNames.isEmpty()) {
            String table;
            if (source) {
                table = SpicyEngineConstants.SOURCE_SCHEMA_NAME + scenarioNo + ".\"" + tableName + "\"";
            } else {
                String newSchemaName = SpicyEngineConstants.TARGET_SCHEMA_NAME + scenarioNo;
                table = newSchemaName + ".\"" + tableName + "\"";
                statement.execute(
                        GenerateSQL.createTriggerFunction(table, newSchemaName, tableName, PKcolumnNames));
                statement.execute(GenerateSQL.createTriggerBeforeInsert(table, newSchemaName, tableName));
            }

            String primaryKeys = String.join(",", PKcolumnNames);
            statement.executeUpdate("ALTER TABLE " + table + " ADD PRIMARY KEY (" + primaryKeys + ");");
        }
        ////
        //}                 
        if (!listOfPath.isEmpty()) {
            KeyConstraint keyConstraint = new KeyConstraint(listOfPath, true);
            dataSource.addKeyConstraint(keyConstraint);
        }
    }
}

From source file:com.formkiq.core.service.workflow.WorkflowEditorServiceImplTest.java

/**
 * testEventStepup03().//from www.  j a  v a 2  s.co m
 * _eventId_stepup up at max size.
 * @throws IOException IOException
 */
@Test
public void testEventStepup03() throws IOException {
    // given
    Workflow wf = expectAction();

    // when
    replayAll();
    this.ws.eventIdstepup(this.flow, this.request, new String[] { "-1" });

    // then
    verifyAll();

    assertEquals("1,2,3", String.join(",", wf.getSteps()));
    assertEquals("1,2,3", String.join(",", wf.getPrintsteps()));
}

From source file:org.ligoj.app.plugin.prov.aws.ProvAwsTerraformService.java

private void copy(final Context context, final String... fragments) throws IOException {
    Files.copy(toInput(String.join("/", fragments)),
            utils.toFile(context.getSubscription(), fragments).toPath(), StandardCopyOption.REPLACE_EXISTING);
}

From source file:de.unihannover.l3s.mws.bean.Hackathon.java

public String searcAll(int nuovo) throws IOException {
    searchResultWeb = new ArrayList<SearchResult>();
    searchClouds = new ArrayList<Cloud>();

    SolrService solrSerObj = new SolrService();
    List<PrometheusDataObject> queryResults;

    String q = "";
    // q+="\""+searchterms.get(0)+"\"";
    q += searchterms.get(0);//from  w ww  . j ava  2 s .c  o m

    queryResults = solrSerObj.search(q, this.resultnumber);

    System.out.println("Query: " + q + "\nResultsConsidered: " + this.resultnumber);
    System.out.println("----------------------------------------------------------");
    System.out.println("Query Results: " + queryResults.size());

    for (int i = 0; i < queryResults.size(); i++) {
        System.out.println("\nResult: " + (i + 1));
        System.out.println("\tTitle: " + queryResults.get(i).getTitle());
        System.out.println("\tURL: " + queryResults.get(i).getUrl());
        System.out.println("\tDescription: " + queryResults.get(i).getDescription());
        System.out.println("\tTimestamp: " + queryResults.get(i).getTimeStamp());
        System.out.println("\tVersions#: " + queryResults.get(i).getVersions().size());
        System.out.println("\tVersionsTimeSpan: " + queryResults.get(i).getFirstCrawlingVersionDate() + " to "
                + queryResults.get(i).getLastCrawlingVersionDate());
        System.out.println("\tVersions: ");
        this.searchResultWeb.clear();
        for (ArchiveUrl obj : queryResults.get(i).getVersions()) {
            SearchResult sr = new SearchResult();
            sr.setTitle(queryResults.get(i).getTitle() + " - " + obj.getTimestamp());
            sr.setUrl(obj.getArchiveUrl());
            this.searchResultWeb.add(sr);
            System.out.println("\t\tURL: " + obj.getArchiveUrl() + "\n\t\tTimestamp: " + obj.getTimestamp());
        }
        dandelionNER();
    }

    /* String s1="http://wayback.archive-it.org/1068/20090606015922/http://www.i-indiaonline.com/";
    String t1="Sat Jun 06 03:59:22 CEST 2009";
    String s2="http://wayback.archive-it.org/1068/20100319192254/http://www.i-indiaonline.com/";
    String t2="Fri Mar 19 20:22:54 CET 2010";
    String t3="Thu Sep 02 20:53:56 CEST 2010";
    String s3=   "http://wayback.archive-it.org/1068/20100902190721/http://www.i-indiaonline.com//";
    String s4="http://wayback.archive-it.org/1068/20100602185839/http://www.i-indiaonline.com/";
    String t4="Wed Jun 02 20:58:39 CEST 2010";
    String t5="Wed Mar 02 20:31:44 CET 2011";
    String s5=   "http://wayback.archive-it.org/1068/20110302222211/http://www.i-indiaonline.com//";
            
    SearchResult sr=new SearchResult();
    sr.setTitle("I-India"+" - "+t1);
    sr.setUrl(s1);
    this.searchResultWeb.add(sr);
    sr=new SearchResult();
    sr.setTitle("I-India"+" - "+t2);
    sr.setUrl(s2);
    this.searchResultWeb.add(sr);
    sr=new SearchResult();
    sr.setTitle("I-India"+" - "+t3);
    sr.setUrl(s3);
    this.searchResultWeb.add(sr);
    sr=new SearchResult();
    sr.setTitle("I-India"+" - "+t4);
    sr.setUrl(s4);
    this.searchResultWeb.add(sr);
    sr=new SearchResult();
    sr.setTitle("I-India"+" - "+t5);
    sr.setUrl(s5);
    this.searchResultWeb.add(sr);
            
    dandelionNER();
    */
    // System.out.println(this.searchClouds.get(1).sameAs(this.searchClouds.get(0)));

    // System.out.println(this.searchClouds.get(0).diff(this.searchClouds.get(1)).getList().size());
    // System.out.println(this.searchClouds.get(1).diff(this.searchClouds.get(3)).getList().size());
    javascriptTimeline = "";
    javascriptTimeline += "var jsontimeline=JSON.parse('{\"title\": {\"media\": { \"url\": \"\",\"caption\": \"\",\"credit\": \"\"},\"text\": { \"headline\": \"Analysis of different version of the URL:<br/>"
            + queryResults.get(0).getUrl() + " <br/> Title: " + queryResults.get(0).getTitle()
            + " \",\"text\": \"\"} }, ";
    javascriptTimeline += "\"events\": [";
    ArrayList<String> events = new ArrayList<String>();
    String first = "0";
    String second = "0";
    for (int k = 0; k < this.searchClouds.size(); k++) {
        Cloud c = this.searchClouds.get(k);
        // System.out.println(c);
        String dateparts[] = c.getStartdate().split(" ");
        String startdate = "\"month\": \"" + dateparts[1] + "\",\"day\": \"" + dateparts[0] + "\",\"year\": \""
                + dateparts[2] + "\"";
        String enddate = "";

        int succ = k + 1;
        while ((succ < this.searchClouds.size()) && c.sameAs(this.searchClouds.get(succ))) {
            System.out.println(k + " e " + succ + " sono uguali!");
            succ++;
        }
        if (succ != k + 1) {
            /* System.out.println(k+" and "+(succ)+" are different");
            if (succ!=this.searchClouds.size()){
               Cloud cdiff=c.bidirectionalDiff(this.searchClouds.get(succ));
               System.out.println(cdiff.toString());
               System.out.println("--------------");
            } */
            String datepartssucc[] = this.searchClouds.get(succ - 1).getStartdate().split(" ");
            enddate = "\"month\": \"" + datepartssucc[1] + "\",\"day\": \"" + datepartssucc[0]
                    + "\",\"year\": \"" + datepartssucc[2] + "\"";
            k = succ - 1;

        } else {
            enddate = "\"month\": \"" + dateparts[1] + "\",\"day\": \"" + dateparts[0] + "\",\"year\": \""
                    + dateparts[2] + "\"";
        }

        // events[k]="{\"media\": {\"url\": \"\",\"caption\": \"\",\"credit\": \"\"},\"start_date\": {\"year\": \""+c.getStartdate()+"\"},\"text\": {\"headline\": \""+c.getName()+"\",\"text\": \"<div id=\\'demo"+c.getName()+"\\'></div>\"}} ";
        events.add("{\"start_date\": {" + startdate + "},\"end_date\": {" + enddate
                + "},\"text\": {\"headline\": \"<a href=\\'#moreinfopanel\\' onclick=showmore(" + first + ","
                + second + ")>" + c.getTitle() + "</a>\",\"text\": \"<div id=\\'demo" + c.getName()
                + "\\' style=\\'margin-left: -150px\\' ></div>\"}} ");
        first = "" + k;
        second = "" + succ;
    }
    javascriptTimeline += String.join(",", events);
    javascriptTimeline += " ] }'); ";
    javascriptTimeline += "timeline = new TL.Timeline('timeline-embed',jsontimeline);";
    //System.out.println(javascriptTimeline);

    return "languageSearchStudent";
}

From source file:org.elasticsearch.client.RequestConvertersTests.java

public void testPutMapping() throws IOException {
    PutMappingRequest putMappingRequest = new PutMappingRequest();

    String[] indices = randomIndicesNames(0, 5);
    putMappingRequest.indices(indices);//  w  w  w  .j  av  a2  s  .c  o  m

    String type = randomAlphaOfLengthBetween(3, 10);
    putMappingRequest.type(type);

    Map<String, String> expectedParams = new HashMap<>();

    setRandomTimeout(putMappingRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams);
    setRandomMasterTimeout(putMappingRequest, expectedParams);

    Request request = RequestConverters.putMapping(putMappingRequest);
    StringJoiner endpoint = new StringJoiner("/", "/", "");
    String index = String.join(",", indices);
    if (Strings.hasLength(index)) {
        endpoint.add(index);
    }
    endpoint.add("_mapping");
    endpoint.add(type);
    assertEquals(endpoint.toString(), request.getEndpoint());

    assertEquals(expectedParams, request.getParameters());
    assertEquals(HttpPut.METHOD_NAME, request.getMethod());
    assertToXContentBody(putMappingRequest, request.getEntity());
}

From source file:chatbot.Chatbot.java

/** *************************************************************************************************
 * This method takes the best result matched by the ChatBot from the method matchBestInput() as input
 * and filters any profane word(s) found in the result before responding to a query.
 *//*from www  .  ja  va2s  .com*/
private ArrayList<String> profanityFilter(ArrayList<String> result) {

    ArrayList<String> filteredResult = new ArrayList<>();
    List<String> profanityList = new ArrayList<>();
    String line;
    Properties prop = new Properties();

    try {
        String profanityFile = "src/main/java/chatbot/resourcefiles/profanity-list.txt";
        String str = String.join(",", result);
        BufferedReader br = new BufferedReader(new FileReader(profanityFile));

        while ((line = br.readLine()) != null) {
            profanityList.add(line);
        }
        for (String profaneWord : profanityList) {
            // in the replaceAll() method call, the regEx searches for any spaces before and after the profane word
            // along with the punctuation marks. (?i) nullifies any case sensitive string matching.
            str = str.replaceAll("[^\\\\s\\\\w( )]*(?i)" + profaneWord + "[[^a-zA-Z0-9\\s][ ][^a-zA-Z0-9\\s]]",
                    " <censored> ");
        }
        filteredResult = new ArrayList<>(Arrays.asList(str.split(",")));
        return filteredResult;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return filteredResult;
}

From source file:com.formkiq.core.service.workflow.WorkflowEditorServiceImplTest.java

/**
 * testEventStepup04().//from www . j  a  v  a2  s. c  o m
 * _eventId_stepup last item of list.
 * @throws IOException IOException
 */
@Test
public void testEventStepup04() throws IOException {
    // given
    Workflow wf = expectAction();

    // when
    replayAll();
    this.ws.eventIdstepup(this.flow, this.request, new String[] { "2" });

    // then
    verifyAll();

    assertEquals("1,3,2", String.join(",", wf.getSteps()));
    assertEquals("1,2,3", String.join(",", wf.getPrintsteps()));
}

From source file:org.ligoj.app.plugin.prov.aws.ProvAwsTerraformService.java

private void template(final Context context, final Function<String, String> formater, final String... fragments)
        throws IOException {
    try (InputStream source = toInput(String.join("/", fragments));
            FileOutputStream target = new FileOutputStream(utils.toFile(context.getSubscription(), fragments));
            Writer targetW = new OutputStreamWriter(target);) {
        targetW.write(formater.apply(IOUtils.toString(source, StandardCharsets.UTF_8)));
    }//  w  w w  .j a  v a  2 s  .  co m
}