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.freedomotic.jfrontend.PluginConfigure.java

private void uninstallButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uninstallButtonActionPerformed
    Plugin item = (Plugin) cmbPlugin.getSelectedItem();

    File boundleRootFolder = item.getFile().getParentFile();
    String uninstallCandidates = clients.getClients().stream().filter(client -> client instanceof Plugin)
            .map(plugin -> (Plugin) plugin)
            .filter(plugin -> plugin.getFile().getParentFile().equals(boundleRootFolder))
            .map(plugin -> "'" + plugin.getName() + "'").collect(Collectors.joining(" "));

    String localizedMessage = api.getI18n().msg("confirm_plugin_delete", new Object[] { uninstallCandidates });

    int result = JOptionPane.showConfirmDialog(null, new JLabel(localizedMessage),
            api.getI18n().msg("confirm_deletion_title"), JOptionPane.OK_CANCEL_OPTION);

    if (result == JOptionPane.OK_OPTION) {
        pluginsManager.uninstallBundle(item);
        dispose();//from  w w  w  . j a va2  s  . c o  m
    }
}

From source file:io.spotnext.maven.mojo.TransformTypesMojo.java

private ClassLoader getClassloader() throws MojoExecutionException {
    try {/*  w  w  w .  ja v  a 2s.c  o m*/
        final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

        final List<URL> classPathUrls = getClasspath();

        final URLClassLoader urlClassLoader = URLClassLoader
                .newInstance(classPathUrls.toArray(new URL[classPathUrls.size()]), contextClassLoader);

        trackExecution(
                "Classpath: " + classPathUrls.stream().map(u -> u.toString()).collect(Collectors.joining(",")));

        Thread.currentThread().setContextClassLoader(urlClassLoader);

        return urlClassLoader;
    } catch (final Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:com.ikanow.aleph2.distributed_services.utils.KafkaUtils.java

/** Generates a connection string by reading ZooKeeper
 * @param curator//  w  ww  .  j  a v a  2s.  c  o m
 * @param path_override
 * @return
 * @throws Exception 
 */
public static String getBrokerListFromZookeeper(final CuratorFramework curator, Optional<String> path_override,
        final ObjectMapper mapper) throws Exception {
    final String path = path_override.orElse("/brokers/ids");
    final List<String> brokers = curator.getChildren().forPath(path);
    return brokers.stream()
            .map(Lambdas.wrap_u(broker_node -> new String(curator.getData().forPath(path + "/" + broker_node))))
            .flatMap(Lambdas.flatWrap_i(broker_str -> mapper.readTree(broker_str))) // (just discard any badly formatted nodes)
            .flatMap(Lambdas.flatWrap_i(json -> json.get("host").asText() + ":" + json.get("port").asText()))
            .collect(Collectors.joining(","));
}

From source file:com.acmutv.ontoqa.core.knowledge.KnowledgeManager.java

/**
 * Checks the query feasibility against ontology.
 * @param ontology the ontology.// w  w  w.  j a v  a 2 s .  c  o m
 * @param query the query.
 * @return true, if the query is feasible with the ontology; false, otherwise.
 */
public static boolean checkFeasibility2(Ontology ontology, Query query) {
    final Set<Node> subjects = new HashSet<>();
    final Set<Node> predicates = new HashSet<>();
    final Set<Node> objects = new HashSet<>();

    final Map<Node, Node> predicateSubjects = new HashMap<>();
    final Map<Node, Node> predicateObjects = new HashMap<>();

    ElementWalker.walk(query.getQueryPattern(), new ElementVisitorBase() {
        public void visit(ElementPathBlock el) {
            Iterator<TriplePath> triples = el.patternElts();
            while (triples.hasNext()) {
                TriplePath triple = triples.next();
                subjects.add(triple.getSubject());
                predicates.add(triple.getPredicate());
                objects.add(triple.getObject());
                predicateSubjects.put(triple.getPredicate(), triple.getSubject());
                predicateObjects.put(triple.getPredicate(), triple.getObject());
            }
        }
    });

    LOGGER.debug("subjects: {}", subjects);
    LOGGER.debug("predicates: {}", predicates);
    LOGGER.debug("objects: {}", objects);
    LOGGER.debug("predicateSubjects: {}", predicateSubjects);
    LOGGER.debug("predicateObjects: {}", predicateObjects);

    //int i = 0;
    Set<String> statements = new HashSet<>();
    Map<String, String> resourceToClassVar = new HashMap<>();
    for (Node predicate : predicates) {
        String subj_iri = predicateSubjects.get(predicate).toString();
        String obj_iri = predicateObjects.get(predicate).toString();
        String predicate_iri = predicate.toString();
        boolean isSubjVar = subj_iri.startsWith("?");
        boolean isObjVar = obj_iri.startsWith("?");

        /*String subjClassVar = resourceToClassVar.getOrDefault(subj_iri, "?subjClass" + i);
        resourceToClassVar.put(subj_iri, subjClassVar);
        String objClassVar = resourceToClassVar.getOrDefault(obj_iri, "?objClass" + i);
        resourceToClassVar.put(obj_iri, objClassVar);
        */

        String subjClassVar = resourceToClassVar.getOrDefault(subj_iri,
                "?class" + resourceToClassVar.keySet().size());
        resourceToClassVar.put(subj_iri, subjClassVar);
        String objClassVar = resourceToClassVar.getOrDefault(obj_iri,
                "?class" + resourceToClassVar.keySet().size());
        resourceToClassVar.put(obj_iri, objClassVar);

        LOGGER.trace("Processing: {} (var: {})| {} | {} (var: {})", subj_iri, isSubjVar, predicate_iri, obj_iri,
                isObjVar);

        String subjectConstraint = String.format("%s <%s> %s", (isSubjVar) ? subj_iri : '<' + subj_iri + '>',
                RDF_TYPE, subjClassVar);

        String objectConstraint = String.format("%s <%s> %s", (isObjVar) ? obj_iri : '<' + obj_iri + '>',
                RDF_TYPE, objClassVar);

        String predicateConstraint = String.format("<%s> <%s> %s . <%s> <%s> %s", predicate_iri, RDFS_DOMAIN,
                subjClassVar, predicate_iri, RDFS_RANGE, objClassVar);

        statements.add(subjectConstraint);
        statements.add(objectConstraint);
        statements.add(predicateConstraint);
        //i++;
    }

    String consistencyStatements = statements.stream().collect(Collectors.joining(" . "));

    Query consistencyQuery = QueryFactory.create("ASK WHERE { " + consistencyStatements + " }");

    LOGGER.debug("consistency query: {}", consistencyQuery);

    QueryResult qQueryResult;
    try {
        qQueryResult = KnowledgeManager.submit(ontology, consistencyQuery);
    } catch (com.acmutv.ontoqa.core.exception.QueryException exc) {
        LOGGER.warn(exc.getMessage());
        return false;
    }
    Answer answer = qQueryResult.toAnswer();

    if (SimpleAnswer.FALSE.equals(answer)) {
        return false;
    }

    return true;
}

From source file:fll.scheduler.SchedulerUI.java

void saveScheduleDescription() {
    if (null == mScheduleDescriptionFile) {
        // prompt the user for a filename to save to

        final String startingDirectory = PREFS.get(DESCRIPTION_STARTING_DIRECTORY_PREF, null);

        final JFileChooser fileChooser = new JFileChooser();
        final FileFilter filter = new BasicFileFilter("FLL Schedule Description (properties)",
                new String[] { "properties" });
        fileChooser.setFileFilter(filter);
        if (null != startingDirectory) {
            fileChooser.setCurrentDirectory(new File(startingDirectory));
        }//from   w  w w  .  j  a  va 2s  .  c o  m

        final int returnVal = fileChooser.showSaveDialog(SchedulerUI.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            final File currentDirectory = fileChooser.getCurrentDirectory();
            PREFS.put(DESCRIPTION_STARTING_DIRECTORY_PREF, currentDirectory.getAbsolutePath());

            mScheduleDescriptionFile = fileChooser.getSelectedFile();
            mDescriptionFilename.setText(mScheduleDescriptionFile.getName());
        } else {
            // user canceled
            return;
        }
    }

    try (final Writer writer = new OutputStreamWriter(new FileOutputStream(mScheduleDescriptionFile),
            Utilities.DEFAULT_CHARSET)) {
        final SolverParams params = mScheduleDescriptionEditor.getParams();
        final List<String> errors = params.isValid();
        if (!errors.isEmpty()) {
            final String formattedErrors = errors.stream().collect(Collectors.joining("\n"));
            JOptionPane.showMessageDialog(SchedulerUI.this,
                    "There are errors that need to be corrected before the description can be saved: "
                            + formattedErrors,
                    "Error saving file", JOptionPane.ERROR_MESSAGE);
        } else {
            final Properties properties = new Properties();
            params.save(properties);
            properties.store(writer, null);
        }
    } catch (final IOException e) {
        final Formatter errorFormatter = new Formatter();
        errorFormatter.format("Error saving file: %s", e.getMessage());
        LOGGER.error(errorFormatter, e);
        JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error saving file",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.simiacryptus.util.Util.java

/**
 * Mk string string.//w  w w . jav  a  2 s. co  m
 *
 * @param separator the separator
 * @param strs      the strs
 * @return the string
 */
public static String mkString(@javax.annotation.Nonnull final String separator, final String... strs) {
    return Arrays.asList(strs).stream().collect(Collectors.joining(separator));
}

From source file:cc.arduino.Compiler.java

private void callArduinoBuilder(TargetBoard board, TargetPlatform platform, TargetPackage aPackage,
        String vidpid, BuilderAction action, OutputStream outStream, OutputStream errStream)
        throws RunnerException {
    List<String> cmd = new ArrayList<>();
    cmd.add(BaseNoGui.getContentFile("arduino-builder").getAbsolutePath());
    cmd.add(action.value);//from   www.  java 2 s .  c o m
    cmd.add("-logger=machine");

    File installedPackagesFolder = new File(BaseNoGui.getSettingsFolder(), "packages");

    addPathFlagIfPathExists(cmd, "-hardware", BaseNoGui.getHardwareFolder());
    addPathFlagIfPathExists(cmd, "-hardware", installedPackagesFolder);
    addPathFlagIfPathExists(cmd, "-hardware", BaseNoGui.getSketchbookHardwareFolder());

    addPathFlagIfPathExists(cmd, "-tools", BaseNoGui.getContentFile("tools-builder"));
    addPathFlagIfPathExists(cmd, "-tools", Paths.get(BaseNoGui.getHardwarePath(), "tools", "avr").toFile());
    addPathFlagIfPathExists(cmd, "-tools", installedPackagesFolder);

    addPathFlagIfPathExists(cmd, "-built-in-libraries", BaseNoGui.getContentFile("libraries"));
    addPathFlagIfPathExists(cmd, "-libraries", BaseNoGui.getSketchbookLibrariesFolder().folder);

    String fqbn = Stream.of(aPackage.getId(), platform.getId(), board.getId(), boardOptions(board))
            .filter(s -> !s.isEmpty()).collect(Collectors.joining(":"));
    cmd.add("-fqbn=" + fqbn);

    if (!"".equals(vidpid)) {
        cmd.add("-vid-pid=" + vidpid);
    }

    cmd.add("-ide-version=" + BaseNoGui.REVISION);
    cmd.add("-build-path");
    cmd.add(buildPath);
    cmd.add("-warnings=" + PreferencesData.get("compiler.warning_level"));

    if (PreferencesData.getBoolean("compiler.cache_core") == true && buildCache != null) {
        cmd.add("-build-cache");
        cmd.add(buildCache.getAbsolutePath());
    }

    PreferencesData.getMap().subTree("runtime.build_properties_custom").entrySet().stream()
            .forEach(kv -> cmd.add("-prefs=" + kv.getKey() + "=" + kv.getValue()));

    cmd.add("-prefs=build.warn_data_percentage=" + PreferencesData.get("build.warn_data_percentage"));

    for (Map.Entry<String, String> entry : BaseNoGui.getBoardPreferences().entrySet()) {
        if (entry.getKey().startsWith("runtime.tools")) {
            cmd.add("-prefs=" + entry.getKey() + "=" + entry.getValue());
        }
    }

    //commandLine.addArgument("-debug-level=10", false);

    if (verbose) {
        cmd.add("-verbose");
    }

    cmd.add(pathToSketch.getAbsolutePath());

    if (verbose) {
        System.out.println(StringUtils.join(cmd, ' '));
    }

    int result;
    try {
        Process proc = ProcessUtils.exec(cmd.toArray(new String[0]));
        MessageSiphon in = new MessageSiphon(proc.getInputStream(), (msg) -> {
            try {
                outStream.write(msg.getBytes());
            } catch (Exception e) {
                exception = new RunnerException(e);
            }
        });
        MessageSiphon err = new MessageSiphon(proc.getErrorStream(), (msg) -> {
            try {
                errStream.write(msg.getBytes());
            } catch (Exception e) {
                exception = new RunnerException(e);
            }
        });

        in.join();
        err.join();
        result = proc.waitFor();
    } catch (Exception e) {
        throw new RunnerException(e);
    }

    if (exception != null)
        throw exception;

    if (result > 1) {
        System.err.println(I18n.format(tr("{0} returned {1}"), cmd.get(0), result));
    }

    if (result != 0) {
        RunnerException re = new RunnerException(
                I18n.format(tr("Error compiling for board {0}."), board.getName()));
        re.hideStackTrace();
        throw re;
    }
}

From source file:com.thoughtworks.go.apiv2.environments.EnvironmentsControllerV2.java

private String calculateEtag(Collection<EnvironmentConfig> environmentConfigs) {
    final String environmentConfigSegment = environmentConfigs.stream().map(this::etagFor)
            .collect(Collectors.joining(SEP_CHAR));

    return DigestUtils.sha256Hex(environmentConfigSegment);
}

From source file:net.staticsnow.nexus.repository.apt.internal.hosted.AptHostedFacet.java

private String buildReleaseFile(String distribution, Collection<String> architectures, String md5,
        String sha256) {//from w w  w . j  ava  2s .  c o  m
    Paragraph p = new Paragraph(Arrays.asList(new ControlFile.ControlField("Suite", distribution),
            new ControlFile.ControlField("Codename", distribution),
            new ControlFile.ControlField("Components", "main"),
            new ControlFile.ControlField("Date", DateUtils.formatDate(new Date())),
            new ControlFile.ControlField("Architectures",
                    architectures.stream().collect(Collectors.joining(" "))),
            new ControlFile.ControlField("SHA256", sha256), new ControlFile.ControlField("MD5Sum", md5)));
    return p.toString();
}

From source file:de.monticore.io.paths.IterablePath.java

@Override
public String toString() {
    if (this.pathMap.isEmpty()) {
        return "[empty iterable path]";
    }/*from   w  ww.  j  a  v  a 2  s  . c  o  m*/
    String result = "[";
    result = result
            + this.pathMap.values().stream().sorted().map(Path::toString).collect(Collectors.joining(", "));
    return result + "]";
}