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:baldrickv.s3streamingtool.S3StreamingTool.java

public static void main(String args[]) throws Exception {
    BasicParser p = new BasicParser();

    Options o = getOptions();//from   w w w  .j av  a2  s  . c om

    CommandLine cl = p.parse(o, args);

    if (cl.hasOption('h')) {
        HelpFormatter hf = new HelpFormatter();
        hf.setWidth(80);

        StringBuilder sb = new StringBuilder();

        sb.append("\n");
        sb.append("Upload:\n");
        sb.append("    -u -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Download:\n");
        sb.append("    -d -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Upload encrypted:\n");
        sb.append("    -u -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Download encrypted:\n");
        sb.append("    -d -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Cleanup in-progress multipart uploads\n");
        sb.append("    -c -r creds -b my_bucket\n");
        System.out.println(sb.toString());

        hf.printHelp("See above", o);

        return;
    }

    int n = 0;
    if (cl.hasOption('d'))
        n++;
    if (cl.hasOption('u'))
        n++;
    if (cl.hasOption('c'))
        n++;
    if (cl.hasOption('m'))
        n++;

    if (n != 1) {
        System.err.println("Must specify at exactly one of -d, -u, -c or -m");
        System.exit(-1);
    }

    if (cl.hasOption('m')) {
        //InputStream in = new java.io.BufferedInputStream(System.in,1024*1024*2);
        InputStream in = System.in;
        System.out.println(TreeHashGenerator.calculateTreeHash(in));
        return;
    }

    require(cl, 'b');

    if (cl.hasOption('d') || cl.hasOption('u')) {
        require(cl, 'f');
    }
    if (cl.hasOption('z')) {
        require(cl, 'k');
    }

    AWSCredentials creds = null;

    if (cl.hasOption('r')) {
        creds = Utils.loadAWSCredentails(cl.getOptionValue('r'));
    } else {
        if (cl.hasOption('i') && cl.hasOption('e')) {
            creds = new BasicAWSCredentials(cl.getOptionValue('i'), cl.getOptionValue('e'));
        } else {

            System.out.println("Must specify either credential file (-r) or AWS key ID and secret (-i and -e)");
            System.exit(-1);
        }
    }

    S3StreamConfig config = new S3StreamConfig();
    config.setEncryption(false);
    if (cl.hasOption('z')) {
        config.setEncryption(true);
        config.setSecretKey(Utils.loadSecretKey(cl.getOptionValue("k")));
    }

    if (cl.hasOption("encryption-mode")) {
        config.setEncryptionMode(cl.getOptionValue("encryption-mode"));
    }
    config.setS3Bucket(cl.getOptionValue("bucket"));
    if (cl.hasOption("file")) {
        config.setS3File(cl.getOptionValue("file"));
    }

    if (cl.hasOption("threads")) {
        config.setIOThreads(Integer.parseInt(cl.getOptionValue("threads")));
    }

    if (cl.hasOption("blocksize")) {
        String s = cl.getOptionValue("blocksize");
        s = s.toUpperCase();
        int multi = 1;

        int end = 0;
        while ((end < s.length()) && (s.charAt(end) >= '0') && (s.charAt(end) <= '9')) {
            end++;
        }
        int size = Integer.parseInt(s.substring(0, end));

        if (end < s.length()) {
            String m = s.substring(end);
            if (m.equals("K"))
                multi = 1024;
            else if (m.equals("M"))
                multi = 1048576;
            else if (m.equals("G"))
                multi = 1024 * 1024 * 1024;
            else if (m.equals("KB"))
                multi = 1024;
            else if (m.equals("MB"))
                multi = 1048576;
            else if (m.equals("GB"))
                multi = 1024 * 1024 * 1024;
            else {
                System.out.println("Unknown suffix on block size.  Only K,M and G understood.");
                System.exit(-1);
            }

        }
        size *= multi;
        config.setBlockSize(size);
    }

    Logger.getLogger("").setLevel(Level.FINE);

    S3StreamingDownload.log.setLevel(Level.FINE);
    S3StreamingUpload.log.setLevel(Level.FINE);

    config.setS3Client(new AmazonS3Client(creds));
    config.setGlacierClient(new AmazonGlacierClient(creds));
    config.getGlacierClient().setEndpoint("glacier.us-west-2.amazonaws.com");

    if (cl.hasOption("glacier")) {
        config.setGlacier(true);
        config.setStorageInterface(new StorageGlacier(config.getGlacierClient()));
    } else {
        config.setStorageInterface(new StorageS3(config.getS3Client()));
    }
    if (cl.hasOption("bwlimit")) {
        config.setMaxBytesPerSecond(Double.parseDouble(cl.getOptionValue("bwlimit")));

    }

    if (cl.hasOption('c')) {
        if (config.getGlacier()) {
            GlacierCleanupMultipart.cleanup(config);
        } else {
            S3CleanupMultipart.cleanup(config);
        }
        return;
    }
    if (cl.hasOption('d')) {
        config.setOutputStream(System.out);
        S3StreamingDownload.download(config);
        return;
    }
    if (cl.hasOption('u')) {
        config.setInputStream(System.in);
        S3StreamingUpload.upload(config);
        return;
    }

}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(443);
    while (true) {
        Socket s = ss.accept();//from  www  .  j  av a 2  s  .  co m
        PrintStream out = new PrintStream(s.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String info = null;
        String request = null;
        String refer = null;

        while ((info = in.readLine()) != null) {
            if (info.startsWith("GET")) {
                request = info;
            }
            if (info.startsWith("Referer:")) {
                refer = info;
            }
            if (info.equals(""))
                break;
        }
        if (request != null) {
            out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html");
            int sp1 = request.indexOf(' ');
            int sp2 = request.indexOf(' ', sp1 + 1);
            String filename = request.substring(sp1 + 2, sp2);
            if (refer != null) {
                sp1 = refer.indexOf(' ');
                refer = refer.substring(sp1 + 1, refer.length());
                if (!refer.endsWith("/")) {
                    refer = refer + "/";
                }
                filename = refer + filename;
            }
            URL con = new URL(filename);
            InputStream gotoin = con.openStream();
            int n = gotoin.available();
            byte buf[] = new byte[1024];
            out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html");
            out.println("Content_Length:" + n + "\n");
            while ((n = gotoin.read(buf)) >= 0) {
                out.write(buf, 0, n);
            }
            out.close();
            s.close();
            in.close();
        }
    }
}

From source file:de.jetwick.snacktory.HtmlFetcher.java

public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new FileReader("urls.txt"));
    String line = null;
    Set<String> existing = new LinkedHashSet<String>();
    while ((line = reader.readLine()) != null) {
        int index1 = line.indexOf("\"");
        int index2 = line.indexOf("\"", index1 + 1);
        String url = line.substring(index1 + 1, index2);
        String domainStr = SHelper.extractDomain(url, true);
        String counterStr = "";
        // TODO more similarities
        if (existing.contains(domainStr))
            counterStr = "2";
        else/*from   w w w  .ja va  2 s  .  c o  m*/
            existing.add(domainStr);

        String html = new HtmlFetcher().fetchAsString(url, 20000);
        String outFile = domainStr + counterStr + ".html";
        BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
        writer.write(html);
        writer.close();
    }
    reader.close();
}

From source file:org.apache.http.examples.client.ClientWithResponseHandler.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //    DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    //    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    try {//from  ww  w .j a v  a2 s .c o  m
        //      HttpGet httpget = new HttpGet("http://localhost/");
        HttpGet httpget = new HttpGet(
                "http://api.map.baidu.com/geocoder/v2/?address=&output=json&ak=E4805d16520de693a3fe707cdc962045&callback=showLocation");
        //      httpget.setHeader("Accept", "180.97.33.90:80");
        httpget.setHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch");
        httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        httpget.setHeader("Cache-Control", "no-cache");
        httpget.setHeader("Connection", "keep-alive");
        httpget.setHeader("Referer",
                "http://developer.baidu.com/map/index.php?title=webapi/guide/changeposition");
        httpget.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36");

        System.out.println("Executing request httpget.getRequestLine() " + httpget.getRequestLine());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, "utf-8") : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);

        //showLocation&&showLocation({"status":0,"result":{"location":{"lng":112.25009284837,"lat":32.229168591538},"precise":0,"confidence":14,"level":"\u533a\u53bf"}})
        System.out.println("----------------------------------------");
        ObjectMapper mapper = new ObjectMapper();
        //      mapper.readValue(responseBody, AddressCoord.class);
        JsonNode root = mapper.readTree(
                responseBody.substring("showLocation&&showLocation(".length(), responseBody.length() - 1));
        //      String name = root.get("name").asText();
        //      int age = root.get("age").asInt();
        String status = root.get("status").asText();
        String lng = root.with("result").with("location").get("lng").asText();
        String lat = root.with("result").with("location").get("lat").asText();
        String level = root.with("result").get("level").asText();
        System.out.println(String.format("'%1$s': [%2$s, %3$s], status: %4$s", level, lng, lat, status));

    } finally {
        httpclient.close();
    }
}

From source file:com.taobao.android.builder.tools.zip.ZipUtils.java

public static void main(String[] args) {
    String name = "T.class";
    System.out.println(name.substring(0, name.length() - 6));
}

From source file:net.itransformers.idiscover.discoverylisteners.TopologyDeviceLogger.java

public static void main(String[] args) throws FileNotFoundException, JAXBException {
    String path = "tmp1";
    File dir = new File(path);
    String[] files = dir.list(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return (name.startsWith("device") && name.endsWith(".xml"));
        }//from   www. j  a va 2 s  .c o  m
    });
    TopologyDeviceLogger logger = new TopologyDeviceLogger(path);
    String host = "10.33.0.5";
    String snmpROComm = "public";
    Map<String, String> resourceParams = new HashMap<String, String>();
    resourceParams.put("community", snmpROComm);
    resourceParams.put("version", "1");
    Resource resource = new Resource(host, null, resourceParams);

    for (String fileName : files) {
        FileInputStream is = new FileInputStream(path + File.separator + fileName);
        DiscoveredDeviceData discoveredDeviceData = null;
        try {
            discoveredDeviceData = JaxbMarshalar.unmarshal(DiscoveredDeviceData.class, is);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String deviceName = fileName.substring("device-".length(), fileName.length() - ".xml".length());
        logger.handleDevice(deviceName, null, discoveredDeviceData, resource);
    }

}

From source file:ExecSQL.java

public static void main(String args[]) {
        try {//from   w  w w.j  a  va 2s .  com
            Scanner in;
            if (args.length == 0)
                in = new Scanner(System.in);
            else
                in = new Scanner(new File(args[0]));

            Connection conn = getConnection();
            try {
                Statement stat = conn.createStatement();

                while (true) {
                    if (args.length == 0)
                        System.out.println("Enter command or EXIT to exit:");

                    if (!in.hasNextLine())
                        return;

                    String line = in.nextLine();
                    if (line.equalsIgnoreCase("EXIT"))
                        return;
                    if (line.trim().endsWith(";")) // remove trailing semicolon
                    {
                        line = line.trim();
                        line = line.substring(0, line.length() - 1);
                    }
                    try {
                        boolean hasResultSet = stat.execute(line);
                        if (hasResultSet)
                            showResultSet(stat);
                    } catch (SQLException ex) {
                        for (Throwable e : ex)
                            e.printStackTrace();
                    }
                }
            } finally {
                conn.close();
            }
        } catch (SQLException e) {
            for (Throwable t : e)
                t.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

From source file:com.glaf.base.modules.sys.service.mybatis.SysTreeServiceImpl.java

public static void main(String[] args) {
    String str1 = "1|2|5|195235|";
    String str2 = "1|2|5|195235|195274|195347|195483|";
    String tmp = str2.substring(str1.length(), str2.length());
    System.out.println(tmp);/*from   w  ww  .ja  va 2  s .com*/
    StringTokenizer token = new StringTokenizer(tmp, "|");
    System.out.println(token.countTokens());
}

From source file:com.jcraft.weirdx.XDMCP.java

public static void main(String[] args) {

    String usage = "usage: [-query|-broadcast] address -display displayname";

    int op = -1;/*w w  w  . j  a v a2 s  .  c o m*/
    String address = null;
    String displayaddress = null;
    int displaynum = 0;

    if (args.length == 0) {
        System.err.println(usage);
        System.exit(-1);
    }

    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("-query")) {
            op = Query;
            i++;
            address = args[i];
            continue;
        }
        if (args[i].equals("-broadcast")) {
            op = BroadcastQuery;
            i++;
            address = args[i];
            continue;
        }
        if (args[i].equals("-display")) {
            i++;
            displayaddress = args[i].substring(0, args[i].indexOf(":"));
            try {
                String foo = args[i].substring(args[i].indexOf(":") + 1, args[i].length());
                foo = foo.substring(0, (foo.indexOf(".") == -1 ? foo.length() : foo.indexOf(".")));
                displaynum = Integer.parseInt(foo);
            } catch (Exception e) {
            }
        }
    }

    if (op == -1 || address == null || displayaddress == null) {
        System.err.println(usage);
        System.exit(-1);
    }

    XDMCP foo = new XDMCP(op, address, displayaddress, displaynum);
    foo.start();
}

From source file:de.morbz.osmpoispbf.Scanner.java

public static void main(String[] args) {
    System.out.println("OsmPoisPbf " + VERSION + " started");

    // Get input file
    if (args.length < 1) {
        System.out.println("Error: Please provide an input file");
        System.exit(-1);/*from  w  ww. j a  va2 s  .  c o  m*/
    }
    String inputFile = args[args.length - 1];

    // Get output file
    String outputFile;
    int index = inputFile.indexOf('.');
    if (index != -1) {
        outputFile = inputFile.substring(0, index);
    } else {
        outputFile = inputFile;
    }
    outputFile += ".csv";

    // Setup CLI parameters
    options = new Options();
    options.addOption("ff", "filterFile", true, "The file that is used to filter categories");
    options.addOption("of", "outputFile", true, "The output CSV file to be written");
    options.addOption("rt", "requiredTags", true, "Comma separated list of tags that are required [name]");
    options.addOption("ut", "undesiredTags", true,
            "Comma separated list of tags=value combinations that should be filtered [key=value]");
    options.addOption("ot", "outputTags", true, "Comma separated list of tags that are exported [name]");
    options.addOption("ph", "printHeader", false,
            "If flag is set, the `outputTags` are printed as first line in the output file.");
    options.addOption("r", "relations", false, "Parse relations");
    options.addOption("nw", "noWays", false, "Don't parse ways");
    options.addOption("nn", "noNodes", false, "Don't parse nodes");
    options.addOption("u", "allowUnclosedWays", false, "Allow ways that aren't closed");
    options.addOption("d", "decimals", true, "Number of decimal places of coordinates [7]");
    options.addOption("s", "separator", true, "Separator character for CSV [|]");
    options.addOption("v", "verbose", false, "Print all found POIs");
    options.addOption("h", "help", false, "Print this help");

    // Parse parameters
    CommandLine line = null;
    try {
        line = (new DefaultParser()).parse(options, args);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        printHelp();
        System.exit(-1);
    }

    // Help
    if (line.hasOption("help")) {
        printHelp();
        System.exit(0);
    }

    // Get filter file
    String filterFile = null;
    if (line.hasOption("filterFile")) {
        filterFile = line.getOptionValue("filterFile");
    }

    // Get output file
    if (line.hasOption("outputFile")) {
        outputFile = line.getOptionValue("outputFile");
    }

    // Check files
    if (inputFile.equals(outputFile)) {
        System.out.println("Error: Input and output files are the same");
        System.exit(-1);
    }
    File file = new File(inputFile);
    if (!file.exists()) {
        System.out.println("Error: Input file doesn't exist");
        System.exit(-1);
    }

    // Check OSM entity types
    boolean parseNodes = true;
    boolean parseWays = true;
    boolean parseRelations = false;
    if (line.hasOption("noNodes")) {
        parseNodes = false;
    }
    if (line.hasOption("noWays")) {
        parseWays = false;
    }
    if (line.hasOption("relations")) {
        parseRelations = true;
    }

    // Unclosed ways allowed?
    if (line.hasOption("allowUnclosedWays")) {
        onlyClosedWays = false;
    }

    // Get CSV separator
    char separator = '|';
    if (line.hasOption("separator")) {
        String arg = line.getOptionValue("separator");
        if (arg.length() != 1) {
            System.out.println("Error: The CSV separator has to be exactly 1 character");
            System.exit(-1);
        }
        separator = arg.charAt(0);
    }
    Poi.setSeparator(separator);

    // Set decimals
    int decimals = 7; // OSM default
    if (line.hasOption("decimals")) {
        String arg = line.getOptionValue("decimals");
        try {
            int dec = Integer.valueOf(arg);
            if (dec < 0) {
                System.out.println("Error: Decimals must not be less than 0");
                System.exit(-1);
            } else {
                decimals = dec;
            }
        } catch (NumberFormatException ex) {
            System.out.println("Error: Decimals have to be a number");
            System.exit(-1);
        }
    }
    Poi.setDecimals(decimals);

    // Verbose mode?
    if (line.hasOption("verbose")) {
        printPois = true;
    }

    // Required tags
    if (line.hasOption("requiredTags")) {
        String arg = line.getOptionValue("requiredTags");
        requiredTags = arg.split(",");
    }

    // Undesired tags
    if (line.hasOption("undesiredTags")) {
        String arg = line.getOptionValue("undesiredTags");
        undesiredTags = new HashMap<>();
        for (String undesired : arg.split(",")) {
            String[] keyVal = undesired.split("=");
            if (keyVal.length != 2) {
                System.out.println("Error: Undesired Tags have to formated like tag=value");
                System.exit(-1);
            }
            if (!undesiredTags.containsKey(keyVal[0])) {
                undesiredTags.put(keyVal[0], new HashSet<>(1));
            }
            undesiredTags.get(keyVal[0]).add(keyVal[1]);
        }
    }

    // Output tags
    if (line.hasOption("outputTags")) {
        String arg = line.getOptionValue("outputTags");
        outputTags = arg.split(",");
    }

    // Get filter rules
    FilterFileParser parser = new FilterFileParser(filterFile);
    filters = parser.parse();
    if (filters == null) {
        System.exit(-1);
    }

    // Setup CSV output
    try {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF8"));
    } catch (IOException e) {
        System.out.println("Error: Output file error");
        System.exit(-1);
    }

    // Print Header
    if (line.hasOption("printHeader")) {
        String header = "category" + separator + "osm_id" + separator + "lat" + separator + "lon";
        for (int i = 0; i < outputTags.length; i++) {
            header += separator + outputTags[i];
        }
        try {
            writer.write(header + "\n");
        } catch (IOException e) {
            System.out.println("Error: Output file write error");
            System.exit(-1);
        }
    }

    // Setup OSMonaut
    EntityFilter filter = new EntityFilter(parseNodes, parseWays, parseRelations);
    Osmonaut naut = new Osmonaut(inputFile, filter, false);

    // Start watch
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    // Start OSMonaut
    String finalSeparator = String.valueOf(separator);
    naut.scan(new IOsmonautReceiver() {

        boolean entityNeeded;

        @Override
        public boolean needsEntity(EntityType type, Tags tags) {
            // Are there any tags?
            if (tags.size() == 0) {
                return false;
            }

            // Check required tags
            for (String tag : requiredTags) {
                if (!tags.hasKey(tag)) {
                    return false;
                }
            }

            entityNeeded = getCategory(tags, filters) != null;

            if (undesiredTags != null && entityNeeded) {
                for (String key : undesiredTags.keySet()) {
                    if (tags.hasKey(key)) {
                        for (String val : undesiredTags.get(key)) {
                            if (tags.hasKeyValue(key, val)) {
                                return false;
                            }
                        }
                    }
                }
            }

            return entityNeeded;
        }

        @Override
        public void foundEntity(Entity entity) {
            // Check if way is closed
            if (onlyClosedWays && entity.getEntityType() == EntityType.WAY) {
                if (!((Way) entity).isClosed()) {
                    return;
                }
            }

            // Get category
            Tags tags = entity.getTags();
            String cat = getCategory(tags, filters);
            if (cat == null) {
                return;
            }

            // Get center
            LatLon center = entity.getCenter();
            if (center == null) {
                return;
            }

            // Make OSM-ID
            String type = "";
            switch (entity.getEntityType()) {
            case NODE:
                type = "node";
                break;
            case WAY:
                type = "way";
                break;
            case RELATION:
                type = "relation";
                break;
            }
            String id = String.valueOf(entity.getId());

            // Make output tags
            String[] values = new String[outputTags.length];
            for (int i = 0; i < outputTags.length; i++) {
                String key = outputTags[i];
                if (tags.hasKey(key)) {
                    values[i] = tags.get(key).replaceAll(finalSeparator, "").replaceAll("\"", "");
                }
            }

            // Make POI
            poisFound++;
            Poi poi = new Poi(values, cat, center, type, id);

            // Output
            if (printPois && System.currentTimeMillis() > lastMillis + 40) {
                printPoisFound();
                lastMillis = System.currentTimeMillis();
            }

            // Write to file
            try {
                writer.write(poi.toCsv() + "\n");
            } catch (IOException e) {
                System.out.println("Error: Output file write error");
                System.exit(-1);
            }
        }
    });

    // Close writer
    try {
        writer.close();
    } catch (IOException e) {
        System.out.println("Error: Output file close error");
        System.exit(-1);
    }

    // Output results
    stopWatch.stop();

    printPoisFound();
    System.out.println();
    System.out.println("Elapsed time in milliseconds: " + stopWatch.getElapsedTime());

    // Quit
    System.exit(0);
}