Example usage for java.lang Integer valueOf

List of usage examples for java.lang Integer valueOf

Introduction

In this page you can find the example usage for java.lang Integer valueOf.

Prototype

@HotSpotIntrinsicCandidate
public static Integer valueOf(int i) 

Source Link

Document

Returns an Integer instance representing the specified int value.

Usage

From source file:main.Main.java

/**
 * The public main function./*from  w ww.j av a 2s .c o  m*/
 * @param args
 */
public static void main(String[] args) {
    System.out.println("Starting");

    Options options = new Options();

    Option solutionOption = new Option("s", "solution", true,
            "This will be the " + "solution of the cross word game. (aka. This will be the first"
                    + " vertical word on the canvas.)");

    //        solutionOption.setRequired(true);

    Option numOfBatchOption = new Option("n", "numOfBatch", true, "");

    Option verboseOption = new Option("v", "verbose", false, "Print some debug information during running.");
    Option veryVerboseOption = new Option("vv", "very-verbose", false, "Print more debug information.");

    options.addOption(solutionOption);
    options.addOption(numOfBatchOption);
    options.addOption(verboseOption);
    options.addOption(veryVerboseOption);

    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("utility-name", options);

        System.exit(1);
        return;
    }

    System.out.println(cmd.getArgList());

    int debugLevel = 0;
    if (cmd.hasOption("verbose")) {
        debugLevel = 1;
    }
    if (cmd.hasOption("very-verbose")) {
        debugLevel = 2;
    }
    String solution = cmd.getOptionValue("solution");
    if (null == solution) {
        startGui();
    } else {
        int numOfBatch = Integer.valueOf(cmd.getOptionValue("numOfBatch", "200"));
        System.out.println(solution);
        Generator gen = new Generator(solution, debugLevel); // <---- EDIT THIS LINE FOR DIFFERENT SOLUTIONS.
        long startTime = System.currentTimeMillis();
        gen.generate(numOfBatch);
        long estimatedTime = System.currentTimeMillis() - startTime;
        System.out.print("estimatedTime: " + estimatedTime + "ms");
    }
}

From source file:com.sm.test.TestPst.java

public static void main(String[] args) {
    String[] opts = new String[] { "-store", "-url", "-times" };
    String[] defaults = new String[] { "campaigns", "localhost:7220", "10", "/Users/mhsieh/test/files",
            "campaigns.0" };
    String[] paras = getOpts(args, opts, defaults);
    String store = paras[0];//  w ww . j a v a2  s  . c om
    String url = paras[1];
    int times = Integer.valueOf(paras[2]);
    String path = paras[3];
    String file = paras[4];
    RemotePersistence client = new NTRemoteClientImpl(url, null, store, false);
    TestPst testPst = new TestPst(path + "/" + file);
    testPst.getListValues("camp100000454", client);
    client.close();
    System.exit(0);
}

From source file:edu.msu.cme.rdp.graph.sandbox.KmerStartsFromKnown.java

public static void main(String[] args) throws Exception {
    final KmerStartsWriter out;
    final boolean translQuery;
    final int wordSize;
    final int translTable;

    try {/*from  ww w.  j  a va 2s .  c o m*/
        CommandLine cmdLine = new PosixParser().parse(options, args);
        args = cmdLine.getArgs();

        if (args.length < 2) {
            throw new Exception("Unexpected number of arguments");
        }

        if (cmdLine.hasOption("out")) {
            out = new KmerStartsWriter(cmdLine.getOptionValue("out"));
        } else {
            out = new KmerStartsWriter(System.out);
        }

        if (cmdLine.hasOption("transl-table")) {
            translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table"));
        } else {
            translTable = 11;
        }

        translQuery = cmdLine.hasOption("transl-kmer");
        wordSize = Integer.valueOf(args[0]);

    } catch (Exception e) {
        new HelpFormatter().printHelp("KmerStartsFromKnown <word_size> [name=]<ref_file> ...", options);
        System.err.println(e.getMessage());
        System.exit(1);
        throw new RuntimeException("Stupid jvm"); //While this will never get thrown it is required to make sure javac doesn't get confused about uninitialized variables
    }

    long startTime = System.currentTimeMillis();

    /*
     * if (args.length == 4) { maxThreads = Integer.valueOf(args[3]); } else
     * {
     */

    //}

    System.err.println("Starting kmer mapping at " + new Date());
    System.err.println("*  References:              " + Arrays.asList(args));
    System.err.println("*  Kmer length:             " + wordSize);

    for (int index = 1; index < args.length; index++) {
        String refName;
        String refFileName = args[index];
        if (refFileName.contains("=")) {
            String[] lexemes = refFileName.split("=");
            refName = lexemes[0];
            refFileName = lexemes[1];
        } else {
            String tmpName = new File(refFileName).getName();
            if (tmpName.contains(".")) {
                refName = tmpName.substring(0, tmpName.lastIndexOf("."));
            } else {
                refName = tmpName;
            }
        }

        File refFile = new File(refFileName);

        if (SeqUtils.guessSequenceType(refFile) != SequenceType.Nucleotide) {
            throw new Exception("Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile)
                    + " sequences but expected nucleotide sequences");
        }

        SequenceReader seqReader = new SequenceReader(refFile);
        Sequence seq;

        while ((seq = seqReader.readNextSequence()) != null) {
            if (seq.getSeqName().startsWith("#")) {
                continue;
            }
            ModelPositionKmerGenerator kmers = new ModelPositionKmerGenerator(seq.getSeqString(), wordSize,
                    SequenceType.Nucleotide);

            for (char[] charmer : kmers) {
                int pos = kmers.getModelPosition() - 1;
                if (translQuery) {
                    if (pos % 3 != 0) {
                        continue;
                    } else {
                        pos /= 3;
                    }
                }

                String kmer = new String(charmer);

                out.write(new KmerStart(refName, seq.getSeqName(), seq.getSeqName(), kmer, 1, pos, translQuery,
                        (translQuery ? ProteinUtils.getInstance().translateToProtein(kmer, true, translTable)
                                : null)));

            }
        }
        seqReader.close();
    }
    out.close();
}

From source file:edu.mit.lib.mama.Mama.java

public static void main(String[] args) {

    Properties props = findConfig(args);
    DBI dbi = new DBI(props.getProperty("dburl"), props);
    // Advanced instrumentation/metrics if requested
    if (System.getenv("MAMA_DB_METRICS") != null) {
        dbi.setTimingCollector(new InstrumentedTimingCollector(metrics));
    }/* w w  w  . j a  v  a 2  s  .  c o m*/
    // reassign default port 4567
    if (System.getenv("MAMA_SVC_PORT") != null) {
        port(Integer.valueOf(System.getenv("MAMA_SVC_PORT")));
    }
    // if API key given, use exception monitoring service
    if (System.getenv("HONEYBADGER_API_KEY") != null) {
        reporter = new HoneybadgerReporter();
    }

    get("/ping", (req, res) -> {
        res.type("text/plain");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        return "pong";
    });

    get("/metrics", (req, res) -> {
        res.type("application/json");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true));
        try (ServletOutputStream outputStream = res.raw().getOutputStream()) {
            objectMapper.writer().withDefaultPrettyPrinter().writeValue(outputStream, metrics);
        }
        return "";
    });

    get("/shutdown", (req, res) -> {
        boolean auth = false;
        try {
            if (!isNullOrEmpty(System.getenv("MAMA_SHUTDOWN_KEY")) && !isNullOrEmpty(req.queryParams("key"))
                    && System.getenv("MAMA_SHUTDOWN_KEY").equals(req.queryParams("key"))) {
                auth = true;
                return "Shutting down";
            } else {
                res.status(401);
                return "Not authorized";
            }
        } finally {
            if (auth) {
                stop();
            }
        }
    });

    get("/item", (req, res) -> {
        if (isNullOrEmpty(req.queryParams("qf")) || isNullOrEmpty(req.queryParams("qv"))) {
            halt(400, "Must supply field and value query parameters 'qf' and 'qv'");
        }
        itemReqs.mark();
        Timer.Context context = respTime.time();
        try (Handle hdl = dbi.open()) {
            if (findFieldId(hdl, req.queryParams("qf")) != -1) {
                List<String> results = findItems(hdl, req.queryParams("qf"), req.queryParams("qv"),
                        req.queryParamsValues("rf"));
                if (results.size() > 0) {
                    res.type("application/json");
                    return "{ " + jsonValue("field", req.queryParams("qf"), true) + ",\n"
                            + jsonValue("value", req.queryParams("qv"), true) + ",\n" + jsonValue("items",
                                    results.stream().collect(Collectors.joining(",", "[", "]")), false)
                            + "\n" + " }";
                } else {
                    res.status(404);
                    return "No items found for: " + req.queryParams("qf") + "::" + req.queryParams("qv");
                }
            } else {
                res.status(404);
                return "No such field: " + req.queryParams("qf");
            }
        } catch (Exception e) {
            if (null != reporter)
                reporter.reportError(e);
            res.status(500);
            return "Internal system error: " + e.getMessage();
        } finally {
            context.stop();
        }
    });

    awaitInitialization();
}

From source file:com.github.projectflink.testPlan.KryoTest.java

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

    // set up the execution environment
    final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

    // get input data
    DataSet<String> text = env.readTextFile(args[0]);
    boolean kryoMode = false;

    if (args[1].equals("kryo")) {
        kryoMode = true;/* w  w w .  j  a  va  2s  .  co  m*/
        DataSet<KryoType> ds = text.map(new MapFunction<String, KryoType>() {
            @Override
            public KryoType map(String s) throws Exception {
                KryoType kt = new KryoType();
                kt.elements = new ArrayList<Object>();
                String[] splits = s.split(" ");
                for (String split : splits) {
                    if (split == null || split.length() == 0)
                        continue;
                    if (StringUtils.isNumeric(split)) {
                        try {
                            kt.elements.add(Integer.valueOf(split));
                        } catch (Throwable t) {
                            kt.elements.add(Integer.valueOf(0));
                        }
                    } else {
                        kt.elements.add(split);
                    }
                }
                return kt;
            }
        });
        DataSet<Tuple2<Object, Integer>> ds1 = ds.rebalance()
                .map(new MapFunction<KryoType, Tuple2<Object, Integer>>() {
                    @Override
                    public Tuple2<Object, Integer> map(KryoType valueType) throws Exception {
                        return new Tuple2<Object, Integer>(valueType.elements.iterator().next(),
                                valueType.elements.size());
                    }
                });
        ds1.output(new DiscardingOutputFormat<Tuple2<Object, Integer>>());
    } else {
        DataSet<ValueType> ds = text.map(new MapFunction<String, ValueType>() {
            @Override
            public ValueType map(String s) throws Exception {
                ValueType vt = new ValueType();
                vt.elements = new ArrayList<Object>();
                String[] splits = s.split(" ");
                for (String split : splits) {
                    if (split == null || split.length() == 0)
                        continue;
                    if (StringUtils.isNumeric(split)) {
                        try {
                            vt.elements.add(Integer.valueOf(split));
                        } catch (Throwable t) {
                            vt.elements.add(Integer.valueOf(0));
                        }

                    } else {
                        vt.elements.add(split);
                    }
                }
                return vt;
            }
        });
        DataSet<Tuple2<Object, Integer>> ds1 = ds.rebalance()
                .map(new MapFunction<ValueType, Tuple2<Object, Integer>>() {
                    @Override
                    public Tuple2<Object, Integer> map(ValueType valueType) throws Exception {
                        return new Tuple2<Object, Integer>(valueType.elements.iterator().next(),
                                valueType.elements.size());
                    }
                });
        ds1.output(new DiscardingOutputFormat<Tuple2<Object, Integer>>());
    }

    // execute program
    env.execute("KryoTest kryoMode=" + kryoMode);
}

From source file:org.eclipse.swt.snippets.Snippet336.java

public static void main(String[] args) {
    display = new Display();
    shell = new Shell(display);
    shell.setText("Snippet 336");
    shell.setLayout(new GridLayout());
    TabFolder folder = new TabFolder(shell, SWT.NONE);
    folder.setLayoutData(new GridData(GridData.FILL_BOTH));

    //Progress tab
    TabItem item = new TabItem(folder, SWT.NONE);
    item.setText("Progress");
    Composite composite = new Composite(folder, SWT.NONE);
    composite.setLayout(new GridLayout());
    item.setControl(composite);/*  w ww . ja  v a  2 s . co m*/
    Listener listener = event -> {
        Button button = (Button) event.widget;
        if (!button.getSelection())
            return;
        TaskItem item1 = getTaskBarItem();
        if (item1 != null) {
            int state = ((Integer) button.getData()).intValue();
            item1.setProgressState(state);
        }
    };
    Group group = new Group(composite, SWT.NONE);
    group.setText("State");
    group.setLayout(new GridLayout());
    group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    Button button;
    String[] stateLabels = { "SWT.DEFAULT", "SWT.INDETERMINATE", "SWT.NORMAL", "SWT.ERROR", "SWT.PAUSED" };
    int[] states = { SWT.DEFAULT, SWT.INDETERMINATE, SWT.NORMAL, SWT.ERROR, SWT.PAUSED };
    for (int i = 0; i < states.length; i++) {
        button = new Button(group, SWT.RADIO);
        button.setText(stateLabels[i]);
        button.setData(Integer.valueOf(states[i]));
        button.addListener(SWT.Selection, listener);
        if (i == 0)
            button.setSelection(true);
    }
    group = new Group(composite, SWT.NONE);
    group.setText("Value");
    group.setLayout(new GridLayout(2, false));
    group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    Label label = new Label(group, SWT.NONE);
    label.setText("Progress");
    final Scale scale = new Scale(group, SWT.NONE);
    scale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    scale.addListener(SWT.Selection, event -> {
        TaskItem item1 = getTaskBarItem();
        if (item1 != null)
            item1.setProgress(scale.getSelection());
    });

    //Overlay text tab
    item = new TabItem(folder, SWT.NONE);
    item.setText("Text");
    composite = new Composite(folder, SWT.NONE);
    composite.setLayout(new GridLayout());
    item.setControl(composite);
    group = new Group(composite, SWT.NONE);
    group.setText("Enter a short text:");
    group.setLayout(new GridLayout(2, false));
    group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    final Text text = new Text(group, SWT.BORDER | SWT.SINGLE);
    GridData data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 2;
    text.setLayoutData(data);
    button = new Button(group, SWT.PUSH);
    button.setText("Set");
    button.addListener(SWT.Selection, event -> {
        TaskItem item1 = getTaskBarItem();
        if (item1 != null)
            item1.setOverlayText(text.getText());
    });
    button = new Button(group, SWT.PUSH);
    button.setText("Clear");
    button.addListener(SWT.Selection, event -> {
        text.setText("");
        TaskItem item1 = getTaskBarItem();
        if (item1 != null)
            item1.setOverlayText("");
    });

    //Overlay image tab
    item = new TabItem(folder, SWT.NONE);
    item.setText("Image");
    composite = new Composite(folder, SWT.NONE);
    composite.setLayout(new GridLayout());
    item.setControl(composite);
    Listener listener3 = event -> {
        Button button1 = (Button) event.widget;
        if (!button1.getSelection())
            return;
        TaskItem item1 = getTaskBarItem();
        if (item1 != null) {
            String text1 = button1.getText();
            Image image = null;
            if (!text1.equals("NONE"))
                image = new Image(display, Snippet336.class.getResourceAsStream(text1));
            Image oldImage = item1.getOverlayImage();
            item1.setOverlayImage(image);
            if (oldImage != null)
                oldImage.dispose();
        }
    };
    group = new Group(composite, SWT.NONE);
    group.setText("Images");
    group.setLayout(new GridLayout());
    group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    button = new Button(group, SWT.RADIO);
    button.setText("NONE");
    button.addListener(SWT.Selection, listener3);
    button.setSelection(true);
    String[] images = { "eclipse.png", "pause.gif", "run.gif", "warning.gif" };
    for (int i = 0; i < images.length; i++) {
        button = new Button(group, SWT.RADIO);
        button.setText(images[i]);
        button.addListener(SWT.Selection, listener3);
    }
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:com.chigix.autosftp.Application.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(Option.builder("P").longOpt("port").hasArg().build())
            .addOption(Option.builder("h").longOpt("help").desc("Print this message").build())
            .addOption(Option.builder("i").argName("identity_file").hasArg().build());
    int port = 22;
    CommandLine line;//from  w w  w . j  a v a 2 s  .  co  m
    try {
        line = new DefaultParser().parse(options, args);
    } catch (UnrecognizedOptionException ex) {
        System.err.println(ex.getMessage());
        return;
    } catch (ParseException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("autosftp /path/to/watch [user@]host2:[file2]", options, true);
        return;
    }
    String givenPort;
    if (line.hasOption("port") && StringUtils.isNumeric(givenPort = line.getOptionValue("port"))) {
        port = Integer.valueOf(givenPort);
    }
    if (line.getArgs().length < 0) {
        System.err.println("Please provide a path to watch.");
        return;
    }
    localPath = Paths.get(line.getArgs()[0]);
    if (line.getArgs().length < 1) {
        System.err.println("Please provide remote ssh information.");
        return;
    }
    SshAddressParser addressParse;
    try {
        addressParse = new SshAddressParser().parse(line.getArgs()[1]);
    } catch (SshAddressParser.InvalidAddressException ex) {
        System.err.println(ex.getMessage());
        return;
    }
    if (addressParse.getDefaultDirectory() != null) {
        remotePath = Paths.get(addressParse.getDefaultDirectory());
    }
    try {
        sshSession = new JSch().getSession(addressParse.getUsername(), addressParse.getHost(), port);
    } catch (JSchException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    try {
        sshOpen();
    } catch (JSchException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        sshClose();
    }
    System.out.println("Remote Default Path: " + remotePath);
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            sshClose();
            System.out.println("Bye~~~");
        }

    });
    try {
        watchDir(Paths.get(line.getArgs()[0]));
    } catch (Exception ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.tommy.stationery.moracle.core.client.load.StompWebSocketLoadTestClient.java

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

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
        host = args[0];//  w ww  . j a v  a 2s .  co m
    }

    int port = 59984;
    if (args.length > 1) {
        port = Integer.valueOf(args[1]);
    }

    String url = "http://" + host + ":" + port + "/home";
    logger.debug("Sending warm-up HTTP request to " + url);
    HttpStatus status = new RestTemplate().getForEntity(url, Void.class).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();

    Executor executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    org.eclipse.jetty.websocket.client.WebSocketClient jettyClient = new WebSocketClient(executor);
    JettyWebSocketClient webSocketClient = new JettyWebSocketClient(jettyClient);
    webSocketClient.start();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
        URI uri = new URI("ws://" + host + ":" + port + "/stomp");
        WebSocketStompClient stompClient = new WebSocketStompClient(uri, null, sockJsClient);
        stompClient.setMessageConverter(new StringMessageConverter());

        logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
        StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
        stopWatch.start();

        List<ConsumerStompMessageHandler> consumers = new ArrayList<>();
        for (int i = 0; i < NUMBER_OF_USERS; i++) {
            consumers.add(new ConsumerStompMessageHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch,
                    messageLatch, disconnectLatch, failure));
            stompClient.connect(consumers.get(i));
        }

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all users connected, remaining: " + connectLatch.getCount());
        }
        if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all users subscribed, remaining: " + subscribeLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users ");
        stopWatch.start();

        ProducerStompMessageHandler producer = new ProducerStompMessageHandler(BROADCAST_MESSAGE_COUNT,
                failure);
        stompClient.connect(producer);

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) {
            for (ConsumerStompMessageHandler consumer : consumers) {
                if (consumer.messageCount.get() < consumer.expectedMessageCount) {
                    logger.debug(consumer);
                }
            }
        }
        if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all handlers received every message, remaining: " + messageLatch.getCount());
        }

        producer.session.disconnect();
        if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        System.out.println("\nPress any key to exit...");
        System.in.read();
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        webSocketClient.stop();
        jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
}

From source file:edu.msu.cme.rdp.kmer.KmerSearch.java

public static void main(String[] args) throws IOException {
    KmerTrie kmerTrie = null;// www  .j a v  a2s  . co m
    SeqReader queryReader = null;
    SequenceType querySeqType = SequenceType.Unknown;
    FastaWriter out = null;
    boolean exhaustive = true;
    boolean translQuery = false;
    int wordSize = -1;
    int translTable = 11;

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

        if (args.length != 3) {
            throw new Exception("Unexpected number of arguments");
        }

        if (cmdLine.hasOption("out")) {
            out = new FastaWriter(cmdLine.getOptionValue("out"));
        } else {
            out = new FastaWriter(System.out);
        }

        if (cmdLine.hasOption("correct")) {
            exhaustive = false;
        } else {
            exhaustive = true;
        }

        if (cmdLine.hasOption("transl-table")) {
            translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table"));
        }

        File trainingFile = new File(args[0]);
        wordSize = Integer.valueOf(args[1]);
        File queryFile = new File(args[2]);

        querySeqType = SeqUtils.guessSequenceType(queryFile);
        queryReader = new SequenceReader(new File(args[2]));

        kmerTrie = KmerTrie.buildTrie(new SequenceReader(trainingFile), wordSize);

        if (querySeqType == SequenceType.Protein && kmerTrie.getTreeSeqType() == SequenceType.Nucleotide) {
            throw new Exception("Trie is made of nucleotide sequences but the query sequences are protein");
        }

        if (querySeqType == SequenceType.Nucleotide && kmerTrie.getTreeSeqType() == SequenceType.Protein) {
            translQuery = true;
            System.err.println(
                    "Query sequences are nucleotide but trie is in protein space, query sequences will be translated");
        }

        if (querySeqType == SequenceType.Protein && exhaustive) {
            System.err.println("Cannot do an exaustive search with protein sequences, disabling");
            exhaustive = false;
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("KmerSearch <ref_file> <word_size> <query_file>", options);
        System.err.println(e.getMessage());
        System.exit(1);
    }

    long startTime = System.currentTimeMillis();
    long seqCount = 0, passedCount = 0;

    Sequence querySeq;

    while ((querySeq = queryReader.readNextSequence()) != null) {
        seqCount++;

        List<Sequence> testSequences;

        if (!exhaustive) {
            if (translQuery) {
                testSequences = Arrays.asList(new Sequence(querySeq.getSeqName(), "", ProteinUtils.getInstance()
                        .translateToProtein(querySeq.getSeqString(), true, translTable)));
            } else {
                testSequences = Arrays.asList(querySeq);
            }
        } else {
            if (translQuery) {
                testSequences = ProteinUtils.getInstance().allTranslate(querySeq);
            } else {
                testSequences = Arrays.asList(querySeq, new Sequence(querySeq.getSeqName(), "",
                        IUBUtilities.reverseComplement(querySeq.getSeqString())));
            }
        }

        boolean passed = false;
        for (Sequence seq : testSequences) {
            for (char[] kmer : KmerGenerator.getKmers(seq.getSeqString(), wordSize)) {
                if (kmerTrie.contains(kmer) != null) {
                    passed = true;
                    break;
                }
            }

            if (passed) {
                out.writeSeq(seq);
                passedCount++;
                break;
            }
        }
    }
    System.err.println("Processed: " + seqCount);
    System.err.println("Passed: " + passedCount);
    System.err.println("Failed: " + (seqCount - passedCount));
    System.err.println("Time: " + (System.currentTimeMillis() - startTime) + " ms");
}

From source file:com.flaptor.indextank.rpc.SearcherClient.java

public static void main(String[] args) {

    // create the parser
    CommandLineParser parser = new PosixParser();
    try {/*from w ww  .j a  v a  2  s  . c om*/
        // parse the command line arguments
        CommandLine line = parser.parse(getOptions(), args);
        if (line.hasOption("help")) {
            printHelp(getOptions(), null);
            System.exit(1);
        }

        if (!line.hasOption("function")) {
            printHelp(getOptions(), null);
            System.exit(1);
        }

        Integer scoringFunctionIndex = Integer.valueOf(line.getOptionValue("function"));

        String host = line.getOptionValue("host", "localhost");
        String basePort = line.getOptionValue("port", "7910");
        int port = Integer.valueOf(basePort) + 2;

        TTransport transport;
        transport = new TSocket(host, port);
        TProtocol protocol = new TBinaryProtocol(transport);
        Searcher.Client client = new Searcher.Client(protocol);

        transport.open();
        ResultSet rs = client.search(line.getArgs()[0], 0, 10, scoringFunctionIndex,
                Collections.<Integer, Double>emptyMap(), Lists.<CategoryFilter>newArrayList(),
                Lists.<RangeFilter>newArrayList(), Lists.<RangeFilter>newArrayList(),
                Collections.<String, String>emptyMap()); // TODO join getArgs
        transport.close();
        System.out.println(rs);
    } catch (InvalidQueryException e) {
        e.printStackTrace();
    } catch (MissingQueryVariableException e) {
        e.printStackTrace();
    } catch (IndextankException e) {
        e.printStackTrace();
    } catch (ParseException exp) {
        printHelp(getOptions(), exp.getMessage());
    } catch (TTransportException e) {
        e.printStackTrace();
    } catch (TException e) {
        e.printStackTrace();
    }
}