Example usage for java.util ArrayList add

List of usage examples for java.util ArrayList add

Introduction

In this page you can find the example usage for java.util ArrayList add.

Prototype

public boolean add(E e) 

Source Link

Document

Appends the specified element to the end of this list.

Usage

From source file:OldStyle.java

public static void main(String args[]) {
    ArrayList list = new ArrayList();

    // These lines store strings, but any type of object 
    // can be stored.  In old-style code, there is no  
    // convenient way restrict the type of objects stored 
    // in a collection 
    list.add("one");
    list.add("two");
    list.add("three");
    list.add("four");

    Iterator itr = list.iterator();
    while (itr.hasNext()) {

        // To retrieve an element, an explicit type cast is needed 
        // because the collection stores only Object. 
        String str = (String) itr.next(); // explicit cast needed here. 

        System.out.println(str + " is " + str.length() + " chars long.");
    }/*from   www .  jav a2 s .  c  o m*/
}

From source file:com.mirth.connect.model.converters.tests.NCPDPTest.java

public static void main(String[] args) throws Exception {
    String testMessage = "";
    ArrayList<String> testFiles = new ArrayList<String>();
    testFiles.add("C:\\NCPDP_51_B1_Request.txt");
    testFiles.add("C:\\NCPDP_51_B1_Request_v2.txt");
    testFiles.add("C:\\NCPDP_51_B1_Response.txt");
    testFiles.add("C:\\NCPDP_51_B1_Response_v2.txt");
    testFiles.add("C:\\NCPDP_51_B1_Response_v3.txt");
    testFiles.add("C:\\NCPDP_51_B1_Response_v4.txt");
    testFiles.add("C:\\NCPDP_51_B1_Response_v5.txt");
    testFiles.add("C:\\NCPDP_51_B1_Response_v6.txt");
    testFiles.add("C:\\NCPDP_51_B1_Response_v7.txt");
    testFiles.add("C:\\NCPDP_51_B1_Response_v8.txt");
    testFiles.add("C:\\NCPDP_51_B1_Response_v9.txt");
    testFiles.add("C:\\NCPDP_51_B2_Request.txt");
    testFiles.add("C:\\NCPDP_51_B2_Request_v2.txt");
    testFiles.add("C:\\NCPDP_51_B2_Response.txt");
    testFiles.add("C:\\NCPDP_51_B2_Response_v2.txt");
    testFiles.add("C:\\NCPDP_51_B2_Response_v3.txt");
    testFiles.add("C:\\NCPDP_51_B3_Request.txt");
    testFiles.add("C:\\NCPDP_51_B3_Response.txt");
    testFiles.add("C:\\NCPDP_51_B3_Response_v2.txt");
    testFiles.add("C:\\NCPDP_51_B3_Response_v3.txt");
    testFiles.add("C:\\NCPDP_51_E1_Request.txt");
    testFiles.add("C:\\NCPDP_51_E1_Response.txt");
    testFiles.add("C:\\NCPDP_51_E1_Response_v2.txt");
    testFiles.add("C:\\NCPDP_51_E1_Response_v3.txt");
    testFiles.add("C:\\NCPDP_51_E1_Response_v4.txt");
    testFiles.add("C:\\NCPDP_51_E1_Response_v5.txt");
    testFiles.add("C:\\NCPDP_51_N1_Request.txt");
    testFiles.add("C:\\NCPDP_51_N2_Request.txt");
    testFiles.add("C:\\NCPDP_51_P1_Request.txt");
    testFiles.add("C:\\NCPDP_51_P1_Response.txt");
    testFiles.add("C:\\NCPDP_51_P1_Response_v2.txt");
    testFiles.add("C:\\NCPDP_51_P1_Response_v3.txt");
    testFiles.add("C:\\NCPDP_51_P2_Request.txt");
    testFiles.add("C:\\NCPDP_51_P2_Response.txt");
    testFiles.add("C:\\NCPDP_51_P3_Request.txt");
    testFiles.add("C:\\NCPDP_51_P3_Response.txt");
    testFiles.add("C:\\NCPDP_51_P3_Response_v2.txt");
    testFiles.add("C:\\NCPDP_51_P4_Request.txt");
    testFiles.add("C:\\NCPDP_51_P4_Response.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_1.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_2.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_3.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_4.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_5.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_6.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_7.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_8.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_9.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_10.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_11.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_12.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_13.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_14.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_15.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_16.txt");
    testFiles.add("C:\\NCPDP_51_CALPOS_17.txt");

    for (String testFile : testFiles) {
        testMessage = new String(FileUtils.readFileToByteArray(new File(testFile)));
        System.out.println("Processing test file:" + testFile);

        try {//from   w ww  . ja  v  a2s.  co m
            long totalExecutionTime = 0;
            int iterations = 1;
            for (int i = 0; i < iterations; i++) {
                totalExecutionTime += runTest(testMessage);
            }

            //System.out.println("Execution time average: " + totalExecutionTime/iterations + " ms");
        }
        // System.out.println(new X12Serializer().toXML("SEG*1*2**4*5"));
        catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:MainClass.java

License:asdf

public static void main(String[] args) throws Exception {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
    document.open();//from   ww  w  .  ja v a2 s . c  o  m
    Paragraph hello = new Paragraph("asdf");
    Chapter universe = new Chapter("A", 1);
    Section section;
    section = universe.addSection("B");
    section.add(hello);
    section = universe.addSection("C");
    section.add(hello);
    document.close();
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    PdfReader reader = new PdfReader("2.pdf");
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("HelloWorldManipulateBookmarks.pdf"));
    stamper.insertPage(1, PageSize.A4);
    PdfContentByte cb = stamper.getOverContent(1);
    cb.beginText();
    cb.setFontAndSize(bf, 18);
    cb.setTextMatrix(36, 770);
    cb.showText("Inserted Title Page");
    cb.endText();
    stamper.addAnnotation(PdfAnnotation.createText(stamper.getWriter(), new Rectangle(30f, 750f, 80f, 800f),
            "inserted page", "This page is the title page.", true, null), 1);
    List list = SimpleBookmark.getBookmark(reader);
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("Title", "Title Page");
    ArrayList kids = new ArrayList();
    HashMap<String, String> kid1 = new HashMap<String, String>();
    kid1.put("Title", "top");
    kid1.put("Action", "GoTo");
    kid1.put("Page", "1 ");
    kids.add(kid1);
    HashMap<String, String> kid2 = new HashMap<String, String>();
    kid2.put("Title", "bottom");
    kid2.put("Action", "GoTo");
    kid2.put("Page", "6");
    kids.add(kid2);
    map.put("Kids", kids);
    list.add(0, map);
    SimpleBookmark.exportToXML(list, new FileOutputStream("manipulated_bookmarks.xml"), "ISO8859-1", true);
    stamper.setOutlines(list);
    stamper.close();
}

From source file:com.tamingtext.classifier.bayes.ClassifyDocument.java

public static void main(String[] args) {
    log.info("Command-line arguments: " + Arrays.toString(args));

    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option inputOpt = obuilder.withLongName("input").withRequired(true)
            .withArgument(abuilder.withName("input").withMinimum(1).withMaximum(1).create())
            .withDescription("Input file").withShortName("i").create();

    Option modelOpt = obuilder.withLongName("model").withRequired(true)
            .withArgument(abuilder.withName("model").withMinimum(1).withMaximum(1).create())
            .withDescription("Model to use when classifying data").withShortName("m").create();

    Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
            .create();/*from   w w  w .j  av a2  s .c om*/

    Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(modelOpt).withOption(helpOpt)
            .create();

    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        CommandLine cmdLine = parser.parse(args);

        if (cmdLine.hasOption(helpOpt)) {
            CommandLineUtil.printHelp(group);
            return;
        }

        File inputFile = new File(cmdLine.getValue(inputOpt).toString());

        if (!inputFile.isFile()) {
            throw new IllegalArgumentException(inputFile + " does not exist or is not a file");
        }

        File modelDir = new File(cmdLine.getValue(modelOpt).toString());

        if (!modelDir.isDirectory()) {
            throw new IllegalArgumentException(modelDir + " does not exist or is not a directory");
        }

        BayesParameters p = new BayesParameters();
        p.set("basePath", modelDir.getCanonicalPath());
        Datastore ds = new InMemoryBayesDatastore(p);
        Algorithm a = new BayesAlgorithm();
        ClassifierContext ctx = new ClassifierContext(a, ds);
        ctx.initialize();

        //TODO: make the analyzer configurable
        StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
        TokenStream ts = analyzer.tokenStream(null,
                new InputStreamReader(new FileInputStream(inputFile), "UTF-8"));

        ArrayList<String> tokens = new ArrayList<String>(1000);
        while (ts.incrementToken()) {
            tokens.add(ts.getAttribute(CharTermAttribute.class).toString());
        }
        String[] document = tokens.toArray(new String[tokens.size()]);

        ClassifierResult[] cr = ctx.classifyDocument(document, "unknown", 5);

        for (ClassifierResult r : cr) {
            System.err.println(r.getLabel() + "\t" + r.getScore());
        }
    } catch (OptionException e) {
        log.error("Exception", e);
        CommandLineUtil.printHelp(group);
    } catch (IOException e) {
        log.error("IOException", e);
    } catch (InvalidDatastoreException e) {
        log.error("InvalidDataStoreException", e);
    } finally {

    }
}

From source file:test.jackson.JacksonNsgiDiscover.java

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

    ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

    String ngsiRcr = new String(Files.readAllBytes(Paths.get(NGSI_FILE)));

    DiscoveryContextAvailabilityRequest dcar = objectMapper.readValue(ngsiRcr,
            DiscoveryContextAvailabilityRequest.class);

    //        System.out.println(objectMapper.writeValueAsString(dcar));
    System.out.println(dcar.getRestriction().getOperationScope().get(1).getScopeValue());

    LinkedHashMap shapeHMap = (LinkedHashMap) dcar.getRestriction().getOperationScope().get(1).getScopeValue();
    //        Association assocObject =  objectMapper.convertValue(shapeHMap, Association.class);
    //        System.out.println(assocObject.getAttributeAssociation().get(0).getSourceAttribute());

    Shape shape = objectMapper.convertValue(shapeHMap, Shape.class);
    System.out.println("Deserialized Class: " + shape.getClass().getSimpleName());
    System.out.println("VALUE: " + shape.getPolygon().getVertices().get(2).getLatitude());
    System.out.println("VALUE: " + shape.getCircle());
    if (!(shape.getCircle() == null))
        System.out.println("This is null");

    Polygon polygon = shape.getPolygon();
    int vertexSize = polygon.getVertices().size();
    Coordinate[] coords = new Coordinate[vertexSize];

    final ArrayList<Coordinate> points = new ArrayList<>();
    for (int i = 0; i < vertexSize; i++) {
        Vertex vertex = polygon.getVertices().get(i);
        points.add(new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude())));
        coords[i] = new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude()));
    }/*  w w w  .  j a  v  a 2  s  .  c  o m*/
    points.add(new Coordinate(Double.valueOf(polygon.getVertices().get(0).getLatitude()),
            Double.valueOf(polygon.getVertices().get(0).getLongitude())));

    final GeometryFactory gf = new GeometryFactory();

    final Coordinate target = new Coordinate(49, -0.6);
    final Point point = gf.createPoint(target);

    Geometry shapeGm = gf.createPolygon(
            new LinearRing(new CoordinateArraySequence(points.toArray(new Coordinate[points.size()])), gf),
            null);
    //    Geometry shapeGm = gf.createPolygon(coords);    
    System.out.println(point.within(shapeGm));

    //        System.out.println(rcr.getContextRegistration().get(0).getContextMetadata().get(0).getValue().getClass().getCanonicalName());

    //        String assocJson = objectMapper.writeValueAsString(association);
    //        Value assocObject =  objectMapper.readValue(objectMapper.writeValueAsString(association), Value.class);
    //        System.out.println(association.values().toString());
    //        System.out.println(assocJson);

}

From source file:calendarevent.CalendarEvent.java

/**
 * @param args the command line arguments
 *//*from w w w.j a  va  2  s .c  om*/
public static void main(String[] args) {
    // TODO code application logic here

    /*       
                
        This has to be replaced with the json data coming from the getJsonData() method
        Expecting the Json will be in the format from the above methid.
                
    */
    String jsonString = "{\n" + " \"kind\": \"calendar#events\",\n"
            + " \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/QElT1PHkP9d3G5VSndpdEMlSzKE\\\"\",\n"
            + " \"summary\": \"PushEvents\",\n" + " \"description\": \"Hackathon\",\n"
            + " \"updated\": \"2014-03-29T22:35:18.495Z\",\n" + " \"timeZone\": \"Asia/Calcutta\",\n"
            + " \"accessRole\": \"reader\",\n" + " \"items\": [\n" + "  {\n"
            + "   \"kind\": \"calendar#event\",\n"
            + "   \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/MTM5NjEyNTQwNzcxMTAwMA\\\"\",\n"
            + "   \"id\": \"q28lprjb8ad3m17955lf1p9d48\",\n" + "   \"status\": \"confirmed\",\n"
            + "   \"htmlLink\": \"https://www.google.com/calendar/event?eid=cTI4bHByamI4YWQzbTE3OTU1bGYxcDlkNDggM3RvcjdvamZxaWhlamNqNjduOWw0dDhnMmNAZw\",\n"
            + "   \"created\": \"2014-03-29T20:36:47.000Z\",\n"
            + "   \"updated\": \"2014-03-29T20:36:47.711Z\",\n" + "   \"summary\": \"Test API\",\n"
            + "   \"creator\": {\n" + "    \"email\": \"vrohitrao@gmail.com\",\n"
            + "    \"displayName\": \"Rohith Vallu\"\n" + "   },\n" + "   \"organizer\": {\n"
            + "    \"email\": \"3tor7ojfqihejcj67n9l4t8g2c@group.calendar.google.com\",\n"
            + "    \"displayName\": \"PushEvents\",\n" + "    \"self\": true\n" + "   },\n"
            + "   \"start\": {\n" + "    \"dateTime\": \"2014-03-30T02:30:00+05:30\"\n" + "   },\n"
            + "   \"end\": {\n" + "    \"dateTime\": \"2014-03-30T03:30:00+05:30\"\n" + "   },\n"
            + "   \"iCalUID\": \"q28lprjb8ad3m17955lf1p9d48@google.com\",\n" + "   \"sequence\": 0\n" + "  },\n"
            + "  {\n" + "   \"kind\": \"calendar#event\",\n"
            + "   \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/MTM5NjEzMjUzMjQxNzAwMA\\\"\",\n"
            + "   \"id\": \"jgpue3stuo3js5qlsodob84voo\",\n" + "   \"status\": \"confirmed\",\n"
            + "   \"htmlLink\": \"https://www.google.com/calendar/event?eid=amdwdWUzc3R1bzNqczVxbHNvZG9iODR2b28gM3RvcjdvamZxaWhlamNqNjduOWw0dDhnMmNAZw\",\n"
            + "   \"created\": \"2014-03-29T22:35:32.000Z\",\n"
            + "   \"updated\": \"2014-03-29T22:35:32.417Z\",\n" + "   \"summary\": \"Test Events\",\n"
            + "   \"description\": \"Hack!!\",\n"
            + "   \"location\": \"Northeastern University, Huntington Avenue, Boston, MA, United States\",\n"
            + "   \"creator\": {\n" + "    \"email\": \"vrohitrao@gmail.com\",\n"
            + "    \"displayName\": \"Rohith Vallu\"\n" + "   },\n" + "   \"organizer\": {\n"
            + "    \"email\": \"3tor7ojfqihejcj67n9l4t8g2c@group.calendar.google.com\",\n"
            + "    \"displayName\": \"PushEvents\",\n" + "    \"self\": true\n" + "   },\n"
            + "   \"start\": {\n" + "    \"dateTime\": \"2014-03-30T04:30:00+05:30\"\n" + "   },\n"
            + "   \"end\": {\n" + "    \"dateTime\": \"2014-03-30T19:30:00+05:30\"\n" + "   },\n"
            + "   \"visibility\": \"public\",\n"
            + "   \"iCalUID\": \"jgpue3stuo3js5qlsodob84voo@google.com\",\n" + "   \"sequence\": 0\n" + "  }\n"
            + " ]\n" + "}";

    Gson gson = new Gson();
    try {
        JSONObject jsonData = new JSONObject(jsonString);
        JSONArray jsonArray = jsonData.getJSONArray("items");
        JSONObject eventData;
        Event event = new Event();
        for (int i = 0; i < jsonArray.length(); i++) {

            System.out.println(jsonArray.get(i).toString());
            Items item = gson.fromJson(jsonArray.get(i).toString(), Items.class);

            event.setSummary(item.getSummary());
            event.setLocation(item.getLocation());

            /* Will be adding the attendees here
             ArrayList<EventAttendee> attendees = new ArrayList<EventAttendee>();
             attendees.add(new EventAttendee().setEmail("attendeeEmail"));
             // ...
             event.setAttendees(attendees);
             */
            Date startDate = new Date();
            Date endDate = new Date(startDate.getTime() + 3600000);
            DateTime start = new DateTime(startDate, TimeZone.getDefault().getDefault().getTimeZone("UTC"));
            event.setStart(new EventDateTime().setDateTime(start));
            DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
            event.setEnd(new EventDateTime().setDateTime(end));
            HttpTransport transport = new NetHttpTransport();
            JsonFactory jsonFactory = new JacksonFactory();
            Calendar.Builder builder = new Calendar.Builder(transport, jsonFactory, null);
            String clientID = "937140966210.apps.googleusercontent.com";
            String redirectURL = "urn:ietf:wg:oauth:2.0:oob";
            String clientSecret = "qMFSb_cadYDG7uh3IDXWiMQY";
            ArrayList<String> scope = new ArrayList<String>();
            scope.add("https://www.googleapis.com/auth/calendar");

            String url = new GoogleAuthorizationCodeRequestUrl(clientID, redirectURL, scope).build();

            System.out.println("Go to the following link in your browser:");
            System.out.println(url);

            // Read the authorization code from the standard input stream.
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("What is the authorization code?");
            String code = in.readLine();

            GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory,
                    clientID, clientSecret, redirectURL, code, redirectURL).execute();

            GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

            Calendar service = new Calendar.Builder(transport, jsonFactory, credential).build();

            Event createdEvent = service.events().insert(item.getSummary(), event).execute();

            System.out.println(createdEvent.getId());

        }

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

From source file:HannonHillSecret.HannonHillSecret.java

/**
 * @param args the command line arguments
 *///  www.j  av  a  2  s .c o m
public static void main(String[] args) {
    // This is a placeholder for the provided value of N
    final int N = 55;
    int currentNum = 0;
    int x = 0;
    int sizePrimes;
    boolean isAdditive = true;
    ArrayList<Integer> primeNumbers = new ArrayList<>();

    currentNum = Primes.nextPrime(currentNum);

    //Add all prime numbers less than or equal to N
    while (currentNum <= N) {
        primeNumbers.add(currentNum);
        currentNum = Primes.nextPrime(currentNum++);
    }

    sizePrimes = primeNumbers.size();

    // If there are only two prime numbers in the arraylist, it means it is empty or there
    // is only one.
    if (sizePrimes < 2) {
        System.out.println("Cannot test if Secret is additive since there "
                + "are not two or more prime numbers less than N!");
    } else // Testing for additive property is possible
    {
        outerloop:
        // Assuming the additive test only requires pair combinations, go through
        // all possible pairs until all pass or one fails
        while (x < sizePrimes && isAdditive) {
            for (int y = x + 1; y <= sizePrimes; y++) {
                isAdditive = isSecretAdditive(primeNumbers.get(x), primeNumbers.get(x));

                //Failed additive test for a combination of prime numbers,
                // so break the while loop and return false
                if (!isAdditive) {
                    break outerloop;
                }
            }
            x++;
        }

        if (isAdditive) {
            System.out.println("Secret is additive!");
        } else {
            System.out.println("Secret is NOT additive!");
        }
    }
}

From source file:deck36.storm.plan9.php.KittenRobbersTopology.java

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

    String env = null;/*from ww w  .j av  a 2 s.  c  o  m*/

    if (args != null && args.length > 0) {
        env = args[0];
    }

    if (!"dev".equals(env))
        if (!"prod".equals(env)) {
            System.out.println("Usage: $0 (dev|prod)\n");
            System.exit(1);
        }

    // Topology config
    Config conf = new Config();

    // Load parameters and add them to the Config
    Map configMap = YamlLoader.loadYamlFromResource("config_" + env + ".yml");

    conf.putAll(configMap);

    log.info(JSONValue.toJSONString((conf)));

    // Set topology loglevel to DEBUG
    conf.put(Config.TOPOLOGY_DEBUG, JsonPath.read(conf, "$.deck36_storm.debug"));

    // Create Topology builder
    TopologyBuilder builder = new TopologyBuilder();

    // if there are not special reasons, start with parallelism hint of 1
    // and multiple tasks. By that, you can scale dynamically later on.
    int parallelism_hint = JsonPath.read(conf, "$.deck36_storm.default_parallelism_hint");
    int num_tasks = JsonPath.read(conf, "$.deck36_storm.default_num_tasks");

    String badgeName = KittenRobbersTopology.class.getSimpleName();

    // construct command to invoke the external bolt implementation
    ArrayList<String> command = new ArrayList(15);

    // Add main execution program (php, hhvm, zend, ..) and parameters
    command.add((String) JsonPath.read(conf, "$.deck36_storm.php.executor"));
    command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.executor_params"));

    // Add main command to be executed (app/console, the phar file, etc.) and global context parameters (environment etc.)
    command.add((String) JsonPath.read(conf, "$.deck36_storm.php.main"));
    command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.main_params"));

    // Add main route to be invoked and its parameters
    command.add((String) JsonPath.read(conf, "$.deck36_storm.KittenRobbersFromOuterSpaceBolt.main"));
    List boltParams = (List<String>) JsonPath.read(conf,
            "$.deck36_storm.KittenRobbersFromOuterSpaceBolt.params");
    if (boltParams != null)
        command.addAll(boltParams);

    // Log the final command
    log.info("Command to start bolt for KittenRobbersFromOuterSpace: " + Arrays.toString(command.toArray()));

    // Add constructed external bolt command to topology using MultilangAdapterBolt
    builder.setBolt("badge", new MultilangAdapterTickTupleBolt(command,
            (Integer) JsonPath.read(conf, "$.deck36_storm.KittenRobbersFromOuterSpaceBolt.robber_frequency"),
            "badge"), parallelism_hint).setNumTasks(num_tasks);

    builder.setBolt("rabbitmq_router",
            new Plan9RabbitMQRouterBolt(
                    (String) JsonPath.read(conf,
                            "$.deck36_storm.KittenRobbersFromOuterSpaceBolt.rabbitmq.target_exchange"),
                    "KittenRobbers" // RabbitMQ routing key
            ), parallelism_hint).setNumTasks(num_tasks).shuffleGrouping("badge");

    builder.setBolt("rabbitmq_producer", new Plan9RabbitMQPushBolt(), parallelism_hint).setNumTasks(num_tasks)
            .shuffleGrouping("rabbitmq_router");

    if ("dev".equals(env)) {
        LocalCluster cluster = new LocalCluster();
        cluster.submitTopology(badgeName + System.currentTimeMillis(), conf, builder.createTopology());
        Thread.sleep(2000000);
    }

    if ("prod".equals(env)) {
        StormSubmitter.submitTopology(badgeName + "-" + System.currentTimeMillis(), conf,
                builder.createTopology());
    }

}

From source file:asl.seedscan.DQAWeb.java

public static void main(String args[]) {
    db = new MetricDatabase("", "", "");
    findConsoleHandler();// ww  w.j  ava  2  s.  c om
    consoleHandler.setLevel(Level.ALL);
    Logger.getLogger("").setLevel(Level.CONFIG);

    // Default locations of config and schema files
    File configFile = new File("dqaweb-config.xml");
    File schemaFile = new File("schemas/DQAWebConfig.xsd");
    boolean parseConfig = true;
    boolean testMode = false;

    ArrayList<File> schemaFiles = new ArrayList<File>();
    schemaFiles.add(schemaFile);
    // ==== Command Line Parsing ====
    Options options = new Options();
    Option opConfigFile = new Option("c", "config-file", true,
            "The config file to use for seedscan. XML format according to SeedScanConfig.xsd.");
    Option opSchemaFile = new Option("s", "schema-file", true,
            "The schame file which should be used to verify the config file format. ");
    Option opTest = new Option("t", "test", false, "Run in test console mode rather than as a servlet.");

    OptionGroup ogConfig = new OptionGroup();
    ogConfig.addOption(opConfigFile);

    OptionGroup ogSchema = new OptionGroup();
    ogConfig.addOption(opSchemaFile);

    OptionGroup ogTest = new OptionGroup();
    ogTest.addOption(opTest);

    options.addOptionGroup(ogConfig);
    options.addOptionGroup(ogSchema);
    options.addOptionGroup(ogTest);

    PosixParser optParser = new PosixParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = optParser.parse(options, args, true);
    } catch (org.apache.commons.cli.ParseException e) {
        logger.severe("Error while parsing command-line arguments.");
        System.exit(1);
    }

    Option opt;
    Iterator iter = cmdLine.iterator();
    while (iter.hasNext()) {
        opt = (Option) iter.next();

        if (opt.getOpt().equals("c")) {
            configFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("s")) {
            schemaFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("t")) {
            testMode = true;
        }
    }
    String query = "";
    System.out.println("Entering Test Mode");
    System.out.println("Enter a query string to view results or type \"help\" for example query strings");
    InputStreamReader input = new InputStreamReader(System.in);
    BufferedReader reader = new BufferedReader(input);
    String result = "";

    while (testMode == true) {
        try {

            System.out.printf("Query: ");
            query = reader.readLine();
            if (query.equals("exit")) {
                testMode = false;
            } else if (query.equals("help")) {
                System.out.println("Need to add some help for people"); //TODO
            } else {
                result = processCommand(query);
            }
            System.out.println(result);
        } catch (IOException err) {
            System.err.println("Error reading line, in DQAWeb.java");
        }
    }
    System.err.printf("DONE.\n");
}

From source file:es.ucm.fdi.ac.outlier.Hampel.java

/**
 * To regenerate cache from command-line use
 * java -cp classes:lib/commons-math-1.1.jar eps.outlier.Hampel
 *///from   w w w.  j  av  a 2  s  .c  o  m
public static void main(String args[]) throws Exception {

    System.err.println("init...");
    Hampel o = new Hampel();
    System.err.println("init OK");

    double[] enes = { 1, 10, 20, 40, 80, 160, 320, 640, 1280, 5120, 10240 }; // 11 rows
    double[] alfas = { 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.2, 0.25, 0.5, 0.75 }; // 10 cols
    double[] values = new double[enes.length * alfas.length];

    long startTime = System.currentTimeMillis();
    for (int i = 0, k = 0; i < enes.length; i++) {
        for (int j = 0; j < alfas.length; j++) {
            long partialStart = System.currentTimeMillis();
            values[k++] = o.montecarloK((int) enes[i], alfas[j]);
            long partialTime = System.currentTimeMillis() - partialStart;
            System.err.println(
                    "" + k + " down (" + (partialTime / 1000.0f) + " s), " + (values.length - k) + " to go...");
        }
    }
    long endTime = System.currentTimeMillis();
    float seconds = (endTime - startTime) / 1000.0f;

    ArrayList<double[]> al = new ArrayList<double[]>();
    al.add(enes);
    al.add(alfas);
    Interpolator ip = new Interpolator(2, al, values);
    ip.saveGrid(new FileWriter("/tmp/saved_grid.txt"));

    System.err.println("Finished after " + seconds + " s");
}