Example usage for java.lang String length

List of usage examples for java.lang String length

Introduction

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

Prototype

public int length() 

Source Link

Document

Returns the length of this string.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");

    Socket socket = new Socket("127.0.0.1", 8080);

    String path = "/servlet";
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
    wr.write("POST " + path + " HTTP/1.0\r\n");
    wr.write("Content-Length: " + data.length() + "\r\n");
    wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
    wr.write("\r\n");

    wr.write(data);//from   w ww . j  a  v a 2  s  .com
    wr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }
    wr.close();
    rd.close();
}

From source file:org.sonar.runner.Main.java

public static void main(String[] args) {
    //Jenkins' user build vars plugin must be set.
    String buildUserId = (String) System.getenv().get("BUILD_USER_ID");
    if (buildUserId == null || buildUserId.length() == 0) {
        buildUserId = DEFAULT_BUILD_USERID;
    }//  w  ww.  java  2  s.c o m
    System.setProperty("build.user.id", buildUserId);

    Cli cli = new Cli().parse(args);
    Main main = new Main(new Exit(), cli, new Conf(cli), new RunnerFactory());
    main.execute();
}

From source file:cz.muni.fi.crocs.JeeTool.Main.java

/**
 * @param args the command line arguments
 *///from   w  w  w  .  ja va 2  s.  c  om
public static void main(String[] args) {
    System.out.println("JeeTool \n");

    checkDependencies();

    Options options = OptionsMain.createOptions();

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println("cannot parse parameters");
        OptionsMain.printHelp(options);
        System.err.println(ex.toString());
        return;
    }
    boolean silent = cmd.hasOption("s");
    boolean verbose = cmd.hasOption("v");

    //help
    if (cmd.hasOption("h")) {
        OptionsMain.printHelp(options);
        return;
    }

    String filepath;
    //path to config list of nodes
    if (cmd.hasOption("a")) {
        filepath = cmd.getOptionValue("a");
    } else {
        filepath = "/opt/motePaths.txt";
    }

    //create motelist
    MoteList moteList = new MoteList(filepath);
    if (verbose) {
        moteList.setVerbose();
    }
    if (silent) {
        moteList.setSilent();
    }

    if (verbose) {
        System.out.println("reading motelist from file " + filepath);
    }

    if (cmd.hasOption("i")) {
        List<Integer> ids = new ArrayList<Integer>();
        String arg = cmd.getOptionValue("i");
        String[] IdArgs = arg.split(",");
        for (String s : IdArgs) {
            if (s.contains("-")) {
                int start = Integer.parseInt(s.substring(0, s.indexOf("-")));
                int end = Integer.parseInt(s.substring(s.indexOf("-") + 1, s.length()));
                for (int i = start; i <= end; i++) {
                    ids.add(i);
                }
            } else {
                ids.add(Integer.parseInt(s));
            }
        }
        moteList.setIds(ids);
    }

    moteList.readFile();

    if (cmd.hasOption("d")) {
        //only detect nodes
        return;
    }

    //if make
    if (cmd.hasOption("m") || cmd.hasOption("c") || cmd.hasOption("u")) {
        UploadMain upload = new UploadMain(moteList, cmd);
        upload.runMake();
    }
}

From source file:eu.fbk.dkm.sectionextractor.WikipediaSectionTitlesExtractor.java

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

    CommandLineWithLogger commandLineWithLogger = new CommandLineWithLogger();
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("wikipedia xml dump file").isRequired().withLongOpt("wikipedia-dump").create("d"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Filter file")
            .withLongOpt("filter").create("f"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("output file")
            .isRequired().withLongOpt("output-file").create("o"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg()
            .withDescription("max depth (default " + MAX_DEPTH + ")").withLongOpt("max-depth").create("m"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg()
            .withDescription("max num of sections").withLongOpt("max-num").create("n"));
    commandLineWithLogger.addOption(new Option("l", "print titles"));

    commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg()
            .withDescription(/*www  .  jav a 2s .c  o m*/
                    "number of threads (default " + AbstractWikipediaXmlDumpParser.DEFAULT_THREADS_NUMBER + ")")
            .withLongOpt("num-threads").create("t"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg()
            .withDescription("number of pages to process (default all)").withLongOpt("num-pages").create("p"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg()
            .withDescription("receive notification every n pages (default "
                    + AbstractWikipediaExtractor.DEFAULT_NOTIFICATION_POINT + ")")
            .withLongOpt("notification-point").create("b"));

    CommandLine commandLine = null;
    try {
        commandLine = commandLineWithLogger.getCommandLine(args);
        PropertyConfigurator.configure(commandLineWithLogger.getLoggerProps());
    } catch (Exception e) {
        System.exit(1);
    }

    int numThreads = Integer.parseInt(commandLine.getOptionValue("num-threads",
            Integer.toString(AbstractWikipediaXmlDumpParser.DEFAULT_THREADS_NUMBER)));
    int numPages = Integer.parseInt(commandLine.getOptionValue("num-pages",
            Integer.toString(AbstractWikipediaExtractor.DEFAULT_NUM_PAGES)));
    int notificationPoint = Integer.parseInt(commandLine.getOptionValue("notification-point",
            Integer.toString(AbstractWikipediaExtractor.DEFAULT_NOTIFICATION_POINT)));

    int configuredDepth = Integer
            .parseInt(commandLine.getOptionValue("max-depth", Integer.toString(MAX_DEPTH)));
    int maxNum = Integer.parseInt(commandLine.getOptionValue("max-num", "0"));
    boolean printTitles = commandLine.hasOption("l");

    HashSet<String> pagesToConsider = null;
    String filterFileName = commandLine.getOptionValue("filter");
    if (filterFileName != null) {
        File filterFile = new File(filterFileName);
        if (filterFile.exists()) {
            pagesToConsider = new HashSet<>();
            List<String> lines = Files.readLines(filterFile, Charsets.UTF_8);
            for (String line : lines) {
                line = line.trim();
                if (line.length() == 0) {
                    continue;
                }

                line = line.replaceAll("\\s+", "_");

                pagesToConsider.add(line);
            }
        }
    }

    File outputFile = new File(commandLine.getOptionValue("output-file"));
    ExtractorParameters extractorParameters = new ExtractorParameters(
            commandLine.getOptionValue("wikipedia-dump"), outputFile.getAbsolutePath());

    WikipediaExtractor wikipediaPageParser = new WikipediaSectionTitlesExtractor(numThreads, numPages,
            extractorParameters.getLocale(), outputFile, configuredDepth, maxNum, printTitles, pagesToConsider);
    wikipediaPageParser.setNotificationPoint(notificationPoint);
    wikipediaPageParser.start(extractorParameters);

    logger.info("extraction ended " + new Date());

}

From source file:Main.java

  public static void main(String[] argv) throws Exception {
  Set result = new HashSet();
  String serviceType = "KeyFactory";
  Provider[] providers = Security.getProviders();
  for (int i = 0; i < providers.length; i++) {
    Set keys = providers[i].keySet();
    for (Iterator it = keys.iterator(); it.hasNext();) {
      String key = (String) it.next();
      key = key.split(" ")[0];

      if (key.startsWith(serviceType + ".")) {
        result.add(key.substring(serviceType.length() + 1));
      } else if (key.startsWith("Alg.Alias." + serviceType + ".")) {
        result.add(key.substring(serviceType.length() + 11));
      }/*  ww w .ja v a  2 s  .  co m*/
    }
  }
  System.out.println(result);
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    SecureRandom random = new SecureRandom();
    IvParameterSpec ivSpec = createCtrIvForAES();
    Key key = createKeyForAES(256, random);
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    String input = "12345678";
    Mac mac = Mac.getInstance("DES", "BC");
    byte[] macKeyBytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
    Key macKey = new SecretKeySpec(macKeyBytes, "DES");

    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

    byte[] cipherText = new byte[cipher.getOutputSize(input.length() + mac.getMacLength())];

    int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText, 0);

    mac.init(macKey);//from w  w  w. j  a v  a  2 s .  co  m
    mac.update(input.getBytes());

    ctLength += cipher.doFinal(mac.doFinal(), 0, mac.getMacLength(), cipherText, ctLength);

    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);

    byte[] plainText = cipher.doFinal(cipherText, 0, ctLength);
    int messageLength = plainText.length - mac.getMacLength();

    mac.init(macKey);
    mac.update(plainText, 0, messageLength);

    byte[] messageHash = new byte[mac.getMacLength()];
    System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.length);

    System.out.println("plain : " + new String(plainText) + " verified: "
            + MessageDigest.isEqual(mac.doFinal(), messageHash));

}

From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java

public static void main(String[] args) {

    if (args == null || args.length < 1) {
        System.out.println("Usage: ch.swisscom.mid.verifier.MobileIdCmsVerifier [OPTIONS]");
        System.out.println();/*from ww w. j  a  va 2 s  .com*/
        System.out.println("Options:");
        System.out.println(
                "  -cms=VALUE or -stdin   - base64 encoded CMS/PKCS7 signature string, either as VALUE or via standard input");
        System.out.println(
                "  -jks=VALUE             - optional path to truststore file (default is 'jks/truststore.jks')");
        System.out.println("  -jkspwd=VALUE          - optional truststore password (default is 'secret')");
        System.out.println();
        System.out.println("Example:");
        System.out.println("  java ch.swisscom.mid.verifier.MobileIdCmsVerifier -cms=MIII...");
        System.out.println("  echo -n MIII... | java ch.swisscom.mid.verifier.MobileIdCmsVerifier -stdin");
        System.exit(1);
    }

    try {

        MobileIdCmsVerifier verifier = null;

        String jks = "jks/truststore.jks";
        String jkspwd = "secret";

        String param;
        for (int i = 0; i < args.length; i++) {
            param = args[i].toLowerCase();
            if (param.contains("-jks=")) {
                jks = args[i].substring(args[i].indexOf("=") + 1).trim();
            } else if (param.contains("-jkspwd=")) {
                jkspwd = args[i].substring(args[i].indexOf("=") + 1).trim();
            } else if (param.contains("-cms=")) {
                verifier = new MobileIdCmsVerifier(args[i].substring(args[i].indexOf("=") + 1).trim());
            } else if (param.contains("-stdin")) {
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                String stdin;
                if ((stdin = in.readLine()) != null && stdin.length() != 0)
                    verifier = new MobileIdCmsVerifier(stdin.trim());
            }
        }

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(jks), jkspwd.toCharArray());

        // If you are behind a Proxy..
        // System.setProperty("proxyHost", "10.185.32.54");
        // System.setProperty("proxyPort", "8079");
        // or set it via VM arguments: -DproxySet=true -DproxyHost=10.185.32.54 -DproxyPort=8079

        // Print Issuer/SubjectDN/SerialNumber of all x509 certificates that can be found in the CMSSignedData
        verifier.printAllX509Certificates();

        // Print Signer's X509 Certificate Details
        System.out.println("X509 SignerCert SerialNumber: " + verifier.getX509SerialNumber());
        System.out.println("X509 SignerCert Issuer: " + verifier.getX509IssuerDN());
        System.out.println("X509 SignerCert Subject DN: " + verifier.getX509SubjectDN());
        System.out.println("X509 SignerCert Validity Not Before: " + verifier.getX509NotBefore());
        System.out.println("X509 SignerCert Validity Not After: " + verifier.getX509NotAfter());
        System.out.println("X509 SignerCert Validity currently valid: " + verifier.isCertCurrentlyValid());

        System.out.println("User's unique Mobile ID SerialNumber: " + verifier.getMIDSerialNumber());

        // Print signed content (should be equal to the DTBS Message of the Signature Request)
        System.out.println("Signed Data: " + verifier.getSignedData());

        // Verify the signature on the SignerInformation object
        System.out.println("Signature Valid: " + verifier.isVerified());

        // Validate certificate path against trust anchor incl. OCSP revocation check
        System.out.println("X509 SignerCert Valid (Path+OCSP): " + verifier.isCertValid(keyStore));

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String[] args) {

    String phrase = new String("www.java2s.com API \n");
    File aFile = new File("test.txt");

    FileOutputStream file = null;
    try {// ww  w  .j  ava  2  s  . co  m
        file = new FileOutputStream(aFile, true);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }
    FileChannel outChannel = file.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(phrase.length());
    byte[] bytes = phrase.getBytes();
    buf.put(bytes);
    buf.flip();

    try {
        outChannel.write(buf);
        file.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

From source file:com.javacreed.examples.sql.Example2.java

public static void main(final String[] args) throws Exception {
    try (BasicDataSource dataSource = DatabaseUtils.createDataSource();
            Connection connection = dataSource.getConnection()) {
        final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") {
            @Override//from ww w  . j a v a  2 s  .  c  om
            protected String parseRow(final ResultSet resultSet) throws Exception {
                try (GZIPInputStream in = new GZIPInputStream(resultSet.getBinaryStream("compressed"))) {
                    return IOUtils.toString(in, "UTF-8");
                }
            }

            @Override
            protected void setPreparedStatement(final String data, final PreparedStatement statement)
                    throws Exception {
                // Compress the data before inserting it. We need to compress before inserting the data to make this process
                // as realistic as possible.
                final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length());
                try (OutputStream out = new GZIPOutputStream(baos, data.length())) {
                    out.write(data.getBytes("UTF-8"));
                }
                statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray()));
            }
        };
        test.runTest();
    }
    Example2.LOGGER.debug("Done");
}

From source file:net.openhft.chronicle.wire.benchmarks.ComparisonMain.java

public static void main(String... args) throws Exception {
    Affinity.setAffinity(2);//from  w w  w.  ja  va  2  s.  com
    if (Jvm.isDebug()) {
        ComparisonMain main = new ComparisonMain();
        for (Method m : ComparisonMain.class.getMethods()) {
            main.s = null;
            main.sb.setLength(0);
            main.mhe.wrap(main.directBuffer, 0).blockLength(0);
            main.buf = null;

            if (m.getAnnotation(Benchmark.class) != null) {
                m.invoke(main);
                String s = main.s;
                if (s != null) {
                    System.out.println("Test " + m.getName() + " used " + s.length() + " chars.");
                    System.out.println(s);
                } else if (main.sb.length() > 0) {
                    System.out.println("Test " + m.getName() + " used " + main.sb.length() + " chars.");
                    System.out.println(main.sb);
                } else if (main.mhd.wrap(main.directBuffer, 0).blockLength() > 0) {
                    int len = main.mhd.wrap(main.directBuffer, 0).blockLength() + main.mhd.encodedLength();
                    System.out.println("Test " + m.getName() + " used " + len + " chars.");
                    System.out.println(new NativeBytesStore<>(main.directBuffer.addressOffset(), len)
                            .bytesForRead().toHexString());
                } else if (main.buf != null) {
                    System.out.println("Test " + m.getName() + " used " + main.buf.length + " chars.");
                    System.out.println(Bytes.wrapForRead(main.buf).toHexString());
                } else if (main.bytes.writePosition() > 0) {
                    main.bytes.readPosition(0);
                    System.out
                            .println("Test " + m.getName() + " used " + main.bytes.readRemaining() + " chars.");
                    System.out.println(main.bytes.toHexString());
                }
            }
        }
    } else {
        int time = Boolean.getBoolean("longTest") ? 30 : 2;
        System.out.println("measurementTime: " + time + " secs");
        Options opt = new OptionsBuilder().include(ComparisonMain.class.getSimpleName())
                //                    .warmupIterations(5)
                .measurementIterations(5).forks(10).mode(Mode.SampleTime)
                .measurementTime(TimeValue.seconds(time)).timeUnit(TimeUnit.NANOSECONDS).build();

        new Runner(opt).run();
    }
}