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:org.eclipse.lyo.client.oslc.samples.DoorsOauthSample.java

/**
 * Login to the DWA server and perform some OSLC actions
 * @param args//from w ww.  j a  v a 2  s . com
 * @throws ParseException 
 */
public static void main(String[] args) throws ParseException {

    Options options = new Options();

    options.addOption("url", true, "url");
    options.addOption("user", true, "user ID");
    options.addOption("password", true, "password");
    options.addOption("project", true, "project area");

    CommandLineParser cliParser = new GnuParser();

    //Parse the command line
    CommandLine cmd = cliParser.parse(options, args);

    if (!validateOptions(cmd)) {
        logger.severe(
                "Syntax:  java <class_name> -url https://<server>:port/<context>/ -user <user> -password <password> -project \"<project_area>\"");
        logger.severe(
                "Example: java DoorsOauthSample -url https://exmple.com:9443/dwa -user ADMIN -password ADMIN -project \"JKE Banking (Requirements Management)\"");
        return;
    }

    String webContextUrl = cmd.getOptionValue("url");
    String user = cmd.getOptionValue("user");
    String passwd = cmd.getOptionValue("password");
    String projectArea = cmd.getOptionValue("project");

    try {

        //STEP 1: Initialize a Jazz rootservices helper and indicate we're looking for the RequirementManagement catalog
        // The root services for DOORs is found at /public level
        JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl + "/public",
                OSLCConstants.OSLC_RM_V2);

        //STEP 2: Create a new OSLC OAuth capable client, the parameter of following call should be provided
        // by the system administrator of the DOORs Web Access server
        OslcOAuthClient client = helper.initOAuthClient("1234567890", "123");

        if (client != null) {

            //STEP 3: Try to access the context URL to trigger the OAuth dance and login
            try {
                client.getResource(webContextUrl, OSLCConstants.CT_RDF);
            } catch (OAuthRedirectException oauthE) {
                validateTokens(client,
                        oauthE.getRedirectURL() + "?oauth_token=" + oauthE.getAccessor().requestToken, user,
                        passwd, webContextUrl + "/j_acegi_security_check");
                // Try to access again
                ClientResponse response = client.getResource(webContextUrl, OSLCConstants.CT_RDF);
                response.getEntity(InputStream.class).close();
            }

            //STEP 4: Get the URL of the OSLC catalog
            String catalogUrl = helper.getCatalogUrl();

            //STEP 5: Find the OSLC Service Provider for the project area we want to work with
            String serviceProviderUrl = lookupServiceProviderUrl(catalogUrl, "Services for " + projectArea,
                    client);

            //STEP 6: Get the Query Capabilities URL so that we can run some OSLC queries
            String queryCapability = client.lookupQueryCapability(serviceProviderUrl, OSLCConstants.OSLC_RM_V2,
                    OSLCConstants.RM_REQUIREMENT_TYPE);

            //STEP 7: Get the Creation Factory URL for default Requirements so that we can create one
            Requirement requirement = new Requirement();
            String requirementFactory = client.lookupCreationFactory(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, requirement.getRdfTypes()[0].toString());

            //STEP 8 Get the default Requirement Type URL
            ResourceShape reqInstanceShape = RmUtil.lookupRequirementsInstanceShapes(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, requirement.getRdfTypes()[0].toString(), client,
                    "Resource shape for a requirement in the " + projectArea);

            if ((reqInstanceShape != null) && (requirementFactory != null)) {
                //STEP 9: Create a Requirement
                requirement.setInstanceShape(reqInstanceShape.getAbout());
                // Add a link
                requirement.addImplementedBy(
                        new Link(new URI("http://google.com"), "Link created by an Eclipse Lyo user"));
                requirement.setDescription("Created By EclipseLyo");

                // Add the PrimaryText
                String primaryText = "My Eclipse Lyo CREATED Primary Text";
                Element obj = RmUtil.convertStringToHTML(primaryText);
                requirement.getExtendedProperties().put(RmConstants.PROPERTY_PRIMARY_TEXT, obj);

                //Create the Requirement
                ClientResponse creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                String req01URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);

                creationResponse.consumeContent();
            }

            //STEP 10: Query of changed values
            OslcQueryParameters queryParams = new OslcQueryParameters();
            queryParams.setPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams.setWhere("oslc_rm:implementedBy=<http://google.com>");
            OslcQuery query = new OslcQuery(client, queryCapability, 10, queryParams);
            OslcQueryResult result = query.submit();
            boolean processAsJavaObjects = false;
            int resultsSize = result.getMembersUrls().length;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for query 1 = " + resultsSize + "\n");

            //STEP 11: Now get the artifact with identifier = 9 
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("dcterms=<http://purl.org/dc/terms/>");
            queryParams.setWhere("dcterms:identifier=9");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            String requirementURL = null;
            // Get the URL of returned requirement
            if (result != null) {
                String[] returnedURLS = result.getMembersUrls();
                if ((returnedURLS != null) && (returnedURLS.length > 0)) {
                    requirementURL = returnedURLS[0];
                }
            }

            // STEP 12 If requirement found, lets get it an modify
            if (requirementURL != null) {
                // Get the requirement
                ClientResponse getResponse = client.getResource(requirementURL,
                        OslcMediaType.APPLICATION_RDF_XML);
                requirement = getResponse.getEntity(Requirement.class);
                // Get the eTAG, we need it to update
                String etag = getResponse.getHeaders().getFirst(OSLCConstants.ETAG);
                getResponse.consumeContent();

                // Following code is needed to workaround an issue in DWA that exposes the Heading inf as encoded XML
                {
                    // Get the type for "Object Heading"
                    org.eclipse.lyo.oslc4j.core.model.Property[] properties = reqInstanceShape.getProperties();
                    String attrDef = null;
                    for (org.eclipse.lyo.oslc4j.core.model.Property property : properties) {
                        if (property.getTitle().equalsIgnoreCase("Object Heading")) {
                            attrDef = property.getPropertyDefinition().toString();
                        }
                    }
                    if (attrDef != null) {
                        String url = attrDef.substring(0, attrDef.lastIndexOf("/") + 1);
                        String name = attrDef.substring(attrDef.lastIndexOf("/") + 1);
                        // QName attr12Name = new QName("https://slot12.gdl.mex.ibm.com:8443/dwa/rm/urn:rational::1-514b30b9627b2a31-M-00000062/types/", "attrDef-12");
                        QName attr12Name = new QName(url, name);
                        String attr12 = (String) requirement.getExtendedProperties().get(attr12Name);
                        attr12 = removeXMLEscape(attr12);
                        Element objattr12 = RmUtil.convertStringToHTML(attr12);
                        requirement.getExtendedProperties().put(attr12Name, objattr12);
                    }
                }

                // Change the Primary text
                String primaryText = "My Eclipse Lyo CHANGED Primary Text";
                // Put in the proper object ( Element for XML Strings )
                Element obj = RmUtil.convertStringToHTML(primaryText);
                requirement.getExtendedProperties().put(RmConstants.PROPERTY_PRIMARY_TEXT, obj);

                // Add a couple of links 
                requirement.addImplementedBy(new Link(new URI("http://google.com"), "ImplementedBy example"));
                requirement.addElaboratedBy(new Link(new URI("http://terra.com.mx"), "ElaboratedBy example"));
                // Update the requirement with the proper etag 
                ClientResponse updateResponse = client.updateResource(requirementURL, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML, etag);

                updateResponse.consumeContent();
            }

        }
    } catch (RootServicesException re) {
        logger.log(Level.SEVERE,
                "Unable to access the Jazz rootservices document at: " + webContextUrl + "/public/rootservices",
                re);
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:fr.tpt.s3.mcdag.generator.MainGenerator.java

/**
 * Main method for the generator: it launches a given number of threads with the parameters
 * given//from www  .  ja v  a2s.c o  m
 * @param args
 */
public static void main(String[] args) {

    /* ============================ Command line ================= */
    Options options = new Options();

    Option o_hi = new Option("mu", "max_utilization", true, "Upper bound utilization");
    o_hi.setRequired(true);
    options.addOption(o_hi);

    Option o_tasks = new Option("nt", "nb_tasks", true, "Number of tasks for the system");
    o_tasks.setRequired(true);
    options.addOption(o_tasks);

    Option o_eprob = new Option("e", "eprobability", true, "Probability of edges");
    o_eprob.setRequired(true);
    options.addOption(o_eprob);

    Option o_levels = new Option("l", "levels", true, "Number of criticality levels");
    o_levels.setRequired(true);
    options.addOption(o_levels);

    Option o_para = new Option("p", "parallelism", true, "Max parallelism for the DAGs");
    o_para.setRequired(true);
    options.addOption(o_para);

    Option o_nbdags = new Option("nd", "num_dags", true, "Number of DAGs");
    o_nbdags.setRequired(true);
    options.addOption(o_nbdags);

    Option o_nbfiles = new Option("nf", "num_files", true, "Number of files");
    o_nbfiles.setRequired(true);
    options.addOption(o_nbfiles);

    Option o_rfactor = new Option("rf", "reduc_factor", true, "Reduction factor for criticality modes");
    o_rfactor.setRequired(false);
    options.addOption(o_rfactor);

    Option o_out = new Option("o", "output", true, "Output file for the DAG");
    o_out.setRequired(true);
    options.addOption(o_out);

    Option graphOpt = new Option("g", "graphviz", false, "Generate a graphviz DOT file");
    graphOpt.setRequired(false);
    options.addOption(graphOpt);

    Option debugOpt = new Option("d", "debug", false, "Enabling debug");
    debugOpt.setRequired(false);
    options.addOption(debugOpt);

    Option jobsOpt = new Option("j", "jobs", true, "Number of jobs");
    jobsOpt.setRequired(false);
    options.addOption(jobsOpt);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("DAG Generator", options);

        System.exit(1);
        return;
    }

    double maxU = Double.parseDouble(cmd.getOptionValue("max_utilization"));
    int edgeProb = Integer.parseInt(cmd.getOptionValue("eprobability"));
    int levels = Integer.parseInt(cmd.getOptionValue("levels"));
    int nbDags = Integer.parseInt(cmd.getOptionValue("num_dags"));
    int nbFiles = Integer.parseInt(cmd.getOptionValue("num_files"));
    int para = Integer.parseInt(cmd.getOptionValue("parallelism"));
    int nbTasks = Integer.parseInt(cmd.getOptionValue("nb_tasks"));
    boolean graph = cmd.hasOption("graphviz");
    boolean debug = cmd.hasOption("debug");
    String output = cmd.getOptionValue("output");
    int nbJobs = 1;
    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));
    double rfactor = 2.0;
    if (cmd.hasOption("reduc_factor"))
        rfactor = Double.parseDouble(cmd.getOptionValue("reduc_factor"));
    /* ============================= Generator parameters ============================= */

    if (nbFiles < 0 || nbDags < 0 || nbJobs < 0) {
        System.err.println("[ERROR] Generator: Number of files & DAGs need to be positive.");
        formatter.printHelp("DAG Generator", options);
        System.exit(1);
        return;
    }

    Thread threads[] = new Thread[nbJobs];

    int nbFilesCreated = 0;
    int count = 0;

    while (nbFilesCreated != nbFiles) {
        int launched = 0;

        for (int i = 0; i < nbJobs && count < nbFiles; i++) {
            String outFile = output.substring(0, output.lastIndexOf('.')).concat("-" + count + ".xml");
            GeneratorThread gt = new GeneratorThread(maxU, nbTasks, edgeProb, levels, para, nbDags, rfactor,
                    outFile, graph, debug);
            threads[i] = new Thread(gt);
            threads[i].setName("GeneratorThread-" + i);
            launched++;
            count++;
            threads[i].start();
        }

        for (int i = 0; i < launched; i++) {
            try {
                threads[i].join();
                nbFilesCreated++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:net.yacy.yacy.java

/**
 * Main-method which is started by java. Checks for special arguments or
 * starts up the application./*from   w  w  w . j  av  a  2  s . com*/
 *
 * @param args
 *            Given arguments from the command line.
 */
public static void main(String args[]) {

    try {
        // check assertion status
        //ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
        boolean assertionenabled = false;
        assert (assertionenabled = true) == true; // compare to true to remove warning: "Possible accidental assignement"
        if (assertionenabled)
            System.out.println("Asserts are enabled");

        // check memory amount
        System.gc();
        final long startupMemFree = MemoryControl.free();
        final long startupMemTotal = MemoryControl.total();

        // maybe go into headless awt mode: we have three cases depending on OS and one exception:
        // windows   : better do not go into headless mode
        // mac       : go into headless mode because an application is shown in gui which may not be wanted
        // linux     : go into headless mode because this does not need any head operation
        // exception : if the -gui option is used then do not go into headless mode since that uses a gui
        boolean headless = true;
        if (OS.isWindows)
            headless = false;
        if (args.length >= 1 && args[0].toLowerCase(Locale.ROOT).equals("-gui"))
            headless = false;
        System.setProperty("java.awt.headless", headless ? "true" : "false");

        String s = "";
        for (final String a : args)
            s += a + " ";
        yacyRelease.startParameter = s.trim();

        File applicationRoot = new File(System.getProperty("user.dir").replace('\\', '/'));
        File dataRoot = applicationRoot;
        //System.out.println("args.length=" + args.length);
        //System.out.print("args=["); for (int i = 0; i < args.length; i++) System.out.print(args[i] + ", "); System.out.println("]");
        if ((args.length >= 1)
                && (args[0].toLowerCase(Locale.ROOT).equals("-startup") || args[0].equals("-start"))) {
            // normal start-up of yacy
            if (args.length > 1) {
                if (args[1].startsWith(File.separator)) {
                    /* data root folder provided as an absolute path */
                    dataRoot = new File(args[1]);
                } else {
                    /* data root folder provided as a path relative to the user home folder */
                    dataRoot = new File(System.getProperty("user.home").replace('\\', '/'), args[1]);
                }
            }
            preReadSavedConfigandInit(dataRoot);
            startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, false);
        } else if (args.length >= 1 && args[0].toLowerCase(Locale.ROOT).equals("-gui")) {
            // start-up of yacy with gui
            if (args.length > 1) {
                if (args[1].startsWith(File.separator)) {
                    /* data root folder provided as an absolute path */
                    dataRoot = new File(args[1]);
                } else {
                    /* data root folder provided as a path relative to the user home folder */
                    dataRoot = new File(System.getProperty("user.home").replace('\\', '/'), args[1]);
                }
            }
            preReadSavedConfigandInit(dataRoot);
            startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, true);
        } else if ((args.length >= 1)
                && ((args[0].toLowerCase(Locale.ROOT).equals("-shutdown")) || (args[0].equals("-stop")))) {
            // normal shutdown of yacy
            if (args.length == 2)
                applicationRoot = new File(args[1]);
            shutdown(applicationRoot);
        } else if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-update"))) {
            // aut-update yacy
            if (args.length == 2)
                applicationRoot = new File(args[1]);
            update(applicationRoot);
        } else if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-version"))) {
            // show yacy version
            System.out.println(copyright);
        } else if ((args.length > 1) && (args[0].toLowerCase(Locale.ROOT).equals("-config"))) {
            // set config parameter. Special handling of adminAccount=user:pwd (generates md5 encoded password)
            // on Windows parameter should be enclosed in doublequotes to accept = sign (e.g. -config "port=8090" "port.ssl=8043")
            File f = new File(dataRoot, "DATA/SETTINGS/");
            if (!f.exists()) {
                mkdirsIfNeseccary(f);
            } else {
                if (new File(dataRoot, "DATA/yacy.running").exists()) {
                    System.out.println("please restart YaCy");
                }
            }
            // use serverSwitch to read config properties (including init values from yacy.init
            serverSwitch ss = new serverSwitch(dataRoot, applicationRoot, "defaults/yacy.init",
                    "DATA/SETTINGS/yacy.conf");

            for (int icnt = 1; icnt < args.length; icnt++) {
                String cfg = args[icnt];
                int pos = cfg.indexOf('=');
                if (pos > 0) {
                    String cmd = cfg.substring(0, pos);
                    String val = cfg.substring(pos + 1);

                    if (!val.isEmpty()) {
                        if (cmd.equalsIgnoreCase(SwitchboardConstants.ADMIN_ACCOUNT)) { // special command to set adminusername and md5-pwd
                            int cpos = val.indexOf(':'); //format adminAccount=adminname:adminpwd
                            if (cpos >= 0) {
                                String username = val.substring(0, cpos);
                                String pwdtxt = val.substring(cpos + 1);
                                if (!username.isEmpty()) {
                                    ss.setConfig(SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME, username);
                                    System.out.println("Set property "
                                            + SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME + " = " + username);
                                } else {
                                    username = ss.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME,
                                            "admin");
                                }
                                ss.setConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5,
                                        "MD5:" + Digest.encodeMD5Hex(username + ":"
                                                + ss.getConfig(SwitchboardConstants.ADMIN_REALM, "YaCy") + ":"
                                                + pwdtxt));
                                System.out.println("Set property " + SwitchboardConstants.ADMIN_ACCOUNT_B64MD5
                                        + " = " + ss.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, ""));
                            }
                        } else {
                            ss.setConfig(cmd, val);
                            System.out.println("Set property " + cmd + " = " + val);
                        }
                    }
                } else {
                    System.out.println(
                            "skip parameter " + cfg + " (equal sign missing, put parameter in doublequotes)");
                }
                System.out.println();
            }
        } else {
            if (args.length == 1) {
                applicationRoot = new File(args[0]);
            }
            preReadSavedConfigandInit(dataRoot);
            startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, false);
        }
    } finally {
        ConcurrentLog.shutdown();
    }
}

From source file:de.gbv.ole.Marc21ToOleBulk.java

/**
 * Convertiert eine MARC21-Datei in eine MarcXML-Bulk-Import-SQL-Datei.
 * @param args      Pfad mit auf .mrc endendem Dateinamen der MARC21-Datei.
 * @throws IOException      Fehler beim Dateilesen oder -schreiben
 *//*from   w w  w.  j av  a2 s.c  o  m*/
public static void main(final String[] args) throws IOException {
    if (args.length < 1 || args.length > 2) {
        usageExit();
    }

    boolean ppn5 = false;
    if (args.length == 2) {
        if ("-5".equals(args[0])) {
            ppn5 = true;
        } else {
            usageExit();
        }
    }
    String infile = args[args.length - 1];

    if (!infile.endsWith(MRCSUFFIX)) {
        System.err.println("Filename ending in .mrc expected, " + "but found filename: " + infile);
        usageExit();
    }

    InputStream in = new FileInputStream(infile);
    MarcStreamReader reader = new MarcStreamReader(in);

    String filename = infile.substring(0, infile.length() - MRCSUFFIX.length());
    Writer bib = utf8Writer(filename + "-bib.sql");
    Writer holdings = utf8Writer(filename + "-holdings.sql");
    Writer item = utf8Writer(filename + "-item.sql");

    while (reader.hasNext()) {
        MarcWriter writer = new Marc21ToOleBulk(bib, holdings, item, ppn5);
        writer.write(reader.next());
        writer.close();
    }

    in.close();
    item.close();
    holdings.close();
    bib.close();
}

From source file:Gen.java

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

    try {//from   ww  w . j a  v  a  2s . c  o  m

        File[] files = null;
        if (System.getProperty("dir") != null && !System.getProperty("dir").equals("")) {
            files = new File(System.getProperty("dir")).listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.toUpperCase().endsWith(".XML");
                };
            });
        } else {
            String fileName = System.getProperty("file") != null && !System.getProperty("file").equals("")
                    ? System.getProperty("file")
                    : "rjmap.xml";
            files = new File[] { new File(fileName) };
        }

        log.info("files : " + Arrays.toString(files));

        if (files == null || files.length == 0) {
            log.info("no files to parse");
            System.exit(0);
        }

        boolean formatsource = true;
        if (System.getProperty("formatsource") != null && !System.getProperty("formatsource").equals("")
                && System.getProperty("formatsource").equalsIgnoreCase("false")) {
            formatsource = false;
        }

        GEN_ROOT = System.getProperty("outputdir");

        if (GEN_ROOT == null || GEN_ROOT.equals("")) {
            GEN_ROOT = new File(files[0].getAbsolutePath()).getParent() + FILE_SEPARATOR + "distrib";
        }

        GEN_ROOT = new File(GEN_ROOT).getAbsolutePath().replace('\\', '/');
        if (GEN_ROOT.endsWith("/"))
            GEN_ROOT = GEN_ROOT.substring(0, GEN_ROOT.length() - 1);

        System.out.println("GEN ROOT:" + GEN_ROOT);

        MAPPING_JAR_NAME = System.getProperty("mappingjar") != null
                && !System.getProperty("mappingjar").equals("") ? System.getProperty("mappingjar")
                        : "mapping.jar";
        if (!MAPPING_JAR_NAME.endsWith(".jar"))
            MAPPING_JAR_NAME += ".jar";

        GEN_ROOT_SRC = GEN_ROOT + FILE_SEPARATOR + "src";
        GEN_ROOT_LIB = GEN_ROOT + FILE_SEPARATOR + "";

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        domFactory.setValidating(false);
        DocumentBuilder documentBuilder = domFactory.newDocumentBuilder();

        for (int f = 0; f < files.length; ++f) {
            log.info("parsing file : " + files[f]);
            Document document = documentBuilder.parse(files[f]);

            Vector<Node> initNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "initScript",
                    initNodes);
            for (int i = 0; i < initNodes.size(); ++i) {
                NamedNodeMap attrs = initNodes.elementAt(i).getAttributes();
                boolean embed = attrs.getNamedItem("embed") != null
                        && attrs.getNamedItem("embed").getNodeValue().equalsIgnoreCase("true");
                StringBuffer vbuffer = new StringBuffer();
                if (attrs.getNamedItem("inline") != null) {
                    vbuffer.append(attrs.getNamedItem("inline").getNodeValue());
                    vbuffer.append('\n');
                } else {
                    String fname = attrs.getNamedItem("name").getNodeValue();
                    if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') {
                        String path = files[f].getAbsolutePath();
                        path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR));
                        fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath();
                    }
                    vbuffer.append(Utils.getFileAsStringBuffer(fname));
                }
                initScriptBuffer.append(vbuffer);
                if (embed)
                    embedScriptBuffer.append(vbuffer);
            }

            Vector<Node> packageInitNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "packageScript",
                    packageInitNodes);
            for (int i = 0; i < packageInitNodes.size(); ++i) {
                NamedNodeMap attrs = packageInitNodes.elementAt(i).getAttributes();
                String packageName = attrs.getNamedItem("package").getNodeValue();

                if (packageName.equals(""))
                    packageName = "rGlobalEnv";

                if (!packageName.endsWith("Function"))
                    packageName += "Function";
                if (packageEmbedScriptHashMap.get(packageName) == null) {
                    packageEmbedScriptHashMap.put(packageName, new StringBuffer());
                }
                StringBuffer vbuffer = packageEmbedScriptHashMap.get(packageName);

                // if (!packageName.equals("rGlobalEnvFunction")) {
                // vbuffer.append("library("+packageName.substring(0,packageName.lastIndexOf("Function"))+")\n");
                // }

                if (attrs.getNamedItem("inline") != null) {
                    vbuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n");
                    initScriptBuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n");
                } else {
                    String fname = attrs.getNamedItem("name").getNodeValue();
                    if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') {
                        String path = files[f].getAbsolutePath();
                        path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR));
                        fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath();
                    }
                    StringBuffer fileBuffer = Utils.getFileAsStringBuffer(fname);
                    vbuffer.append(fileBuffer);
                    initScriptBuffer.append(fileBuffer);
                }
            }

            Vector<Node> functionsNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "functions"), "function",
                    functionsNodes);
            for (int i = 0; i < functionsNodes.size(); ++i) {
                NamedNodeMap attrs = functionsNodes.elementAt(i).getAttributes();
                String functionName = attrs.getNamedItem("name").getNodeValue();

                boolean forWeb = attrs.getNamedItem("forWeb") != null
                        && attrs.getNamedItem("forWeb").getNodeValue().equalsIgnoreCase("true");

                String signature = (attrs.getNamedItem("signature") == null ? ""
                        : attrs.getNamedItem("signature").getNodeValue() + ",");
                String renameTo = (attrs.getNamedItem("renameTo") == null ? null
                        : attrs.getNamedItem("renameTo").getNodeValue());

                HashMap<String, FAttributes> sigMap = Globals._functionsToPublish.get(functionName);

                if (sigMap == null) {
                    sigMap = new HashMap<String, FAttributes>();
                    Globals._functionsToPublish.put(functionName, sigMap);

                    if (attrs.getNamedItem("returnType") == null) {
                        _functionsVector.add(new String[] { functionName });
                    } else {
                        _functionsVector.add(
                                new String[] { functionName, attrs.getNamedItem("returnType").getNodeValue() });
                    }

                }

                sigMap.put(signature, new FAttributes(renameTo, forWeb));

                if (forWeb)
                    _webPublishingEnabled = true;

            }

            if (System.getProperty("targetjdk") != null && !System.getProperty("targetjdk").equals("")
                    && System.getProperty("targetjdk").compareTo("1.5") < 0) {
                if (_webPublishingEnabled || (System.getProperty("ws.r.api") != null
                        && System.getProperty("ws.r.api").equalsIgnoreCase("true"))) {
                    log.info("be careful, web publishing disabled beacuse target JDK<1.5");
                }
                _webPublishingEnabled = false;
            } else {

                if (System.getProperty("ws.r.api") == null || System.getProperty("ws.r.api").equals("")
                        || !System.getProperty("ws.r.api").equalsIgnoreCase("false")) {
                    _webPublishingEnabled = true;
                }

                if (_webPublishingEnabled && System.getProperty("java.version").compareTo("1.5") < 0) {
                    log.info("be careful, web publishing disabled beacuse a JDK<1.5 is in use");
                    _webPublishingEnabled = false;
                }
            }

            Vector<Node> s4Nodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "s4classes"), "class", s4Nodes);

            if (s4Nodes.size() > 0) {
                String formalArgs = "";
                String signature = "";
                for (int i = 0; i < s4Nodes.size(); ++i) {
                    NamedNodeMap attrs = s4Nodes.elementAt(i).getAttributes();
                    String s4Name = attrs.getNamedItem("name").getNodeValue();
                    formalArgs += "p" + i + (i == s4Nodes.size() - 1 ? "" : ",");
                    signature += "'" + s4Name + "'" + (i == s4Nodes.size() - 1 ? "" : ",");
                }
                String genBeansScriptlet = "setGeneric('" + PUBLISH_S4_HEADER + "', function(" + formalArgs
                        + ") standardGeneric('" + PUBLISH_S4_HEADER + "'));" + "setMethod('" + PUBLISH_S4_HEADER
                        + "', signature(" + signature + ") , function(" + formalArgs + ") {   })";
                initScriptBuffer.append(genBeansScriptlet);
                _functionsVector.add(new String[] { PUBLISH_S4_HEADER, "numeric" });
            }

        }

        if (!new File(GEN_ROOT_LIB).exists())
            regenerateDir(GEN_ROOT_LIB);
        else {
            clean(GEN_ROOT_LIB, true);
        }

        for (int i = 0; i < rwebservicesScripts.length; ++i)
            DirectJNI.getInstance().getRServices().sourceFromResource(rwebservicesScripts[i]);

        String lastStatus = DirectJNI.getInstance().runR(new ExecutionUnit() {
            public void run(Rengine e) {
                DirectJNI.getInstance().toggleMarker();
                DirectJNI.getInstance().sourceFromBuffer(initScriptBuffer.toString());
                log.info(" init  script status : " + DirectJNI.getInstance().cutStatusSinceMarker());

                for (int i = 0; i < _functionsVector.size(); ++i) {

                    String[] functionPair = _functionsVector.elementAt(i);
                    log.info("dealing with : " + functionPair[0]);

                    regenerateDir(GEN_ROOT_SRC);

                    String createMapStr = "createMap(";
                    boolean isGeneric = e.rniGetBoolArrayI(
                            e.rniEval(e.rniParse("isGeneric(\"" + functionPair[0] + "\")", 1), 0))[0] == 1;

                    log.info("is Generic : " + isGeneric);
                    if (isGeneric) {
                        createMapStr += functionPair[0];
                    } else {
                        createMapStr += "\"" + functionPair[0] + "\"";
                    }
                    createMapStr += ", outputDirectory=\"" + GEN_ROOT_SRC
                            .substring(0, GEN_ROOT_SRC.length() - "/src".length()).replace('\\', '/') + "\"";
                    createMapStr += ", typeMode=\"robject\"";
                    createMapStr += (functionPair.length == 1 || functionPair[1] == null
                            || functionPair[1].trim().equals("") ? ""
                                    : ", S4DefaultTypedSig=TypedSignature(returnType=\"" + functionPair[1]
                                            + "\")");
                    createMapStr += ")";

                    log.info("------------------------------------------");
                    log.info("-- createMapStr=" + createMapStr);
                    DirectJNI.getInstance().toggleMarker();
                    e.rniEval(e.rniParse(createMapStr, 1), 0);
                    String createMapStatus = DirectJNI.getInstance().cutStatusSinceMarker();
                    log.info(" createMap status : " + createMapStatus);
                    log.info("------------------------------------------");

                    deleteDir(GEN_ROOT_SRC + "/org/kchine/r/rserviceJms");
                    compile(GEN_ROOT_SRC);
                    jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", null);

                    URL url = null;
                    try {
                        url = new URL(
                                "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar")
                                        .replace('\\', '/') + "!/");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    DirectJNI.generateMaps(url, true);
                }

            }
        });

        log.info(lastStatus);

        log.info(DirectJNI._rPackageInterfacesHash);
        regenerateDir(GEN_ROOT_SRC);
        for (int i = 0; i < _functionsVector.size(); ++i) {
            unjar(GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", GEN_ROOT_SRC);
        }

        regenerateRPackageClass(true);

        generateS4BeanRef();

        if (formatsource)
            applyJalopy(GEN_ROOT_SRC);

        compile(GEN_ROOT_SRC);

        for (String k : DirectJNI._rPackageInterfacesHash.keySet()) {
            Rmic rmicTask = new Rmic();
            rmicTask.setProject(_project);
            rmicTask.setTaskName("rmic_packages");
            rmicTask.setClasspath(new Path(_project, GEN_ROOT_SRC));
            rmicTask.setBase(new File(GEN_ROOT_SRC));
            rmicTask.setClassname(k + "ImplRemote");
            rmicTask.init();
            rmicTask.execute();
        }

        // DirectJNI._rPackageInterfacesHash=new HashMap<String,
        // Vector<Class<?>>>();
        // DirectJNI._rPackageInterfacesHash.put("org.bioconductor.packages.rGlobalEnv.rGlobalEnvFunction",new
        // Vector<Class<?>>());

        if (_webPublishingEnabled) {

            jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar", null);
            URL url = new URL(
                    "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").replace('\\', '/') + "!/");
            ClassLoader cl = new URLClassLoader(new URL[] { url }, Globals.class.getClassLoader());

            for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
                if (cl.loadClass(className + "Web").getDeclaredMethods().length == 0)
                    continue;
                log.info("######## " + className);

                WsGen wsgenTask = new WsGen();
                wsgenTask.setProject(_project);
                wsgenTask.setTaskName("wsgen");

                FileSet rjb_fileSet = new FileSet();
                rjb_fileSet.setProject(_project);
                rjb_fileSet.setDir(new File("."));
                rjb_fileSet.setIncludes("RJB.jar");

                DirSet src_dirSet = new DirSet();
                src_dirSet.setDir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                Path classPath = new Path(_project);
                classPath.addFileset(rjb_fileSet);
                classPath.addDirset(src_dirSet);
                wsgenTask.setClasspath(classPath);
                wsgenTask.setKeep(true);
                wsgenTask.setDestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                wsgenTask.setResourcedestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                wsgenTask.setSei(className + "Web");

                wsgenTask.init();
                wsgenTask.execute();
            }

            new File(GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").delete();

        }

        embedRScripts();

        HashMap<String, String> marker = new HashMap<String, String>();
        marker.put("RJBMAPPINGJAR", "TRUE");

        Properties props = new Properties();
        props.put("PACKAGE_NAMES", PoolUtils.objectToHex(DirectJNI._packageNames));
        props.put("S4BEANS_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMapping));
        props.put("S4BEANS_REVERT_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMappingRevert));
        props.put("FACTORIES_MAPPING", PoolUtils.objectToHex(DirectJNI._factoriesMapping));
        props.put("S4BEANS_HASH", PoolUtils.objectToHex(DirectJNI._s4BeansHash));
        props.put("R_PACKAGE_INTERFACES_HASH", PoolUtils.objectToHex(DirectJNI._rPackageInterfacesHash));
        props.put("ABSTRACT_FACTORIES", PoolUtils.objectToHex(DirectJNI._abstractFactories));
        new File(GEN_ROOT_SRC + "/" + "maps").mkdirs();
        FileOutputStream fos = new FileOutputStream(GEN_ROOT_SRC + "/" + "maps/rjbmaps.xml");
        props.storeToXML(fos, null);
        fos.close();

        jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME, marker);

        if (_webPublishingEnabled)
            genWeb();

        DirectJNI._mappingClassLoader = null;

    } finally {

        System.exit(0);

    }
}

From source file:herddb.server.ServerMain.java

public static void main(String... args) {
    try {/*from  w  w  w .ja  v  a2 s  .  c om*/
        LOG.log(Level.INFO, "Starting HerdDB version {0}", herddb.utils.Version.getVERSION());
        Properties configuration = new Properties();

        boolean configFileFromParameter = false;
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (!arg.startsWith("-")) {
                File configFile = new File(args[i]).getAbsoluteFile();
                LOG.log(Level.INFO, "Reading configuration from {0}", configFile);
                try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile),
                        StandardCharsets.UTF_8)) {
                    configuration.load(reader);
                }
                configFileFromParameter = true;
            } else if (arg.equals("--use-env")) {
                System.getenv().forEach((key, value) -> {
                    System.out.println("Considering env as system property " + key + " -> " + value);
                    System.setProperty(key, value);
                });
            } else if (arg.startsWith("-D")) {
                int equals = arg.indexOf('=');
                if (equals > 0) {
                    String key = arg.substring(2, equals);
                    String value = arg.substring(equals + 1);
                    System.setProperty(key, value);
                }
            }
        }
        if (!configFileFromParameter) {
            File configFile = new File("conf/server.properties").getAbsoluteFile();
            LOG.log(Level.INFO, "Reading configuration from {0}", configFile);
            if (configFile.isFile()) {
                try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile),
                        StandardCharsets.UTF_8)) {
                    configuration.load(reader);
                }
            }
        }

        System.getProperties().forEach((k, v) -> {
            String key = k + "";
            if (!key.startsWith("java") && !key.startsWith("user")) {
                configuration.put(k, v);
            }
        });

        LogManager.getLogManager().readConfiguration();

        Runtime.getRuntime().addShutdownHook(new Thread("ctrlc-hook") {

            @Override
            public void run() {
                System.out.println("Ctrl-C trapped. Shutting down");
                ServerMain _brokerMain = runningInstance;
                if (_brokerMain != null) {
                    _brokerMain.close();
                }
            }

        });
        runningInstance = new ServerMain(configuration);
        runningInstance.start();

        runningInstance.join();

    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

From source file:se.technipelago.weather.chart.Generator.java

public static void main(String[] args) {

    Generator generator = new Generator();

    if (args.length > 0) {
        String outputDir = args[0];
        if (outputDir.endsWith("/")) {
            outputDir = outputDir.substring(0, outputDir.length() - 1);
        }/*from   w  w w .j a va 2 s  . co  m*/
        generator.setOutputDirectory(outputDir);
    }

    // Generate charts.
    generator.init();
    Map<String, Object> data = generator.getWeatherData();
    generator.generateCurrentCharts(data);
    generator.generateHistoryCharts(-30, 31);
    int year = Calendar.getInstance().get(Calendar.YEAR);
    generator.generateMonthlyCharts(year);
    generator.generateYearlyCharts(year);
}

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

/**
 * @param args the command line arguments
 *///from   w  ww .ja  v a 2  s .  c  o 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:fr.tpt.s3.mcdag.bench.MainBench.java

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

    // Command line options
    Options options = new Options();

    Option input = new Option("i", "input", true, "MC-DAG XML models");
    input.setRequired(true);/*from   w  w  w.ja va  2  s  .co  m*/
    input.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(input);

    Option output = new Option("o", "output", true, "Folder where results have to be written.");
    output.setRequired(true);
    options.addOption(output);

    Option uUti = new Option("u", "utilization", true, "Utilization.");
    uUti.setRequired(true);
    options.addOption(uUti);

    Option output2 = new Option("ot", "output-total", true, "File where total results are being written");
    output2.setRequired(true);
    options.addOption(output2);

    Option oCores = new Option("c", "cores", true, "Cores given to the test");
    oCores.setRequired(true);
    options.addOption(oCores);

    Option oLvls = new Option("l", "levels", true, "Levels tested for the system");
    oLvls.setRequired(true);
    options.addOption(oLvls);

    Option jobs = new Option("j", "jobs", true, "Number of threads to be launched.");
    jobs.setRequired(false);
    options.addOption(jobs);

    Option debug = new Option("d", "debug", false, "Debug logs.");
    debug.setRequired(false);
    options.addOption(debug);

    /*
     * Parsing of the command line
     */
    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("Benchmarks MultiDAG", options);
        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    String outputFilePath = cmd.getOptionValue("output");
    String outputFilePathTotal = cmd.getOptionValue("output-total");
    double utilization = Double.parseDouble(cmd.getOptionValue("utilization"));
    boolean boolDebug = cmd.hasOption("debug");
    int nbLvls = Integer.parseInt(cmd.getOptionValue("levels"));
    int nbJobs = 1;
    int nbFiles = inputFilePath.length;

    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));

    int nbCores = Integer.parseInt(cmd.getOptionValue("cores"));

    /*
     *  While files need to be allocated
     *  run the tests in the pool of threads
     */

    // For dual-criticality systems we call a specific thread
    if (nbLvls == 2) {

        System.out.println(">>>>>>>>>>>>>>>>>>>>> NB levels " + nbLvls);

        int i_files2 = 0;
        String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.'))
                .concat("-schedulability.csv");
        PrintWriter writer = new PrintWriter(outFile, "UTF-8");
        writer.println(
                "Thread; File; FSched (%); FPreempts; FAct; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization");
        writer.close();

        ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs);
        while (i_files2 != nbFiles) {
            BenchThreadDualCriticality bt2 = new BenchThreadDualCriticality(inputFilePath[i_files2], outFile,
                    nbCores, boolDebug);

            executor2.execute(bt2);
            i_files2++;
        }

        executor2.shutdown();
        executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

        int fedTotal = 0;
        int laxTotal = 0;
        int edfTotal = 0;
        int hybridTotal = 0;
        int fedPreempts = 0;
        int laxPreempts = 0;
        int edfPreempts = 0;
        int hybridPreempts = 0;
        int fedActiv = 0;
        int laxActiv = 0;
        int edfActiv = 0;
        int hybridActiv = 0;
        // Read lines in file and do average
        int i = 0;
        File f = new File(outFile);
        @SuppressWarnings("resource")
        Scanner line = new Scanner(f);
        while (line.hasNextLine()) {
            String s = line.nextLine();
            if (i > 0) { // To skip the first line
                try (Scanner inLine = new Scanner(s).useDelimiter("; ")) {
                    int j = 0;

                    while (inLine.hasNext()) {
                        String val = inLine.next();
                        if (j == 2) {
                            fedTotal += Integer.parseInt(val);
                        } else if (j == 3) {
                            fedPreempts += Integer.parseInt(val);
                        } else if (j == 4) {
                            fedActiv += Integer.parseInt(val);
                        } else if (j == 5) {
                            laxTotal += Integer.parseInt(val);
                        } else if (j == 6) {
                            laxPreempts += Integer.parseInt(val);
                        } else if (j == 7) {
                            laxActiv += Integer.parseInt(val);
                        } else if (j == 8) {
                            edfTotal += Integer.parseInt(val);
                        } else if (j == 9) {
                            edfPreempts += Integer.parseInt(val);
                        } else if (j == 10) {
                            edfActiv += Integer.parseInt(val);
                        } else if (j == 11) {
                            hybridTotal += Integer.parseInt(val);
                        } else if (j == 12) {
                            hybridPreempts += Integer.parseInt(val);
                        } else if (j == 13) {
                            hybridActiv += Integer.parseInt(val);
                        }
                        j++;
                    }
                }
            }
            i++;
        }

        // Write percentage
        double fedPerc = (double) fedTotal / nbFiles;
        double laxPerc = (double) laxTotal / nbFiles;
        double edfPerc = (double) edfTotal / nbFiles;
        double hybridPerc = (double) hybridTotal / nbFiles;

        double fedPercPreempts = (double) fedPreempts / fedActiv;
        double laxPercPreempts = (double) laxPreempts / laxActiv;
        double edfPercPreempts = (double) edfPreempts / edfActiv;
        double hybridPercPreempts = (double) hybridPreempts / hybridActiv;

        Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true));
        wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + fedPerc + "; "
                + fedPreempts + "; " + fedActiv + "; " + fedPercPreempts + "; " + laxPerc + "; " + laxPreempts
                + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts + "; "
                + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; "
                + hybridActiv + "; " + hybridPercPreempts + "\n");
        wOutput.close();

    } else if (nbLvls > 2) {
        int i_files2 = 0;
        String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.'))
                .concat("-schedulability.csv");
        PrintWriter writer = new PrintWriter(outFile, "UTF-8");
        writer.println(
                "Thread; File; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization");
        writer.close();

        ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs);
        while (i_files2 != nbFiles) {
            BenchThreadNLevels bt2 = new BenchThreadNLevels(inputFilePath[i_files2], outFile, nbCores,
                    boolDebug);

            executor2.execute(bt2);
            i_files2++;
        }

        executor2.shutdown();
        executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

        int laxTotal = 0;
        int edfTotal = 0;
        int hybridTotal = 0;
        int laxPreempts = 0;
        int edfPreempts = 0;
        int hybridPreempts = 0;
        int laxActiv = 0;
        int edfActiv = 0;
        int hybridActiv = 0;
        // Read lines in file and do average
        int i = 0;
        File f = new File(outFile);
        @SuppressWarnings("resource")
        Scanner line = new Scanner(f);
        while (line.hasNextLine()) {
            String s = line.nextLine();
            if (i > 0) { // To skip the first line
                try (Scanner inLine = new Scanner(s).useDelimiter("; ")) {
                    int j = 0;

                    while (inLine.hasNext()) {
                        String val = inLine.next();
                        if (j == 2) {
                            laxTotal += Integer.parseInt(val);
                        } else if (j == 3) {
                            laxPreempts += Integer.parseInt(val);
                        } else if (j == 4) {
                            laxActiv += Integer.parseInt(val);
                        } else if (j == 5) {
                            edfTotal += Integer.parseInt(val);
                        } else if (j == 6) {
                            edfPreempts += Integer.parseInt(val);
                        } else if (j == 7) {
                            edfActiv += Integer.parseInt(val);
                        } else if (j == 8) {
                            hybridTotal += Integer.parseInt(val);
                        } else if (j == 9) {
                            hybridPreempts += Integer.parseInt(val);
                        } else if (j == 10) {
                            hybridActiv += Integer.parseInt(val);
                        }
                        j++;
                    }
                }
            }
            i++;
        }

        // Write percentage
        double laxPerc = (double) laxTotal / nbFiles;
        double edfPerc = (double) edfTotal / nbFiles;
        double hybridPerc = (double) hybridTotal / nbFiles;

        double laxPercPreempts = (double) laxPreempts / laxActiv;
        double edfPercPreempts = (double) edfPreempts / edfActiv;
        double hybridPercPreempts = (double) hybridPreempts / hybridActiv;

        Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true));
        wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + laxPerc + "; "
                + laxPreempts + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts
                + "; " + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; "
                + hybridActiv + "; " + hybridPercPreempts + "\n");
        wOutput.close();

    } else {
        System.err.println("Wrong number of levels");
        System.exit(-1);
    }

    System.out.println("[BENCH Main] Done benchmarking U = " + utilization + " Levels " + nbLvls);
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.out.println("Use: ContentFetcher mainurl contenturl destdir"); //$NON-NLS-1$
        System.out.println(//from  w w  w.ja v a 2  s  . com
                "Example: ContentFetcher http://site.com http://site.com/dir[0-2]/image_A[001-040].jpg c:/temp"); //$NON-NLS-1$
        System.out.println(
                "Result: accessing http://site.com for cookie, reading http://site.com/dir1/image_A004.jpg writing c:/temp/dir_1_image_A004.jpg"); //$NON-NLS-1$
    } else {
        String url = args[1];
        String destdir = args[2];

        List parts = new ArrayList();
        int dir_from = 0;
        int dir_to = 0;
        int dir_fill = 0;
        int from = 0;
        int to = 0;
        int fill = 0;

        StringTokenizer tk = new StringTokenizer(url, "[]", true); //$NON-NLS-1$
        boolean hasDir = (tk.countTokens() > 5);
        boolean inDir = hasDir;
        System.out.println("hasDir " + hasDir); //$NON-NLS-1$
        boolean inTag = false;
        while (tk.hasMoreTokens()) {
            String token = tk.nextToken();
            if (token.equals("[")) //$NON-NLS-1$
            {
                inTag = true;
                continue;
            }
            if (token.equals("]")) //$NON-NLS-1$
            {
                inTag = false;
                if (inDir)
                    inDir = false;
                continue;
            }
            if (inTag) {
                int idx = token.indexOf('-');
                String s_from = token.substring(0, idx);
                int a_from = new Integer(s_from).intValue();
                int a_fill = s_from.length();
                int a_to = new Integer(token.substring(idx + 1)).intValue();
                if (inDir) {
                    dir_from = a_from;
                    dir_to = a_to;
                    dir_fill = a_fill;
                } else {
                    from = a_from;
                    to = a_to;
                    fill = a_fill;
                }
            } else {
                parts.add(token);
            }
        }

        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpGet main = new HttpGet(args[0]);
        HttpResponse res = client.execute(main);
        ;
        int main_rs = res.getStatusLine().getStatusCode();
        if (main_rs != 200) {
            System.out.println("main page retrieval failed " + main_rs); //$NON-NLS-1$
            return;
        }

        for (int d = dir_from; d <= dir_to; d++) {
            String dir_number = "" + d; //$NON-NLS-1$
            if (dir_fill > 1) {
                dir_number = "000000" + d; //$NON-NLS-1$
                int dir_digits = (int) (Math.log(fill) / Math.log(10));
                System.out.println("dir_digits " + dir_digits); //$NON-NLS-1$
                dir_number = dir_number.substring(dir_number.length() - (dir_fill - dir_digits),
                        dir_number.length());
            }
            for (int i = from; i <= to; i++) {
                try {
                    String number = "" + i; //$NON-NLS-1$
                    if (fill > 1) {
                        number = "000000" + i; //$NON-NLS-1$
                        int digits = (int) (Math.log(fill) / Math.log(10));
                        System.out.println("digits " + digits); //$NON-NLS-1$
                        number = number.substring(number.length() - (fill - digits), number.length());
                    }
                    int part = 0;
                    StringBuffer surl = new StringBuffer((String) parts.get(part++));
                    if (hasDir) {
                        surl.append(dir_number);
                        surl.append(parts.get(part++));
                    }
                    surl.append(number);
                    surl.append(parts.get(part++));
                    System.out.println("reading url " + surl); //$NON-NLS-1$

                    int indx = surl.toString().lastIndexOf('/');
                    StringBuffer sfile = new StringBuffer(destdir);
                    sfile.append("\\"); //$NON-NLS-1$
                    if (hasDir) {
                        sfile.append("dir_"); //$NON-NLS-1$
                        sfile.append(dir_number);
                        sfile.append("_"); //$NON-NLS-1$
                    }
                    sfile.append(surl.toString().substring(indx + 1));
                    File file = new File(sfile.toString());
                    if (file.exists()) {
                        file = new File("" + System.currentTimeMillis() + sfile.toString());
                    }
                    System.out.println("write file " + file.getAbsolutePath()); //$NON-NLS-1$

                    //                  URL iurl = createURLFromString(surl.toString());
                    HttpGet get = new HttpGet(surl.toString());

                    HttpResponse response = client.execute(get);
                    int result = response.getStatusLine().getStatusCode();
                    System.out.println("page http result " + result); //$NON-NLS-1$
                    if (result == 200) {
                        InputStream is = response.getEntity().getContent();
                        FileOutputStream fos = new FileOutputStream(file);
                        Utils.streamCopy(is, fos);
                        fos.close();
                    }
                } catch (Exception e) {
                    System.err.println(e);
                }
            }
        }
    }
}