List of usage examples for java.lang String join
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
From source file:com.hp.octane.integrations.services.events.EventsServiceImpl.java
private void logEventsToBeSent(OctaneConfiguration configuration, CIEventsList eventsList) { try {//from ww w. j a va2 s .co m String targetOctane = configuration.getUrl() + ", SP: " + configuration.getSharedSpace(); List<String> eventsStringified = new LinkedList<>(); for (CIEvent event : eventsList.getEvents()) { eventsStringified.add(event.getProject() + ":" + event.getBuildCiId() + ":" + event.getEventType()); } logger.info( "sending [" + String.join(", ", eventsStringified) + "] event/s to [" + targetOctane + "]..."); } catch (Exception e) { logger.error("failed to log events to be sent", e); } }
From source file:io.spring.initializr.generator.CommandLineHelpGenerator.java
private static String buildTagRepresentation(Type type) { if (type.getTags().isEmpty()) { return ""; }//from ww w. j a va2s. c om return String.join(",", type.getTags().entrySet().stream() .map((entry) -> entry.getKey() + ":" + entry.getValue()).toArray(String[]::new)); }
From source file:it.polimi.diceH2020.SPACE4CloudWS.solvers.solversImpl.MINLPSolver.MINLPDataFileBuilder.java
String build() throws IOException { addFooter(); return String.join("\n", lines); }
From source file:org.createnet.raptor.db.mapdb.MapDBConnection.java
protected String getIndexKey(List<String> keys) { String[] arrKeys = new String[keys.size()]; arrKeys = keys.toArray(arrKeys);//from w w w .j ava 2s . c om Arrays.sort(arrKeys); return String.join(keySeparator, arrKeys); }
From source file:com.baifendian.swordfish.dao.mapper.ExecutionFlowMapperProvider.java
/** * , ???//from w ww . j a v a 2s. com */ public String selectByFlowIdAndTimesAndStatusLimit(Map<String, Object> parameter) { List<FlowStatus> flowStatuses = (List<FlowStatus>) parameter.get("status"); List<String> workflowList = (List<String>) parameter.get("workflowList"); List<String> workflowList2 = new ArrayList<>(); Date startDate = (Date) parameter.get("startDate"); Date endDate = (Date) parameter.get("endDate"); if (CollectionUtils.isNotEmpty(workflowList)) { for (String workflow : workflowList) { workflowList2.add("p_f.name like '" + workflow + "%'"); } } List<String> flowStatusStrList = new ArrayList<>(); if (CollectionUtils.isNotEmpty(flowStatuses)) { for (FlowStatus status : flowStatuses) { flowStatusStrList.add(String.valueOf(status.ordinal())); } } String where = String.join(",", flowStatusStrList); String sql = new SQL() { { SELECT("p_f.name as flow_name"); SELECT("p.name as project_name"); SELECT("u.name as owner"); SELECT("e_f.*"); FROM(TABLE_NAME + " e_f"); JOIN("project_flows p_f on e_f.flow_id = p_f.id"); JOIN("project p on p_f.project_id = p.id"); JOIN("user u on p_f.owner = u.id"); WHERE("p.name = #{projectName}"); if (CollectionUtils.isNotEmpty(workflowList)) { WHERE(" ( " + String.join(" or ", workflowList2) + " ) "); } if (startDate != null && endDate != null) { WHERE("start_time >= #{startDate}"); WHERE("start_time <= #{endDate}"); } if (CollectionUtils.isNotEmpty(flowStatuses)) { WHERE("`status` in (" + where + ") "); } } }.toString(); String sql2 = new SQL() { { SELECT("u.name as submit_user_name"); SELECT("e_f.*"); FROM("(" + sql + ") e_f"); JOIN("user u on e_f.submit_user = u.id"); } }.toString() + " order by start_time DESC limit #{start},#{limit}"; return sql2; }
From source file:com.github.lukaszbudnik.dqueue.QueueClientImpl.java
@Override public Future<Optional<Item>> consume(Map<String, ?> filters) { if (filters == null) { throw new IllegalArgumentException( "Filters cannot be null, if no filters are to be used pass an empty map"); }/* w w w. j av a 2s.c o m*/ Future<Optional<Item>> itemFuture = executorService.submit(() -> { String filterNames; if (filters.isEmpty()) { filterNames = NO_FILTERS; } else { filterNames = String.join("_", filters.keySet()); } String wholeOperationMetricName = "dqueue.consume." + filterNames + ".whole.timer"; Optional<Timer.Context> consumeTimer = Optional.ofNullable(metricRegistry) .map(m -> m.timer(wholeOperationMetricName).time()); InterProcessMutex interProcessMutex = new InterProcessMutex(zookeeperClient, "/dqueue/" + filterNames); try { String mutexAcquireOperationMetricName = "dqueue.consume." + filterNames + ".mutextAcquire.timer"; executeAndMeasureTime(() -> interProcessMutex.acquire(), mutexAcquireOperationMetricName); String tableName = createTableIfNotExists("consume", filterNames, filters); Select.Where select = buildSelect(tableName, filters); String cassandraSelectOperationMetricName = "dqueue.consume." + filterNames + ".cassandraSelect.timer"; ResultSet resultSet = executeAndMeasureTime(() -> session.executeAsync(select).getUninterruptibly(), cassandraSelectOperationMetricName); Row row = resultSet.one(); if (row == null) { return Optional.empty(); } UUID startTime = row.getUUID("start_time"); ByteBuffer contents = row.getBytes("contents"); Delete.Where delete = buildDelete(tableName, startTime, filters); String cassandraDeleteOperationMetricName = "dqueue.consume." + filterNames + ".cassandraDelete.timer"; executeAndMeasureTime(() -> session.executeAsync(delete).getUninterruptibly(), cassandraDeleteOperationMetricName); return Optional.of(new Item(startTime, contents, filters)); } finally { interProcessMutex.release(); consumeTimer.ifPresent(Timer.Context::stop); } }); return itemFuture; }
From source file:it.polimi.diceH2020.SPACE4CloudWS.solvers.solversImpl.SPNSolver.SPNSolver.java
@Override protected Pair<List<File>, List<File>> createWorkingFiles(@NotNull SolutionPerJob solutionPerJob) throws IOException { Pair<List<File>, List<File>> returnValue; List<File> netFileList = dataProcessor.retrieveInputFiles(".net", solutionPerJob.getParentID(), solutionPerJob.getId(), dataProcessor.getProviderName(), solutionPerJob.getTypeVMselected().getId()); List<File> defFileList = dataProcessor.retrieveInputFiles(".def", solutionPerJob.getParentID(), solutionPerJob.getId(), dataProcessor.getProviderName(), solutionPerJob.getTypeVMselected().getId()); List<File> statFileList = dataProcessor.retrieveInputFiles(".stat", solutionPerJob.getParentID(), solutionPerJob.getId(), dataProcessor.getProviderName(), solutionPerJob.getTypeVMselected().getId()); final String experiment = String.format("%s, class %s, provider %s, VM %s, # %d", solutionPerJob.getParentID(), solutionPerJob.getId(), dataProcessor.getProviderName(), solutionPerJob.getTypeVMselected().getId(), solutionPerJob.getNumberVM()); if (netFileList.isEmpty() || defFileList.isEmpty() || statFileList.isEmpty()) { logger.debug(String.format("Generating SPN model for %s", experiment)); usingInputModel = false;//from ww w.ja v a 2s . c o m returnValue = generateSPNModel(solutionPerJob); } else { logger.debug(String.format("Using input SPN model for %s", experiment)); usingInputModel = true; // TODO now it just takes the first file, I would expect a single file per list File inputNetFile = netFileList.get(0); File inputDefFile = defFileList.get(0); File inputStatFile = statFileList.get(0); String prefix = filePrefix(solutionPerJob); final String originalLabel = String.join("", Files.readAllLines(inputStatFile.toPath())); label = statSafeLabel; Map<String, String> placeHolders = new TreeMap<>(); placeHolders.put("@@CONCURRENCY@@", Long.toUnsignedString(solutionPerJob.getNumberUsers().longValue())); placeHolders.put("@@CORES@@", Long.toUnsignedString(solutionPerJob.getNumberContainers().longValue())); logger.trace("@@CORES@@ replaced with " + solutionPerJob.getNumberContainers().toString()); placeHolders.put(originalLabel, label); List<String> outcomes = processPlaceholders(inputDefFile, placeHolders); File defFile = fileUtility.provideTemporaryFile(prefix, ".def"); writeLinesToFile(outcomes, defFile); outcomes = processPlaceholders(inputNetFile, placeHolders); File netFile = fileUtility.provideTemporaryFile(prefix, ".net"); writeLinesToFile(outcomes, netFile); File statFile = fileUtility.provideTemporaryFile(prefix, ".stat"); List<String> statContent = new ArrayList<>(1); statContent.add(label); writeLinesToFile(statContent, statFile); List<File> model = new ArrayList<>(3); model.add(netFile); model.add(defFile); model.add(statFile); returnValue = new ImmutablePair<>(model, new ArrayList<>()); } return returnValue; }
From source file:alluxio.cli.ValidateEnv.java
private static boolean validateRemote(String node, String target, String name, CommandLine cmd) throws InterruptedException { System.out.format("Validating %s environment on %s...%n", target, node); if (!Utils.isAddressReachable(node, 22)) { System.err.format("Unable to reach ssh port 22 on node %s.%n", node); return false; }//from ww w.j a v a 2 s. c o m // args is not null. String argStr = String.join(" ", cmd.getArgs()); String homeDir = Configuration.get(PropertyKey.HOME); String remoteCommand = String.format("%s/bin/alluxio validateEnv %s %s %s", homeDir, target, name == null ? "" : name, argStr); String localCommand = String.format( "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand); String[] command = { "bash", "-c", localCommand }; try { ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); builder.redirectOutput(ProcessBuilder.Redirect.INHERIT); builder.redirectInput(ProcessBuilder.Redirect.INHERIT); Process process = builder.start(); process.waitFor(); return process.exitValue() == 0; } catch (IOException e) { System.err.format("Unable to validate on node %s: %s.%n", node, e.getMessage()); return false; } }
From source file:org.wallride.service.ArticleService.java
@CacheEvict(value = WallRideCacheConfiguration.ARTICLE_CACHE, allEntries = true) public Article createArticle(ArticleCreateRequest request, Post.Status status, AuthorizedUser authorizedUser) { LocalDateTime now = LocalDateTime.now(); String code = request.getCode(); if (code == null) { try {//from w w w. j av a 2 s . co m code = new CodeFormatter().parse(request.getTitle(), LocaleContextHolder.getLocale()); } catch (ParseException e) { throw new ServiceException(e); } } if (!StringUtils.hasText(code)) { if (!status.equals(Post.Status.DRAFT)) { throw new EmptyCodeException(); } } if (!status.equals(Post.Status.DRAFT)) { Post duplicate = postRepository.findOneByCodeAndLanguage(code, request.getLanguage()); if (duplicate != null) { throw new DuplicateCodeException(code); } } Article article = new Article(); if (!status.equals(Post.Status.DRAFT)) { article.setCode(code); article.setDraftedCode(null); } else { article.setCode(null); article.setDraftedCode(code); } Media cover = null; if (request.getCoverId() != null) { cover = entityManager.getReference(Media.class, request.getCoverId()); } article.setCover(cover); article.setTitle(request.getTitle()); article.setBody(request.getBody()); article.setAuthor(entityManager.getReference(User.class, authorizedUser.getId())); LocalDateTime date = request.getDate(); if (Post.Status.PUBLISHED.equals(status)) { if (date == null) { date = now; } else if (date.isAfter(now)) { status = Post.Status.SCHEDULED; } } article.setDate(date); article.setStatus(status); article.setLanguage(request.getLanguage()); article.getCategories().clear(); for (long categoryId : request.getCategoryIds()) { article.getCategories().add(entityManager.getReference(Category.class, categoryId)); } article.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()); article.setCreatedAt(now); article.setCreatedBy(authorizedUser.toString()); article.setUpdatedAt(now); article.setUpdatedBy(authorizedUser.toString()); tag = tagRepository.saveAndFlush(tag); } article.getTags().add(tag); } } article.getRelatedPosts().clear(); Set<Post> relatedPosts = new HashSet<>(); for (long relatedId : request.getRelatedPostIds()) { relatedPosts.add(entityManager.getReference(Post.class, relatedId)); } article.setRelatedToPosts(relatedPosts); Seo seo = new Seo(); seo.setTitle(request.getSeoTitle()); seo.setDescription(request.getSeoDescription()); seo.setKeywords(request.getSeoKeywords()); article.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); } } article.setMedias(medias); article.setCreatedAt(now); article.setCreatedBy(authorizedUser.toString()); article.setUpdatedAt(now); article.setUpdatedBy(authorizedUser.toString()); article.getCustomFieldValues().clear(); if (!CollectionUtils.isEmpty(request.getCustomFieldValues())) { for (CustomFieldValueEditForm valueForm : request.getCustomFieldValues()) { CustomFieldValue value = new CustomFieldValue(); value.setCustomField(entityManager.getReference(CustomField.class, valueForm.getCustomFieldId())); value.setPost(article); 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()) { article.getCustomFieldValues().add(value); } } } return articleRepository.save(article); }
From source file:com.wx3.galacdecks.Bootstrap.java
private void importRules(GameDatastore datastore, String path) throws IOException { Files.walk(Paths.get(path)).forEach(filePath -> { if (Files.isRegularFile(filePath)) { try { if (FilenameUtils.getExtension(filePath.getFileName().toString()).toLowerCase().equals("js")) { String id = FilenameUtils.removeExtension(filePath.getFileName().toString()); List<String> lines = Files.readAllLines(filePath); if (lines.size() < 3) { throw new RuntimeException( "Script file should have at least 3 lines: description, trigger, and code."); }//ww w . j av a2 s. com String description = lines.get(0).substring(2).trim(); String trigger = lines.get(1).substring(11).trim(); // Check that this actually is a valid trigger event: try { if (!trigger.equals(GameRules.BUFF_PHASE)) { Class.forName(eventPackage + "." + trigger); } } catch (ClassNotFoundException e) { throw new RuntimeException("No such GameEvent: " + trigger); } String script = String.join("\n", lines); EntityRule rule = EntityRule.createRule(trigger, script, id, description); datastore.createRule(rule); ruleCache.put(id, rule); logger.info("Imported rule " + id); } } catch (Exception e) { throw new RuntimeException("Failed to parse " + filePath + ": " + e.getMessage()); } } }); }