Example usage for java.lang String lastIndexOf

List of usage examples for java.lang String lastIndexOf

Introduction

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

Prototype

public int lastIndexOf(String str) 

Source Link

Document

Returns the index within this string of the last occurrence of the specified substring.

Usage

From source file:com.sxjun.core.generate.Generate.java

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

    // ==========  ?? ====================
    // ??????/* w w w. j  av a2s.  c  o  m*/
    // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className}
    // packageName ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4?
    String packageName = "com.sxjun";
    String moduleName = "retrieval"; // ???sys
    String subModuleName = ""; // ????? 
    String className = "IndexManager"; // ??user
    String classAuthor = "sxjun"; // ThinkGem
    String functionName = "?"; // ??

    // ???
    Boolean isEnable = true;
    // ==========  ?? ====================
    if (!isEnable) {
        logger.error("????isEnable = true");
        return;
    }

    if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(moduleName) || StringUtils.isBlank(className)
            || StringUtils.isBlank(functionName)) {
        logger.error("??????????????");
        return;
    }

    // ?
    String separator = File.separator;
    String classPath = new DefaultResourceLoader().getResource("").getFile().getPath();
    String templatePath = classPath.replace(
            separator + "WebRoot" + separator + "WEB-INF" + separator + "classes",
            separator + "src" + separator + "com" + separator + "sxjun" + separator + "retrieval");
    String javaPath = classPath.replace(separator + "WebRoot" + separator + "WEB-INF" + separator + "classes",
            separator + "src" + separator + (StringUtils.lowerCase(packageName)).replace(".", separator));
    String viewPath = classPath.replace(separator + "classes", separator + "retrieval");

    // ???
    Configuration cfg = new Configuration();
    cfg.setDirectoryForTemplateLoading(new File(templatePath.substring(0, templatePath.lastIndexOf(separator))
            + separator + "generate" + separator + "template"));

    // ???
    Map<String, String> model = Maps.newHashMap();
    model.put("packageName", StringUtils.lowerCase(packageName));
    model.put("moduleName", StringUtils.lowerCase(moduleName));
    model.put("subModuleName",
            StringUtils.isNotBlank(subModuleName) ? "." + StringUtils.lowerCase(subModuleName) : "");
    model.put("className", StringUtils.uncapitalize(className));
    model.put("ClassName", StringUtils.capitalize(className));
    model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools");
    model.put("classVersion", DateUtils.getDate());
    model.put("functionName", functionName);
    model.put("urlPrefix",
            (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) + "/" : "")
                    + model.get("className"));
    model.put("viewPrefix",
            StringUtils.substringAfterLast(model.get("packageName"), ".") + "/" + model.get("urlPrefix"));

    // ? Entity
    Template template = cfg.getTemplate("pojo.ftl");
    String content = FreeMarkers.renderTemplate(template, model);
    String filePath = javaPath + separator + model.get("moduleName") + separator + "pojo" + separator
            + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + ".java";
    writeFile(content, filePath);
    logger.info(filePath);

    // ? Dao
    /*template = cfg.getTemplate("dao.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = javaPath+separator+model.get("moduleName")+separator+"dao"+separator
    +StringUtils.lowerCase(subModuleName)+separator+model.get("ClassName")+"Dao.java";
    writeFile(content, filePath);
    logger.info(filePath);
            
    // ? Service
    template = cfg.getTemplate("service.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = javaPath+separator+model.get("moduleName")+separator+"service"+separator
    +StringUtils.lowerCase(subModuleName)+separator+model.get("ClassName")+"Service.java";
    writeFile(content, filePath);
    logger.info(filePath);*/

    // ? Controller
    template = cfg.getTemplate("controller.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = javaPath + separator + model.get("moduleName") + separator + "controller" + separator
            + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Controller.java";
    writeFile(content, filePath);
    logger.info(filePath);

    // ? ViewForm
    template = cfg.getTemplate("viewForm.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = viewPath + separator + model.get("className") + separator + model.get("className") + "Form.jsp";
    writeFile(content, filePath);
    logger.info(filePath);

    // ? ViewList
    template = cfg.getTemplate("viewList.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = viewPath + separator + model.get("className") + separator + model.get("className") + "List.jsp";
    writeFile(content, filePath);
    logger.info(filePath);

    logger.info("????");
}

From source file:ReflectClass.java

public static void main(String args[]) {
    Constructor cn[];/*w  w  w  . j  av  a2 s  .  co m*/
    Class cc[];
    Method mm[];
    Field ff[];
    Class c = null;
    Class supClass;
    String x, y, s1, s2, s3;
    Hashtable classRef = new Hashtable();

    if (args.length == 0) {
        System.out.println("Please specify a class name on the command line.");
        System.exit(1);
    }

    try {
        c = Class.forName(args[0]);
    } catch (ClassNotFoundException ee) {
        System.out.println("Couldn't find class '" + args[0] + "'");
        System.exit(1);
    }

    /*
     * Step 0: If our name contains dots we're in a package so put
     * that out first.
     */
    x = c.getName();
    if (x.lastIndexOf(".") != -1) {
        y = x.substring(0, x.lastIndexOf("."));
        System.out.println("package " + y + ";\n\r");
    }

    /*
     * Let's use the Reflection API to sift through what is
     * inside this class.
     *
     * Step 1: Collect referenced classes
     * This step is used so that I can regenerate the import statements.
     * It isn't strictly required of course, Java works just fine with
     * fully qualified object class names, but it looks better when you
     * use 'String' rather than 'java.lang.String' as the return type.
     */

    ff = c.getDeclaredFields();
    for (int i = 0; i < ff.length; i++) {
        x = tName(ff[i].getType().getName(), classRef);
    }

    cn = c.getDeclaredConstructors();
    for (int i = 0; i < cn.length; i++) {
        Class cx[] = cn[i].getParameterTypes();
        if (cx.length > 0) {
            for (int j = 0; j < cx.length; j++) {
                x = tName(cx[j].getName(), classRef);
            }
        }
    }

    mm = c.getDeclaredMethods();
    for (int i = 0; i < mm.length; i++) {
        x = tName(mm[i].getReturnType().getName(), classRef);
        Class cx[] = mm[i].getParameterTypes();
        if (cx.length > 0) {
            for (int j = 0; j < cx.length; j++) {
                x = tName(cx[j].getName(), classRef);
            }
        }
    }

    // Don't import ourselves ...
    classRef.remove(c.getName());

    /*
     * Step 2: Start class description generation, start by printing
     *  out the import statements.
     *
     * This is the line that goes 'public SomeClass extends Foo {'
     */
    for (Enumeration e = classRef.keys(); e.hasMoreElements();) {
        System.out.println("import " + e.nextElement() + ";");
    }
    System.out.println();

    /*
     * Step 3: Print the class or interface introducer. We use
     * a convienience method in Modifer to print the whole string.
     */
    int mod = c.getModifiers();
    System.out.print(Modifier.toString(mod));

    if (Modifier.isInterface(mod)) {
        System.out.print(" interface ");
    } else {
        System.out.print(" class ");
    }
    System.out.print(tName(c.getName(), null));

    supClass = c.getSuperclass();
    if (supClass != null) {
        System.out.print(" extends " + tName(supClass.getName(), classRef));
    }
    System.out.println(" {");

    /*
     * Step 4: Print out the fields (internal class members) that are declared
     * by this class.
     *
     * Fields are of the form [Modifiers] [Type] [Name] ;
     */

    System.out.println("\n\r/*\n\r * Field Definitions.\r\n */");
    for (int i = 0; i < ff.length; i++) {
        Class ctmp = ff[i].getType();
        int md = ff[i].getModifiers();

        System.out.println("    " + Modifier.toString(md) + " " + tName(ff[i].getType().getName(), null) + " "
                + ff[i].getName() + ";");
    }

    /*
     * Step 5: Print out the constructor declarations.
     *
     * We note the name of the class which is the 'name' for all
     * constructors. Also there is no type, so the definition is
     * simplye [Modifiers] ClassName ( [ Parameters ] ) { }
     *
     */
    System.out.println("\n\r/*\n\r * Declared Constructors. \n\r */");
    x = tName(c.getName(), null);
    for (int i = 0; i < cn.length; i++) {
        int md = cn[i].getModifiers();
        System.out.print("    " + Modifier.toString(md) + " " + x);

        Class cx[] = cn[i].getParameterTypes();
        System.out.print("( ");
        if (cx.length > 0) {
            for (int j = 0; j < cx.length; j++) {
                System.out.print(tName(cx[j].getName(), null));
                if (j < (cx.length - 1))
                    System.out.print(", ");
            }
        }
        System.out.print(") ");
        System.out.println("{ ... }");
    }

    /*
     * Step 6: Print out the method declarations.
     *
     * Now methods have a name, a return type, and an optional
     * set of parameters so they are :
     *  [modifiers] [type] [name] ( [optional parameters] ) { }
     */
    System.out.println("\n\r/*\n\r * Declared Methods.\n\r */");
    for (int i = 0; i < mm.length; i++) {
        int md = mm[i].getModifiers();
        System.out.print("    " + Modifier.toString(md) + " " + tName(mm[i].getReturnType().getName(), null)
                + " " + mm[i].getName());

        Class cx[] = mm[i].getParameterTypes();
        System.out.print("( ");
        if (cx.length > 0) {
            for (int j = 0; j < cx.length; j++) {
                System.out.print(tName(cx[j].getName(), classRef));
                if (j < (cx.length - 1))
                    System.out.print(", ");
            }
        }
        System.out.print(") ");
        System.out.println("{ ... }");
    }

    /*
     * Step 7: Print out the closing brace and we're done!
     */
    System.out.println("}");
}

From source file:de.ipbhalle.metfusion.main.SubstructureSearch.java

public static void main(String[] args) {
    String token = "eeca1d0f-4c03-4d81-aa96-328cdccf171a";
    //String token = "a1004d0f-9d37-47e0-acdd-35e58e34f603";
    //test();/*from   w  w  w  .  j  a v  a 2 s.co m*/

    //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/136m0498_MSMS.mf");
    //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/148m0859_MSMS.mf");
    //      File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/164m0445a_MSMS.mf");
    //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/192m0757a_MSMS.mf");
    //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/naringenin.mf");

    //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Known_BT_MSMS_ChemSp/1MeBT_MSMS.mf");

    //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/150m0655a_MSMS.mf");
    File file = new File(
            "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/192m0757b_MSMS.mf");

    MetFusionBatchFileHandler mbf = new MetFusionBatchFileHandler(file);
    try {
        mbf.readFile();
    } catch (IOException e) {
        //System.out.println(e.getMessage());
        System.err.println(
                "Error reading from MetFusion settings file [" + file.getAbsolutePath() + "]. Aborting!");
        System.exit(-1);
    }

    MetFusionBatchSettings settings = mbf.getBatchSettings();
    List<String> absent = settings.getSubstrucAbsent();
    List<String> present = settings.getSubstrucPresent();
    for (String s : present) {
        System.out.println("present -> " + s);
    }
    for (String s : absent) {
        System.out.println("absent -> " + s);
    }
    String formula = settings.getMfFormula();
    System.out.println("formula -> " + formula);

    boolean useFormulaAsQuery = true;
    boolean useSDF = false;
    String sdfFile = "";
    if (useSDF) {
        sdfFile = "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/results_afterFormulaQuery/192m0757b_MSMS.sdf";
        if (sdfFile.isEmpty()) { // TODO alternatively use SDF file from query file?
            System.err.println("SDF file needs to be specified! Exiting.");
            System.exit(-1);
        }
    }

    SubstructureSearch ss = new SubstructureSearch(present, absent, token, formula, mbf, useFormulaAsQuery,
            useSDF, sdfFile);
    ss.run();
    List<ResultSubstructure> remaining = ss.getResultsRemaining();
    List<Result> resultsForSDF = new ArrayList<Result>();

    StringBuilder sb = new StringBuilder();
    String sep = ",";
    for (ResultSubstructure rs : remaining) {
        sb.append(rs.getId()).append(sep);

        Result r = new Result(rs.getPort(), rs.getId(), rs.getName(), rs.getScore());
        r.setMol(rs.getMol());
        r.setSmiles(rs.getSmiles());
        r.setInchi(rs.getInchi());
        r.setInchikey(rs.getInchikey());
        resultsForSDF.add(r);
    }
    String ids = sb.toString();

    String fileSep = System.getProperty("file.separator");
    if (!ids.isEmpty()) {
        ids = ids.substring(0, ids.length() - 1);
        System.out.println("ids -> " + ids);
        settings.setMfDatabaseIDs(ids);
        String filename = file.getName();
        String prefix = filename.substring(0, filename.lastIndexOf("."));
        filename = filename.replace(prefix, prefix + "_ids");
        String dir = file.getParent();
        System.out.println("dir -> " + dir);
        if (!dir.endsWith(fileSep))
            dir += fileSep;

        File output = new File(file.getParent(), filename);
        mbf.writeFile(output, settings);
        SDFOutputHandler so = new SDFOutputHandler(dir + prefix + ".sdf");
        boolean writeOK = so.writeOriginalResults(resultsForSDF, false);
        if (!writeOK)
            System.err.println("Error writing SDF [" + so.getFilename());
    }
}

From source file:org.eclipse.lyo.client.oslc.samples.DoorsOauthSample.java

/**
 * Login to the DWA server and perform some OSLC actions
 * @param args/*from   www .j a  v  a 2  s . c  o  m*/
 * @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/* www  .j  ava  2  s .  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:Gen.java

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

    try {//from   ww w . j  ava 2  s. 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:at.tuwien.ifs.somtoolbox.apps.helper.VectorSimilarityWriter.java

public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
        IllegalAccessException, IOException, SOMToolboxException {
    JSAPResult config = OptionFactory.parseResults(args, OptionFactory.OPTIONS_INPUT_SIMILARITY_COMPUTER);
    String inputVectorDistanceMatrix = config.getString("inputVectorDistanceMatrix");
    String inputVectorFileName = config.getString("inputVectorFile");
    int numNeighbours = config.getInt("numberNeighbours");
    String outputFormat = config.getString("outputFormat");

    InputVectorDistanceMatrix matrix = null;
    InputData data = new SOMLibSparseInputData(inputVectorFileName);

    if (StringUtils.isNotBlank(inputVectorDistanceMatrix)) {
        matrix = InputVectorDistanceMatrix.initFromFile(inputVectorDistanceMatrix);
    } else {/*w  w  w  . j av  a  2  s . c o  m*/
        String metricName = config.getString("metric");
        DistanceMetric metric = AbstractMetric.instantiate(metricName);
        matrix = new LeightWeightMemoryInputVectorDistanceMatrix(data, metric);
    }

    String outputFileName = config.getString("output");
    PrintWriter w = FileUtils.openFileForWriting("Similarity File", outputFileName);

    if (outputFormat.equals("SAT-DB")) {
        // find feature type
        String type = "";
        if (inputVectorFileName.endsWith(".rh") || inputVectorFileName.endsWith(".rp")
                || inputVectorFileName.endsWith(".ssd")) {
            type = "_" + inputVectorFileName.substring(inputVectorFileName.lastIndexOf(".") + 1);
        }
        w.println("INSERT INTO `sat_track_similarity_ifs" + type
                + "` (`TRACKID`, `SIMILARITYCOUNT`, `SIMILARITYIDS`) VALUES ");
    }

    int numVectors = matrix.numVectors();
    // numVectors = 10; // for testing
    StdErrProgressWriter progress = new StdErrProgressWriter(numVectors, "Writing similarities for vector ", 1);
    for (int i = 0; i < numVectors; i++) {
        int[] nearest = matrix.getNNearest(i, numNeighbours);
        if (outputFormat.equals("SAT-DB")) {
            w.print("  (" + i + " , NULL, '");
            for (int j = 0; j < nearest.length; j++) {
                String label = data.getLabel(nearest[j]);
                w.print(label.replace(".mp3", "")); // strip ending
                if (j + 1 < nearest.length) {
                    w.print(",");
                } else {
                    w.print("')");
                }
            }
            if (i + 1 < numVectors) {
                w.print(",");
            }
        } else {
            w.print(data.getLabel(i) + ",");
            for (int j = 0; j < nearest.length; j++) {
                w.print(data.getLabel(nearest[j]));
                if (j + 1 < nearest.length) {
                    w.print(",");
                }
            }
        }
        w.println();
        w.flush();
        progress.progress();
    }
    if (outputFormat.equals("SAT-DB")) {
        w.print(";");
    }
    w.flush();
    w.close();
}

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  ww.j  av  a  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:AndroidUninstallStock.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    try {/*from  ww w . ja  va2 s.c o  m*/
        String lang = Locale.getDefault().getLanguage();
        GnuParser cmdparser = new GnuParser();
        Options cmdopts = new Options();
        for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) {
            // hack for printOptions
            java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld);
            fieldopt.setAccessible(true);
            fieldopt.set(cmdopts, new LinkedHashMap<>());
        }
        cmdopts.addOption("h", "help", false, "Help");
        cmdopts.addOption("t", "test", false, "Show only report");
        cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg()
                .withDescription("Path to ADB from Android SDK").create("a"));
        cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg()
                .withDescription("Select device (\"adb devices\")").create("d"));
        cmdopts.addOption(null, "restore", false,
                "If packages have not yet removed and are disabled, " + "you can activate them again");
        cmdopts.addOption(null, "google", false, "Delete packages are in the Google section");
        cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex"
                + System.lineSeparator() + "(It is required to repeat command execution)");
        cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]");
        //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)");
        cmdopts.addOption(null, "scanlibs", false,
                "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib");

        cmdopts.addOptionGroup(new OptionGroup() {
            {
                addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired()
                        .withDescription("Create file with list packages").create());
                addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create());
            }
        });
        cmdopts.getOption("lang").setDescription(
                "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market");
        CommandLine cmd = cmdparser.parse(cmdopts, args);

        if (args.length == 0 || cmd.hasOption("help")) {
            PrintWriter console = new PrintWriter(System.out);
            HelpFormatter cmdhelp = new HelpFormatter();
            cmdhelp.setOptionComparator(new Comparator<Option>() {
                @Override
                public int compare(Option o1, Option o2) {
                    return 0;
                }
            });
            console.println("WARNING: Before use make a backup with ClockworkMod Recovery!");
            console.println();
            console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]");
            cmdhelp.printOptions(console, 80, cmdopts, 3, 2);
            console.flush();
            return;
        }

        String adb = cmd.getOptionValue("adb", "adb");
        try {
            run(adb, "start-server");
        } catch (IOException e) {
            System.out.println("Error: Not found ADB! Use -a or --adb");
            return;
        }

        final boolean NotTest = !cmd.hasOption("test");

        String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev"));
        if (!deverror.isEmpty()) {
            System.out.println(deverror);
            return;
        }

        System.out.println("Getting list packages:");
        LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>();
        for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) {
            // "pm list packages" give list sorted by packages ;)
            String pckg = ln.substring("package:".length());
            String pckgname = ln.substring(ln.lastIndexOf('=') + 1);
            pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1);
            if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) {
                apklist.put(pckg, pckgname);
            }
        }
        for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) {
            String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk");
            if (!apklist.containsKey(path)) {
                apklist.put(path, "");
            }
        }
        apklist.remove("/system/app/mcRegistry");
        for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        String genfile = cmd.getOptionValue("genfile");
        if (genfile != null) {
            Path genpath = Paths.get(genfile);
            try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8,
                    new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
                            StandardOpenOption.WRITE })) {
                if (cmd.getOptionValue("lang") != null) {
                    lang = cmd.getOptionValue("lang");
                }

                LinkedHashSet<String> listsystem = new LinkedHashSet<String>() {
                    {
                        add("com.android");
                        add("com.google.android");
                        //add("com.sec.android.app");
                        add("com.monotype.android");
                        add("eu.chainfire.supersu");
                    }
                };

                // \r\n for Windows Notepad
                gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
                gen.write("<!-- & raplace with &amp; or use <![CDATA[ ]]> -->\r\n");
                gen.write("<AndroidUninstallStock>\r\n\r\n");
                gen.write("<Normal>\r\n");
                System.out.println();
                System.out.println("\tNormal:");
                writeInfo(gen, apklist, lang, listsystem, true);
                gen.write("\t<apk name=\"Exclude Google and etc\">\r\n");
                for (String exc : listsystem) {
                    gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n");
                }
                gen.write("\t</apk>\r\n");
                gen.write("</Normal>\r\n\r\n");
                gen.write("<Google>\r\n");
                System.out.println();
                System.out.println("\tGoogle:");
                writeInfo(gen, apklist, lang, listsystem, false);
                gen.write("</Google>\r\n\r\n");
                gen.write("</AndroidUninstallStock>\r\n");
                System.out.println("File " + genpath.toAbsolutePath() + " created.");
            }
            return;
        }

        String[] FileName = cmd.getArgs();
        if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) {
            System.out.println("Error: File " + FileName[0] + " not found!");
            return;
        }

        DocumentBuilderFactory xmlfactory = getXmlDocFactory();

        // DocumentBuilder.setErrorHandler() for print errors
        Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0]));

        LinkedList<AusInfo> Normal = new LinkedList<AusInfo>();
        LinkedList<AusInfo> Google = new LinkedList<AusInfo>();

        NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes();
        for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) {
            Node ndnow = ndaus.item(ndausx);
            NodeList nd = ndnow.getChildNodes();
            String ndname = ndnow.getNodeName();
            for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) {
                if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) {
                    continue;
                }
                if (ndname.equalsIgnoreCase("Normal")) {
                    Normal.add(getApkInfo(nd.item(ndx)));
                } else if (ndname.equalsIgnoreCase("Google")) {
                    Google.add(getApkInfo(nd.item(ndx)));
                }
            }
        }

        // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages.
        //       Now requires a restart.
        System.out.println();
        System.out.println("Include and Exclude packages (Normal):");
        LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false);
        System.out.println();
        System.out.println("Global Exclude packages (Normal):");
        apkNormal = getApkFromPattern(apkNormal, Normal, true);
        System.out.println();
        System.out.println("Final list packages (Normal):");
        for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>();
        if (cmd.hasOption("google")) {
            System.out.println();
            System.out.println("Include and Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apklist, Google, false);
            System.out.println();
            System.out.println("Global Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apkGoogle, Google, true);
            System.out.println();
            System.out.println("Final list packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) {
                System.out.println(info.getValue() + " = " + info.getKey());
            }
        }

        if (NotTest) {
            if (!hasRoot(adb)) {
                System.out.println("No Root");
                System.out.println();
                System.out.println("FINISH :)");
                return;
            }
        }

        if (cmd.hasOption("restore")) {
            System.out.println();
            System.out.println("Enable (Restore) packages (Normal):");
            damage(adb, "pm enable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Enable (Restore) packages (Google):");
                damage(adb, "pm enable ", NotTest, apkGoogle, 2);
            }
            System.out.println();
            System.out.println("FINISH :)");
            return;
        } else {
            System.out.println();
            System.out.println("Disable packages (Normal):");
            damage(adb, "pm disable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Disable packages (Google):");
                damage(adb, "pm disable ", NotTest, apkGoogle, 2);
            }
        }

        if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) {
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }

        // Reboot now not needed
        /*if (NotTest) {
        reboot(adb, "-s", lastdevice, "reboot");
        if (!hasRoot(adb)) {
            System.out.println("No Root");
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }
        }*/

        if (cmd.hasOption("unlib")) {
            // "find" not found
            System.out.println();
            System.out.println("Getting list libraries:");
            LinkedList<String> liblist = new LinkedList<String>();
            liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/"));
            String dircur = "/system/lib/";
            for (int x = 0; x < liblist.size(); x++) {
                if (liblist.get(x).startsWith("scan:")) {
                    dircur = liblist.get(x).substring("scan:".length());
                    liblist.remove(x);
                    x--;
                } else if (liblist.get(x).startsWith("d")) {
                    String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/";
                    liblist.remove(x);
                    x--;
                    liblist.add("scan:/system/lib/" + dir);
                    liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir));
                    continue;
                }
                liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4));
                System.out.println(liblist.get(x));
            }

            final boolean scanlibs = cmd.hasOption("scanlibs");
            LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal,
                    "Normal", scanlibs);
            libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal");
            System.out.println();
            System.out.println("Final list libraries (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                System.out.println(info.getKey() + " = " + info.getValue());
            }

            LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>();
            if (cmd.hasOption("google")) {
                libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs);
                libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google");
                System.out.println();
                System.out.println("Final list libraries (Google):");
                for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                    System.out.println(info.getKey() + " = " + info.getValue());
                }
            }

            LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist);
            for (String key : apkNormal.keySet()) {
                apkExclude.remove(key);
            }
            for (String key : apkGoogle.keySet()) {
                apkExclude.remove(key);
            }

            System.out.println();
            System.out.println("Include libraries from Exclude packages:");
            LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude);
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libNormal.remove(info.getKey());
                }
            }
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libGoogle.remove(info.getKey());
                }
            }

            System.out.println();
            System.out.println("Delete libraries (Normal):");
            damage(adb, "rm ", NotTest, libNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete libraries (Google):");
                damage(adb, "rm ", NotTest, libGoogle, 1);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Cleaning data packages (Normal):");
            damage(adb, "pm clear ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Cleaning data packages (Google):");
                damage(adb, "pm clear ", NotTest, apkGoogle, 2);
            }

            System.out.println();
            System.out.println("Uninstall packages (Normal):");
            damage(adb, "pm uninstall ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Uninstall packages (Google):");
                damage(adb, "pm uninstall ", NotTest, apkGoogle, 2);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Delete packages (Normal):");
            LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>();
            for (Map.Entry<String, String> apk : apkNormal.entrySet()) {
                dexNormal.put(apk.getKey(), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
            }
            damage(adb, "rm ", NotTest, dexNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete packages (Google):");
                LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>();
                for (Map.Entry<String, String> apk : apkGoogle.entrySet()) {
                    dexGoogle.put(apk.getKey(), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
                }
                damage(adb, "rm ", NotTest, dexGoogle, 1);
            }
        }

        if (NotTest) {
            run(adb, "-s", lastdevice, "reboot");
        }
        System.out.println();
        System.out.println("FINISH :)");
    } catch (SAXException e) {
        System.out.println("Error parsing list: " + e);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:com.cedarsoft.serialization.SplittingPerformanceRunner.java

public static void main(String[] args) throws Exception {
    final String uri = "http://www.cedarsoft.com/some/slashes/1.0.0";

    run("String.plit", new Callable<String>() {
        @Override/*from www. j a  v  a 2  s  . co m*/
        public String call() throws Exception {
            String[] parts = uri.split("/");
            return parts[parts.length - 1];
        }
    });

    run("Splitter", new Callable<String>() {
        @Override
        public String call() throws Exception {
            Splitter splitter = Splitter.on("/");
            Iterable<String> parts = splitter.split(uri);

            Iterator<String> iterator = parts.iterator();
            while (true) {
                String current = iterator.next();
                if (!iterator.hasNext()) {
                    return current;
                }
            }
        }
    });

    run("static Splitter", new Callable<String>() {
        @Override
        public String call() throws Exception {
            Iterable<String> parts = SPLITTER.split(uri);

            Iterator<String> iterator = parts.iterator();
            while (true) {
                String current = iterator.next();
                if (!iterator.hasNext()) {
                    return current;
                }
            }
        }
    });

    run("indexOf", new Callable<String>() {
        @Override
        public String call() throws Exception {
            int index = uri.lastIndexOf("/");
            return uri.substring(index + 1);
        }
    });
}