Example usage for java.lang System lineSeparator

List of usage examples for java.lang System lineSeparator

Introduction

In this page you can find the example usage for java.lang System lineSeparator.

Prototype

String lineSeparator

To view the source code for java.lang System lineSeparator.

Click Source Link

Usage

From source file:com.pearson.eidetic.driver.threads.subthreads.SnapshotVolumeSyncValidator.java

public boolean snapshotDecision(AmazonEC2Client ec2Client, Volume vol, Integer createAfter) {
    if ((ec2Client == null) || (vol == null) || (createAfter == null)) {
        return false;
    }/*from  www .  jav a2  s  .  com*/
    try {

        List<Snapshot> int_snapshots = getAllSnapshotsOfVolume(ec2Client, vol, numRetries_,
                maxApiRequestsPerSecond_, uniqueAwsAccountIdentifier_);

        List<Snapshot> comparelist = new ArrayList();

        for (Snapshot snapshot : int_snapshots) {
            String sndesc = snapshot.getDescription();
            if (sndesc.startsWith("sync_snapshot")) {
                comparelist.add(snapshot);
            }
        }

        List<Snapshot> sortedCompareList = new ArrayList<>(comparelist);
        sortSnapshotsByDate(sortedCompareList);

        int hours = getHoursBetweenNowAndNewestSnapshot(sortedCompareList);
        int days = getDaysBetweenNowAndNewestSnapshot(sortedCompareList);

        if (hours <= createAfter) {
            return false;
        }

    } catch (Exception e) {
        logger.info("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                + "\",Event=\"Error\", Error=\"error in snapshotDecision\", stacktrace=\"" + e.toString()
                + System.lineSeparator() + StackTrace.getStringFromStackTrace(e) + "\"");
        return false;
    }

    return true;
}

From source file:org.apache.zeppelin.submarine.hadoop.YarnClient.java

public List<Map<String, Object>> getAppAttemptsContainers(String appId, String appAttemptId) {
    List<Map<String, Object>> appAttemptsContainers = new ArrayList<>();
    String appUrl = this.yarnWebHttpAddr + "/ws/v1/cluster/apps/" + appId + "/appattempts/" + appAttemptId
            + "/containers?_=" + System.currentTimeMillis();

    InputStream inputStream = null;
    try {// w ww  .j a v a 2  s.com
        HttpResponse response = callRestUrl(appUrl, principal, HTTP.GET);
        inputStream = response.getEntity().getContent();
        String result = new BufferedReader(new InputStreamReader(inputStream)).lines()
                .collect(Collectors.joining(System.lineSeparator()));
        if (response.getStatusLine().getStatusCode() != 200 /*success*/) {
            LOGGER.warn("Status code " + response.getStatusLine().getStatusCode());
            LOGGER.warn("message is :" + Arrays.deepToString(response.getAllHeaders()));
            LOGGER.warn("result\n" + result);
        }

        // parse app status json
        appAttemptsContainers = parseAppAttemptsContainers(result);
    } catch (Exception exp) {
        exp.printStackTrace();
    } finally {
        try {
            if (null != inputStream) {
                inputStream.close();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    return appAttemptsContainers;
}

From source file:com.thoughtworks.go.config.GoFileConfigDataSource.java

public synchronized EntityConfigSaveResult writeEntityWithLock(EntityConfigUpdateCommand updatingCommand,
        GoConfigHolder configHolder, Username currentUser) {
    CruiseConfig modifiedConfig = cloner.deepClone(configHolder.configForEdit);
    try {//  www  .  j a  v a 2 s  . com
        updatingCommand.update(modifiedConfig);
    } catch (Exception e) {
        bomb(e);
    }
    List<PartialConfig> lastValidPartials = cachedGoPartials.lastValidPartials();
    List<PartialConfig> lastKnownPartials = cachedGoPartials.lastKnownPartials();
    if (lastKnownPartials.isEmpty()
            || areKnownPartialsSameAsValidPartials(lastKnownPartials, lastValidPartials)) {
        return trySavingEntity(updatingCommand, currentUser, modifiedConfig, lastValidPartials);
    }
    try {
        return trySavingEntity(updatingCommand, currentUser, modifiedConfig, lastValidPartials);
    } catch (GoConfigInvalidException e) {
        StringBuilder errorMessageBuilder = new StringBuilder();
        try {
            String message = String.format(
                    "Merged update operation failed on VALID %s partials. Falling back to using LAST KNOWN %s partials. Exception message was: [%s %s]",
                    lastValidPartials.size(), lastKnownPartials.size(), e.getMessage(),
                    e.getAllErrorMessages());
            errorMessageBuilder.append(message);
            LOGGER.warn(message, e);
            updatingCommand.clearErrors();
            modifiedConfig.setPartials(lastKnownPartials);
            String configAsXml = configAsXml(modifiedConfig, false);
            GoConfigHolder holder = internalLoad(configAsXml,
                    new ConfigModifyingUser(currentUser.getUsername().toString()), lastKnownPartials);
            LOGGER.info(
                    "Update operation on merged configuration succeeded with {} KNOWN partials. Now there are {} LAST KNOWN partials",
                    lastKnownPartials.size(), cachedGoPartials.lastKnownPartials().size());
            return new EntityConfigSaveResult(holder.config, holder);
        } catch (Exception exceptionDuringFallbackValidation) {
            String message = String.format(
                    "Merged config update operation failed using fallback LAST KNOWN %s partials. Exception message was: %s",
                    lastKnownPartials.size(), exceptionDuringFallbackValidation.getMessage());
            LOGGER.warn(message, exceptionDuringFallbackValidation);
            errorMessageBuilder.append(System.lineSeparator());
            errorMessageBuilder.append(message);
            throw new GoConfigInvalidException(e.getCruiseConfig(), errorMessageBuilder.toString());
        }
    }

}

From source file:org.apache.nifi.processors.kite.TestInferAvroSchema.java

static byte[] unix2PlatformSpecificLineEndings(final File file) throws IOException {
    try (final BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
            final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        byte eol[] = System.lineSeparator().getBytes(StandardCharsets.UTF_8);
        int justRead;
        while ((justRead = in.read()) != -1) {
            if (justRead == '\n') {
                out.write(eol);/*from  www  .  java2  s  . c  om*/
            } else {
                out.write(justRead);
            }
        }
        return out.toByteArray();
    }
}

From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java

public static String updateFormDesign(FormModel formModel, String design) {
    try {/*  ww  w .j a  v  a  2s.  co  m*/
        StringBuilder designBuilder = new StringBuilder();
        for (FieldModel field : formModel.getParameters()) {
            String line = FieldModelUtil.getFormDesignElement(field, null);
            if (!line.isEmpty()) {
                designBuilder.append(line).append(System.lineSeparator());
            }
        }
        for (FileModel file : formModel.getFiles()) {
            String line = FileModelUtil.getFormDesignElement(file);
            if (!line.isEmpty()) {
                designBuilder.append(line).append(System.lineSeparator());
            }
        }
        return replaceGeneratedCode(design, designBuilder.toString(), SyntaxConstant.FORM_DESIGN_START,
                SyntaxConstant.FORM_DESIGN_END);
    } catch (Exception ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);
        return design;
    }
}

From source file:com.pearson.eidetic.driver.threads.RefreshAwsAccountVolumes.java

private ConcurrentHashMap<Region, ArrayList<Volume>> refreshCopyVolumeSnapshots(Volume volume,
        JSONObject eideticParameters, ConcurrentHashMap<Region, ArrayList<Volume>> localCopyVolumeSnapshots,
        Region region) {//from   w  w  w  .  java  2  s. c o m
    if (volume == null || eideticParameters == null || region == null) {
        return localCopyVolumeSnapshots;
    }
    if (!eideticParameters.containsKey("CopySnapshot")) {
        //and it previously did
        if (volCopyHasTag_.containsKey(volume)) {
            //We leave volCopyHasTag_ at false
            return localCopyVolumeSnapshots;
            //else it previously did not, and we do not worry
        } else {
            //we continue along to the next volume.
            return localCopyVolumeSnapshots;
        }
        //It does have CopySnapshot
    } else {
        //Did it previously?
        if (volCopyHasTag_.containsKey(volume)) {
            //Yeah it does, set to true
            try {
                volCopyHasTag_.replace(volume, true);
            } catch (Exception e) {
                logger.info("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=\"Error\", Error=\"error adding vol to CopyVolumeSnapshots\", Volume_id=\""
                        + volume.getVolumeId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
            }
        } else {
            //It did not, we add to localCopyVolumeSnapshots
            try {
                localCopyVolumeSnapshots.get(region).add(volume);
            } catch (Exception e) {
                logger.info("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=\"Error\", Error=\"error adding vol to CopyVolumeSnapshots\", Volume_id=\""
                        + volume.getVolumeId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
            }

            try {
                volCopyHasTag_.put(volume, true);
            } catch (Exception e) {
                logger.info("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=\"Error\", Error=\"error adding vol to CopyVolumeSnapshots\", Volume_id=\""
                        + volume.getVolumeId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
            }
        }
    }
    return localCopyVolumeSnapshots;
}

From source file:com.floragunn.searchguard.tools.SearchGuardAdmin.java

private static void main0(final String[] args) throws Exception {

    System.setProperty("sg.nowarn.client", "true");

    final HelpFormatter formatter = new HelpFormatter();
    Options options = new Options();
    options.addOption("nhnv", "disable-host-name-verification", false, "Disable hostname verification");
    options.addOption("nrhn", "disable-resolve-hostname", false, "Disable hostname beeing resolved");
    options.addOption(Option.builder("ts").longOpt("truststore").hasArg().argName("file").required()
            .desc("Path to truststore (JKS/PKCS12 format)").build());
    options.addOption(Option.builder("ks").longOpt("keystore").hasArg().argName("file").required()
            .desc("Path to keystore (JKS/PKCS12 format").build());
    options.addOption(Option.builder("tst").longOpt("truststore-type").hasArg().argName("type")
            .desc("JKS or PKCS12, if not given use file ext. to dectect type").build());
    options.addOption(Option.builder("kst").longOpt("keystore-type").hasArg().argName("type")
            .desc("JKS or PKCS12, if not given use file ext. to dectect type").build());
    options.addOption(Option.builder("tspass").longOpt("truststore-password").hasArg().argName("password")
            .desc("Truststore password").build());
    options.addOption(Option.builder("kspass").longOpt("keystore-password").hasArg().argName("password")
            .desc("Keystore password").build());
    options.addOption(Option.builder("cd").longOpt("configdir").hasArg().argName("directory")
            .desc("Directory for config files").build());
    options.addOption(Option.builder("h").longOpt("hostname").hasArg().argName("host")
            .desc("Elasticsearch host").build());
    options.addOption(Option.builder("p").longOpt("port").hasArg().argName("port")
            .desc("Elasticsearch transport port (normally 9300)").build());
    options.addOption(Option.builder("cn").longOpt("clustername").hasArg().argName("clustername")
            .desc("Clustername").build());
    options.addOption("sniff", "enable-sniffing", false, "Enable client.transport.sniff");
    options.addOption("icl", "ignore-clustername", false, "Ignore clustername");
    options.addOption(Option.builder("r").longOpt("retrieve").desc("retrieve current config").build());
    options.addOption(Option.builder("f").longOpt("file").hasArg().argName("file").desc("file").build());
    options.addOption(/*  w  w  w .j ava  2 s  .  c om*/
            Option.builder("t").longOpt("type").hasArg().argName("file-type").desc("file-type").build());
    options.addOption(Option.builder("tsalias").longOpt("truststore-alias").hasArg().argName("alias")
            .desc("Truststore alias").build());
    options.addOption(Option.builder("ksalias").longOpt("keystore-alias").hasArg().argName("alias")
            .desc("Keystore alias").build());
    options.addOption(Option.builder("ec").longOpt("enabled-ciphers").hasArg().argName("cipers")
            .desc("Comma separated list of TLS ciphers").build());
    options.addOption(Option.builder("ep").longOpt("enabled-protocols").hasArg().argName("protocols")
            .desc("Comma separated list of TLS protocols").build());
    //TODO mark as deprecated and replace it with "era" if "era" is mature enough
    options.addOption(Option.builder("us").longOpt("update_settings").hasArg().argName("number of replicas")
            .desc("update the number of replicas and reload configuration on all nodes and exit").build());
    options.addOption(Option.builder("i").longOpt("index").hasArg().argName("indexname")
            .desc("The index Searchguard uses to store its configs in").build());
    options.addOption(Option.builder("era").longOpt("enable-replica-autoexpand")
            .desc("enable replica auto expand and exit").build());
    options.addOption(Option.builder("dra").longOpt("disable-replica-autoexpand")
            .desc("disable replica auto expand and exit").build());
    options.addOption(
            Option.builder("rl").longOpt("reload").desc("reload configuration on all nodes and exit").build());
    options.addOption(
            Option.builder("ff").longOpt("fail-fast").desc("fail-fast if something goes wrong").build());
    options.addOption(
            Option.builder("dg").longOpt("diagnose").desc("Log diagnostic trace into a file").build());
    options.addOption(Option.builder("dci").longOpt("delete-config-index")
            .desc("Delete 'searchguard' config index and exit.").build());
    options.addOption(Option.builder("esa").longOpt("enable-shard-allocation")
            .desc("Enable all shard allocation and exit.").build());

    String hostname = "localhost";
    int port = 9300;
    String kspass = System.getenv(SG_KS_PASS) != null ? System.getenv(SG_KS_PASS) : "changeit";
    String tspass = System.getenv(SG_TS_PASS) != null ? System.getenv(SG_TS_PASS) : kspass;
    String cd = ".";
    String ks;
    String ts;
    String kst = null;
    String tst = null;
    boolean nhnv = false;
    boolean nrhn = false;
    boolean sniff = false;
    boolean icl = false;
    String clustername = "elasticsearch";
    String file = null;
    String type = null;
    boolean retrieve = false;
    String ksAlias = null;
    String tsAlias = null;
    String[] enabledProtocols = new String[0];
    String[] enabledCiphers = new String[0];
    Integer updateSettings = null;
    String index = ConfigConstants.SG_DEFAULT_CONFIG_INDEX;
    Boolean replicaAutoExpand = null;
    boolean reload = false;
    boolean failFast = false;
    boolean diagnose = false;
    boolean deleteConfigIndex = false;
    boolean enableShardAllocation = false;

    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine line = parser.parse(options, args);
        hostname = line.getOptionValue("h", hostname);
        port = Integer.parseInt(line.getOptionValue("p", String.valueOf(port)));
        kspass = line.getOptionValue("kspass", kspass); //TODO null? //when no passwd is set
        tspass = line.getOptionValue("tspass", tspass); //TODO null? //when no passwd is set
        cd = line.getOptionValue("cd", cd);

        if (!cd.endsWith(File.separator)) {
            cd += File.separator;
        }

        ks = line.getOptionValue("ks");
        ts = line.getOptionValue("ts");
        kst = line.getOptionValue("kst", kst);
        tst = line.getOptionValue("tst", tst);
        nhnv = line.hasOption("nhnv");
        nrhn = line.hasOption("nrhn");
        clustername = line.getOptionValue("cn", clustername);
        sniff = line.hasOption("sniff");
        icl = line.hasOption("icl");
        file = line.getOptionValue("f", file);
        type = line.getOptionValue("t", type);
        retrieve = line.hasOption("r");
        ksAlias = line.getOptionValue("ksalias", ksAlias);
        tsAlias = line.getOptionValue("tsalias", tsAlias);
        index = line.getOptionValue("i", index);

        String enabledCiphersString = line.getOptionValue("ec", null);
        String enabledProtocolsString = line.getOptionValue("ep", null);

        if (enabledCiphersString != null) {
            enabledCiphers = enabledCiphersString.split(",");
        }

        if (enabledProtocolsString != null) {
            enabledProtocols = enabledProtocolsString.split(",");
        }

        updateSettings = line.hasOption("us") ? Integer.parseInt(line.getOptionValue("us")) : null;

        reload = line.hasOption("rl");

        if (line.hasOption("era")) {
            replicaAutoExpand = true;
        }

        if (line.hasOption("dra")) {
            replicaAutoExpand = false;
        }

        failFast = line.hasOption("ff");
        diagnose = line.hasOption("dg");
        deleteConfigIndex = line.hasOption("dci");
        enableShardAllocation = line.hasOption("esa");

    } catch (ParseException exp) {
        System.err.println("ERR: Parsing failed.  Reason: " + exp.getMessage());
        formatter.printHelp("sgadmin.sh", options, true);
        return;
    }

    if (port < 9300) {
        System.out.println("WARNING: Seems you want connect to the a HTTP port." + System.lineSeparator()
                + "         sgadmin connect through the transport port which is normally 9300.");
    }

    System.out.print("Will connect to " + hostname + ":" + port);
    Socket socket = new Socket();

    try {

        socket.connect(new InetSocketAddress(hostname, port));

    } catch (java.net.ConnectException ex) {
        System.out.println();
        System.out.println(
                "ERR: Seems there is no elasticsearch running on " + hostname + ":" + port + " - Will exit");
        System.exit(-1);
    } finally {
        try {
            socket.close();
        } catch (Exception e) {
            //ignore
        }
    }

    System.out.println(" ... done");

    final Settings.Builder settingsBuilder = Settings.builder().put("path.home", ".").put("path.conf", ".")
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH, ks)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, ts)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_PASSWORD, kspass)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_PASSWORD, tspass)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENFORCE_HOSTNAME_VERIFICATION, !nhnv)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENFORCE_HOSTNAME_VERIFICATION_RESOLVE_HOST_NAME,
                    !nrhn)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLED, true)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_TYPE,
                    kst == null ? (ks.endsWith(".jks") ? "JKS" : "PKCS12") : kst)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_TYPE,
                    tst == null ? (ts.endsWith(".jks") ? "JKS" : "PKCS12") : tst)

            .putArray(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLED_CIPHERS, enabledCiphers)
            .putArray(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLED_PROTOCOLS, enabledProtocols)

            .put("cluster.name", clustername).put("client.transport.ignore_cluster_name", icl)
            .put("client.transport.sniff", sniff);

    if (ksAlias != null) {
        settingsBuilder.put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_ALIAS, ksAlias);
    }

    if (tsAlias != null) {
        settingsBuilder.put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_ALIAS, tsAlias);
    }

    Settings settings = settingsBuilder.build();

    try (TransportClient tc = TransportClient.builder().settings(settings).addPlugin(SearchGuardSSLPlugin.class)
            .addPlugin(SearchGuardPlugin.class) //needed for config update action only
            .build()
            .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(hostname, port)))) {

        if (updateSettings != null) {
            Settings indexSettings = Settings.builder().put("index.number_of_replicas", updateSettings).build();
            tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(
                    new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }))
                    .actionGet();
            final UpdateSettingsResponse response = tc.admin().indices()
                    .updateSettings((new UpdateSettingsRequest(index).settings(indexSettings))).actionGet();
            System.out.println("Reload config on all nodes");
            System.out.println("Update number of replicas to " + (updateSettings) + " with result: "
                    + response.isAcknowledged());
            System.exit(response.isAcknowledged() ? 0 : -1);
        }

        if (reload) {
            tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(
                    new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }))
                    .actionGet();
            System.out.println("Reload config on all nodes");
            System.exit(0);
        }

        if (replicaAutoExpand != null) {
            Settings indexSettings = Settings.builder()
                    .put("index.auto_expand_replicas", replicaAutoExpand ? "0-all" : "false").build();
            tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(
                    new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }))
                    .actionGet();
            final UpdateSettingsResponse response = tc.admin().indices()
                    .updateSettings((new UpdateSettingsRequest(index).settings(indexSettings))).actionGet();
            System.out.println("Reload config on all nodes");
            System.out.println("Auto-expand replicas " + (replicaAutoExpand ? "enabled" : "disabled"));
            System.exit(response.isAcknowledged() ? 0 : -1);
        }

        if (enableShardAllocation) {
            final boolean successful = tc.admin().cluster()
                    .updateSettings(new ClusterUpdateSettingsRequest()
                            .transientSettings(ENABLE_ALL_ALLOCATIONS_SETTINGS)
                            .persistentSettings(ENABLE_ALL_ALLOCATIONS_SETTINGS))
                    .actionGet().isAcknowledged();

            if (successful) {
                System.out.println("Persistent and transient shard allocation enabled");
            } else {
                System.out.println("ERR: Unable to enable shard allocation");
            }

            System.exit(successful ? 0 : -1);
        }

        if (failFast) {
            System.out.println("Failfast is activated");
        }

        if (diagnose) {
            generateDiagnoseTrace(tc);
        }

        System.out.println(
                "Contacting elasticsearch cluster '" + clustername + "' and wait for YELLOW clusterstate ...");

        ClusterHealthResponse chr = null;

        while (chr == null) {
            try {
                chr = tc.admin().cluster().health(
                        new ClusterHealthRequest().timeout(TimeValue.timeValueMinutes(5)).waitForYellowStatus())
                        .actionGet();
            } catch (Exception e) {
                if (!failFast) {
                    System.out.println("Cannot retrieve cluster state due to: " + e.getMessage()
                            + ". This is not an error, will keep on trying ...");
                    System.out.println(
                            "   * Try running sgadmin.sh with -icl and -nhnv (If thats works you need to check your clustername as well as hostnames in your SSL certificates)");
                    System.out.println(
                            "   * If this is not working, try running sgadmin.sh with --diagnose and see diagnose trace log file)");

                } else {
                    System.out.println("ERR: Cannot retrieve cluster state due to: " + e.getMessage() + ".");
                    System.out.println(
                            "   * Try running sgadmin.sh with -icl and -nhnv (If thats works you need to check your clustername as well as hostnames in your SSL certificates)");
                    System.out.println(
                            "   * If this is not working, try running sgadmin.sh with --diagnose and see diagnose trace log file)");

                    System.exit(-1);
                }

                Thread.sleep(3000);
                continue;
            }
        }

        final boolean timedOut = chr.isTimedOut();

        if (timedOut) {
            System.out.println("ERR: Timed out while waiting for a green or yellow cluster state.");
            System.out.println(
                    "   * Try running sgadmin.sh with -icl and -nhnv (If thats works you need to check your clustername as well as hostnames in your SSL certificates)");
            System.exit(-1);
        }

        System.out.println("Clustername: " + chr.getClusterName());
        System.out.println("Clusterstate: " + chr.getStatus());
        System.out.println("Number of nodes: " + chr.getNumberOfNodes());
        System.out.println("Number of data nodes: " + chr.getNumberOfDataNodes());

        final boolean indexExists = tc.admin().indices().exists(new IndicesExistsRequest(index)).actionGet()
                .isExists();

        final NodesInfoResponse nodesInfo = tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet();

        if (deleteConfigIndex) {

            boolean success = true;

            if (indexExists) {
                success = tc.admin().indices().delete(new DeleteIndexRequest(index)).actionGet()
                        .isAcknowledged();
                System.out.print("Deleted index '" + index + "'");
            } else {
                System.out.print("No index '" + index + "' exists, so no need to delete it");
            }

            System.exit(success ? 0 : -1);
        }

        if (!indexExists) {
            System.out.print(index + " index does not exists, attempt to create it ... ");
            int replicas = chr.getNumberOfDataNodes() - 1;
            final boolean indexCreated = tc.admin().indices().create(new CreateIndexRequest(index)
                    // .mapping("config", source)
                    // .settings(settings)
                    //TODO "index.auto_expand_replicas", "0-all"
                    .settings("index.number_of_shards", 1, "index.number_of_replicas", replicas)).actionGet()
                    .isAcknowledged();

            if (indexCreated) {
                System.out.println("done (with " + replicas + " replicas, auto expand replicas is off)");
            } else {
                System.out.println("failed!");
                System.out.println("FAIL: Unable to create the " + index
                        + " index. See elasticsearch logs for more details");
                System.exit(-1);
            }

        } else {
            System.out.println(index + " index already exists, so we do not need to create one.");

            try {
                ClusterHealthResponse chrsg = tc.admin().cluster().health(new ClusterHealthRequest(index))
                        .actionGet();

                if (chrsg.isTimedOut()) {
                    System.out.println("ERR: Timed out while waiting for " + index + " index state.");
                }

                if (chrsg.getStatus() == ClusterHealthStatus.RED) {
                    System.out.println("ERR: " + index + " index state is RED.");
                }

                if (chrsg.getStatus() == ClusterHealthStatus.YELLOW) {
                    System.out.println(
                            "INFO: " + index + " index state is YELLOW, it seems you miss some replicas");
                }

            } catch (Exception e) {
                if (!failFast) {
                    System.out.println("Cannot retrieve " + index + " index state state due to "
                            + e.getMessage() + ". This is not an error, will keep on trying ...");
                } else {
                    System.out.println("ERR: Cannot retrieve " + index + " index state state due to "
                            + e.getMessage() + ".");
                    System.exit(-1);
                }
            }
        }

        if (retrieve) {
            String date = DATE_FORMAT.format(new Date());

            boolean success = retrieveFile(tc, cd + "sg_config_" + date + ".yml", index, "config");
            success = success & retrieveFile(tc, cd + "sg_roles_" + date + ".yml", index, "roles");
            success = success
                    & retrieveFile(tc, cd + "sg_roles_mapping_" + date + ".yml", index, "rolesmapping");
            success = success
                    & retrieveFile(tc, cd + "sg_internal_users_" + date + ".yml", index, "internalusers");
            success = success
                    & retrieveFile(tc, cd + "sg_action_groups_" + date + ".yml", index, "actiongroups");
            System.exit(success ? 0 : -1);
        }

        boolean isCdAbs = new File(cd).isAbsolute();

        System.out.println("Populate config from " + (isCdAbs ? cd : new File(".", cd).getCanonicalPath()));

        if (file != null) {
            if (type == null) {
                System.out.println("ERR: type missing");
                System.exit(-1);
            }

            if (!Arrays
                    .asList(new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" })
                    .contains(type)) {
                System.out.println("ERR: Invalid type '" + type + "'");
                System.exit(-1);
            }

            boolean success = uploadFile(tc, file, index, type);
            System.exit(success ? 0 : -1);
        }

        boolean success = uploadFile(tc, cd + "sg_config.yml", index, "config");
        success = success & uploadFile(tc, cd + "sg_roles.yml", index, "roles");
        success = success & uploadFile(tc, cd + "sg_roles_mapping.yml", index, "rolesmapping");
        success = success & uploadFile(tc, cd + "sg_internal_users.yml", index, "internalusers");
        success = success & uploadFile(tc, cd + "sg_action_groups.yml", index, "actiongroups");

        if (failFast && !success) {
            System.out.println("ERR: cannot upload configuration, see errors above");
            System.exit(-1);
        }

        ConfigUpdateResponse cur = tc
                .execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(
                        new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }))
                .actionGet();

        success = success & checkConfigUpdateResponse(cur, nodesInfo, 5);

        System.out.println("Done with " + (success ? "success" : "failures"));
        System.exit(success ? 0 : -1);
    }
    // TODO audit changes to searchguard index
}

From source file:kmi.taa.core.PredicateObjectRetriever.java

public String rmSeeAlso(String predobjpair) {
    String[] str = predobjpair.split(System.lineSeparator());
    StringBuilder builder = new StringBuilder();

    for (String line : str) {
        if (line.contains("seeAlso") || line.contains("link_source")) {
            continue;
        }/*from  w  ww . j  a  v a 2s.  com*/
        builder.append(line);
        builder.append(System.lineSeparator());
    }
    return builder.toString();
}

From source file:com.delpac.bean.OrdenRetiroBean.java

public void enviarMail() throws EmailException, SQLException, IOException {
    StringBuilder sb = new StringBuilder();
    MultiPartEmail email = new HtmlEmail();
    try {/*w w  w  .  j  a  v  a2s  .  c  o  m*/
        EmailAttachment attachment = new EmailAttachment();
        String exportDir = System.getProperty("catalina.base") + "/OrdenesRetiro/";
        String nom_archivo = "Orden_de_Retiro" + ord.getCod_ordenretiro() + ".pdf";
        attachment.setPath(exportDir + nom_archivo);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("Orden de retiro");
        attachment.setName(nom_archivo);
        //Mail
        String authuser = "Customerservice@delpac-sa.com";//LosInkas
        String authpwd = "cs6609";//LosInkas
        //            String authuser = "jorge.castaneda@bottago.com";
        //            String authpwd = "jorgec012";
        //            String authuser = "jorgito14@gmail.com";
        //            String authpwd = "p4s4j3r0";
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
        email.setSSLOnConnect(false); //LosInkas
        //            email.setSSLOnConnect(true); //Gmail
        email.setDebug(true);
        email.setHostName("mailserver.losinkas.com"); //LosInkas
        //            email.setHostName("ns0.ovh.net");
        //            email.setHostName("smtp.gmail.com");
        email.getMailSession().getProperties().put("mail.smtps.auth", "false");
        email.getMailSession().getProperties().put("mail.debug", "true");
        email.getMailSession().getProperties().put("mail.smtp.port", "26"); //LosInkas
        //            email.getMailSession().getProperties().put("mail.smtp.port", "587");
        //            email.getMailSession().getProperties().put("mail.smtps.socketFactory.port", "587"); //gmail
        email.getMailSession().getProperties().put("mail.smtps.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory"); //gmail
        email.getMailSession().getProperties().put("mail.smtps.socketFactory.fallback", "false");
        email.getMailSession().getProperties().put("mail.smtp.ssl.enable", "false");
        email.setFrom("Customerservice@delpac-sa.com", "Servico al cliente Delpac");//LosInkas
        //            email.setFrom("jorgito14@gmail.com", "Prueba envo de correo");
        email.setSubject(ord.getCia_nombre() + " / " + ord.getPto_nombre() + "/ BOOKING " + ord.getBooking()
                + " " + ord.getDsp_itinerario());

        sb.append("<strong>Estimados:</strong><br />").append(System.lineSeparator());
        sb.append("Buenas, adjunto la orden de retiro para la nave <strong>" + ord.getDsp_itinerario()
                + "</strong><br />").append(System.lineSeparator());
        sb.append("<br />" + "<ul><li>Favor retirar el sello en nuestras oficinas.</li>"
                + "<li><strong>Traer la orden de retiro</strong> para poder formalizar la entrega del sello.</li>"
                + "<li><strong>Copia de cedula</strong> de la persona que retirar el sello.</li>"
                + "<li><strong>Traer carta de autorizacin</strong> por parte del exportador nombrando al delegado que retirar el sello.</li>"
                + "<li><strong>MUY IMPORTANTE: Se recuerda que a partir del 1 de Julio, 2016 todo contenedor deber contar con certificado de "
                + "VGM (Masa Bruta Verificada) antes del embarque, caso contrario el contenedor no podr ser considerado para embarque. CUT OFF VGM, "
                + "24 horas antes del atraque de la nave.</strong></li> " + "<br /><br />")
                .append(System.lineSeparator());
        sb.append("Seores de <strong>" + ord.getLoc_salidades() + "</strong> favor " + ord.getCondicion()
                + "<br /><br />").append(System.lineSeparator());
        if (!ord.getDetalle().isEmpty()) {
            sb.append(ord.getDetalle()).append(System.lineSeparator());
            sb.append(
                    "<br /><strong>Requerimiento Especial: " + ord.getReq_especial2() + "</strong><br /><br />")
                    .append(System.lineSeparator());
            sb.append("<strong>Remark:</strong> " + ord.getRemark() + " <br /><br />")
                    .append(System.lineSeparator());
            sb.append("Gracias.<br /><br />" + "<strong>Saludos Cordiales / Best Regards</strong><br />"
                    + "JOSE CARRIEL M. II DELPAC S.A. II Av. 9 de Octubre 2009 y Los Ros, Edificio el Marqus II Guayaquil - Ecuador <br />"
                    + "Tel.: +593 42371 172/ +593 42365 626 II Cel.: +59 998152266 II Mail: jcarriel@delpac-sa.com");
        } else {
            sb.append(
                    "<br /><strong>Requerimiento Especial: " + ord.getReq_especial2() + "</strong><br /><br />")
                    .append(System.lineSeparator());
            sb.append("<strong>Remark:</strong> " + ord.getRemark() + " <br /><br />")
                    .append(System.lineSeparator());
            sb.append("Gracias.<br /><br />" + "<strong>Saludos Cordiales / Best Regards</strong><br />"
                    + "JOSE CARRIEL M. II DELPAC S.A. II Av. 9 de Octubre 2009 y Los Ros, Edificio el Marqus II Guayaquil - Ecuador <br />"
                    + "Tel.: +593 42371 172/ +593 42365 626 II Cel.: +59 998152266 II Mail: jcarriel@delpac-sa.com");
            email.setMsg(sb.toString());
        }
        email.setMsg(sb.toString());
        email.addTo(ord.getDestinario().split(","));
        //email.addTo("gint1@tercon.com.ec, gout2@tercon.com.ec, controlgate@tercon.com.ec, " + ord.getDestinario().split(",")); //LosInkas
        if (!ord.getCc().isEmpty()) {
            //email.addCc("dgonzalez@delpac-sa.com, charmsen@delpac-sa.com, vmendoza@delpac-sa.com, vzambrano@delpac-sa.com, vchiriboga@delpac-sa.com, vortiz@delpac-sa.com, mbenitez@delpac-sa.com, crobalino@delpac-sa.com, jcarriel@delpac-sa.com, fsalame@delpac-sa.com," + ord.getCc().split(",")); //LosInkas
            email.addCc("jorge_3_11_91@hotmail," + ord.getCc().split(",")); //LosInkas
        } else {
            //                email.addCc("dgonzalez@delpac-sa.com, charmsen@delpac-sa.com, vmendoza@delpac-sa.com, vzambrano@delpac-sa.com, vchiriboga@delpac-sa.com, vortiz@delpac-sa.com, mbenitez@delpac-sa.com, crobalino@delpac-sa.com, jcarriel@delpac-sa.com, fsalame@delpac-sa.com"); //LosInkas
            email.addCc("jorge_3_11_91@hotmail.com"); //LosInkas
        }

        //Add attach
        email.attach(attachment);

        //Send mail
        email.send();
        daoOrdenRetiro.updateVerificaPDF(ord, ord.getCod_ordenretiro());
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage("",
                new FacesMessage(FacesMessage.SEVERITY_INFO, "Atencin", "El mail ha sido enviado"));
    } catch (EmailException ee) {
        ee.printStackTrace();
    }
}

From source file:me.schiz.jmeter.protocol.pop3.sampler.POP3Sampler.java

private void setResponse(SampleResult sr, String[] replies) {
    if (replies == null)
        return;//from   ww  w  .j  a  va2  s .c  om
    if (replies.length == 0)
        return;
    StringBuilder builder = new StringBuilder();
    for (String reply : replies) {
        builder.append(reply);
        builder.append(System.lineSeparator());
    }
    sr.setResponseData(builder.toString().getBytes());
}