Example usage for java.lang String equals

List of usage examples for java.lang String equals

Introduction

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

Prototype

public boolean equals(Object anObject) 

Source Link

Document

Compares this string to the specified object.

Usage

From source file:edu.umass.cs.gigapaxos.paxospackets.RequestPacket.java

public static void main(String[] args) throws UnsupportedEncodingException, UnknownHostException {
    Util.assertAssertionsEnabled();
    int numReqs = 25;
    RequestPacket[] reqs = new RequestPacket[numReqs];
    RequestPacket req = new RequestPacket("asd" + 999, true);
    for (int i = 0; i < numReqs; i++) {
        reqs[i] = new RequestPacket("asd" + i, true);
    }//from w  w w.  j a v a 2 s.  co m

    System.out.println("Decision size estimate = " + SIZE_ESTIMATE);

    req.latchToBatch(reqs);
    String reqStr = req.toString();
    try {
        RequestPacket reqovered = new RequestPacket(req.toJSONObject());
        String reqoveredStr = reqovered.toString();
        assert (reqStr.equals(reqoveredStr));
        System.out.println("batchSize = " + reqovered.batched.length);
        // System.out.println(reqovered.batched[3]);
        System.out.println(samplePValue);

        System.out.println(reqs[1]);
        System.out.println(new RequestPacket(reqs[1].toBytes()));

        System.out.println(req);
        System.out.println(reqovered = new RequestPacket(req.toBytes()));
        assert (req.toString().equals(reqovered.toString()));

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:agilejson.Base64.java

/**
 * Main program. Used for testing.//from   w ww  .  java 2s.  c  o m
 * 
 * Encodes or decodes two files from the command line
 * 
 * @param args command arguments
 */
public final static void main(String[] args) {
    if (args.length < 3) {
        usage("Not enough arguments.");

    } else {
        String flag = args[0];
        String infile = args[1];
        String outfile = args[2];
        if (flag.equals("-e")) { // encode
            encodeFileToFile(infile, outfile);

        } else if (flag.equals("-d")) { // decode
            decodeFileToFile(infile, outfile);

        } else {
            usage("Unknown flag: " + flag);
        }
    }
}

From source file:com.healthmarketscience.rmiio.RemoteStreamServerTest.java

public static void main(String[] args) throws Exception {
    int argc = 0;
    String appType = null;
    if (args.length > argc) {
        appType = args[argc++];// ww w .  j  av a  2s  .co  m
    }

    // create sub-argument list
    int subArgsLength = ((args.length > argc) ? (args.length - argc) : 0);
    String[] subArgs = new String[subArgsLength];
    if (subArgsLength > 0) {
        System.arraycopy(args, argc, subArgs, 0, subArgsLength);
    }

    List<AccumulateRemoteStreamMonitor<?>> monitors = new ArrayList<AccumulateRemoteStreamMonitor<?>>();
    List<Throwable> clientExceptions = new ArrayList<Throwable>();
    if (appType.equals("-server")) {
        FileServer.main(subArgs);
    } else if (appType.equals("-client")) {
        FileClient.main(subArgs);
    } else if (appType.equals("-test")) {
        mainTest(subArgs, clientExceptions, null);
    } else {
        LOG.debug("First argument must be '-server' or 'client'");
        System.exit(1);
    }

    if (!clientExceptions.isEmpty()) {
        LOG.debug("Client exceptions: " + clientExceptions);
    }
}

From source file:edu.brown.costmodel.SingleSitedCostModel.java

/**
 * MAIN!/*w ww .ja  va2s. c  o  m*/
 * 
 * @param vargs
 * @throws Exception
 */
public static void main(String[] vargs) throws Exception {
    ArgumentsParser args = ArgumentsParser.load(vargs);
    args.require(ArgumentsParser.PARAM_CATALOG, ArgumentsParser.PARAM_WORKLOAD,
            ArgumentsParser.PARAM_PARTITION_PLAN);
    assert (args.workload.getTransactionCount() > 0) : "No transactions were loaded from " + args.workload_path;

    if (args.hasParam(ArgumentsParser.PARAM_CATALOG_HOSTS)) {
        ClusterConfiguration cc = new ClusterConfiguration(args.getParam(ArgumentsParser.PARAM_CATALOG_HOSTS));
        args.updateCatalog(FixCatalog.addHostInfo(args.catalog, cc), null);
    }

    // Enable compact output
    final boolean table_output = (args.getOptParams().contains("table"));

    // If given a PartitionPlan, then update the catalog
    File pplan_path = new File(args.getParam(ArgumentsParser.PARAM_PARTITION_PLAN));
    PartitionPlan pplan = new PartitionPlan();
    pplan.load(pplan_path.getAbsolutePath(), args.catalog_db);
    if (args.getBooleanParam(ArgumentsParser.PARAM_PARTITION_PLAN_REMOVE_PROCS, false)) {
        for (Procedure catalog_proc : pplan.proc_entries.keySet()) {
            pplan.setNullProcParameter(catalog_proc);
        } // FOR
    }
    if (args.getBooleanParam(ArgumentsParser.PARAM_PARTITION_PLAN_RANDOM_PROCS, false)) {
        for (Procedure catalog_proc : pplan.proc_entries.keySet()) {
            pplan.setRandomProcParameter(catalog_proc);
        } // FOR
    }
    pplan.apply(args.catalog_db);

    System.out.println("Applied PartitionPlan '" + pplan_path + "' to catalog\n" + pplan);
    System.out.print(StringUtil.DOUBLE_LINE);
    // if (!table_output) {
    //
    // }
    // } else if (!table_output) {
    // System.err.println("PartitionPlan file '" + pplan_path +
    // "' does not exist. Ignoring...");
    // }
    if (args.hasParam(ArgumentsParser.PARAM_PARTITION_PLAN_OUTPUT)) {
        String output = args.getParam(ArgumentsParser.PARAM_PARTITION_PLAN_OUTPUT);
        if (output.equals("-"))
            output = pplan_path.getAbsolutePath();
        pplan.save(output);
        System.out.println("Saved PartitionPlan to '" + output + "'");
    }

    System.out.flush();

    // TODO: REMOVE STORED PROCEDURE ROUTING FOR SCHISM

    long singlepartition = 0;
    long multipartition = 0;
    long total = 0;
    SingleSitedCostModel costmodel = new SingleSitedCostModel(args.catalog_db);
    Collection<Integer> all_partitions = CatalogUtil.getAllPartitionIds(args.catalog_db);
    // costmodel.setEntropyWeight(4.0);
    // costmodel.setJavaExecutionWeightEnabled(true);
    // costmodel.setJavaExecutionWeight(100);

    // XXX: 2011-10-28
    costmodel.setCachingEnabled(true);
    Histogram<String> hist = new Histogram<String>();
    for (int i = 0; i < 2; i++) {
        ProfileMeasurement time = new ProfileMeasurement("costmodel").start();
        hist.clear();
        for (AbstractTraceElement<? extends CatalogType> element : args.workload) {
            if (element instanceof TransactionTrace) {
                total++;
                TransactionTrace xact = (TransactionTrace) element;
                boolean is_singlesited = costmodel.processTransaction(args.catalog_db, xact, null).singlesited;
                if (is_singlesited) {
                    singlepartition++;
                    hist.put(xact.getCatalogItemName());
                } else {
                    multipartition++;
                    if (!hist.contains(xact.getCatalogItemName()))
                        hist.put(xact.getCatalogItemName(), 0);
                }
            }
        } // FOR
        System.err.println("ESTIMATE TIME: " + time.stop().getTotalThinkTimeSeconds());
        break; // XXX
    } // FOR
      // long total_partitions_touched_txns =
      // costmodel.getTxnPartitionAccessHistogram().getSampleCount();
      // long total_partitions_touched_queries =
      // costmodel.getQueryPartitionAccessHistogram().getSampleCount();

    Histogram<Integer> h = null;
    if (!table_output) {
        System.out.println("Workload Procedure Histogram:");
        System.out.println(StringUtil.addSpacers(args.workload.getProcedureHistogram().toString()));
        System.out.print(StringUtil.DOUBLE_LINE);

        System.out.println("SinglePartition Procedure Histogram:");
        System.out.println(StringUtil.addSpacers(hist.toString()));
        System.out.print(StringUtil.DOUBLE_LINE);

        System.out.println("Java Execution Histogram:");
        h = costmodel.getJavaExecutionHistogram();
        h.setKeepZeroEntries(true);
        h.putAll(all_partitions, 0);
        System.out.println(StringUtil.addSpacers(h.toString()));
        System.out.print(StringUtil.DOUBLE_LINE);

        System.out.println("Transaction Partition Histogram:");
        h = costmodel.getTxnPartitionAccessHistogram();
        h.setKeepZeroEntries(true);
        h.putAll(all_partitions, 0);
        System.out.println(StringUtil.addSpacers(h.toString()));
        System.out.print(StringUtil.DOUBLE_LINE);

        System.out.println("Query Partition Touch Histogram:");
        h = costmodel.getQueryPartitionAccessHistogram();
        h.setKeepZeroEntries(true);
        h.putAll(all_partitions, 0);
        System.out.println(StringUtil.addSpacers(h.toString()));
        System.out.print(StringUtil.DOUBLE_LINE);
    }

    Map<String, Object> maps[] = new Map[2];
    int idx = 0;
    ListOrderedMap<String, Object> m = null;

    // Execution Cost
    m = new ListOrderedMap<String, Object>();
    m.put("SINGLE-PARTITION", singlepartition);
    m.put("MULTI-PARTITION", multipartition);
    m.put("TOTAL", total + " [" + singlepartition / (double) total + "]");
    m.put("PARTITIONS TOUCHED (TXNS)", costmodel.getTxnPartitionAccessHistogram().getSampleCount());
    m.put("PARTITIONS TOUCHED (QUERIES)", costmodel.getQueryPartitionAccessHistogram().getSampleCount());
    maps[idx++] = m;

    // Utilization
    m = new ListOrderedMap<String, Object>();
    costmodel.getJavaExecutionHistogram().setKeepZeroEntries(false);
    int active_partitions = costmodel.getJavaExecutionHistogram().getValueCount();
    m.put("ACTIVE PARTITIONS", active_partitions);
    m.put("IDLE PARTITIONS", (all_partitions.size() - active_partitions));
    // System.out.println("Partitions Touched By Queries: " +
    // total_partitions_touched_queries);

    Histogram<Integer> entropy_h = costmodel.getJavaExecutionHistogram();
    m.put("JAVA SKEW",
            SkewFactorUtil.calculateSkew(all_partitions.size(), entropy_h.getSampleCount(), entropy_h));

    entropy_h = costmodel.getTxnPartitionAccessHistogram();
    m.put("TRANSACTION SKEW",
            SkewFactorUtil.calculateSkew(all_partitions.size(), entropy_h.getSampleCount(), entropy_h));

    // TimeIntervalCostModel<SingleSitedCostModel> timecostmodel = new
    // TimeIntervalCostModel<SingleSitedCostModel>(args.catalog_db,
    // SingleSitedCostModel.class, 1);
    // timecostmodel.estimateCost(args.catalog_db, args.workload);
    // double entropy = timecostmodel.getLastEntropyCost()
    m.put("UTILIZATION",
            (costmodel.getJavaExecutionHistogram().getValueCount() / (double) all_partitions.size()));
    maps[idx++] = m;

    System.out.println(StringUtil.formatMaps(maps));
}

From source file:com.serena.rlc.provider.tfs.client.TFSClient.java

static public void main(String[] args) {
    TFSClient tfs = new TFSClient(null, "https://digitalparkingsolutions.visualstudio.com", "1.0",
            "https://digitalparkingsolutions.vsrm.visualstudio.com", "3.0-preview.1", "2.0",
            "DefaultCollection", "kevinalee", "67popgoaxbdm2ducvhaf54fgmtzbouronq22rfdb6fddt542c3va");

    Project firstProj = null;//from   w ww .  j a  va2s. co m
    Query firstQuery = null;
    WorkItem firstWorkItem = null;
    ReleaseDefinition firstReleaseDefinition = null;
    Release firstRelease = null;
    Environment firstEnvironment = null;
    BuildDefinition firstBuildDefinition = null;
    BuildQueue firstBuildQueue = null;
    Build firstBuild = null;

    System.out.println("Retrieving TFS Projects...");
    List<Project> projects = null;
    try {
        projects = tfs.getProjects();
        for (Project p : projects) {
            if (firstProj == null)
                firstProj = p;
            System.out.println("Found Project: " + p.getTitle());
            System.out.println("Description: " + p.getDescription());
            System.out.println("URL: " + p.getUrl());
        }
    } catch (TFSClientException e) {
        System.out.print(e.toString());
    }

    System.out.println("Retrieving TFS Queries...");
    List<Query> queries = null;
    try {
        queries = tfs.getQueries(firstProj.getId(), "Shared Queries");
        for (Query q : queries) {
            if (firstQuery == null)
                firstQuery = q;
            System.out.println("Found Query: " + q.getTitle());
            System.out.println("Path: " + q.getPath());
            System.out.println("URL: " + q.getUrl());
        }
    } catch (TFSClientException e) {
        System.out.print(e.toString());
    }

    for (Query query : queries) {
        System.out.println("Retrieving Work Items for Query: " + query.getTitle());
        if (query.getIsFolder())
            continue;
        List<WorkItem> workItems = null;
        try {
            workItems = tfs.getWorkItems(query.getId(), "", 2);
            if (workItems != null) {
                for (WorkItem wi : workItems) {
                    if (firstWorkItem == null)
                        firstWorkItem = wi;
                    System.out.println("Found Work Item: " + wi.getId());
                    System.out.println("Title: " + wi.getTitle());
                    System.out.println("Description: " + wi.getDescription());
                    System.out.println("Severity: " + wi.getSeverity());
                }
            }
        } catch (TFSClientException e) {
            System.out.print(e.toString());
        }
    }

    System.out.println("Retrieving Work Item: " + firstWorkItem.getId() + "...");
    try {
        WorkItem wi = tfs.getWorkItem(firstWorkItem.getId());
        System.out.println("Found Work Item: " + wi.getId());
        System.out.println("Title: " + wi.getTitle());
        System.out.println("State: " + wi.getState());
        System.out.println("Severity: " + wi.getSeverity());
        System.out.println("Type: " + wi.getType());
        System.out.println("Project: " + wi.getProject());
    } catch (TFSClientException e) {
        System.out.print(e.toString());
    }

    System.out.println("Retrieving TFS Release Definitions...");
    List<ReleaseDefinition> releaseDefinitions = null;
    try {
        releaseDefinitions = tfs.getReleaseDefinitions(firstProj.getId());
        for (ReleaseDefinition rd : releaseDefinitions) {
            if (firstReleaseDefinition == null)
                firstReleaseDefinition = rd;
            System.out.println("Found Release Definition: " + rd.getId() + " - " + rd.getTitle());
            System.out.println("URL: " + rd.getUrl());
        }
    } catch (TFSClientException e) {
        System.out.print(e.toString());
    }

    System.out.println("Retrieving TFS Releases...");
    List<Release> releases = null;
    try {
        releases = tfs.getReleases(firstProj.getId(), firstReleaseDefinition.getId());
        for (Release r : releases) {
            if (firstRelease == null)
                firstRelease = r;
            System.out.println("Found Release: " + r.getId() + " - " + r.getTitle());
            System.out.println("Status: " + r.getState());
            for (Environment e : r.getEnvironments()) {
                if (firstEnvironment == null) {
                    firstEnvironment = e;
                }
                System.out.println("with Environment: " + e.getId() + " - " + e.getTitle());
            }
        }
    } catch (TFSClientException e) {
        System.out.print(e.toString());
    }

    System.out.println("Deploying Release " + firstRelease.getTitle() + " to " + firstEnvironment.getTitle());
    try {
        Release release = tfs.deployRelease(firstProj.getId(), firstRelease.getId(), firstEnvironment.getId());
        System.out.println("Release " + release.getTitle() + " has status: " + release.getState());
    } catch (TFSClientException e) {
        System.out.print(e.toString());
    }

    int pollCount = 0;
    String deployStatus = null;
    while (pollCount < 100) {
        try {
            Thread.sleep(6000);
            deployStatus = tfs.getReleaseEnvironmentStatus(firstProj.getId(), firstRelease.getId(),
                    firstEnvironment.getId());
            System.out.println("Environment Deployment Status = " + deployStatus);
        } catch (TFSClientException e) {
            logger.debug("Error checking release status ({}) - {}", firstRelease.getId(), e.getMessage());
        } catch (InterruptedException e) {
        }
        if (deployStatus != null && (deployStatus.equals("succeeded") || deployStatus.equals("rejected")
                || deployStatus.equals("failed"))) {
            break;
        }

        pollCount++;
    }

    if (deployStatus != null && deployStatus.equals("succeeded")) {
        System.out.println("Release " + firstRelease.getTitle() + " has succeeded");
    } else {
        System.out.println("Release " + firstRelease.getTitle()
                + " has failed/rejected or its status cannot be retrieved.");
    }

    System.out.println("Retrieving TFS Build Definitions...");
    List<BuildDefinition> buildDefinitions = null;
    try {
        buildDefinitions = tfs.getBuildDefinitions(firstProj.getId(), "");
        for (BuildDefinition bd : buildDefinitions) {
            if (firstBuildDefinition == null)
                firstBuildDefinition = bd;
            System.out.println("Found Build Definition: " + bd.getId() + " - " + bd.getTitle());
            System.out.println("URL: " + bd.getUrl());
        }
    } catch (TFSClientException e) {
        System.out.print(e.toString());
    }

    System.out.println("Retrieving TFS Build Queues...");
    List<BuildQueue> buildQueues = null;
    try {
        buildQueues = tfs.getBuildQueues("buildController", "");
        for (BuildQueue bq : buildQueues) {
            if (firstBuildQueue == null)
                firstBuildQueue = bq;
            System.out.println("Found Build Queue: " + bq.getId() + " - " + bq.getTitle());
            System.out.println("URL: " + bq.getUrl());
        }
    } catch (TFSClientException e) {
        System.out.print(e.toString());
    }

    System.out.println("Retrieving TFS Builds...");
    List<Build> builds = null;
    try {
        builds = tfs.getBuilds(firstProj.getId(), firstBuildDefinition.getId(), "", "", 50);
        for (Build b : builds) {
            if (firstBuild == null)
                firstBuild = b;
            System.out.println("Found Build: " + b.getId() + " - " + b.getBuildNumber());
            System.out.println("Status: " + b.getState());
            System.out.println("Result: " + b.getBuildResult());
        }
    } catch (TFSClientException e) {
        System.out.print(e.toString());
    }

    Build queuedBuild = null;
    System.out.println("Queuing Build for Definition " + firstBuildDefinition.getTitle());
    try {
        queuedBuild = tfs.queueBuild(firstProj.getId(), firstBuildDefinition.getId(), firstBuildQueue.getId(),
                null);
        System.out.println("Build " + queuedBuild.getBuildNumber() + " has status: " + queuedBuild.getState());
    } catch (TFSClientException e) {
        System.out.print(e.toString());
    }

    pollCount = 0;
    String buildStatus = null;
    String buildResult = null;
    while (pollCount < 100) {
        try {
            Thread.sleep(6000);
            Build tmpBuild = tfs.getBuild(firstProj.getId(), queuedBuild.getId());
            buildStatus = tmpBuild.getState();
            System.out.println("Build Status = " + buildStatus);
            System.out.println("Build Result = " + buildResult);
        } catch (TFSClientException e) {
            logger.debug("Error checking build status ({}) - {}", queuedBuild.getId(), e.getMessage());
        } catch (InterruptedException e) {
        }
        if (buildStatus != null && buildStatus.equals("completed")) {
            break;
        }

        pollCount++;
    }

    if (buildStatus != null && buildStatus.equals("completed")) {
        System.out.println("Build " + queuedBuild.getId() + " has completed with result " + buildResult);
    } else {
        System.out.println("Build " + queuedBuild.getId() + " result cannot be retrieved.");
    }

}

From source file:com.adobe.aem.demomachine.RegExp.java

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

    String fileName = null;//from w  w  w. j a  va  2s.  c  o  m
    String regExp = null;
    String position = null;
    String value = "n/a";
    List<String> allMatches = new ArrayList<String>();

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Filename");
    options.addOption("r", true, "RegExp");
    options.addOption("p", true, "Position");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            fileName = cmd.getOptionValue("f");
        }

        if (cmd.hasOption("f")) {
            regExp = cmd.getOptionValue("r");
        }

        if (cmd.hasOption("p")) {
            position = cmd.getOptionValue("p");
        }

        if (fileName == null || regExp == null || position == null) {
            System.out.println("Command line parameters: -f fileName -r regExp -p position");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    String content = readFile(fileName, Charset.defaultCharset());

    if (content != null) {
        Matcher m = Pattern.compile(regExp).matcher(content);
        while (m.find()) {
            String group = m.group();
            int pos = group.indexOf(".zip");
            if (pos > 0) {
                group = group.substring(0, pos);
            }
            logger.debug("RegExp: " + m.group() + " found returning " + group);
            allMatches.add(group);
        }

        if (allMatches.size() > 0) {

            if (position.equals("first")) {
                value = allMatches.get(0);
            }

            if (position.equals("last")) {
                value = allMatches.get(allMatches.size() - 1);
            }
        }
    }

    System.out.println(value);

}

From source file:ca.uqac.dim.mapreduce.ltl.LTLValidation.java

/**
 * Program entry point.//from www  . java 2  s .c o  m
 * @param args Command-line arguments
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    // Define and process command line arguments
    Options options = new Options();
    HelpFormatter help_formatter = new HelpFormatter();
    Option opt;
    options.addOption("h", "help", false, "Show help");
    opt = OptionBuilder.withArgName("property").hasArg()
            .withDescription("Property to verify, enclosed in double quotes").create("p");
    options.addOption(opt);
    opt = OptionBuilder.withArgName("filename").hasArg().withDescription("Input filename").create("i");
    options.addOption(opt);
    opt = OptionBuilder.withArgName("x").hasArg()
            .withDescription("Set verbosity level to x (default: 0 = quiet)").create("v");
    options.addOption(opt);
    opt = OptionBuilder.withArgName("ParserType").hasArg().withDescription("Parser type (Dom or Sax)")
            .create("t");
    options.addOption(opt);
    opt = OptionBuilder.withLongOpt("redirection").withArgName("x").hasArg()
            .withDescription("Set the redirection file for the System.out").create("r");
    options.addOption(opt);
    CommandLine c_line = parseCommandLine(options, args);

    String redirectionFile = "";

    //Contains a redirection file for the output
    if (c_line.hasOption("redirection")) {
        try {
            redirectionFile = c_line.getOptionValue("redirection");
            PrintStream ps;
            ps = new PrintStream(redirectionFile);
            System.setOut(ps);
        } catch (FileNotFoundException e) {
            System.out.println("Redirection error !!!");
            e.printStackTrace();
        }
    }

    if (!c_line.hasOption("p") || !c_line.hasOption("i") | c_line.hasOption("h")) {
        help_formatter.printHelp(app_name, options);
        System.exit(1);
    }
    assert c_line.hasOption("p");
    assert c_line.hasOption("i");
    String trace_filename = c_line.getOptionValue("i");
    String trace_format = getExtension(trace_filename);
    String property_str = c_line.getOptionValue("p");
    String ParserType = "";

    if (c_line.hasOption("t")) {
        ParserType = c_line.getOptionValue("t");
    } else {
        System.err.println("No Parser Type in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    if (c_line.hasOption("v"))
        m_verbosity = Integer.parseInt(c_line.getOptionValue("v"));

    // Obtain the property to verify and break into subformulas
    Operator property = null;
    try {
        int preset = Integer.parseInt(property_str);
        property = new Edoc2012Presets().property(preset);
    } catch (NumberFormatException e) {
        try {
            property = Operator.parseFromString(property_str);
        } catch (Operator.ParseException pe) {
            System.err.println("ERROR: parsing");
            System.exit(1);
        }
    }
    Set<Operator> subformulas = property.getSubformulas();

    // Initialize first collector depending on input file format
    int max_loops = property.getDepth();
    int max_tuples_total = 0, total_tuples_total = 0;
    long time_begin = System.nanoTime();
    TraceCollector initial_collector = null;
    {
        File in_file = new File(trace_filename);
        if (trace_format.compareToIgnoreCase(".txt") == 0) {
            initial_collector = new CharacterTraceCollector(in_file, subformulas);
        } else if (trace_format.compareToIgnoreCase(".xml") == 0) {
            if (ParserType.equals("Dom")) {
                initial_collector = new XmlDomTraceCollector(in_file, subformulas);
            } else if (ParserType.equals("Sax")) {
                initial_collector = new XmlSaxTraceCollector(in_file, subformulas);
            } else {
                initial_collector = new XmlSaxTraceCollector(in_file, subformulas);
            }
        }
    }
    if (initial_collector == null) {
        System.err.println("ERROR: unrecognized input format");
        System.exit(1);
    }

    // Start workflow
    int trace_len = initial_collector.getTraceLength();
    InCollector<Operator, LTLTupleValue> loop_collector = initial_collector;
    print(System.out, property.toString(), 2);
    print(System.out, loop_collector.toString(), 3);
    for (int i = 0; i < max_loops; i++) {
        print(System.out, "Loop " + i, 2);
        LTLSequentialWorkflow w = new LTLSequentialWorkflow(new LTLMapper(subformulas),
                new LTLReducer(subformulas, trace_len), loop_collector);
        loop_collector = w.run();
        max_tuples_total += w.getMaxTuples();
        total_tuples_total += w.getTotalTuples();

        if (m_verbosity >= 3) {
            print(System.out, loop_collector.toString(), 3);
        }

    }
    boolean result = getVerdict(loop_collector, property);
    long time_end = System.nanoTime();
    if (result)
        print(System.out, "Formula is true", 1);
    else
        print(System.out, "Formula is false", 1);

    long time_total = (time_end - time_begin) / 1000000;
    System.out.println(trace_len + "," + max_tuples_total + "," + total_tuples_total + "," + time_total);
}

From source file:net.massbank.validator.RecordValidator.java

public static void main(String[] args) {
    RequestDummy request;//w  w  w  . ja  va 2s . c  om

    PrintStream out = System.out;

    Options lvOptions = new Options();
    lvOptions.addOption("h", "help", false, "show this help.");
    lvOptions.addOption("r", "recdata", true,
            "points to the recdata directory containing massbank records. Reads all *.txt files in there.");

    CommandLineParser lvParser = new BasicParser();
    CommandLine lvCmd = null;
    try {
        lvCmd = lvParser.parse(lvOptions, args);
        if (lvCmd.hasOption('h')) {
            printHelp(lvOptions);
            return;
        }
    } catch (org.apache.commons.cli.ParseException pvException) {
        System.out.println(pvException.getMessage());
    }

    String recDataPath = lvCmd.getOptionValue("recdata");

    // ---------------------------------------------
    // ????
    // ---------------------------------------------

    final String baseUrl = MassBankEnv.get(MassBankEnv.KEY_BASE_URL);
    final String dbRootPath = "./";
    final String dbHostName = MassBankEnv.get(MassBankEnv.KEY_DB_HOST_NAME);
    final String tomcatTmpPath = ".";
    final String tmpPath = (new File(tomcatTmpPath + sdf.format(new Date()))).getPath() + File.separator;
    GetConfig conf = new GetConfig(baseUrl);
    int recVersion = 2;
    String selDbName = "";
    Object up = null; // Was: file Upload
    boolean isResult = true;
    String upFileName = "";
    boolean upResult = false;
    DatabaseAccess db = null;

    try {
        // ----------------------------------------------------
        // ???
        // ----------------------------------------------------
        // if (FileUpload.isMultipartContent(request)) {
        // (new File(tmpPath)).mkdir();
        // String os = System.getProperty("os.name");
        // if (os.indexOf("Windows") == -1) {
        // isResult = FileUtil.changeMode("777", tmpPath);
        // if (!isResult) {
        // out.println(msgErr("[" + tmpPath
        // + "]  chmod failed."));
        // return;
        // }
        // }
        // up = new FileUpload(request, tmpPath);
        // }

        // ----------------------------------------------------
        // ?DB????
        // ----------------------------------------------------
        List<String> dbNameList = Arrays.asList(conf.getDbName());
        ArrayList<String> dbNames = new ArrayList<String>();
        dbNames.add("");
        File[] dbDirs = (new File(dbRootPath)).listFiles();
        if (dbDirs != null) {
            for (File dbDir : dbDirs) {
                if (dbDir.isDirectory()) {
                    int pos = dbDir.getName().lastIndexOf("\\");
                    String dbDirName = dbDir.getName().substring(pos + 1);
                    pos = dbDirName.lastIndexOf("/");
                    dbDirName = dbDirName.substring(pos + 1);
                    if (dbNameList.contains(dbDirName)) {
                        // DB???massbank.conf???DB????
                        dbNames.add(dbDirName);
                    }
                }
            }
        }
        if (dbDirs == null || dbNames.size() == 0) {
            out.println(msgErr("[" + dbRootPath + "] directory not exist."));
            return;
        }
        Collections.sort(dbNames);

        // ----------------------------------------------------
        // ?
        // ----------------------------------------------------
        // if (FileUpload.isMultipartContent(request)) {
        // HashMap<String, String[]> reqParamMap = new HashMap<String,
        // String[]>();
        // reqParamMap = up.getRequestParam();
        // if (reqParamMap != null) {
        // for (Map.Entry<String, String[]> req : reqParamMap
        // .entrySet()) {
        // if (req.getKey().equals("ver")) {
        // try {
        // recVersion = Integer
        // .parseInt(req.getValue()[0]);
        // } catch (NumberFormatException nfe) {
        // }
        // } else if (req.getKey().equals("db")) {
        // selDbName = req.getValue()[0];
        // }
        // }
        // }
        // } else {
        // if (request.getParameter("ver") != null) {
        // try {
        // recVersion = Integer.parseInt(request
        // .getParameter("ver"));
        // } catch (NumberFormatException nfe) {
        // }
        // }
        // selDbName = request.getParameter("db");
        // }
        // if (selDbName == null || selDbName.equals("")
        // || !dbNames.contains(selDbName)) {
        // selDbName = dbNames.get(0);
        // }

        // ---------------------------------------------
        // 
        // ---------------------------------------------
        out.println("Database: ");
        for (int i = 0; i < dbNames.size(); i++) {
            String dbName = dbNames.get(i);
            out.print("dbName");
            if (dbName.equals(selDbName)) {
                out.print(" selected");
            }
            if (i == 0) {
                out.println("------------------");
            } else {
                out.println(dbName);
            }
        }
        out.println("Record Version : ");
        out.println(recVersion);

        out.println("Record Archive :");

        // ---------------------------------------------
        // 
        // ---------------------------------------------
        //         HashMap<String, Boolean> upFileMap = up.doUpload();
        //         if (upFileMap != null) {
        //            for (Map.Entry<String, Boolean> e : upFileMap.entrySet()) {
        //               upFileName = e.getKey();
        //               upResult = e.getValue();
        //               break;
        //            }
        //            if (upFileName.equals("")) {
        //               out.println(msgErr("please select file."));
        //               isResult = false;
        //            } else if (!upResult) {
        //               out.println(msgErr("[" + upFileName
        //                     + "] upload failed."));
        //               isResult = false;
        //            } else if (!upFileName.endsWith(ZIP_EXTENSION)
        //                  && !upFileName.endsWith(MSBK_EXTENSION)) {
        //               out.println(msgErr("please select ["
        //                     + UPLOAD_RECDATA_ZIP
        //                     + "] or ["
        //                     + UPLOAD_RECDATA_MSBK + "]."));
        //               up.deleteFile(upFileName);
        //               isResult = false;
        //            }
        //         } else {
        //            out.println(msgErr("server error."));
        //            isResult = false;
        //         }
        //         up.deleteFileItem();
        //         if (!isResult) {
        //            return;
        //         }

        // ---------------------------------------------
        // ???
        // ---------------------------------------------
        //         final String upFilePath = (new File(tmpPath + File.separator
        //               + upFileName)).getPath();
        //         isResult = FileUtil.unZip(upFilePath, tmpPath);
        //         if (!isResult) {
        //            out.println(msgErr("["
        //                  + upFileName
        //                  + "]  extraction failed. possibility of time-out."));
        //            return;
        //         }

        // ---------------------------------------------
        // ??
        // ---------------------------------------------
        final String recPath = (new File(dbRootPath + File.separator + selDbName)).getPath();
        File tmpRecDir = new File(recDataPath);
        if (!tmpRecDir.isDirectory()) {
            tmpRecDir.mkdirs();
        }

        // ---------------------------------------------
        // ???
        // ---------------------------------------------
        // data?
        //         final String recDataPath = (new File(tmpPath + File.separator
        //               + RECDATA_DIR_NAME)).getPath()
        //               + File.separator;
        //
        //         if (!(new File(recDataPath)).isDirectory()) {
        //            if (upFileName.endsWith(ZIP_EXTENSION)) {
        //               out.println(msgErr("["
        //                     + RECDATA_DIR_NAME
        //                     + "]  directory is not included in the up-loading file."));
        //            } else if (upFileName.endsWith(MSBK_EXTENSION)) {
        //               out.println(msgErr("The uploaded file is not record data."));
        //            }
        //            return;
        //         }

        // ---------------------------------------------
        // DB
        // ---------------------------------------------
        //         db = new DatabaseAccess(dbHostName, selDbName);
        //         isResult = db.open();
        //         if (!isResult) {
        //            db.close();
        //            out.println(msgErr("not connect to database."));
        //            return;
        //         }

        // ---------------------------------------------
        // ??
        // ---------------------------------------------
        TreeMap<String, String> resultMap = validationRecord(db, out, recDataPath, recPath, recVersion);
        if (resultMap.size() == 0) {
            return;
        }

        // ---------------------------------------------
        // ?
        // ---------------------------------------------
        isResult = dispResult(out, resultMap);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (db != null) {
            db.close();
        }
        File tmpDir = new File(tmpPath);
        if (tmpDir.exists()) {
            FileUtil.removeDir(tmpDir.getPath());
        }
    }

}

From source file:edu.msu.cme.rdp.seqmatch.cli.SeqmatchCheckRevSeq.java

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

    String trainingFile = null;//from   w  w  w  .  j ava2 s  .co  m
    String queryFile = null;
    String outputFile = null;
    PrintWriter revOutputWriter = new PrintWriter(System.out);
    PrintStream correctedQueryOut = System.out;
    String traineeDesc = null;
    int numOfResults = 20;
    boolean checkReverse = false;

    float diffScoreCutoff = CheckReverseSeq.DIFF_SCORE_CUTOFF;
    String format = "txt"; // default

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("c")) {
            checkReverse = true;
        }

        if (line.hasOption("t")) {
            trainingFile = line.getOptionValue("t");
        } else {
            throw new Exception("training file must be specified");
        }
        if (line.hasOption("q")) {
            queryFile = line.getOptionValue("q");
        } else {
            throw new Exception("query file must be specified");
        }
        if (line.hasOption("o")) {
            outputFile = line.getOptionValue("o");
        } else {
            throw new Exception("output file must be specified");
        }
        if (line.hasOption("r")) {
            revOutputWriter = new PrintWriter(line.getOptionValue("r"));
        }
        if (line.hasOption("s")) {
            correctedQueryOut = new PrintStream(line.getOptionValue("s"));
        }
        if (line.hasOption("d")) {
            diffScoreCutoff = Float.parseFloat(line.getOptionValue("d"));
        }
        if (line.hasOption("h")) {
            traineeDesc = line.getOptionValue("h");
        }
        if (line.hasOption("n")) {
            numOfResults = Integer.parseInt(line.getOptionValue("n"));
        }
        if (line.hasOption("f")) {
            format = line.getOptionValue("f");
            if (!format.equals("tab") && !format.equals("dbformat") && !format.equals("xml")) {
                throw new IllegalArgumentException("Only dbformat, tab or xml format available");
            }
        }

    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(120, "SeqmatchCheckRevSeq", "", options, "", true);
        return;
    }

    SeqmatchCheckRevSeq theObj = new SeqmatchCheckRevSeq();

    if (!checkReverse) {
        theObj.doUserLibMatch(queryFile, trainingFile, outputFile, numOfResults, format, traineeDesc);
    } else {
        theObj.checkRevSeq(queryFile, trainingFile, outputFile, revOutputWriter, correctedQueryOut,
                diffScoreCutoff, format, traineeDesc);
    }
}

From source file:DokeosConverter.java

public static void main(String[] arguments) throws Exception {
    CommandLineParser commandLineParser = new PosixParser();
    CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments);

    int port = SocketOpenOfficeConnection.DEFAULT_PORT;
    if (commandLine.hasOption(OPTION_PORT.getOpt())) {
        port = Integer.parseInt(commandLine.getOptionValue(OPTION_PORT.getOpt()));
    }//  w  ww .ja  v a  2 s  . c  o  m

    String outputFormat = null;
    if (commandLine.hasOption(OPTION_OUTPUT_FORMAT.getOpt())) {
        outputFormat = commandLine.getOptionValue(OPTION_OUTPUT_FORMAT.getOpt());
    }

    boolean verbose = false;
    if (commandLine.hasOption(OPTION_VERBOSE.getOpt())) {
        verbose = true;
    }

    String dokeosMode = "woogie";
    if (commandLine.hasOption(OPTION_DOKEOS_MODE.getOpt())) {
        dokeosMode = commandLine.getOptionValue(OPTION_DOKEOS_MODE.getOpt());
    }
    int width = 800;
    if (commandLine.hasOption(OPTION_WIDTH.getOpt())) {
        width = Integer.parseInt(commandLine.getOptionValue(OPTION_WIDTH.getOpt()));
    }

    int height = 600;
    if (commandLine.hasOption(OPTION_HEIGHT.getOpt())) {
        height = Integer.parseInt(commandLine.getOptionValue(OPTION_HEIGHT.getOpt()));
    }

    String[] fileNames = commandLine.getArgs();
    if ((outputFormat == null && fileNames.length != 2 && dokeosMode != null) || fileNames.length < 1) {
        String syntax = "convert [options] input-file output-file; or\n"
                + "[options] -f output-format input-file [input-file...]";
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(syntax, OPTIONS);
        System.exit(EXIT_CODE_TOO_FEW_ARGS);
    }

    OpenOfficeConnection connection = new DokeosSocketOfficeConnection(port);
    try {
        if (verbose) {
            System.out.println("-- connecting to OpenOffice.org on port " + port);
        }
        connection.connect();
    } catch (ConnectException officeNotRunning) {
        System.err.println(
                "ERROR: connection failed. Please make sure OpenOffice.org is running and listening on port "
                        + port + ".");
        System.exit(EXIT_CODE_CONNECTION_FAILED);
    }
    try {

        // choose the good constructor to deal with the conversion
        DocumentConverter converter;
        if (dokeosMode.equals("oogie")) {
            converter = new OogieDocumentConverter(connection, new DokeosDocumentFormatRegistry(), width,
                    height);
        } else if (dokeosMode.equals("woogie")) {
            converter = new WoogieDocumentConverter(connection, new DokeosDocumentFormatRegistry(), width,
                    height);
        } else {
            converter = new OpenOfficeDocumentConverter(connection);
        }

        if (outputFormat == null) {
            File inputFile = new File(fileNames[0]);
            File outputFile = new File(fileNames[1]);
            convertOne(converter, inputFile, outputFile, verbose);
        } else {
            for (int i = 0; i < fileNames.length; i++) {
                File inputFile = new File(fileNames[i]);
                File outputFile = new File(FilenameUtils.getFullPath(fileNames[i])
                        + FilenameUtils.getBaseName(fileNames[i]) + "." + outputFormat);
                convertOne(converter, inputFile, outputFile, verbose);
            }
        }
    } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
        connection.disconnect();
        System.err.println("ERROR: conversion failed.");
        System.exit(EXIT_CODE_CONVERSION_FAILED);
    } finally {
        if (verbose) {
            System.out.println("-- disconnecting");
        }
        connection.disconnect();
    }
}