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:edu.msu.cme.rdp.probematch.cli.PrimerMatch.java

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

    PrintStream out = new PrintStream(System.out);
    int maxDist = Integer.MAX_VALUE;

    try {//from w  w w.j  a va2  s  . c o  m
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption("outFile")) {
            out = new PrintStream(new File(line.getOptionValue("outFile")));
        }
        if (line.hasOption("maxDist")) {
            maxDist = Integer.valueOf(line.getOptionValue("maxDist"));
        }
        args = line.getArgs();

        if (args.length != 2) {
            throw new Exception("Unexpected number of command line arguments");
        }
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        new HelpFormatter().printHelp("PrimerMatch <primer_list | primer_file> <seq_file>", options);
        return;
    }

    List<PatternBitMask64> primers = new ArrayList();
    if (new File(args[0]).exists()) {
        File primerFile = new File(args[0]);
        SequenceFormat seqformat = SeqUtils.guessFileFormat(primerFile);

        if (seqformat.equals(SequenceFormat.FASTA)) {
            SequenceReader reader = new SequenceReader(primerFile);
            Sequence seq;

            while ((seq = reader.readNextSequence()) != null) {
                primers.add(new PatternBitMask64(seq.getSeqString(), true, seq.getSeqName()));
            }
            reader.close();
        } else {
            BufferedReader reader = new BufferedReader(new FileReader(args[0]));
            String line;

            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.equals("")) {
                    primers.add(new PatternBitMask64(line, true));
                }
            }
            reader.close();
        }
    } else {
        for (String primer : args[0].split(",")) {
            primers.add(new PatternBitMask64(primer, true));
        }
    }

    SeqReader seqReader = new SequenceReader(new File(args[1]));
    Sequence seq;
    String primerRegion;

    out.println("#seqname\tdesc\tprimer_index\tprimer_name\tposition\tmismatches\tseq_primer_region");
    while ((seq = seqReader.readNextSequence()) != null) {
        for (int index = 0; index < primers.size(); index++) {
            PatternBitMask64 primer = primers.get(index);
            BitVector64Result results = BitVector64.process(seq.getSeqString().toCharArray(), primer, maxDist);

            for (BitVector64Match result : results.getResults()) {
                primerRegion = seq.getSeqString().substring(
                        Math.max(0, result.getPosition() - primer.getPatternLength()), result.getPosition());

                if (result.getPosition() < primer.getPatternLength()) {
                    for (int pad = result.getPosition(); pad < primer.getPatternLength(); pad++) {
                        primerRegion = "x" + primerRegion;
                    }
                }

                out.println(seq.getSeqName() + "\t" + seq.getDesc() + "\t" + (index + 1) + "\t"
                        + primer.getPrimerName() + "\t" + result.getPosition() + "\t" + result.getScore() + "\t"
                        + primerRegion);
            }
        }
    }
    out.close();
    seqReader.close();
}

From source file:com.linecorp.platform.channel.sample.Main.java

public static void main(String[] args) {

    BusinessConnect bc = new BusinessConnect();

    /**//from   w ww. j  av a  2s . c om
     * Prepare the required channel secret and access token
     */
    String channelSecret = System.getenv("CHANNEL_SECRET");
    String channelAccessToken = System.getenv("CHANNEL_ACCESS_TOKEN");
    if (channelSecret == null || channelSecret.isEmpty() || channelAccessToken == null
            || channelAccessToken.isEmpty()) {
        System.err.println("Error! Environment variable CHANNEL_SECRET and CHANNEL_ACCESS_TOKEN not defined.");
        return;
    }

    port(Integer.valueOf(System.getenv("PORT")));
    staticFileLocation("/public");

    /**
     * Define the callback url path
     */
    post("/events", (request, response) -> {
        String requestBody = request.body();

        /**
         * Verify whether the channel signature is valid or not
         */
        String channelSignature = request.headers("X-LINE-CHANNELSIGNATURE");
        if (channelSignature == null || channelSignature.isEmpty()) {
            response.status(400);
            return "Please provide valid channel signature and try again.";
        }
        if (!bc.validateBCRequest(requestBody, channelSecret, channelSignature)) {
            response.status(401);
            return "Invalid channel signature.";
        }

        /**
         * Parse the http request body
         */
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
        objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        EventList events;
        try {
            events = objectMapper.readValue(requestBody, EventList.class);
        } catch (IOException e) {
            response.status(400);
            return "Invalid request body.";
        }

        ApiHttpClient apiHttpClient = new ApiHttpClient(channelAccessToken);

        /**
         * Process the incoming messages/operations one by one
         */
        List<String> toUsers;
        for (Event event : events.getResult()) {
            switch (event.getEventType()) {
            case Constants.EventType.MESSAGE:
                toUsers = new ArrayList<>();
                toUsers.add(event.getContent().getFrom());

                // @TODO: We strongly suggest you should modify this to process the incoming message/operation async
                bc.sendTextMessage(toUsers, "You said: " + event.getContent().getText(), apiHttpClient);
                break;
            case Constants.EventType.OPERATION:
                if (event.getContent().getOpType() == Constants.OperationType.ADDED_AS_FRIEND) {
                    String newFriend = event.getContent().getParams().get(0);
                    Profile profile = bc.getProfile(newFriend, apiHttpClient);
                    String displayName = profile == null ? "Unknown" : profile.getDisplayName();
                    toUsers = new ArrayList<>();
                    toUsers.add(newFriend);
                    bc.sendTextMessage(toUsers, displayName + ", welcome to be my friend!", apiHttpClient);
                    Connection connection = null;
                    connection = DatabaseUrl.extract().getConnection();
                    toUsers = bc.getFriends(newFriend, connection);
                    if (toUsers.size() > 0) {
                        bc.sendTextMessage(toUsers, displayName + " just join us, let's welcome him/her!",
                                apiHttpClient);
                    }
                    bc.addFriend(newFriend, displayName, connection);
                    if (connection != null) {
                        connection.close();
                    }
                }
                break;
            default:
                // Unknown type?
            }
        }
        return "Events received successfully.";
    });

    get("/", (request, response) -> {
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("message", "Hello World!");
        return new ModelAndView(attributes, "index.ftl");
    }, new FreeMarkerEngine());
}

From source file:com.sm.replica.TestReplicaClient.java

public static void main(String[] args) {
    String[] opts = new String[] { "-store", "-url", "-times" };
    String[] defaults = new String[] { "campaigns", "localhost:7320", "3" };
    String[] paras = getOpts(args, opts, defaults);
    String store = paras[0];/*  w w  w  . ja  va 2s . c om*/
    String url = paras[1];
    int times = Integer.valueOf(paras[2]);
    MockClient client = new MockClient(url, store);

    for (int i = 0; i < times; i++) {
        try {
            Header header = new Header(store, i, (byte) 0, 1);
            ParaList paraList = createParaList(1, i);
            Request request = new Request(header, paraList.toBytes());
            Response resp = client.sendRequest(request);
            if (resp.getPayload() instanceof ParaList) {
                ParaList pList = (ParaList) resp.getPayload();
                logger.info(resp.toString() + " pList " + pList.getLists().size() + " error " + errorNo(pList));
            } else
                logger.info(
                        "class " + resp.getPayload().getClass().getName() + " " + resp.getPayload().toString());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }

    }
    //client.close();

}

From source file:net.morphbank.webclient.ProcessFiles.java

/**
 * @param args//from w ww  .ja v a  2  s  . c  o  m
 *            args[0] directory including terminal '/' 
 *            args[1] prefix of request files 
 *            args[2] number of digits in file index value
 *            args[3] number of files 
 *            args[4] index of first file (default 0) 
 *            args[5] prefix of service 
 *            args[6] prefix of response files (default args[1] + "Resp")
 */
public static void main(String[] args) {
    ProcessFiles fileProcessor = new ProcessFiles();
    // restTest.processRequest(URL, UPLOAD_FILE);

    String zeros = "0000000";

    if (args.length < 4) {
        System.out.println("Too few parameters");
    } else {
        try {
            // get parameters
            String reqDir = args[0];
            String reqPrefix = args[1];
            int numDigits = Integer.valueOf(args[2]);
            if (numDigits > zeros.length())
                numDigits = zeros.length();
            NumberFormat intFormat = new DecimalFormat(zeros.substring(0, numDigits));
            int numFiles = Integer.valueOf(args[3]);
            int firstFile = 0;

            BufferedReader fileIn = new BufferedReader(new FileReader(FILE_IN_PATH));
            String line = fileIn.readLine();
            fileIn.close();
            firstFile = Integer.valueOf(line);
            // firstFile = 189;
            // numFiles = 1;
            int lastFile = firstFile + numFiles - 1;
            String url = URL;
            String respPrefix = reqPrefix + "Resp";
            if (args.length > 5)
                respPrefix = args[5];
            if (args.length > 6)
                url = args[6];

            // process files
            for (int i = firstFile; i <= lastFile; i++) {
                String xmlOutputFile = null;
                String requestFile = reqDir + reqPrefix + intFormat.format(i) + ".xml";
                System.out.println("Processing request file " + requestFile);
                String responseFile = reqDir + respPrefix + intFormat.format(i) + ".xml";
                System.out.println("Response file " + responseFile);
                // restTest.processRequest(URL, UPLOAD_FILE);
                fileProcessor.processRequest(url, requestFile, responseFile);
                Writer fileOut = new FileWriter(FILE_IN_PATH, false);
                fileOut.append(Integer.toString(i + 1));
                fileOut.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.sm.store.test.LoadTestStoreClient.java

public static void main(String[] args) throws Exception {
    String[] opts = new String[] { "-thread", "-times", "-url", "-store" };
    String[] defaults = new String[] { "2", "10", "localhost:7100", "store" };
    String[] paras = getOpts(args, opts, defaults);
    int threads = Integer.valueOf(paras[0]);
    int times = Integer.valueOf(paras[1]);
    String url = paras[2];//from w w w.j a va 2s  .com
    String store = paras[3];
    RemoteClientImpl client = new NTRemoteClientImpl(url, null, store);
    for (int i = 0; i < threads; i++) {
        logger.info("start thread # " + i);
        new Thread(new ClientThread(client, times)).start();
    }
    //System.exit(0);
}

From source file:edu.gslis.ts.RunQuery.java

public static void main(String[] args) {
    try {/*from w w  w  . j a v  a  2s.com*/
        // Get the commandline options
        Options options = createOptions();
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        String inputPath = cmd.getOptionValue("input");
        String eventsPath = cmd.getOptionValue("events");
        String stopPath = cmd.getOptionValue("stop");
        int queryId = Integer.valueOf(cmd.getOptionValue("query"));

        List<String> ids = FileUtils.readLines(new File(inputPath + File.separator + "ids.txt"));

        Stopper stopper = new Stopper(stopPath);
        Map<Integer, FeatureVector> queries = readEvents(eventsPath, stopper);

        FeatureVector query = queries.get(queryId);

        Pairtree ptree = new Pairtree();
        Bag<String> words = new HashBag<String>();

        for (String streamId : ids) {

            String ppath = ptree.mapToPPath(streamId.replace("-", ""));

            String inpath = inputPath + File.separator + ppath + File.separator + streamId + ".xz";
            //                System.out.println(inpath);
            File infile = new File(inpath);
            InputStream in = new XZInputStream(new FileInputStream(infile));

            TTransport inTransport = new TIOStreamTransport(new BufferedInputStream(in));
            TBinaryProtocol inProtocol = new TBinaryProtocol(inTransport);
            inTransport.open();
            final StreamItem item = new StreamItem();

            while (true) {
                try {
                    item.read(inProtocol);
                    //                        System.out.println("Read " + item.stream_id);

                } catch (TTransportException tte) {
                    // END_OF_FILE is used to indicate EOF and is not an exception.
                    if (tte.getType() != TTransportException.END_OF_FILE)
                        tte.printStackTrace();
                    break;
                }
            }

            // Do something with this document...
            String docText = item.getBody().getClean_visible();

            StringTokenizer itr = new StringTokenizer(docText);
            while (itr.hasMoreTokens()) {
                words.add(itr.nextToken());
            }

            inTransport.close();

        }

        for (String term : words.uniqueSet()) {
            System.out.println(term + ":" + words.getCount(term));
        }

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

From source file:com.sm.store.TestClient.java

public static void main(String[] args) throws Exception {
    String[] opts = new String[] { "-thread", "-times", "-host", "-port" };
    String[] defaults = new String[] { "2", "10", "localhost", "7100" };
    String[] paras = getOpts(args, opts, defaults);
    int threads = Integer.valueOf(paras[0]);
    int times = Integer.valueOf(paras[1]);
    String host = paras[2];//from  w  w w . j  a v a  2 s .c  o  m
    int port = Integer.valueOf(paras[3]);

    for (int i = 0; i < threads; i++) {
        TCPClient client = createClient(host, port);
        logger.info("start thread  =>" + i);
        new Thread(new RunnerThread(client, times, i), "thread-" + i).start();
    }
}

From source file:examples.cidr.SubnetUtilsExample.java

public static void main(String[] args) {
    String subnet = "192.168.0.3/31";
    SubnetUtils utils = new SubnetUtils(subnet);
    SubnetInfo info = utils.getInfo();//from ww w .  j  a va2s  . c  om

    System.out.printf("Subnet Information for %s:\n", subnet);
    System.out.println("--------------------------------------");
    System.out.printf("IP Address:\t\t\t%s\t[%s]\n", info.getAddress(),
            Integer.toBinaryString(info.asInteger(info.getAddress())));
    System.out.printf("Netmask:\t\t\t%s\t[%s]\n", info.getNetmask(),
            Integer.toBinaryString(info.asInteger(info.getNetmask())));
    System.out.printf("CIDR Representation:\t\t%s\n\n", info.getCidrSignature());

    System.out.printf("Supplied IP Address:\t\t%s\n\n", info.getAddress());

    System.out.printf("Network Address:\t\t%s\t[%s]\n", info.getNetworkAddress(),
            Integer.toBinaryString(info.asInteger(info.getNetworkAddress())));
    System.out.printf("Broadcast Address:\t\t%s\t[%s]\n", info.getBroadcastAddress(),
            Integer.toBinaryString(info.asInteger(info.getBroadcastAddress())));
    System.out.printf("Low Address:\t\t\t%s\t[%s]\n", info.getLowAddress(),
            Integer.toBinaryString(info.asInteger(info.getLowAddress())));
    System.out.printf("High Address:\t\t\t%s\t[%s]\n", info.getHighAddress(),
            Integer.toBinaryString(info.asInteger(info.getHighAddress())));

    System.out.printf("Total usable addresses: \t%d\n", Integer.valueOf(info.getAddressCount()));
    System.out.printf("Address List: %s\n\n", Arrays.toString(info.getAllAddresses()));

    final String prompt = "Enter an IP address (e.g. 192.168.0.10):";
    System.out.println(prompt);
    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNextLine()) {
        String address = scanner.nextLine();
        System.out.println("The IP address [" + address + "] is " + (info.isInRange(address) ? "" : "not ")
                + "within the subnet [" + subnet + "]");
        System.out.println(prompt);
    }

}

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

public static void main(String[] args) throws Exception {
    String[] opts = new String[] { "-configPath", "-url", "-store", "-times" };
    String[] defaults = new String[] { "", "localhost:6172", "store1", "2" };
    String[] paras = getOpts(args, opts, defaults);

    String configPath = paras[0];
    if (configPath.length() == 0) {
        logger.error("missing config path or host");
        throw new RuntimeException("missing -configPath or -host");
    }//from w w w  .jav  a 2 s .  c o  m

    String url = paras[1];
    String store = paras[2];
    int times = Integer.valueOf(paras[3]);
    ClusterClientFactory ccf = ClusterClientFactory.connect(url, store);
    ClusterClient client = ccf.getDefaultStore(8000L);
    TestError testClient = new TestError(client);
    for (int i = 0; i < times; i++) {
        try {
            Key key = Key.createKey("test" + i);
            //client.put(key, "times-" + i);
            Value value = client.get(key);
            value.setVersion(value.getVersion() - 2);
            client.put(key, value);
            logger.info(value == null ? "null" : value.getData().toString());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
    testClient.client.close();
    ccf.close();
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step1PrepareContainers.java

public static void main(String[] args) throws IOException {
    // queries with narratives in CSV
    File queries = new File(args[0]);
    File relevantInformationExamplesFile = new File(args[1]);

    Map<Integer, Map<Integer, List<String>>> relevantInformationMap = parseRelevantInformationFile(
            relevantInformationExamplesFile);

    // output dir
    File outputDir = new File(args[2]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();//w w  w.  ja  v a  2s .  c om
    }

    // iterate over queries
    CSVParser csvParser = CSVParser.parse(queries, Charset.forName("utf-8"), CSVFormat.DEFAULT);
    for (CSVRecord record : csvParser) {
        // create new container, fill, and store
        QueryResultContainer container = new QueryResultContainer();
        container.qID = record.get(0);
        container.query = record.get(1);

        // Fill some dummy text first
        container.relevantInformationExamples.addAll(Collections.singletonList("ERROR. Information missing."));
        container.irrelevantInformationExamples
                .addAll(Collections.singletonList("ERROR. Information missing."));

        // and now fill it with existing information if available
        Integer queryID = Integer.valueOf(container.qID);
        if (relevantInformationMap.containsKey(queryID)) {
            if (relevantInformationMap.get(queryID).containsKey(0)) {
                container.irrelevantInformationExamples = new ArrayList<>(
                        relevantInformationMap.get(queryID).get(0));
            }

            if (relevantInformationMap.get(queryID).containsKey(1)) {
                container.relevantInformationExamples = new ArrayList<>(
                        relevantInformationMap.get(queryID).get(1));
            }
        }

        File outputFile = new File(outputDir, container.qID + ".xml");
        FileUtils.writeStringToFile(outputFile, container.toXML());
        System.out.println("Finished " + outputFile);
    }
}