Example usage for java.lang String valueOf

List of usage examples for java.lang String valueOf

Introduction

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

Prototype

public static String valueOf(double d) 

Source Link

Document

Returns the string representation of the double argument.

Usage

From source file:com.datatorrent.stram.api.IotDev.java

public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
    ClassLoader loader = IotDev.class.getClassLoader();
    LOG.debug(String.valueOf(loader.getResource("\n\nPATH : \nfoo/Test.class")));

    FileInputStream f = new FileInputStream("/home/" + name + "/fileURL");
    LinkedHashSet<URL> launchDependencies = read(f);
    loadDependencies(launchDependencies);

    LOG.debug("\n\nURLS\n\n");

    for (URL l : launchDependencies) {
        LOG.debug("\n URL " + l);
    }/*  w ww.  ja va2  s .c  om*/

    // FileInputStream fis = new FileInputStream("./" + LogicalPlan.SER_FILE_NAME);
    FileInputStream fis = new FileInputStream("/home/" + name + "/file");
    try {
        lp = LogicalPlan.read(fis);
    } finally {
        fis.close();
    }
    StramLocalCluster lc = new StramLocalCluster(lp);
    lc.run();
}

From source file:edu.snu.leader.discrete.simulator.Main.java

public static void main(String[] args) {
    System.setProperty("sim-properties", "cfg/sim/discrete/sim-properties.parameters");

    _simulationProperties = MiscUtils.loadProperties("sim-properties");

    String stringShouldRunGraphical = _simulationProperties.getProperty("run-graphical");
    Validate.notEmpty(stringShouldRunGraphical, "Run graphical option required");
    shouldRunGraphical = Boolean.parseBoolean(stringShouldRunGraphical);

    String stringTotalRuns = _simulationProperties.getProperty("run-count");
    Validate.notEmpty(stringTotalRuns, "Run count required");
    totalRuns = Integer.parseInt(stringTotalRuns);

    if (!shouldRunGraphical) {
        // run just text
        for (int run = 1; run <= totalRuns; run++) {
            System.out.println("Run " + run);
            System.out.println();

            // create and initialize simulator
            Simulator simulator = new Simulator(run);
            _simulationProperties.put("current-run", String.valueOf(run));
            simulator.initialize(_simulationProperties);
            // run it
            simulator.execute();//w w w. j av a 2s .  c o  m
        }
    } else {
        // run graphical
        DebugLocationsStructure db = new DebugLocationsStructure("Conflict Simulation", 800, 600, 60);
        _simulationProperties.put("current-run", String.valueOf(1));
        db.initialize(_simulationProperties, 1);
        db.run();
    }
}

From source file:org.hyperic.hq.hqapi1.tools.PasswordEncryptor.java

public static void main(String[] args) throws Exception {
    String password1 = String.valueOf(PasswordField.getPassword(System.in, "Enter password: "));
    String password2 = String.valueOf(PasswordField.getPassword(System.in, "Re-Enter password: "));
    String encryptionKey = "defaultkey";
    if (password1.equals(password2)) {
        System.out.print("Encryption Key: ");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        encryptionKey = in.readLine();//  w w  w  .  ja  v a  2s . c o  m
        if (encryptionKey.length() < 8) {
            System.out.println("Encryption key too short. Please use at least 8 characters");
            System.exit(-1);
        }
    } else {
        System.out.println("Passwords don't match");
        System.exit(-1);
    }

    System.out.println("The encrypted password is " + encryptPassword(password1, encryptionKey));
}

From source file:com.bhc.test.ClientFormLogin.java

public static void main(String[] args) throws Exception {
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    URI uri = null;/*  w  w w .j av  a  2s. co m*/
    try {
        uri = new URIBuilder().setScheme("https").setHost("user.qunar.com").setPath("/captcha/api/image")
                .setParameter("k", "{en7mni(z").setParameter("p", "ucenter_login")
                .setParameter("c", "ef7d278eca6d25aa6aec7272d57f0a9a")
                .setParameter("t", String.valueOf(new Date().getTime())).build();
        HttpGet httpget = new HttpGet(uri);
        CloseableHttpResponse response1 = httpclient.execute(httpget);
        try {
            HttpEntity entity = response1.getEntity();

            System.out.println("Login form get: " + response1.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response1.close();
        }

        HttpUriRequest login = RequestBuilder.post().setUri(new URI("https://someportal/"))
                .addParameter("IDToken1", "username").addParameter("IDToken2", "password").build();
        CloseableHttpResponse response2 = httpclient.execute(login);
        try {
            HttpEntity entity = response2.getEntity();

            System.out.println("Login form get: " + response2.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Post logon cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:keepassj.cli.KeepassjCli.java

/**
 * @param args the command line arguments
 * @throws org.apache.commons.cli.ParseException
 * @throws java.io.IOException//from  w w  w  . j  a  v  a  2  s  .c  o m
 */
public static void main(String[] args) throws ParseException, IOException {
    Options options = KeepassjCli.getOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);
    if (!KeepassjCli.validateOptions(cmd)) {
        HelpFormatter help = new HelpFormatter();
        help.printHelp("Usage: java -jar KeepassjCli -f dbfile [options]", options);
    } else {
        String password;
        if (cmd.hasOption('p')) {
            password = cmd.getOptionValue('p');
        } else {
            Console console = System.console();
            char[] hiddenString = console.readPassword("Enter password for %s\n", cmd.getOptionValue('f'));
            password = String.valueOf(hiddenString);
        }
        KeepassjCli instance = new KeepassjCli(cmd.getOptionValue('f'), password, cmd.getOptionValue('k'));
        System.out.println("Description:" + instance.db.getDescription());
        PwGroup rootGroup = instance.db.getRootGroup();
        System.out.println(String.valueOf(rootGroup.GetEntriesCount(true)) + " entries");
        if (cmd.hasOption('l')) {
            instance.printEntries(rootGroup.GetEntries(true), false);
        } else if (cmd.hasOption('s')) {
            PwObjectList<PwEntry> results = instance.search(cmd.getOptionValue('s'));
            System.out.println("Found " + results.getUCount() + " results for:" + cmd.getOptionValue('s'));
            instance.printEntries(results, false);
        } else if (cmd.hasOption('i')) {
            System.out.println("Entering interactive mode.");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String input = null;
            PwObjectList<PwEntry> results = null;
            while (!"\\q".equals(input)) {
                if (results != null) {
                    System.out.println("Would you like to view a specific entry? y/n");
                    input = bufferedReader.readLine();
                    if ("y".equalsIgnoreCase(input)) {
                        System.out.print("Enter the title number:");
                        input = bufferedReader.readLine();
                        instance.printCompleteEntry(results.GetAt(Integer.parseInt(input) - 1)); // Since humans start counting at 1
                    }
                    results = null;
                    System.out.println();
                } else {
                    System.out.print("Enter something to search for (or \\q to quit):");
                    input = bufferedReader.readLine();
                    if (!"\\q".equalsIgnoreCase(input)) {
                        results = instance.search(input);
                        instance.printEntries(results, true);
                    }
                }
            }
        }

        // Close before exit
        instance.db.Close();
    }
}

From source file:org.apache.flink.streaming.tests.Elasticsearch6SinkExample.java

public static void main(String[] args) throws Exception {

    final ParameterTool parameterTool = ParameterTool.fromArgs(args);

    if (parameterTool.getNumberOfParameters() < 3) {
        System.out.println(//  w w  w. j a  v a2s  .com
                "Missing parameters!\n" + "Usage: --numRecords <numRecords> --index <index> --type <type>");
        return;
    }

    final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    env.getConfig().disableSysoutLogging();
    env.enableCheckpointing(5000);

    DataStream<Tuple2<String, String>> source = env.generateSequence(0, parameterTool.getInt("numRecords") - 1)
            .flatMap(new FlatMapFunction<Long, Tuple2<String, String>>() {
                @Override
                public void flatMap(Long value, Collector<Tuple2<String, String>> out) {
                    final String key = String.valueOf(value);
                    final String message = "message #" + value;
                    out.collect(Tuple2.of(key, message + "update #1"));
                    out.collect(Tuple2.of(key, message + "update #2"));
                }
            });

    List<HttpHost> httpHosts = new ArrayList<>();
    httpHosts.add(new HttpHost("127.0.0.1", 9200, "http"));

    ElasticsearchSink.Builder<Tuple2<String, String>> esSinkBuilder = new ElasticsearchSink.Builder<>(httpHosts,
            (Tuple2<String, String> element, RuntimeContext ctx, RequestIndexer indexer) -> {
                indexer.add(createIndexRequest(element.f1, parameterTool));
                indexer.add(createUpdateRequest(element, parameterTool));
            });

    // this instructs the sink to emit after every element, otherwise they would be buffered
    esSinkBuilder.setBulkFlushMaxActions(1);

    source.addSink(esSinkBuilder.build());

    env.execute("Elasticsearch 6.x end to end sink test example");
}

From source file:com.camel.crawler.WebCrawler.java

public static void main(String[] args) {
    WebCrawler crawler = new WebCrawler();

    boolean finished = true;

    while (finished) {
        try {//from w  w w . java2s  .  c  o  m
            pageInit++;
            System.out.println("url num:=" + pageInit);
            try {
                crawler.fetchWeb(URL_PRE + String.valueOf(pageInit) + "/");
            } catch (IOException e) {
                pageInit--;
                e.printStackTrace();
                //?1?
                try {
                    System.out.println("exception sleep 1 min");
                    Thread.sleep(60000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
            //????crawler
            if (pageInit == pageEnd) {
                finished = false;
            }
            try {
                Thread.sleep(700);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            System.out.println("unknow exception");
            e.printStackTrace();
        }
    }
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5GoldLabelEstimator.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    String inputDir = args[0];//  w w w.  j av  a2s .com
    File outputDir = new File(args[1]);

    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    // we will process only a subset first
    List<AnnotatedArgumentPair> allArgumentPairs = new ArrayList<>();

    Collection<File> files = IOHelper.listXmlFiles(new File(inputDir));

    for (File file : files) {
        allArgumentPairs.addAll((List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file));
    }

    // collect turkers and csv
    List<String> turkerIDs = extractAndSortTurkerIDs(allArgumentPairs);
    String preparedCSV = prepareCSV(allArgumentPairs, turkerIDs);

    // save CSV and run MACE
    Path tmpDir = Files.createTempDirectory("mace");
    File maceInputFile = new File(tmpDir.toFile(), "input.csv");
    FileUtils.writeStringToFile(maceInputFile, preparedCSV, "utf-8");

    File outputPredictions = new File(tmpDir.toFile(), "predictions.txt");
    File outputCompetence = new File(tmpDir.toFile(), "competence.txt");

    // run MACE
    MACE.main(new String[] { "--iterations", "500", "--threshold", String.valueOf(MACE_THRESHOLD), "--restarts",
            "50", "--outputPredictions", outputPredictions.getAbsolutePath(), "--outputCompetence",
            outputCompetence.getAbsolutePath(), maceInputFile.getAbsolutePath() });

    // read back the predictions and competence
    List<String> predictions = FileUtils.readLines(outputPredictions, "utf-8");

    // check the output
    if (predictions.size() != allArgumentPairs.size()) {
        throw new IllegalStateException("Wrong size of the predicted file; expected " + allArgumentPairs.size()
                + " lines but was " + predictions.size());
    }

    String competenceRaw = FileUtils.readFileToString(outputCompetence, "utf-8");
    String[] competence = competenceRaw.split("\t");
    if (competence.length != turkerIDs.size()) {
        throw new IllegalStateException(
                "Expected " + turkerIDs.size() + " competence number, got " + competence.length);
    }

    // rank turkers by competence
    Map<String, Double> turkerIDCompetenceMap = new TreeMap<>();
    for (int i = 0; i < turkerIDs.size(); i++) {
        turkerIDCompetenceMap.put(turkerIDs.get(i), Double.valueOf(competence[i]));
    }

    // sort by value descending
    Map<String, Double> sortedCompetences = IOHelper.sortByValue(turkerIDCompetenceMap, false);
    System.out.println("Sorted turker competences: " + sortedCompetences);

    // assign the gold label and competence

    for (int i = 0; i < allArgumentPairs.size(); i++) {
        AnnotatedArgumentPair annotatedArgumentPair = allArgumentPairs.get(i);
        String goldLabel = predictions.get(i).trim();

        // might be empty
        if (!goldLabel.isEmpty()) {
            // so far the gold label has format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal
            // strip now only the gold label
            annotatedArgumentPair.setGoldLabel(goldLabel);
        }

        // update turker competence
        for (AnnotatedArgumentPair.MTurkAssignment assignment : annotatedArgumentPair.mTurkAssignments) {
            String turkID = assignment.getTurkID();

            int turkRank = getTurkerRank(turkID, sortedCompetences);
            assignment.setTurkRank(turkRank);

            double turkCompetence = turkerIDCompetenceMap.get(turkID);
            assignment.setTurkCompetence(turkCompetence);
        }
    }

    // now sort the data back according to their original file name
    Map<String, List<AnnotatedArgumentPair>> fileNameAnnotatedPairsMap = new HashMap<>();
    for (AnnotatedArgumentPair argumentPair : allArgumentPairs) {
        String fileName = IOHelper.createFileName(argumentPair.getDebateMetaData(),
                argumentPair.getArg1().getStance());

        if (!fileNameAnnotatedPairsMap.containsKey(fileName)) {
            fileNameAnnotatedPairsMap.put(fileName, new ArrayList<AnnotatedArgumentPair>());
        }

        fileNameAnnotatedPairsMap.get(fileName).add(argumentPair);
    }

    // and save them to the output file
    for (Map.Entry<String, List<AnnotatedArgumentPair>> entry : fileNameAnnotatedPairsMap.entrySet()) {
        String fileName = entry.getKey();
        List<AnnotatedArgumentPair> argumentPairs = entry.getValue();

        File outputFile = new File(outputDir, fileName);

        // and save all sampled pairs into a XML file
        XStreamTools.toXML(argumentPairs, outputFile);

        System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile);
    }

}

From source file:com.ciphertool.zodiacengine.CipherSolutionExecutor.java

/**
 * @param args//from w  w  w .  ja  va  2 s.  c om
 * @throws InterruptedException
 */
public static void main(String[] args) throws InterruptedException {
    // Spin up the Spring application context
    setUp();

    CipherDto cipherDto = null;

    Cipher cipher = cipherDao.findByCipherName(cipherName);

    long start = System.currentTimeMillis();

    ExecutorService executor = Executors.newFixedThreadPool(maxThreads);

    cipherDto = new CipherDto(String.valueOf(0), cipher);

    /*
     * We want to generate and validate a specific number of solutions, no
     * matter how long it takes.
     */
    if (applicationDurationType == ApplicationDurationType.ITERATION) {
        if (numIterations <= 0) {
            throw new IllegalArgumentException(
                    "ApplicationDurationType set to ITERATION, but numIterations was not set or was set incorrectly.");
        }

        log.info("Beginning solution generation.  Generating " + numIterations + " solutions using "
                + maxThreads + " threads.");

        for (long i = 1; i <= numIterations; i++) {
            Runnable cipherTask = new CipherSolutionSynchronizedRunnable(solutionGenerator, solutionEvaluator,
                    cipherDto);

            executor.execute(cipherTask);
        }

        // Make executor accept no new threads and finish all existing
        // threads in the queue
        executor.shutdown();
    }
    /*
     * We want to generate and validate solutions for a set amount of time,
     * no matter how many we can generate in that time period.
     */
    else if (applicationDurationType == ApplicationDurationType.TEMPORAL) {
        if (applicationRunMillis <= 0) {
            throw new IllegalArgumentException(
                    "ApplicationDurationType set to TEMPORAL, but applicationRunMillis was not set or was set incorrectly.");
        }

        log.info("Beginning solution generation.  Generating solutions for " + applicationRunMillis
                + "ms using " + maxThreads + " threads.");

        long count = 0;

        while (true) {
            Runnable cipherTask = new CipherSolutionSynchronizedRunnable(solutionGenerator, solutionEvaluator,
                    cipherDto);

            executor.execute(cipherTask);

            /*
             * This is a fairly rudimentary way of managing the number of
             * tasks sent to the executor.
             * 
             * If we don't manage it somehow, the app will get bogged down
             * by the continuous while loop and performance will degrade
             * significantly.
             */
            if (++count >= queueTaskLimit) {
                count = 0;

                executor.shutdown();

                /*
                 * We are mainly concerned about blocking until all tasks
                 * are finished, so the timeout is not a big concern.
                 */
                executor.awaitTermination(1, TimeUnit.MINUTES);

                executor = Executors.newFixedThreadPool(maxThreads);

                if ((System.currentTimeMillis() - start) > applicationRunMillis) {
                    break;
                }
            }
        }

        // Make executor stop immediately
        executor.shutdownNow();
    }

    // Wait until all threads are finished
    while (!executor.isTerminated()) {
    }

    SolutionChromosome solutionMostMatches = cipherDto.getSolutionMostMatches();
    SolutionChromosome solutionMostUnique = cipherDto.getSolutionMostUnique();
    SolutionChromosome solutionMostAdjacent = cipherDto.getSolutionMostAdjacent();

    /*
     * Print out summary information
     */
    log.info("Took " + (System.currentTimeMillis() - start) + "ms to generate and validate "
            + cipherDto.getNumSolutions() + " solutions.");
    log.info("Highest total matches achieved: " + solutionMostMatches.getTotalMatches());
    log.info("Average total matches: " + (cipherDto.getTotalMatchSum() / cipherDto.getNumSolutions()));
    log.info("Best solution found: " + solutionMostMatches);
    log.info("Most unique matches achieved: " + solutionMostUnique.getUniqueMatches());
    log.info("Average unique matches: " + (cipherDto.getUniqueMatchSum() / cipherDto.getNumSolutions()));
    log.info("Solution with most unique matches found: " + solutionMostUnique);
    log.info("Most adjacent matches achieved: " + solutionMostAdjacent.getAdjacentMatchCount());
    log.info("Average adjacent matches: " + (cipherDto.getAdjacentMatchSum() / cipherDto.getNumSolutions()));
    log.info("Solution with most adjacent matches found: " + solutionMostAdjacent);
}

From source file:edu.washington.data.sentimentreebank.StanfordNLPDict.java

public static void main(String args[]) {
    Options options = new Options();
    options.addOption("d", "dict", true, "dictionary file.");
    options.addOption("s", "sentiment", true, "sentiment value file.");

    CommandLineParser parser = new GnuParser();
    try {// w ww. j  a v a  2  s . c  o m
        CommandLine line = parser.parse(options, args);
        if (!line.hasOption("dict") && !line.hasOption("sentiment")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("StanfordNLPDict", options);
            return;
        }

        Path dictPath = Paths.get(line.getOptionValue("dict"));
        Path sentimentPath = Paths.get(line.getOptionValue("sentiment"));

        StanfordNLPDict snlp = new StanfordNLPDict(dictPath, sentimentPath);
        String sentence = "take off";
        System.out.printf("sentence [%1$s] %2$s\n", sentence,
                String.valueOf(snlp.getPhraseSentiment(sentence)));

    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("StanfordNLPDict", options);
    } catch (IOException ex) {
        Logger.getLogger(StanfordNLPDict.class.getName()).log(Level.SEVERE, null, ex);
    }
}