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) 

Source Link

Document

Returns a string that is a substring of this string.

Usage

From source file:examples.mail.IMAPImportMbox.java

public static void main(String[] args) throws IOException {
    if (args.length < 2) {
        System.err.println(//from  w  w w  .j  av  a 2 s.c  om
                "Usage: IMAPImportMbox imap[s]://user:password@host[:port]/folder/path <mboxfile> [selectors]");
        System.err.println("\tWhere: a selector is a list of numbers/number ranges - 1,2,3-10"
                + " - or a list of strings to match in the initial From line");
        System.exit(1);
    }

    final URI uri = URI.create(args[0]);
    final String file = args[1];

    final File mbox = new File(file);
    if (!mbox.isFile() || !mbox.canRead()) {
        throw new IOException("Cannot read mailbox file: " + mbox);
    }

    String path = uri.getPath();
    if (path == null || path.length() < 1) {
        throw new IllegalArgumentException("Invalid folderPath: '" + path + "'");
    }
    String folder = path.substring(1); // skip the leading /

    List<String> contains = new ArrayList<String>(); // list of strings to find
    BitSet msgNums = new BitSet(); // list of message numbers

    for (int i = 2; i < args.length; i++) {
        String arg = args[i];
        if (arg.matches("\\d+(-\\d+)?(,\\d+(-\\d+)?)*")) { // number,m-n
            for (String entry : arg.split(",")) {
                String[] parts = entry.split("-");
                if (parts.length == 2) { // m-n
                    int low = Integer.parseInt(parts[0]);
                    int high = Integer.parseInt(parts[1]);
                    for (int j = low; j <= high; j++) {
                        msgNums.set(j);
                    }
                } else {
                    msgNums.set(Integer.parseInt(entry));
                }
            }
        } else {
            contains.add(arg); // not a number/number range
        }
    }
    //        System.out.println(msgNums.toString());
    //        System.out.println(java.util.Arrays.toString(contains.toArray()));

    // Connect and login
    final IMAPClient imap = IMAPUtils.imapLogin(uri, 10000, null);

    int total = 0;
    int loaded = 0;
    try {
        imap.setSoTimeout(6000);

        final BufferedReader br = new BufferedReader(new FileReader(file)); // TODO charset?

        String line;
        StringBuilder sb = new StringBuilder();
        boolean wanted = false; // Skip any leading rubbish
        while ((line = br.readLine()) != null) {
            if (line.startsWith("From ")) { // start of message; i.e. end of previous (if any)
                if (process(sb, imap, folder, total)) { // process previous message (if any)
                    loaded++;
                }
                sb.setLength(0);
                total++;
                wanted = wanted(total, line, msgNums, contains);
            } else if (startsWith(line, PATFROM)) { // Unescape ">+From " in body text
                line = line.substring(1);
            }
            // TODO process first Received: line to determine arrival date?
            if (wanted) {
                sb.append(line);
                sb.append(CRLF);
            }
        }
        br.close();
        if (wanted && process(sb, imap, folder, total)) { // last message (if any)
            loaded++;
        }
    } catch (IOException e) {
        System.out.println(imap.getReplyString());
        e.printStackTrace();
        System.exit(10);
        return;
    } finally {
        imap.logout();
        imap.disconnect();
    }
    System.out.println("Processed " + total + " messages, loaded " + loaded);
}

From source file:GetWebPageApp.java

public static void main(String args[]) throws Exception {
    String resource, host, file;
    int slashPos;

    resource = "www.java2s.com/index.htm"; // skip HTTP://
    slashPos = resource.indexOf('/'); // find host/file separator
    if (slashPos < 0) {
        resource = resource + "/";
        slashPos = resource.indexOf('/');
    }/*w w  w  .java 2  s. c  om*/
    file = resource.substring(slashPos); // isolate host and file parts
    host = resource.substring(0, slashPos);
    System.out.println("Host to contact: '" + host + "'");
    System.out.println("File to fetch : '" + file + "'");

    SocketChannel channel = null;

    try {
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = charset.newDecoder();
        CharsetEncoder encoder = charset.newEncoder();

        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        CharBuffer charBuffer = CharBuffer.allocate(1024);

        InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(socketAddress);

        selector = Selector.open();

        channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);

        while (selector.select(500) > 0) {
            Set readyKeys = selector.selectedKeys();
            try {
                Iterator readyItor = readyKeys.iterator();

                while (readyItor.hasNext()) {

                    SelectionKey key = (SelectionKey) readyItor.next();
                    readyItor.remove();
                    SocketChannel keyChannel = (SocketChannel) key.channel();

                    if (key.isConnectable()) {
                        if (keyChannel.isConnectionPending()) {
                            keyChannel.finishConnect();
                        }
                        String request = "GET " + file + " \r\n\r\n";
                        keyChannel.write(encoder.encode(CharBuffer.wrap(request)));
                    } else if (key.isReadable()) {
                        keyChannel.read(buffer);
                        buffer.flip();

                        decoder.decode(buffer, charBuffer, false);
                        charBuffer.flip();
                        System.out.print(charBuffer);

                        buffer.clear();
                        charBuffer.clear();

                    } else {
                        System.err.println("Unknown key");
                    }
                }
            } catch (ConcurrentModificationException e) {
            }
        }
    } catch (UnknownHostException e) {
        System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException ignored) {
            }
        }
    }
    System.out.println("\nDone.");
}

From source file:mujava.cli.testnew.java

public static void main(String[] args) throws IOException {
    testnewCom jct = new testnewCom();
    String[] argv = { "Flower", "/Users/dmark/mujava/src/Flower" };
    new JCommander(jct, args);

    muJavaHomePath = Util.loadConfig();
    // muJavaHomePath= "/Users/dmark/mujava";

    // check if debug mode
    if (jct.isDebug() || jct.isDebugMode()) {
        Util.debug = true;//from   www. j  av a  2  s.  com
    }
    System.out.println(jct.getParameters().size());
    sessionName = jct.getParameters().get(0); // set first parameter as the
    // session name

    ArrayList<String> srcFiles = new ArrayList<>();

    for (int i = 1; i < jct.getParameters().size(); i++) {
        srcFiles.add(jct.getParameters().get(i)); // retrieve all src file
        // names from parameters
    }

    // get all existing session name
    File folder = new File(muJavaHomePath);
    if (!folder.isDirectory()) {
        Util.Error("ERROR: cannot locate the folder specified in mujava.config");
        return;
    }
    File[] listOfFiles = folder.listFiles();
    // null checking
    // check the specified folder has files or not
    if (listOfFiles == null) {
        Util.Error("ERROR: no files in the muJava home folder " + muJavaHomePath);
        return;
    }
    List<String> fileNameList = new ArrayList<>();
    for (File file : listOfFiles) {
        fileNameList.add(file.getName());
    }

    // check if the session is new or not
    if (fileNameList.contains(sessionName)) {
        Util.Error("Session already exists.");
    } else {
        // create sub-directory for the session
        setupSessionDirectory(sessionName);

        // move src files into session folder
        for (String srcFile : srcFiles) {
            // new (dir, name)
            // check abs path or not

            // need to check if srcFile has .java at the end or not
            if (srcFile.length() > 5) {
                if (srcFile.substring(srcFile.length() - 5).equals(".java")) // name has .java at the end, e.g. cal.java
                {
                    // delete .java, e.g. make it cal
                    srcFile = srcFile.substring(0, srcFile.length() - 5);
                }
            }

            File source = new File(srcFile + ".java");

            if (!source.isAbsolute()) // relative path, attach path, e.g. cal.java, make it c:\mujava\cal.java
            {
                source = new File(muJavaHomePath + "/src" + java.io.File.separator + srcFile + ".java");

            }

            File desc = new File(muJavaHomePath + "/" + sessionName + "/src");
            FileUtils.copyFileToDirectory(source, desc);

            // compile src files
            // String srcName = "t";
            boolean result = compileSrc(srcFile);
            if (result)
                Util.Print("Session is built successfully.");
        }

    }

    // System.exit(0);
}

From source file:ZipExploder.java

/**
 * Main command line entry point.//from   w ww.  j  a v a2  s . c  o  m
 * 
 * @param args
 */
public static void main(final String[] args) {
    if (args.length == 0) {
        printHelp();
        System.exit(0);
    }
    List zipNames = new ArrayList();
    List jarNames = new ArrayList();
    String destDir = null;
    boolean jarActive = false, zipActive = false, destDirActive = false;
    boolean verbose = false;
    // process arguments
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (arg.charAt(0) == '-') { // switch
            arg = arg.substring(1);
            if (arg.equalsIgnoreCase("jar")) {
                jarActive = true;
                zipActive = false;
                destDirActive = false;
            } else if (arg.equalsIgnoreCase("zip")) {
                zipActive = true;
                jarActive = false;
                destDirActive = false;
            } else if (arg.equalsIgnoreCase("dir")) {
                jarActive = false;
                zipActive = false;
                destDirActive = true;
            } else if (arg.equalsIgnoreCase("verbose")) {
                verbose = true;
            } else {
                reportError("Invalid switch - " + arg);
            }
        } else {
            if (jarActive) {
                jarNames.add(arg);
            } else if (zipActive) {
                zipNames.add(arg);
            } else if (destDirActive) {
                if (destDir != null) {
                    reportError("duplicate argument - " + "-destDir");
                }
                destDir = arg;
            } else {
                reportError("Too many parameters - " + arg);
            }
        }
    }
    if (destDir == null || (zipNames.size() + jarNames.size()) == 0) {
        reportError("Missing parameters");
    }
    if (verbose) {
        System.out.println("Effective command: " + ZipExploder.class.getName() + " "
                + (jarNames.size() > 0 ? "-jars " + jarNames + " " : "")
                + (zipNames.size() > 0 ? "-zips " + zipNames + " " : "") + "-dir " + destDir);
    }
    try {
        ZipExploder ze = new ZipExploder(verbose);
        ze.process((String[]) zipNames.toArray(new String[zipNames.size()]),
                (String[]) jarNames.toArray(new String[jarNames.size()]), destDir);
    } catch (IOException ioe) {
        System.err.println("Exception - " + ioe.getMessage());
        ioe.printStackTrace(); // *** debug ***
        System.exit(2);
    }
}

From source file:com.sun.faban.harness.util.CLI.java

/**
 * The first argument to the CLI is the action. It can be:<ul>
 * <li>pending</li>//  www .  j a  v  a 2  s.c o  m
 * <li>status runId</li>
 * <li>submit benchmark profile configfile.xml</ul>
 * </ul>
 *
 * @param args The command line arguments.
 */
public static void main(String[] args) {

    if (args.length == 0) {
        printUsage();
        System.exit(1);
    }

    ArrayList<String> argList = new ArrayList<String>();
    // Do the getopt thing.
    char opt = (char) -1;
    String master = null;
    String user = null;
    String password = null;

    for (String arg : args) {
        if (arg.startsWith("-M")) {
            String optArg = arg.substring(2);
            if (optArg.length() == 0) {
                opt = 'M';
                continue;
            }
            master = optArg;
        } else if (arg.startsWith("-U")) {
            String optArg = arg.substring(2);
            if (optArg.length() == 0) {
                opt = 'U';
                continue;
            }
            user = optArg;
        } else if (arg.startsWith("-P")) {
            String optArg = arg.substring(2);
            if (optArg.length() == 0) {
                opt = 'P';
                continue;
            }
            password = optArg;
        } else if (opt != (char) -1) {
            switch (opt) {
            case 'M':
                master = arg;
                opt = (char) -1;
                break;
            case 'U':
                user = arg;
                opt = (char) -1;
                break;
            case 'P':
                password = arg;
                opt = (char) -1;
                break;
            }
        } else {
            argList.add(arg);
            opt = (char) -1;
        }
    }

    if (master == null)
        master = "http://localhost:9980/";
    else if (!master.endsWith("/"))
        master += '/';

    CLI cli = new CLI();
    String action = argList.get(0);

    try {
        if ("pending".equals(action)) {
            cli.doGet(master + "pending");
        } else if ("status".equals(action)) {
            if (argList.size() > 1)
                cli.doGet(master + "status/" + argList.get(1));
            else
                printUsage();
        } else if ("submit".equals(action)) {
            if (argList.size() > 3) {
                cli.doPostSubmit(master, user, password, argList);
            } else {
                printUsage();
                System.exit(1);
            }
        } else if ("kill".equals(action)) {
            if (argList.size() > 1) {
                cli.doPostKill(master, user, password, argList);
            } else {
                printUsage();
                System.exit(1);
            }
        } else if ("wait".equals(action)) {
            if (argList.size() > 1) {
                cli.pollStatus(master + "status/" + argList.get(1));
            } else {
                printUsage();
                System.exit(1);
            }
        } else if ("showlogs".equals(action)) {
            StringBuilder url = new StringBuilder();
            if (argList.size() > 1) {
                url.append(master).append("logs/");
                url.append(argList.get(1));
            } else {
                printUsage();
            }
            for (int i = 2; i < argList.size(); i++) {
                if ("-t".equals(argList.get(i)))
                    url.append("/tail");
                if ("-f".equals(argList.get(i)))
                    url.append("/follow");
                if ("-ft".equals(argList.get(i)))
                    url.append("/tail/follow");
                if ("-tf".equals(argList.get(i)))
                    url.append("/tail/follow");
            }
            cli.doGet(url.toString());
        } else {
            printUsage();
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
}

From source file:com.jbrisbin.groovy.mqdsl.RabbitMQDsl.java

public static void main(String[] argv) {

    // Parse command line arguments
    CommandLine args = null;/*from   www  .jav  a 2  s  .c  o  m*/
    try {
        Parser p = new BasicParser();
        args = p.parse(cliOpts, argv);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }

    // Check for help
    if (args.hasOption('?')) {
        printUsage();
        return;
    }

    // Runtime properties
    Properties props = System.getProperties();

    // Check for ~/.rabbitmqrc
    File userSettings = new File(System.getProperty("user.home"), ".rabbitmqrc");
    if (userSettings.exists()) {
        try {
            props.load(new FileInputStream(userSettings));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    // Load Groovy builder file
    StringBuffer script = new StringBuffer();
    BufferedInputStream in = null;
    String filename = "<STDIN>";
    if (args.hasOption("f")) {
        filename = args.getOptionValue("f");
        try {
            in = new BufferedInputStream(new FileInputStream(filename));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        in = new BufferedInputStream(System.in);
    }

    // Read script
    if (null != in) {
        byte[] buff = new byte[4096];
        try {
            for (int read = in.read(buff); read > -1;) {
                script.append(new String(buff, 0, read));
                read = in.read(buff);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        System.err.println("No script file to evaluate...");
    }

    PrintStream stdout = System.out;
    PrintStream out = null;
    if (args.hasOption("o")) {
        try {
            out = new PrintStream(new FileOutputStream(args.getOptionValue("o")), true);
            System.setOut(out);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    }

    String[] includes = (System.getenv().containsKey("MQDSL_INCLUDE")
            ? System.getenv("MQDSL_INCLUDE").split(String.valueOf(File.pathSeparatorChar))
            : new String[] { System.getenv("HOME") + File.separator + ".mqdsl.d" });

    try {
        // Setup RabbitMQ
        String username = (args.hasOption("U") ? args.getOptionValue("U")
                : props.getProperty("mq.user", "guest"));
        String password = (args.hasOption("P") ? args.getOptionValue("P")
                : props.getProperty("mq.password", "guest"));
        String virtualHost = (args.hasOption("v") ? args.getOptionValue("v")
                : props.getProperty("mq.virtualhost", "/"));
        String host = (args.hasOption("h") ? args.getOptionValue("h")
                : props.getProperty("mq.host", "localhost"));
        int port = Integer.parseInt(
                args.hasOption("p") ? args.getOptionValue("p") : props.getProperty("mq.port", "5672"));

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        if (null != virtualHost) {
            connectionFactory.setVirtualHost(virtualHost);
        }

        // The DSL builder
        RabbitMQBuilder builder = new RabbitMQBuilder();
        builder.setConnectionFactory(connectionFactory);
        // Our execution environment
        Binding binding = new Binding(args.getArgs());
        binding.setVariable("mq", builder);
        String fileBaseName = filename.replaceAll("\\.groovy$", "");
        binding.setVariable("log",
                LoggerFactory.getLogger(fileBaseName.substring(fileBaseName.lastIndexOf("/") + 1)));
        if (null != out) {
            binding.setVariable("out", out);
        }

        // Include helper files
        GroovyShell shell = new GroovyShell(binding);
        for (String inc : includes) {
            File f = new File(inc);
            if (f.isDirectory()) {
                File[] files = f.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File file, String s) {
                        return s.endsWith(".groovy");
                    }
                });
                for (File incFile : files) {
                    run(incFile, shell, binding);
                }
            } else {
                run(f, shell, binding);
            }
        }

        run(script.toString(), shell, binding);

        while (builder.isActive()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }

        if (null != out) {
            out.close();
            System.setOut(stdout);
        }

    } finally {
        System.exit(0);
    }
}

From source file:com.qiangbang.controller.wap.BusinessController.java

public static void main(String[] args) {
    String username = "mfdsfsdfs";
    System.out.println("**" + username.substring(2));
}

From source file:ExtractSubstring.java

public static void main(String[] args) {
    String text = "To be or not to be";
    int count = 0;
    char separator = ' ';

    int index = 0;
    do {/*from   w w  w . j  a  va  2  s  . co  m*/
        ++count;
        ++index;
        index = text.indexOf(separator, index);
    } while (index != -1);

    String[] subStr = new String[count];
    index = 0;
    int endIndex = 0;
    for (int i = 0; i < count; i++) {
        endIndex = text.indexOf(separator, index);
        if (endIndex == -1)
            subStr[i] = text.substring(index);
        else
            subStr[i] = text.substring(index, endIndex);
        index = endIndex + 1;
    }

    for (int i = 0; i < subStr.length; i++)
        System.out.println(subStr[i]);
}

From source file:com.github.xmltopdf.JasperPdfGenerator.java

/**.
 * @param args/*from   ww  w  . j  a  va 2s. co  m*/
 *            the arguments
 * @throws IOException in case IO error
 */
public static void main(String[] args) throws IOException {
    if (args.length == 0) {
        LOG.info(null, USAGE);
        return;
    }
    List<String> templates = new ArrayList<String>();
    List<String> xmls = new ArrayList<String>();
    List<String> types = new ArrayList<String>();
    for (String arg : args) {
        if (arg.endsWith(".jrxml")) {
            templates.add(arg);
        } else if (arg.endsWith(".xml")) {
            xmls.add(arg);
        } else if (arg.startsWith(DOC_TYPE)) {
            types = Arrays
                    .asList(arg.substring(DOC_TYPE.length()).replaceAll("\\s+", "").toUpperCase().split(","));
        }
    }
    if (templates.isEmpty()) {
        LOG.info(null, USAGE);
        return;
    }
    if (types.isEmpty()) {
        types.add("PDF");
    }
    for (String type : types) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        if (DocType.valueOf(type) != null) {
            new JasperPdfGenerator().createDocument(templates, xmls, os, DocType.valueOf(type));
            os.writeTo(
                    new FileOutputStream(templates.get(0).replaceFirst("\\.jrxml$", "." + type.toLowerCase())));
        }
    }
}

From source file:com.netthreads.mavenize.Pommel.java

/**
 * Arguments: <source dir> <target dir> <project type> [Optional parameter 
 * can be intellij, netbeans]/*from ww w .ja v  a  2 s.co m*/
 * 
 * @param args
 */
public static void main(String[] args) {
    if (args.length > 1) {
        String sourcePath = "";
        String mapFilePath = "";

        boolean isInput = false;
        boolean isMap = false;
        for (String arg : args) {
            try {
                if (arg.startsWith(ARG_INPUT)) {
                    sourcePath = arg.substring(ARG_INPUT.length());
                    isInput = true;
                } else if (arg.startsWith(ARG_MAP)) {
                    mapFilePath = arg.substring(ARG_MAP.length());
                    isMap = true;
                }
            } catch (Exception e) {
                logger.error("Can't process argument, " + arg + ", " + e.getMessage());
            }
        }

        // Execute mapping.
        try {
            if (isInput && isMap) {
                Pommel pommel = new Pommel();

                pommel.process(sourcePath, mapFilePath);
            } else {
                System.out.println(APP_MESSAGE + ARGS_MESSAGE);
            }
        } catch (PommelException e) {
            System.out.println("Application error, " + e.getMessage());
        }
    } else {
        System.out.println(APP_MESSAGE + ARGS_MESSAGE);
    }
}