Example usage for java.lang String substring

List of usage examples for java.lang String substring

Introduction

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

Prototype

public String substring(int beginIndex, int endIndex) 

Source Link

Document

Returns a string that is a substring of this string.

Usage

From source file:HashCollider.java

/**i
 * @param args the command line arguments
 *//* w  w  w .ja  va  2  s . co m*/
public static void main(String[] args) {
    Random random = new Random();
    byte[] nbytes1 = new byte[64];
    byte[] nbytes2 = new byte[64];
    float average = 0;
    // set number of bits for checking collision
    int number_of_bits = 4;
    random.nextBytes(nbytes1);
    random.nextBytes(nbytes2);

    String sha1 = DigestUtils.sha256Hex(nbytes1);
    String sha2 = DigestUtils.sha256Hex(nbytes2);

    String nsh1 = new BigInteger(sha1, 16).toString(2);
    String nsh2 = new BigInteger(sha2, 16).toString(2);
    int i = 0;
    for (int j = 0; j < 5; j++) {
        while (true) {
            if (nsh1.substring(0, number_of_bits - 1).equals(nsh2.substring(0, number_of_bits - 1))) {
                System.out.println(i);
                average += i;
                break;
            }
            i++;
            //            System.out.println("......"+i);
            random.nextBytes(nbytes1);
            random.nextBytes(nbytes2);
            sha1 = DigestUtils.sha256Hex(nbytes1);
            sha2 = DigestUtils.sha256Hex(nbytes2);
            nsh1 = new BigInteger(sha1, 16).toString(2);
            nsh2 = new BigInteger(sha2, 16).toString(2);
        }
        i = 0;
        //        System.out.println(nsh1+"\n"+nsh2);
        random.nextBytes(nbytes1);
        random.nextBytes(nbytes2);
        sha1 = DigestUtils.sha256Hex(nbytes1);
        sha2 = DigestUtils.sha256Hex(nbytes2);
        nsh1 = new BigInteger(sha1, 16).toString(2);
        nsh2 = new BigInteger(sha2, 16).toString(2);

    }
    //
    System.out.println("Average for  " + number_of_bits + " bits is  " + average / 5);

}

From source file:MainClass.java

public static void main(String args[]) {
    String org = "This is a test. This is, too.";
    String search = "is";
    String sub = "was";
    String result = "";
    int i;/*from w  ww . j  a v  a2  s . c o  m*/

    do {
        System.out.println(org);
        i = org.indexOf(search);
        if (i != -1) {
            result = org.substring(0, i);
            result = result + sub;
            result = result + org.substring(i + search.length());
            org = result;
        }
    } while (i != -1);

}

From source file:com.github.zerkseez.codegen.wrappergenerator.Main.java

public static void main(final String[] args) throws Exception {
    final Options options = new Options();
    options.addOption(Option.builder().longOpt("outputDirectory").hasArg().required().build());
    options.addOption(Option.builder().longOpt("classMappings").hasArgs().required().build());

    final CommandLineParser parser = new DefaultParser();

    try {//from w ww  .j a v  a2 s .  c  o m
        final CommandLine line = parser.parse(options, args);
        final String outputDirectory = line.getOptionValue("outputDirectory");
        final String[] classMappings = line.getOptionValues("classMappings");
        for (String classMapping : classMappings) {
            final String[] tokens = classMapping.split(":");
            if (tokens.length != 2) {
                throw new IllegalArgumentException(
                        String.format("Invalid class mapping format \"%s\"", classMapping));
            }
            final Class<?> wrappeeClass = Class.forName(tokens[0]);
            final String fullWrapperClassName = tokens[1];
            final int indexOfLastDot = fullWrapperClassName.lastIndexOf('.');
            final String wrapperPackageName = (indexOfLastDot == -1) ? ""
                    : fullWrapperClassName.substring(0, indexOfLastDot);
            final String simpleWrapperClassName = (indexOfLastDot == -1) ? fullWrapperClassName
                    : fullWrapperClassName.substring(indexOfLastDot + 1);

            System.out.println(String.format("Generating wrapper class for %s...", wrappeeClass));
            final WrapperGenerator generator = new WrapperGenerator(wrappeeClass, wrapperPackageName,
                    simpleWrapperClassName);
            generator.writeTo(outputDirectory, true);
        }
        System.out.println("Done");
    } catch (MissingOptionException e) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(String.format("java -cp CLASSPATH %s", Main.class.getName()), options);
    }
}

From source file:com.joliciel.jochre.search.JochreSearch.java

/**
 * @param args//from   www  .  ja v  a2  s.co  m
 */
public static void main(String[] args) {
    try {
        Map<String, String> argMap = new HashMap<String, String>();

        for (String arg : args) {
            int equalsPos = arg.indexOf('=');
            String argName = arg.substring(0, equalsPos);
            String argValue = arg.substring(equalsPos + 1);
            argMap.put(argName, argValue);
        }

        String command = argMap.get("command");
        argMap.remove("command");

        String logConfigPath = argMap.get("logConfigFile");
        if (logConfigPath != null) {
            argMap.remove("logConfigFile");
            Properties props = new Properties();
            props.load(new FileInputStream(logConfigPath));
            PropertyConfigurator.configure(props);
        }

        LOG.debug("##### Arguments:");
        for (Entry<String, String> arg : argMap.entrySet()) {
            LOG.debug(arg.getKey() + ": " + arg.getValue());
        }

        SearchServiceLocator locator = SearchServiceLocator.getInstance();
        SearchService searchService = locator.getSearchService();

        if (command.equals("buildIndex")) {
            String indexDirPath = argMap.get("indexDir");
            String documentDirPath = argMap.get("documentDir");
            File indexDir = new File(indexDirPath);
            indexDir.mkdirs();
            File documentDir = new File(documentDirPath);

            JochreIndexBuilder builder = searchService.getJochreIndexBuilder(indexDir);
            builder.updateDocument(documentDir);
        } else if (command.equals("updateIndex")) {
            String indexDirPath = argMap.get("indexDir");
            String documentDirPath = argMap.get("documentDir");
            boolean forceUpdate = false;
            if (argMap.containsKey("forceUpdate")) {
                forceUpdate = argMap.get("forceUpdate").equals("true");
            }
            File indexDir = new File(indexDirPath);
            indexDir.mkdirs();
            File documentDir = new File(documentDirPath);

            JochreIndexBuilder builder = searchService.getJochreIndexBuilder(indexDir);
            builder.updateIndex(documentDir, forceUpdate);
        } else if (command.equals("search")) {
            HighlightServiceLocator highlightServiceLocator = HighlightServiceLocator.getInstance(locator);
            HighlightService highlightService = highlightServiceLocator.getHighlightService();

            String indexDirPath = argMap.get("indexDir");
            File indexDir = new File(indexDirPath);
            JochreQuery query = searchService.getJochreQuery(argMap);

            JochreIndexSearcher searcher = searchService.getJochreIndexSearcher(indexDir);
            TopDocs topDocs = searcher.search(query);

            Set<Integer> docIds = new LinkedHashSet<Integer>();
            for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
                docIds.add(scoreDoc.doc);
            }
            Set<String> fields = new HashSet<String>();
            fields.add("text");

            Highlighter highlighter = highlightService.getHighlighter(query, searcher.getIndexSearcher());
            HighlightManager highlightManager = highlightService
                    .getHighlightManager(searcher.getIndexSearcher());
            highlightManager.setDecimalPlaces(query.getDecimalPlaces());
            highlightManager.setMinWeight(0.0);
            highlightManager.setIncludeText(true);
            highlightManager.setIncludeGraphics(true);

            Writer out = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
            if (command.equals("highlight")) {
                highlightManager.highlight(highlighter, docIds, fields, out);
            } else {
                highlightManager.findSnippets(highlighter, docIds, fields, out);
            }
        } else {
            throw new RuntimeException("Unknown command: " + command);
        }
    } catch (RuntimeException e) {
        LogUtils.logError(LOG, e);
        throw e;
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static void main(String[] args) {
    String r = "This is a test.";
    String[] s = new String[10];
    int len = r.length();
    int l = 3;//from w w  w  . ja  v a2  s.  c  o  m
    int last;
    int f = 0;
    for (int i = 0;; i++) {
        last = (f + l);
        if ((last) >= len) {
            last = len;
        }
        s[i] = r.substring(f, last);
        System.out.println(s[i]);

        if (last == len) {
            break;
        }
        f = (f + l);
    }
}

From source file:com.chinarewards.gwt.license.util.FileUploadServlet.java

public static void main(String[] args) {
    String realPath = "D:\\ServerRoot\\jboss-5.1.0.GA\\server";
    realPath = realPath.substring(0, realPath.indexOf("jboss-5.1.0.GA"));
    System.out.println(realPath);
}

From source file:fuse.okuyamafs.OkuyamaFuse.java

public static void main(String[] args) {

    String fuseArgs[] = new String[args.length - 1];
    System.arraycopy(args, 0, fuseArgs, 0, fuseArgs.length);

    ImdstDefine.valueCompresserLevel = 9;
    try {/*from w  w w. jav a 2 s . c  om*/
        String okuyamaStr = args[args.length - 1];

        // Raid0?????????
        if (okuyamaStr.indexOf("#") != -1) {
            stripingDataBlock = true;
            okuyamaStr = okuyamaStr.substring(0, (okuyamaStr.length() - 1));
        }

        String[] masterNodeInfos = null;
        if (okuyamaStr.indexOf(",") != -1) {
            masterNodeInfos = okuyamaStr.split(",");
        } else {
            masterNodeInfos = (okuyamaStr + "," + okuyamaStr).split(",");
        }
        // 1=Memory
        // 2=okuyama
        // 3=LocalCacheOkuyama

        String[] optionParams = { "2", "true" };
        String fsystemMode = optionParams[0].trim();
        boolean singleFlg = new Boolean(optionParams[1].trim()).booleanValue();

        OkuyamaFilesystem.storageType = new Integer(fsystemMode).intValue();
        if (OkuyamaFilesystem.storageType == 1)
            OkuyamaFilesystem.blockSize = OkuyamaFilesystem.blockSize;

        CoreMapFactory.init(new Integer(fsystemMode.trim()).intValue(), masterNodeInfos, stripingDataBlock);
        FilesystemCheckDaemon loopDaemon = new FilesystemCheckDaemon(1, fuseArgs[fuseArgs.length - 1]);
        loopDaemon.start();

        if (OkuyamaFilesystem.storageType == 2) {
            FilesystemCheckDaemon bufferCheckDaemon = new FilesystemCheckDaemon(2, null);
            bufferCheckDaemon.start();
        }

        Runtime.getRuntime().addShutdownHook(new JVMShutdownSequence());
        FuseMount.mount(fuseArgs, new OkuyamaFilesystem(fsystemMode, singleFlg), log);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cloud.sample.UserCloudAPIExecutor.java

public static void main(String[] args) {
    // Host/*from www.  j a  v a2 s  .c o  m*/
    String host = null;

    // Fully qualified URL with http(s)://host:port
    String apiUrl = null;

    // ApiKey and secretKey as given by your CloudStack vendor
    String apiKey = null;
    String secretKey = null;

    try {
        Properties prop = new Properties();
        prop.load(new FileInputStream("usercloud.properties"));

        // host
        host = prop.getProperty("host");
        if (host == null) {
            System.out.println(
                    "Please specify a valid host in the format of http(s)://:/client/api in your usercloud.properties file.");
        }

        // apiUrl
        apiUrl = prop.getProperty("apiUrl");
        if (apiUrl == null) {
            System.out.println(
                    "Please specify a valid API URL in the format of command=&param1=&param2=... in your usercloud.properties file.");
        }

        // apiKey
        apiKey = prop.getProperty("apiKey");
        if (apiKey == null) {
            System.out.println(
                    "Please specify your API Key as provided by your CloudStack vendor in your usercloud.properties file.");
        }

        // secretKey
        secretKey = prop.getProperty("secretKey");
        if (secretKey == null) {
            System.out.println(
                    "Please specify your secret Key as provided by your CloudStack vendor in your usercloud.properties file.");
        }

        if (apiUrl == null || apiKey == null || secretKey == null) {
            return;
        }

        System.out.println("Constructing API call to host = '" + host + "' with API command = '" + apiUrl
                + "' using apiKey = '" + apiKey + "' and secretKey = '" + secretKey + "'");

        // Step 1: Make sure your APIKey is URL encoded
        String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8");

        // Step 2: URL encode each parameter value, then sort the parameters and apiKey in
        // alphabetical order, and then toLowerCase all the parameters, parameter values and apiKey.
        // Please note that if any parameters with a '&' as a value will cause this test client to fail since we are using
        // '&' to delimit
        // the string
        List<String> sortedParams = new ArrayList<String>();
        sortedParams.add("apikey=" + encodedApiKey.toLowerCase());
        StringTokenizer st = new StringTokenizer(apiUrl, "&");
        String url = null;
        boolean first = true;
        while (st.hasMoreTokens()) {
            String paramValue = st.nextToken();
            String param = paramValue.substring(0, paramValue.indexOf("="));
            String value = URLEncoder
                    .encode(paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length()), "UTF-8");
            if (first) {
                url = param + "=" + value;
                first = false;
            } else {
                url = url + "&" + param + "=" + value;
            }
            sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase());
        }
        Collections.sort(sortedParams);

        System.out.println("Sorted Parameters: " + sortedParams);

        // Step 3: Construct the sorted URL and sign and URL encode the sorted URL with your secret key
        String sortedUrl = null;
        first = true;
        for (String param : sortedParams) {
            if (first) {
                sortedUrl = param;
                first = false;
            } else {
                sortedUrl = sortedUrl + "&" + param;
            }
        }
        System.out.println("sorted URL : " + sortedUrl);
        String encodedSignature = signRequest(sortedUrl, secretKey);

        // Step 4: Construct the final URL we want to send to the CloudStack Management Server
        // Final result should look like:
        // http(s)://://client/api?&apiKey=&signature=
        String finalUrl = host + "?" + url + "&apiKey=" + apiKey + "&signature=" + encodedSignature;
        System.out.println("final URL : " + finalUrl);

        // Step 5: Perform a HTTP GET on this URL to execute the command
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(finalUrl);
        int responseCode = client.executeMethod(method);
        if (responseCode == 200) {
            // SUCCESS!
            System.out.println("Successfully executed command");
        } else {
            // FAILED!
            System.out.println("Unable to execute command with response code: " + responseCode);
        }

    } catch (Throwable t) {
        System.out.println(t);
    }
}

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

/**
 * @param args the command line arguments
 *///from  w w  w.  j  a  v  a2s  .  co m
public static void main(String[] args) {
    System.out.println("JeeTool \n");

    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");

    if (!silent) {
        System.out.println(ANSI_GREEN + "EduHoc home is: " + System.getenv("EDU_HOC_HOME") + "\n" + ANSI_RESET);
    }

    //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 = System.getenv("EDU_HOC_HOME") + "/config/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();
    }

    //if execute command
    if (cmd.hasOption("E")) {
        try {
            ExecuteShellCommand com = new ExecuteShellCommand();
            if (verbose) {
                System.out.println("Executing shell command " + cmd.getOptionValue("E"));
            }

            com.executeCommand(cmd.getOptionValue("E"));
        } catch (IOException ex) {
            System.err.println("Execute command " + cmd.getOptionValue("E") + " failed");
        }
    }

    //if serial
    if (cmd.hasOption("l") || cmd.hasOption("w")) {
        SerialMain serial = new SerialMain(cmd, moteList);
        if (silent) {
            serial.setSilent();
        }
        if (verbose) {
            serial.setVerbose();
        }
        serial.startSerial();
    }

}

From source file:de.tudarmstadt.lt.lm.app.GenerateNgrams.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options opts = new Options();
    opts.addOption(OptionBuilder.withLongOpt("help").withDescription("Display help message.").create("?"));
    opts.addOption(OptionBuilder.withLongOpt("ptype").withArgName("class").hasArg().withDescription(
            "specify the instance of the language model provider that you want to use: {LtSegProvider, BreakIteratorStringProvider, UimaStringProvider, PreTokenizedStringProvider} (default: LtSegProvider)")
            .create("p"));
    opts.addOption(OptionBuilder.withLongOpt("cardinality").withArgName("ngram-order").hasArg().withDescription(
            "Specify the cardinality of the ngrams (min. 1). Specify a range using 'from-to'. (Examples: 5 = extract 5grams; 1-5 = extract 1grams, 2grams, ..., 5grams; default: 1-5).")
            .create("n"));
    opts.addOption(OptionBuilder.withLongOpt("dir").withArgName("directory").isRequired().hasArg()
            .withDescription(//ww w  .  java 2  s  .c om
                    "specify the directory that contains '.txt' files that are used as source for generating ngrams.")
            .create("d"));
    opts.addOption(OptionBuilder.withLongOpt("overwrite").withDescription("Overwrite existing ngram file.")
            .create("w"));

    CommandLine cli = null;
    try {
        cli = new GnuParser().parse(opts, args);
    } catch (Exception e) {
        print_usage(opts, e.getMessage());
    }
    if (cli.hasOption("?"))
        print_usage(opts, null);

    AbstractStringProvider prvdr = null;
    try {
        prvdr = StartLM
                .getStringProviderInstance(cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName()));
    } catch (Exception e) {
        print_usage(opts, String.format("Could not instantiate LmProvider '%s': %s",
                cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName()), e.getMessage()));
    }

    String n_ = cli.getOptionValue("cardinality", "1-5");
    int dash_index = n_.indexOf('-');
    int n_e = Integer.parseInt(n_.substring(dash_index + 1, n_.length()).trim());
    int n_b = n_e;
    if (dash_index == 0)
        n_b = 1;
    if (dash_index > 0)
        n_b = Math.max(1, Integer.parseInt(n_.substring(0, dash_index).trim()));

    final File src_dir = new File(cli.getOptionValue("dir"));
    boolean overwrite = Boolean.parseBoolean(cli.getOptionValue("overwrite", "false"));

    generateNgrams(src_dir, prvdr, n_b, n_e, overwrite);

}