Example usage for java.lang String charAt

List of usage examples for java.lang String charAt

Introduction

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

Prototype

public char charAt(int index) 

Source Link

Document

Returns the char value at the specified index.

Usage

From source file:com.glaf.jbpm.action.MultiPooledTaskInstanceAction.java

public static void main(String[] args) throws Exception {
    String actorIdxy = "{joy,sam},{pp,qq},{kit,cora},{eyb2000,huangcw}";
    StringTokenizer st2 = new StringTokenizer(actorIdxy, ";");
    while (st2.hasMoreTokens()) {
        String elem2 = st2.nextToken();
        if (StringUtils.isNotEmpty(elem2)) {
            elem2 = elem2.trim();//w  w  w  . ja  v a2 s .  c om
            if ((elem2.length() > 0 && elem2.charAt(0) == '{') && elem2.endsWith("}")) {
                elem2 = elem2.substring(elem2.indexOf("{") + 1, elem2.indexOf("}"));
                Set<String> actorIds = new HashSet<String>();
                StringTokenizer st4 = new StringTokenizer(elem2, ",");
                while (st4.hasMoreTokens()) {
                    String elem4 = st4.nextToken();
                    elem4 = elem4.trim();
                    if (elem4.length() > 0) {
                        actorIds.add(elem4);
                    }
                }
                System.out.println(actorIds);
            }
        }
    }
}

From source file:ZipExploder.java

/**
 * Main command line entry point.//from w  w  w . ja  v  a  2  s .c om
 * 
 * @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.github.brandtg.switchboard.FileLogAggregator.java

/** Main. */
public static void main(String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption("h", "help", false, "Prints help message");
    opts.addOption("f", "file", true, "File to output aggregated logs to");
    opts.addOption("s", "separator", true, "Line separator in log");
    CommandLine cli = new GnuParser().parse(opts, args);

    if (cli.getArgs().length == 0 || cli.hasOption("help")) {
        new HelpFormatter().printHelp("usage: [opts] sourceHost:port ...", opts);
        System.exit(1);//from  w w w.ja v a 2s . c o  m
    }

    // Parse sources
    Set<InetSocketAddress> sources = new HashSet<>();
    for (int i = 0; i < cli.getArgs().length; i++) {
        String[] tokens = cli.getArgs()[i].split(":");
        sources.add(new InetSocketAddress(tokens[0], Integer.valueOf(tokens[1])));
    }

    // Parse output stream
    OutputStream outputStream;
    if (cli.hasOption("file")) {
        outputStream = new FileOutputStream(cli.getOptionValue("file"));
    } else {
        outputStream = System.out;
    }

    // Separator
    String separator = cli.getOptionValue("separator", "\n");
    if (separator.length() != 1) {
        throw new IllegalArgumentException("Separator must only be 1 character");
    }

    final FileLogAggregator fileLogAggregator = new FileLogAggregator(sources, separator.charAt(0),
            outputStream);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                fileLogAggregator.stop();
            } catch (Exception e) {
                LOG.error("Error when stopping log aggregator", e);
            }
        }
    });

    fileLogAggregator.start();
}

From source file:jfs.sync.meta.MetaFileStorageAccess.java

/**
 *
 * Extract one file from encrypted repository.
 *
 * TODO: list directories/*from   ww w  . jav a2 s . c  o  m*/
 *
 */
public static void main(String[] args) throws Exception {
    final String password = args[0];
    MetaFileStorageAccess storage = new MetaFileStorageAccess("Twofish", false) {

        protected String getPassword(String relativePath) {
            String result = "";

            String pwd = password;

            int i = 0;
            int j = relativePath.length() - 1;
            while ((i < pwd.length()) || (j >= 0)) {
                if (i < pwd.length()) {
                    result += pwd.charAt(i++);
                } // if
                if (j >= 0) {
                    result += relativePath.charAt(j--);
                } // if
            } // while

            return result;
        } // getPassword()
    };
    String encryptedPath = args[2];
    String[] elements = encryptedPath.split("\\\\");
    String path = "";
    for (int i = 0; i < elements.length; i++) {
        String encryptedName = elements[i];
        String plain = storage.getDecryptedFileName(path, encryptedName);
        path += storage.getSeparator();
        path += plain;
        System.out.println(path);
    } // for

    String cipherSpec = storage.getCipherSpec();
    byte[] credentials = storage.getFileCredentials(path);
    Cipher cipher = SecurityUtils.getCipher(cipherSpec, Cipher.DECRYPT_MODE, credentials);

    InputStream is = storage.getInputStream(args[1], path);
    is = JFSEncryptedStream.createInputStream(is, JFSEncryptedStream.DONT_CHECK_LENGTH, cipher);
    int b = 0;
    while (b >= 0) {
        b = is.read();
        System.out.print((char) b);
    } // while
    is.close();
}

From source file:baldrickv.s3streamingtool.S3StreamingTool.java

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

    Options o = getOptions();// w ww  .ja v  a  2  s. c  o m

    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:RegExTest.java

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter pattern: ");
    String patternString = in.nextLine();

    Pattern pattern = null;//from   ww  w .  ja  v a2  s .  c o  m
    try {
        pattern = Pattern.compile(patternString);
    } catch (PatternSyntaxException e) {
        System.out.println("Pattern syntax error");
        System.exit(1);
    }

    while (true) {
        System.out.println("Enter string to match: ");
        String input = in.nextLine();
        if (input == null || input.equals(""))
            return;
        Matcher matcher = pattern.matcher(input);
        if (matcher.matches()) {
            System.out.println("Match");
            int g = matcher.groupCount();
            if (g > 0) {
                for (int i = 0; i < input.length(); i++) {
                    for (int j = 1; j <= g; j++)
                        if (i == matcher.start(j))
                            System.out.print('(');
                    System.out.print(input.charAt(i));
                    for (int j = 1; j <= g; j++)
                        if (i + 1 == matcher.end(j))
                            System.out.print(')');
                }
                System.out.println();
            }
        } else
            System.out.println("No match");
    }
}

From source file:de.citec.sc.matoll.process.Matoll_CreateMax.java

public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException,
        InstantiationException, IllegalAccessException, ClassNotFoundException, Exception {

    String directory;//from w w  w .  j  a  v  a2  s .  com
    String gold_standard_lexicon;
    String output_lexicon;
    String configFile;
    Language language;
    String output;

    Stopwords stopwords = new Stopwords();

    HashMap<String, Double> maxima;
    maxima = new HashMap<String, Double>();

    if (args.length < 3) {
        System.out.print("Usage: Matoll --mode=train/test <DIRECTORY> <CONFIG>\n");
        return;

    }

    //      Classifier classifier;

    directory = args[1];
    configFile = args[2];

    final Config config = new Config();

    config.loadFromFile(configFile);

    gold_standard_lexicon = config.getGoldStandardLexicon();

    String model_file = config.getModel();

    output_lexicon = config.getOutputLexicon();
    output = config.getOutput();

    language = config.getLanguage();

    LexiconLoader loader = new LexiconLoader();
    Lexicon gold = loader.loadFromFile(gold_standard_lexicon);

    Set<String> uris = new HashSet<>();
    //        Map<Integer,String> sentence_list = new HashMap<>();
    Map<Integer, Set<Integer>> mapping_words_sentences = new HashMap<>();

    //consider only properties
    for (LexicalEntry entry : gold.getEntries()) {
        try {
            for (Sense sense : entry.getSenseBehaviours().keySet()) {
                String tmp_uri = sense.getReference().getURI().replace("http://dbpedia.org/ontology/", "");
                if (!Character.isUpperCase(tmp_uri.charAt(0))) {
                    uris.add(sense.getReference().getURI());
                }
            }
        } catch (Exception e) {
        }
        ;
    }

    ModelPreprocessor preprocessor = new ModelPreprocessor(language);
    preprocessor.setCoreferenceResolution(false);
    Set<String> dep = new HashSet<>();
    dep.add("prep");
    dep.add("appos");
    dep.add("nn");
    dep.add("dobj");
    dep.add("pobj");
    dep.add("num");
    preprocessor.setDEP(dep);

    List<File> list_files = new ArrayList<>();

    if (config.getFiles().isEmpty()) {
        File folder = new File(directory);
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.toString().contains(".ttl"))
                list_files.add(file);
        }
    } else {
        list_files.addAll(config.getFiles());
    }
    System.out.println(list_files.size());

    int sentence_counter = 0;
    Map<String, Set<Integer>> bag_words_uri = new HashMap<>();
    Map<String, Integer> mapping_word_id = new HashMap<>();
    for (File file : list_files) {
        Model model = RDFDataMgr.loadModel(file.toString());
        for (Model sentence : getSentences(model)) {
            String reference = getReference(sentence);
            reference = reference.replace("http://dbpedia/", "http://dbpedia.org/");
            if (uris.contains(reference)) {
                sentence_counter += 1;
                Set<Integer> words_ids = getBagOfWords(sentence, stopwords, mapping_word_id);
                //TODO: add sentence preprocessing
                String obj = getObject(sentence);
                String subj = getSubject(sentence);
                preprocessor.preprocess(sentence, subj, obj, language);
                //TODO: also return marker if object or subject of property (in SPARQL this has to be optional of course)
                String parsed_sentence = getParsedSentence(sentence);
                try (FileWriter fw = new FileWriter("mapping_sentences_to_ids_goldstandard.tsv", true);
                        BufferedWriter bw = new BufferedWriter(fw);
                        PrintWriter out = new PrintWriter(bw)) {
                    out.println(sentence_counter + "\t" + parsed_sentence);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                for (Integer word_id : words_ids) {
                    if (mapping_words_sentences.containsKey(word_id)) {
                        Set<Integer> tmp_set = mapping_words_sentences.get(word_id);
                        tmp_set.add(sentence_counter);
                        mapping_words_sentences.put(word_id, tmp_set);

                    } else {
                        Set<Integer> tmp_set = new HashSet<>();
                        tmp_set.add(sentence_counter);
                        mapping_words_sentences.put(word_id, tmp_set);
                    }

                }
                if (bag_words_uri.containsKey(reference)) {
                    Set<Integer> tmp = bag_words_uri.get(reference);
                    for (Integer w : words_ids) {
                        tmp.add(w);

                    }
                    bag_words_uri.put(reference, tmp);
                } else {
                    Set<Integer> tmp = new HashSet<>();
                    for (Integer w : words_ids) {
                        tmp.add(w);
                    }
                    bag_words_uri.put(reference, tmp);
                }
            }

        }
        model.close();

    }

    PrintWriter writer = new PrintWriter("bag_of_words_only_goldstandard.tsv");
    StringBuilder string_builder = new StringBuilder();
    for (String r : bag_words_uri.keySet()) {
        string_builder.append(r);
        for (Integer i : bag_words_uri.get(r)) {
            string_builder.append("\t");
            string_builder.append(i);
        }
        string_builder.append("\n");
    }
    writer.write(string_builder.toString());
    writer.close();

    writer = new PrintWriter("mapping_words_to_sentenceids_goldstandard.tsv");
    string_builder = new StringBuilder();
    for (Integer w : mapping_words_sentences.keySet()) {
        string_builder.append(w);
        for (int i : mapping_words_sentences.get(w)) {
            string_builder.append("\t");
            string_builder.append(i);
        }
        string_builder.append("\n");
    }
    writer.write(string_builder.toString());
    writer.close();

}

From source file:at.tuwien.ifs.feature.evaluation.SimilarityRetrievalWriter.java

public static void main(String[] args) throws SOMToolboxException, IOException {
    // register and parse all options
    JSAPResult config = OptionFactory.parseResults(args, OPTIONS);
    File inputVectorFile = config.getFile("inputVectorFile");
    String outputDirStr = AbstractOptionFactory.getFilePath(config, "outputDirectory");
    File outputDirBase = new File(outputDirStr);
    outputDirBase.mkdirs();//from w ww.j  av  a 2s . c o m
    String metricName = config.getString("metric");
    DistanceMetric metric = AbstractMetric.instantiateNice(metricName);

    int neighbours = config.getInt("numberNeighbours");
    int startIndex = config.getInt("startIndex");
    int numberItems = config.getInt("numberItems", -1);

    try {
        SOMLibSparseInputData data = new SOMLibSparseInputData(inputVectorFile.getAbsolutePath());
        int endIndex = data.numVectors();
        if (numberItems != -1) {
            if (startIndex + numberItems > endIndex) {
                System.out.println("Specified number of items (" + numberItems + ") exceeds maximum ("
                        + data.numVectors() + "), limiting to " + (endIndex - startIndex) + ".");
            } else {
                endIndex = startIndex + numberItems;
            }
        }
        StdErrProgressWriter progress = new StdErrProgressWriter(endIndex - startIndex, "processing vector ");
        // SortedSet<InputDistance> distances;
        for (int inputDatumIndex = startIndex; inputDatumIndex < endIndex; inputDatumIndex++) {

            InputDatum inputDatum = data.getInputDatum(inputDatumIndex);
            String inputLabel = inputDatum.getLabel();
            if (inputDatumIndex == -1) {
                throw new IllegalArgumentException(
                        "Input with label '" + inputLabel + "' not found in vector file '" + inputVectorFile
                                + "'; possible labels are: " + StringUtils.toString(data.getLabels(), 15));
            }

            File outputDir = new File(outputDirBase,
                    inputLabel.charAt(2) + "/" + inputLabel.charAt(3) + "/" + inputLabel.charAt(4));
            outputDir.mkdirs();
            File outputFile = new File(outputDir, inputLabel + ".txt");

            boolean fileExistsAndValid = false;
            if (outputFile.exists()) {
                // check if it the valid data
                String linesInvalid = "";
                int validLineCount = 0;
                ArrayList<String> lines = FileUtils.readLinesAsList(outputFile.getAbsolutePath());
                for (String string : lines) {
                    if (string.trim().length() == 0) {
                        continue;
                    }
                    String[] parts = string.split("\t");
                    if (parts.length != 2) {
                        linesInvalid += "Line '" + string + "' invalid - contains " + parts.length
                                + " elements.\n";
                    } else if (!NumberUtils.isNumber(parts[1])) {
                        linesInvalid = "Line '" + string + "' invalid - 2nd part is not a number.\n";
                    } else {
                        validLineCount++;
                    }
                }
                if (validLineCount != neighbours) {
                    linesInvalid = "Not enough valid lines; expected " + neighbours + ", found "
                            + validLineCount + ".\n";
                }
                fileExistsAndValid = true;
                if (org.apache.commons.lang.StringUtils.isNotBlank(linesInvalid)) {
                    System.out.println("File " + outputFile.getAbsolutePath() + " exists, but is not valid:\n"
                            + linesInvalid);
                }
            }

            if (fileExistsAndValid) {
                Logger.getLogger("at.tuwien.ifs.feature.evaluation").finer(
                        "File " + outputFile.getAbsolutePath() + " exists and is valid; not recomputing");
            } else {
                PrintWriter p = new PrintWriter(outputFile);
                SmallestElementSet<InputDistance> distances = data.getNearestDistances(inputDatumIndex,
                        neighbours, metric);
                for (InputDistance inputDistance : distances) {
                    p.println(inputDistance.getInput().getLabel() + "\t" + inputDistance.getDistance());
                }
                p.close();
            }
            progress.progress();
        }

    } catch (IllegalArgumentException e) {
        System.out.println(e.getMessage() + ". Aborting.");
        System.exit(-1);
    }
}

From source file:com.mycompany.myelasticsearch.MainClass.java

/**
 * @param args the command line arguments
 *//*from  www. j  ava  2  s.  co m*/
public static void main(String[] args) {

    // TODO code application logic here
    Tika tika = new Tika();
    String fileEntry = "C:\\Contract\\Contract1.pdf";
    String filetype = tika.detect(fileEntry);
    System.out.println("FileType " + filetype);
    BodyContentHandler handler = new BodyContentHandler(-1);
    String text = "";
    Metadata metadata = new Metadata();

    FileInputStream inputstream = null;

    try {
        inputstream = new FileInputStream(fileEntry);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    ParseContext pcontext = new ParseContext();

    //parsing the document using PDF parser
    PDFParser pdfparser = new PDFParser();
    try {
        pdfparser.parse(inputstream, handler, metadata, pcontext);
    } catch (IOException ex) {

        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TikaException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    String docText = "";
    String outputArray[];
    String out[];
    //getting the content of the document
    docText = handler.toString().replaceAll("(/[^\\da-zA-Z.]/)", "");

    // PhraseDetection.getPhrases(docText);
    try {
        Node node = nodeBuilder().node();
        Client client = node.client();
        DocumentReader.parseString(docText, client);
        //"Borrowing should be replaced by the user input key"
        Elastic.getDefinedTerm(client, "definedterms", "term", "1", "Borrowing");
        node.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    Stanford.getSentence(docText);

    int definedTermsEnd = docText.indexOf("SCHEDULES");
    String toc = docText.substring(0, definedTermsEnd);
    String c = docText.substring(definedTermsEnd);

    System.out.println("Table of content" + toc);
    System.out.println("--------------------------------");
    System.out.println("content" + c);

    out = toc.split("Article|article|ARTICLE");
    int count = 0;
    String outputArrayString = "";
    int s = 0;
    StringBuffer tocOutput = new StringBuffer();

    for (String o : out) {
        if (count != 0) {
            s = Integer.parseInt(String.valueOf(o.charAt(1)));
            if (s == count) {
                tocOutput.append(o);
                tocOutput.append("JigarAnkitNeeraj");
                System.out.println(s);
            }
        }
        outputArrayString += "Count" + count + o;
        count++;
        System.out.println();
    }
    System.out.println("---------------------------------------------------Content---------");
    count = 1;
    StringBuffer contentOutput = new StringBuffer();

    String splitContent[] = c.split("ARTICLE|Article");
    Node node = nodeBuilder().node();
    Client client = node.client();
    for (String o : splitContent) {
        o = o.replaceAll("[^a-zA-Z0-9.,\\/#!$%\\^&\\*;:{}=\\-_`~()?\\s]+", "");
        o = o.replaceAll("\n", " ");
        char input = o.charAt(1);
        if (input >= '0' && input <= '9') {
            s = Integer.parseInt(String.valueOf(o.charAt(1)));
            if (s == count) {
                //System.out.println(s);
                JSONObject articleJSONObject = new JSONObject();
                contentOutput.append(" \n MyArticlesSeparated \n ");
                articleJSONObject.put("Article" + count, o.toString());
                try {
                    try {
                        JSONObject articleJSONObject1 = new JSONObject();
                        articleJSONObject1.put("hi", "j");
                        client.prepareIndex("contract", "article", String.valueOf(count))
                                .setSource(articleJSONObject.toString()).execute().actionGet();
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    //"Borrowing should be replaced by the user input key"

                } catch (Exception ex) {
                    Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.out.println(s);
                count++;
            }
            //outputArrayString += "Count" + count + o;

            contentOutput.append(o);
        }
    }
    Elastic.getDocument(client, "contract", "article", "1");
    Elastic.searchDocument(client, "contract", "article", "Lenders");
    Elastic.searchDocument(client, "contract", "article", "Negative Covenants");

    Elastic.searchDocument(client, "contract", "article", "Change in Law");
    String tableOfContent[];
    tableOfContent = tocOutput.toString().split("JigarAnkitNeeraj");

    String splitContectsAccordingToArticles[];
    splitContectsAccordingToArticles = contentOutput.toString().split("MyArticlesSeparated");
    int numberOfArticle = splitContectsAccordingToArticles.length;

    int countArticle = 1;
    Double toBeTruncated = new Double("" + countArticle + ".00");

    String section = "Section";
    toBeTruncated += 0.01;

    System.out.println(toBeTruncated);
    String sectionEnd;
    StringBuffer sectionOutput = new StringBuffer();
    int skipFirstArtcile = 0;
    JSONObject obj = new JSONObject();

    for (String article : splitContectsAccordingToArticles) {
        if (skipFirstArtcile != 0) {
            DecimalFormat f = new DecimalFormat("##.00");
            String sectionStart = section + " " + f.format(toBeTruncated);
            int start = article.indexOf(sectionStart);
            toBeTruncated += 0.01;

            System.out.println();
            sectionEnd = section + " " + f.format(toBeTruncated);

            int end = article.indexOf(sectionEnd);
            while (end != -1) {
                sectionStart = section + " " + f.format(toBeTruncated - 0.01);
                sectionOutput.append(" \n Key:" + sectionStart);
                if (start < end) {
                    sectionOutput.append("\n Value:" + article.substring(start, end));
                    obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " "));
                    try {
                        try {
                            JSONObject articleJSONObject1 = new JSONObject();
                            articleJSONObject1.put("hi", "j");
                            client.prepareIndex("contract", "section", String.valueOf(count))
                                    .setSource(obj.toString()).execute().actionGet();
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        }
                        //"Borrowing should be replaced by the user input key"

                    } catch (Exception ex) {
                        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }

                start = end;
                toBeTruncated += 0.01;
                sectionEnd = section + " " + f.format(toBeTruncated);
                System.out.println("SectionEnd " + sectionEnd);
                try {
                    end = article.indexOf(sectionEnd);
                } catch (Exception e) {
                    System.out.print(e.getMessage());
                }

                System.out.println("End section index " + end);
            }
            end = article.length() - 1;
            sectionOutput.append(" \n Key:" + sectionStart);
            try {
                sectionOutput.append(" \n Value:" + article.substring(start, end));
                obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " "));
            } catch (Exception e) {
                //What if Article has No Sections
                String numberOnly = article.replaceAll("[^0-9]", "").substring(0, 1);
                String sectionArticle = "ARTICLE " + numberOnly;
                sectionOutput.append(" \n Value:" + article);
                obj.put(sectionArticle, article);

                System.out.println(e.getMessage());
            }

            DecimalFormat ff = new DecimalFormat("##");
            toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01;
        }
        skipFirstArtcile++;
    }

    for (String article : splitContectsAccordingToArticles) {
        if (skipFirstArtcile != 0) {
            DecimalFormat f = new DecimalFormat("##.00");
            String sectionStart = section + " " + f.format(toBeTruncated);
            int start = article.indexOf(sectionStart);
            toBeTruncated += 0.01;
            System.out.println();
            sectionEnd = section + " " + f.format(toBeTruncated);

            int end = article.indexOf(sectionEnd);
            while (end != -1) {
                sectionStart = section + " " + f.format(toBeTruncated - 0.01);
                sectionOutput.append(" \n Key:" + sectionStart);
                if (start < end) {
                    sectionOutput.append("\n Value:" + article.substring(start, end));
                    System.out.println(sectionOutput);
                    String patternStr = "\\n\\n+[(]";
                    String paragraphSubstringArray[] = article.substring(start, end).split(patternStr);

                    JSONObject paragraphObject = new JSONObject();
                    int counter = 0;
                    for (String paragraphSubstring : paragraphSubstringArray) {
                        counter++;
                        paragraphObject.put("Paragraph " + counter, paragraphSubstring);

                    }
                    obj.put(sectionStart, paragraphObject);

                }

                start = end;
                toBeTruncated += 0.01;
                sectionEnd = section + " " + f.format(toBeTruncated);
                System.out.println("SectionEnd " + sectionEnd);
                try {
                    end = article.indexOf(sectionEnd);
                } catch (Exception e) {
                    System.out.print(e.getMessage());
                }

                System.out.println("End section index " + end);
            }
            end = article.length() - 1;
            sectionOutput.append(" \n Key:" + sectionStart);
            try {
                sectionOutput.append(" \n Value:" + article.substring(start, end));
                obj.put(sectionStart, article.substring(start, end));
                PhraseDetection.getPhrases(docText);
            } catch (Exception e) {
                //What if Article has No Sections
                String sectionArticle = "ARTICLE";
                System.out.println(e.getMessage());
            }
            DecimalFormat ff = new DecimalFormat("##");
            toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01;
        }
        skipFirstArtcile++;
    }

    Elastic.getDocument(client, "contract", "section", "1");
    Elastic.searchDocument(client, "contract", "section", "Lenders");
    Elastic.searchDocument(client, "contract", "section", "Negative Covenants");
    try {
        FileWriter file = new FileWriter("TableOfIndex.txt");
        file.write(tocOutput.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        FileWriter file = new FileWriter("Contract3_JSONFile.txt");
        file.write(obj.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        FileWriter file = new FileWriter("Contract1_KeyValueSections.txt");
        file.write(sectionOutput.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ZipImploder.java

/**
 * Main command line entry point.//  w  w  w  .j ava 2  s . co m
 * 
 * @param args
 */
public static void main(final String[] args) {
    if (args.length == 0) {
        printHelp();
        System.exit(0);
    }
    String zipName = null;
    String jarName = null;
    String manName = null;
    String sourceDir = null;
    String leadDir = null;
    boolean jarActive = false, manActive = false, zipActive = false, sourceDirActive = false,
            leadDirActive = false;
    boolean verbose = false;
    boolean noDirs = 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;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("manifest")) {
                jarActive = false;
                manActive = true;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("zip")) {
                zipActive = true;
                manActive = false;
                jarActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("dir")) {
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = true;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("lead")) {
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = true;
            } else if (arg.equalsIgnoreCase("noDirs")) {
                noDirs = true;
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("verbose")) {
                verbose = true;
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else {
                reportError("Invalid switch - " + arg);
            }
        } else {
            if (jarActive) {
                if (jarName != null) {
                    reportError("Duplicate value - " + arg);
                }
                jarName = arg;
            } else if (manActive) {
                if (manName != null) {
                    reportError("Duplicate value - " + arg);
                }
                manName = arg;
            } else if (zipActive) {
                if (zipName != null) {
                    reportError("Duplicate value - " + arg);
                }
                zipName = arg;
            } else if (sourceDirActive) {
                if (sourceDir != null) {
                    reportError("Duplicate value - " + arg);
                }
                sourceDir = arg;
            } else if (leadDirActive) {
                if (leadDir != null) {
                    reportError("Duplicate value - " + arg);
                }
                leadDir = arg;
            } else {
                reportError("Too many parameters - " + arg);
            }
        }
    }
    if (sourceDir == null || (zipName == null && jarName == null)) {
        reportError("Missing parameters");
    }
    if (manName != null && zipName != null) {
        reportError("Manifests not supported on ZIP files");
    }
    if (leadDir == null) {
        leadDir = new File(sourceDir).getAbsolutePath().replace('\\', '/') + '/';
    }
    if (verbose) {
        System.out.println("Effective command: " + ZipImploder.class.getName()
                + (jarName != null ? " -jar " + jarName + (manName != null ? " -manifest " + manName : "") : "")
                + (zipName != null ? " -zip " + zipName : "") + " -dir " + sourceDir + " -lead " + leadDir
                + (noDirs ? " -noDirs" : "") + (verbose ? " -verbose" : ""));
    }
    try {
        ZipImploder zi = new ZipImploder(verbose);
        if (leadDir != null) {
            zi.setBaseDir(leadDir);
        }
        if (manName != null) {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(manName));
            try {
                zi.setManifest(new Manifest(bis));
            } finally {
                bis.close();
            }
        }
        zi.setIncludeDirs(!noDirs);
        zi.process(zipName, jarName, sourceDir);
        if (verbose) {
            System.out.println("\nDone Directories=" + zi.getDirCount() + " Files=" + zi.getFileCount());
        }
    } catch (IOException ioe) {
        System.err.println("Exception - " + ioe.getMessage());
        // ioe.printStackTrace(); // *** debug ***
        System.exit(2);
    }
}