Example usage for java.util List get

List of usage examples for java.util List get

Introduction

In this page you can find the example usage for java.util List get.

Prototype

E get(int index);

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:com.wso2telco.dep.reportingservice.dao.TaxDAO.java

/**
 * The main method./*w  w w  .  j  a va 2 s  .c  o  m*/
 *
 * @param args the arguments
 * @throws Exception the exception
 */
public static void main(String[] args) throws Exception {

    TaxDAO taxDAO = new TaxDAO();

    try {
        List<Tax> taxList = taxDAO.getTaxesForSubscription(00, 25);
        for (int i = 0; i < taxList.size(); i++) {
            Tax tax = taxList.get(i);
            System.out.println(tax.getType() + " ~ " + tax.getEffective_from() + " ~ " + tax.getEffective_to()
                    + " ~ " + tax.getValue());
        }

        Map<String, List<APIRequestDTO>> reqMap = taxDAO.getAPIRequestTimesForApplication(
                "yx1eZTmtbBaYqfIuEYMVgIKonSga", (short) 2014, (short) 1, "admin");
        System.out.println(reqMap);

    } catch (APIManagementException e) {
        e.printStackTrace();
    } catch (APIMgtUsageQueryServiceClientException e) {
        e.printStackTrace();
    }
}

From source file:de.uniwue.info6.database.SQLParserTest.java

public static void main(String[] args) throws Exception {
    String test = "Dies ist ein einfacher Test";
    System.out.println(StringTools.forgetOneWord(test));

    System.exit(0);/*from   ww  w.jav a 2 s  .  c o  m*/
    // SimpleTupel<String, Integer> test1 =  new SimpleTupel<String, Integer>("test1", 1);
    // SimpleTupel<String, Integer> test2 =  new SimpleTupel<String, Integer>("test1", 12);

    // ArrayList<SimpleTupel<String, Integer>> test = new ArrayList<SimpleTupel<String, Integer>>();
    // test.add(test1);
    // System.out.println(test1.equals(test2));
    // System.exit(0);

    final boolean resetDb = true;
    // Falls nur nach einer bestimmten Aufgabe gesucht wird
    final Integer exerciseID = 39;
    final Integer scenarioID = null;
    final int threadSize = 1;

    final EquivalenceLock<Long[]> equivalenceLock = new EquivalenceLock<Long[]>();
    final Long[] performance = new Long[] { 0L, 0L };

    // ------------------------------------------------ //
    final ScenarioDao scenarioDao = new ScenarioDao();
    final ExerciseDao exerciseDao = new ExerciseDao();
    final ExerciseGroupDao groupDao = new ExerciseGroupDao();
    final UserDao userDao = new UserDao();
    final ArrayList<Thread> threads = new ArrayList<Thread>();

    // ------------------------------------------------ //
    try {
        ConnectionManager.offline_instance();
        if (resetDb) {
            Cfg.inst().setProp(MAIN_CONFIG, IMPORT_EXAMPLE_SCENARIO, true);
            Cfg.inst().setProp(MAIN_CONFIG, FORCE_RESET_DATABASE, true);
            new GenerateData().resetDB();
            ConnectionTools.inst().addSomeTestData();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // ------------------------------------------------ //

    final List<Scenario> scenarios = scenarioDao.findAll();

    try {
        // ------------------------------------------------ //
        String userID;
        for (int i = 2; i < 100; i++) {
            userID = "user_" + i;
            User userToInsert = new User();
            userToInsert.setId(userID);
            userToInsert.setIsAdmin(false);
            userDao.insertNewInstance(userToInsert);
        }
        // ------------------------------------------------ //

        for (int i = 0; i < threadSize; i++) {
            Thread thread = new Thread() {

                public void run() {
                    // ------------------------------------------------ //
                    try {
                        Thread.sleep(new Random().nextInt(30));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // ------------------------------------------------ //

                    User user = userDao.getRandom();
                    Thread.currentThread().setName(user.getId());
                    System.err.println(
                            "\n\nINFO (ueps): Thread '" + Thread.currentThread().getName() + "' started\n");

                    // ------------------------------------------------ //

                    for (Scenario scenario : scenarios) {
                        if (scenarioID != null && !scenario.getId().equals(scenarioID)) {
                            continue;
                        }

                        System.out.println(StringUtils.repeat("#", 90));
                        System.out.println("SCENARIO: " + scenario.getId());

                        // ------------------------------------------------ //
                        for (ExerciseGroup group : groupDao.findByScenario(scenario)) {
                            System.out.println(StringUtils.repeat("#", 90));
                            System.out.println("GROUP: " + group.getId());
                            System.out.println(StringUtils.repeat("#", 90));
                            List<Exercise> exercises = exerciseDao.findByExGroup(group);

                            // ------------------------------------------------ //
                            for (Exercise exercise : exercises) {
                                if (exerciseID != null && !exercise.getId().equals(exerciseID)) {
                                    continue;
                                }
                                long startTime = System.currentTimeMillis();

                                for (int i = 0; i < 100; i++) {
                                    String userID = "user_" + new Random().nextInt(100000);
                                    User userToInsert = new User();
                                    userToInsert.setId(userID);
                                    userToInsert.setIsAdmin(false);
                                    userDao.insertNewInstance(userToInsert);
                                    user = userDao.getById(userID);

                                    List<SolutionQuery> solutions = new ExerciseDao().getSolutions(exercise);
                                    String solution = solutions.get(0).getQuery();
                                    ExerciseController exc = new ExerciseController().init_debug(scenario,
                                            exercise, user);
                                    exc.setUserString(solution);

                                    String fd = exc.getFeedbackList().get(0).getFeedback();
                                    System.out.println("Used Query: " + solution);
                                    if (fd.trim().toLowerCase().equals("bestanden")) {
                                        System.out.println(exercise.getId() + ": " + fd);
                                    } else {
                                        System.err.println(exercise.getId() + ": " + fd + "\n");
                                    }
                                    System.out.println(StringUtils.repeat("-", 90));
                                }

                                long elapsedTime = System.currentTimeMillis() - startTime;

                                // if (i > 5) {
                                //   try {
                                //     equivalenceLock.lock(performance);
                                //     performance[0] += elapsedTime;
                                //     performance[1]++;
                                //   } catch (Exception e) {
                                //   } finally {
                                //     equivalenceLock.release(performance);
                                //   }
                                // }
                            }
                        }
                    }

                    System.err
                            .println("INFO (ueps): Thread '" + Thread.currentThread().getName() + "' stopped");
                }
            };
            thread.start();
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.join();
        }

        // try {
        //   equivalenceLock.lock(performance);

        //   long elapsedTime = (performance[0] / performance[1]);
        //   System.out.println("\n" + String.format("perf : %d.%03dsec", elapsedTime / 1000, elapsedTime % 1000));
        // } catch (Exception e) {
        // } finally {
        //   equivalenceLock.release(performance);
        // }

    } finally {
    }
}

From source file:es.upm.oeg.tools.rdfshapes.utils.CadinalityResultGenerator.java

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

    String endpoint = "http://3cixty.eurecom.fr/sparql";

    List<String> classList = Files.readAllLines(Paths.get(classListPath), Charset.defaultCharset());

    String classPropertyQueryString = readFile(classPropertyQueryPath, Charset.defaultCharset());
    String propertyCardinalityQueryString = readFile(propertyCardinalityQueryPath, Charset.defaultCharset());
    String individualCountQueryString = readFile(individualCountQueryPath, Charset.defaultCharset());

    DecimalFormat df = new DecimalFormat("0.0000");

    //Create the Excel workbook and sheet
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet("Cardinality");

    int currentExcelRow = 0;
    int classStartRow = 0;

    for (String clazz : classList) {

        Map<String, String> litMap = new HashMap<>();
        Map<String, String> iriMap = ImmutableMap.of("class", clazz);

        String queryString = bindQueryString(individualCountQueryString,
                ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));

        int individualCount;
        List<RDFNode> c = executeQueryForList(queryString, endpoint, "c");
        if (c.size() == 1) {
            individualCount = c.get(0).asLiteral().getInt();
        } else {//from  w  w  w.j a v a2  s  . co  m
            continue;
        }

        // If there are zero individuals, continue
        if (individualCount == 0) {
            throw new IllegalStateException("Check whether " + classListPath + " and " + endpoint + " match.");
        }

        //            System.out.println("***");
        //            System.out.println("### **" + clazz + "** (" + individualCount + ")");
        //            System.out.println("***");
        //            System.out.println();

        classStartRow = currentExcelRow;
        XSSFRow row = sheet.createRow(currentExcelRow);
        XSSFCell cell = row.createCell(0);
        cell.setCellValue(clazz);
        cell.getCellStyle().setAlignment(CellStyle.ALIGN_CENTER);

        queryString = bindQueryString(classPropertyQueryString,
                ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));

        List<RDFNode> nodeList = executeQueryForList(queryString, endpoint, "p");

        for (RDFNode property : nodeList) {
            if (property.isURIResource()) {

                DescriptiveStatistics stats = new DescriptiveStatistics();

                String propertyURI = property.asResource().getURI();
                //                    System.out.println("* " + propertyURI);
                //                    System.out.println();

                XSSFRow propertyRow = sheet.getRow(currentExcelRow);
                if (propertyRow == null) {
                    propertyRow = sheet.createRow(currentExcelRow);
                }
                currentExcelRow++;

                XSSFCell propertyCell = propertyRow.createCell(1);
                propertyCell.setCellValue(propertyURI);

                Map<String, String> litMap2 = new HashMap<>();
                Map<String, String> iriMap2 = ImmutableMap.of("class", clazz, "p", propertyURI);

                queryString = bindQueryString(propertyCardinalityQueryString,
                        ImmutableMap.of(IRI_BINDINGS, iriMap2, LITERAL_BINDINGS, litMap2));

                List<Map<String, RDFNode>> solnMaps = executeQueryForList(queryString, endpoint,
                        ImmutableSet.of("card", "count"));

                int sum = 0;
                List<CardinalityCount> cardinalityList = new ArrayList<>();
                if (solnMaps.size() > 0) {

                    for (Map<String, RDFNode> soln : solnMaps) {
                        int count = soln.get("count").asLiteral().getInt();
                        int card = soln.get("card").asLiteral().getInt();

                        for (int i = 0; i < count; i++) {
                            stats.addValue(card);
                        }

                        CardinalityCount cardinalityCount = new CardinalityCount(card, count,
                                (((double) count) / individualCount) * 100);
                        cardinalityList.add(cardinalityCount);
                        sum += count;
                    }

                    // Check for zero cardinality instances
                    int count = individualCount - sum;
                    if (count > 0) {
                        for (int i = 0; i < count; i++) {
                            stats.addValue(0);
                        }
                        CardinalityCount cardinalityCount = new CardinalityCount(0, count,
                                (((double) count) / individualCount) * 100);
                        cardinalityList.add(cardinalityCount);
                    }
                }

                Map<Integer, Double> cardMap = new HashMap<>();
                for (CardinalityCount count : cardinalityList) {
                    cardMap.put(count.getCardinality(), count.getPrecentage());
                }

                XSSFCell instanceCountCell = propertyRow.createCell(2);
                instanceCountCell.setCellValue(individualCount);

                XSSFCell minCell = propertyRow.createCell(3);
                minCell.setCellValue(stats.getMin());

                XSSFCell maxCell = propertyRow.createCell(4);
                maxCell.setCellValue(stats.getMax());

                XSSFCell p1 = propertyRow.createCell(5);
                p1.setCellValue(stats.getPercentile(1));

                XSSFCell p99 = propertyRow.createCell(6);
                p99.setCellValue(stats.getPercentile(99));

                XSSFCell mean = propertyRow.createCell(7);
                mean.setCellValue(df.format(stats.getMean()));

                for (int i = 0; i < 21; i++) {
                    XSSFCell dataCell = propertyRow.createCell(8 + i);
                    Double percentage = cardMap.get(i);
                    if (percentage != null) {
                        dataCell.setCellValue(df.format(percentage));
                    } else {
                        dataCell.setCellValue(0);
                    }
                }

                //                    System.out.println("| Min Card. |Max Card. |");
                //                    System.out.println("|---|---|");
                //                    System.out.println("| ? | ? |");
                //                    System.out.println();

            }
        }

        //System.out.println("class start: " + classStartRow + ", class end: " + (currentExcelRow -1));
        //We have finished writting properties of one class, now it's time to merge the cells
        int classEndRow = currentExcelRow - 1;
        if (classStartRow < classEndRow) {
            sheet.addMergedRegion(new CellRangeAddress(classStartRow, classEndRow, 0, 0));
        }

    }

    String filename = "3cixty.xls";
    FileOutputStream fileOut = new FileOutputStream(filename);
    wb.write(fileOut);
    fileOut.close();
}

From source file:jena.RuleMap.java

/**
 * General command line utility to process one RDF file into another
 * by application of a set of forward chaining rules. 
 * <pre>/*from ww  w.  j  a  v  a  2 s  . c  om*/
 * Usage:  RuleMap [-il inlang] [-ol outlang] -d infile rulefile
 * </pre>
 */
public static void main(String[] args) {
    try {

        // Parse the command line
        String usage = "Usage:  RuleMap [-il inlang] [-ol outlang] [-d] rulefile infile (- for stdin)";
        final CommandLineParser parser = new DefaultParser();
        Options options = new Options().addOption("il", "inputLang", true, "input language")
                .addOption("ol", "outputLang", true, "output language").addOption("d", "Deductions only?");
        CommandLine cl = parser.parse(options, args);
        final List<String> filenameArgs = cl.getArgList();
        if (filenameArgs.size() != 2) {
            System.err.println(usage);
            System.exit(1);
        }

        String inLang = cl.getOptionValue("inputLang");
        String fname = filenameArgs.get(1);
        Model inModel = null;
        if (fname.equals("-")) {
            inModel = ModelFactory.createDefaultModel();
            inModel.read(System.in, null, inLang);
        } else {
            inModel = FileManager.get().loadModel(fname, inLang);
        }

        String outLang = cl.hasOption("outputLang") ? cl.getOptionValue("outputLang") : "N3";

        boolean deductionsOnly = cl.hasOption('d');

        // Fetch the rule set and create the reasoner
        BuiltinRegistry.theRegistry.register(new Deduce());
        Map<String, String> prefixes = new HashMap<>();
        List<Rule> rules = loadRules(filenameArgs.get(0), prefixes);
        Reasoner reasoner = new GenericRuleReasoner(rules);

        // Process
        InfModel infModel = ModelFactory.createInfModel(reasoner, inModel);
        infModel.prepare();
        infModel.setNsPrefixes(prefixes);

        // Output
        try (PrintWriter writer = new PrintWriter(System.out)) {
            if (deductionsOnly) {
                Model deductions = infModel.getDeductionsModel();
                deductions.setNsPrefixes(prefixes);
                deductions.setNsPrefixes(inModel);
                deductions.write(writer, outLang);
            } else {
                infModel.write(writer, outLang);
            }
        }
    } catch (Throwable t) {
        System.err.println("An error occured: \n" + t);
        t.printStackTrace();
    }
}

From source file:AmazonKinesisGet.java

public static void main(String[] args) throws Exception {
    init();/*from ww  w .j  a  v  a  2s. c om*/

    final String myStreamName = "philsteststream";
    final Integer myStreamSize = 1;

    // list all of my streams
    ListStreamsRequest listStreamsRequest = new ListStreamsRequest();
    listStreamsRequest.setLimit(10);
    ListStreamsResult listStreamsResult = kinesisClient.listStreams(listStreamsRequest);
    List<String> streamNames = listStreamsResult.getStreamNames();
    while (listStreamsResult.isHasMoreStreams()) {
        if (streamNames.size() > 0) {
            listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1));
        }

        listStreamsResult = kinesisClient.listStreams(listStreamsRequest);

        streamNames.addAll(listStreamsResult.getStreamNames());

    }
    LOG.info("Printing my list of streams : ");

    // print all of my streams.
    if (!streamNames.isEmpty()) {
        System.out.println("List of my streams: ");
    }
    for (int i = 0; i < streamNames.size(); i++) {
        System.out.println(streamNames.get(i));
    }

    //System.out.println(streamNames.get(0));
    String myownstream = streamNames.get(0);

    // Retrieve the Shards from a Stream
    DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest();
    describeStreamRequest.setStreamName(myownstream);
    DescribeStreamResult describeStreamResult;
    List<Shard> shards = new ArrayList<>();
    String lastShardId = null;

    do {
        describeStreamRequest.setExclusiveStartShardId(lastShardId);
        describeStreamResult = kinesisClient.describeStream(describeStreamRequest);
        shards.addAll(describeStreamResult.getStreamDescription().getShards());
        if (shards.size() > 0) {
            lastShardId = shards.get(shards.size() - 1).getShardId();
        }
    } while (describeStreamResult.getStreamDescription().getHasMoreShards());

    // Get Data from the Shards in a Stream
    // Hard-coded to use only 1 shard
    String shardIterator;
    GetShardIteratorRequest getShardIteratorRequest = new GetShardIteratorRequest();
    getShardIteratorRequest.setStreamName(myownstream);
    //get(0) shows hardcoded to 1 stream
    getShardIteratorRequest.setShardId(shards.get(0).getShardId());
    // using TRIM_HORIZON but could use alternatives
    getShardIteratorRequest.setShardIteratorType("TRIM_HORIZON");

    GetShardIteratorResult getShardIteratorResult = kinesisClient.getShardIterator(getShardIteratorRequest);
    shardIterator = getShardIteratorResult.getShardIterator();

    // Continuously read data records from shard.
    List<Record> records;

    while (true) {
        // Create new GetRecordsRequest with existing shardIterator.
        // Set maximum records to return to 1000.

        GetRecordsRequest getRecordsRequest = new GetRecordsRequest();
        getRecordsRequest.setShardIterator(shardIterator);
        getRecordsRequest.setLimit(1000);

        GetRecordsResult result = kinesisClient.getRecords(getRecordsRequest);

        // Put result into record list. Result may be empty.
        records = result.getRecords();

        // Print records
        for (Record record : records) {
            ByteBuffer byteBuffer = record.getData();
            System.out.println(String.format("Seq No: %s - %s", record.getSequenceNumber(),
                    new String(byteBuffer.array())));
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException exception) {
            throw new RuntimeException(exception);
        }

        shardIterator = result.getNextShardIterator();
    }

}

From source file:net.oneandone.shared.artifactory.App.java

public static void main(String[] args) throws ParseException, IOException, NotFoundException {
    initLogging();/*  w  w w .j  a  v a  2  s. c om*/
    LOG.info("CLI: {}", Arrays.toString(args));
    final Options options = new Options()
            .addOption("l", "uri", true, "Base-URI in the form of " + DEFAULT_ARTIFACTORY_URI)
            .addOption("u", "user", true, "Username").addOption("p", "password", true, "Password")
            .addOption("d", "debug", false, "Turn on debugging");
    final CommandLine commandline = new BasicParser().parse(options, args);
    if (commandline.hasOption("d")) {
        LOG.info("Setting debug");
        java.util.logging.Logger.getLogger("net.oneandone.shared.artifactory").setLevel(Level.ALL);
    }
    final List<String> argList = commandline.getArgList();
    LOG.info("ARGS: {}", argList);
    Injector injector = Guice.createInjector(new ArtifactoryModule());
    App instance = injector.getInstance(App.class);
    instance.preemptiveRequestInterceptor.addCredentialsForHost("web.de", "foo", "bar");
    List<ArtifactoryStorage> search = instance.searchByGav.search("repo1-cache", Gav.valueOf(argList.get(0)));
    LOG.info("Got {} search results", search.size());
}

From source file:com.github.lucapino.sheetmaker.PreviewJFrame.java

public static void main(String[] args) {
    System.setProperty("awt.useSystemAAFontSettings", "on");
    System.setProperty("swing.aatext", "true");
    SwingUtilities.invokeLater(new Runnable() {

        @Override/*from   w  w  w .  j av  a2  s . c o  m*/
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                File tmpFolder = new File("/tmp/images");
                tmpFolder.mkdir();

                String coverPath = tmpFolder.getAbsolutePath().replaceAll("\\\\", "/") + "/cover.jpg";
                String backdropPath = tmpFolder.getAbsolutePath().replaceAll("\\\\", "/") + "/backdrop.jpg";
                String fanart1Path = tmpFolder.getAbsolutePath().replaceAll("\\\\", "/") + "/fanart1.jpg";
                String fanart2Path = tmpFolder.getAbsolutePath().replaceAll("\\\\", "/") + "/fanart2.jpg";
                String fanart3Path = tmpFolder.getAbsolutePath().replaceAll("\\\\", "/") + "/fanart3.jpg";

                PreviewJFrame frame = new PreviewJFrame();
                logger.info("Creating parser...");
                InfoRetriever parser = new MediaInfoRetriever();
                MovieInfo movieInfo = parser.getMovieInfo("/media/tagliani/Elements/Film/JackRyan.mkv");
                logger.info("Retrieving movie file info...");
                logger.info("Creating dataretriever...");
                DataRetriever retriever = new DataRetrieverImpl();
                logger.info("Retrieving movie data...");
                Movie movie = retriever.retrieveMovieFromImdbID("tt1205537", "IT");
                logger.info("Retrieving backdrops and fanart...");
                List<Artwork> images = movie.getBackdrops();
                // background
                logger.info("Saving backdrop...");
                IOUtils.copyLarge(new URL(images.get(0).getImageURL()).openStream(),
                        new FileOutputStream(backdropPath));
                for (int i = 1; i < 4; i++) {
                    // fanart1
                    // fanart2
                    // fanart3
                    String imageURL = images.get(i).getImageURL();
                    logger.info("Saving fanart{}...", i);
                    IOUtils.copyLarge(new URL(imageURL).openStream(),
                            new FileOutputStream(tmpFolder.getAbsolutePath() + "/fanart" + i + ".jpg"));
                }
                // cover
                logger.info("Retrieving cover...");
                Artwork cover = movie.getPosters().get(0);
                String imageURL = cover.getImageURL();
                logger.info("Saving cover...");
                IOUtils.copyLarge(new URL(imageURL).openStream(), new FileOutputStream(coverPath));

                Map<String, String> tokenMap = TemplateFilter.createTokenMap(movie, movieInfo, null);

                logger.info("Creating renderer...");
                JavaTemplateRenderer renderer = new JavaTemplateRenderer();
                JPanel imagePanel = null;
                try {
                    logger.info("Rendering image...");
                    imagePanel = renderer.renderTemplate(
                            this.getClass().getResource("/templates/simplicity/template.xml"), tokenMap,
                            backdropPath, fanart1Path, fanart2Path, fanart3Path, coverPath);
                    logger.info("Adding image to frame...");
                    frame.add(imagePanel);

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                imagePanel.setPreferredSize(new Dimension(imagePanel.getWidth(), imagePanel.getHeight()));
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.setVisible(true);
                frame.pack();
                logger.info("Creating image for save...");
                BufferedImage imageTosave = ScreenImage.createImage(imagePanel);
                logger.info("Saving image...");
                ScreenImage.writeImage(imageTosave, "/tmp/images/final.png");
                logger.info("Image saved...");
            } catch (Exception ex) {
                logger.error("Error: ", ex);
            }
        }

    });

}

From source file:frankhassanabad.com.github.Jasperize.java

/**
 * Main method to call through Java in order to take a LinkedInProfile on disk and load it.
 *
 * @param args command line arguments where the options are stored
 * @throws FileNotFoundException Thrown if any file its expecting cannot be found.
 * @throws JRException  If there's generic overall Jasper issues.
 * @throws ParseException If there's command line parsing issues.
 *///from   w  w w  .j a v  a 2 s  . c  o  m
public static void main(String[] args) throws IOException, JRException, ParseException {

    Options options = new Options();
    options.addOption("h", "help", false, "Shows the help documentation");
    options.addOption("v", "version", false, "Shows the help documentation");
    options.addOption("cl", "coverLetter", false, "Utilizes a cover letter defined in coverletter.xml");
    options.addOption("sig", true, "Picture of your signature to add to the cover letter.");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jasperize [OPTIONS] [InputJrxmlFile] [OutputExportFile]", options);
        System.exit(0);
    }
    if (cmd.hasOption("v")) {
        System.out.println("Version:" + version);
        System.exit(0);
    }
    boolean useCoverLetter = cmd.hasOption("cl");
    String signatureLocation = cmd.getOptionValue("sig");
    BufferedImage signatureImage = null;
    if (signatureLocation != null) {
        signatureImage = ImageIO.read(new File(signatureLocation));
        ;
    }

    @SuppressWarnings("unchecked")
    List<String> arguments = cmd.getArgList();

    final String jrxmlFile;
    final String jasperOutput;
    if (arguments.size() == 2) {
        jrxmlFile = arguments.get(0);
        jasperOutput = arguments.get(1);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else if (arguments.size() == 3) {
        jrxmlFile = arguments.get(1);
        jasperOutput = arguments.get(2);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else {
        System.out.println("Using the default arguments of:");
        jrxmlFile = "data/jasperTemplates/resume1.jrxml";
        jasperOutput = "data/jasperOutput/linkedInResume.pdf";
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    }

    final String compiledMasterFile;
    final String outputType;
    final String jrPrintFile;
    //Split the inputFile
    final String[] inputSplit = jrxmlFile.split("\\.");
    if (inputSplit.length != 2 || !(inputSplit[1].equalsIgnoreCase("jrxml"))) {
        //Error
        System.out.println("Your [InputjrxmlFile] (1st argument) should have a jrxml extension like such:");
        System.out.println("    data/jasperTemplates/resume1.jrxml");
        System.exit(1);
    }
    //Split the outputFile
    final String[] outputSplit = jasperOutput.split("\\.");
    if (outputSplit.length != 2) {
        //Error
        System.out.println("Your [OutputExportFile] (2nd argument) should have a file extension like such:");
        System.out.println("    data/jasperOutput/linkedInResume.pdf");
        System.exit(1);
    }

    File inputFile = new File(inputSplit[0]);
    String inputFileName = inputFile.getName();
    String inputFileParentPath = inputFile.getParent();

    File outputFile = new File(outputSplit[0]);
    String outputFileParentPath = outputFile.getParent();

    System.out.println("Compiling report(s)");
    compileAllJrxmlTemplateFiles(inputFileParentPath, outputFileParentPath);
    System.out.println("Done compiling report(s)");

    compiledMasterFile = outputFileParentPath + File.separator + inputFileName + ".jasper";
    jrPrintFile = outputFileParentPath + File.separator + inputFileName + ".jrprint";

    System.out.println("Filling report: " + compiledMasterFile);
    Reporting.fill(compiledMasterFile, useCoverLetter, signatureImage);
    System.out.println("Done filling reports");
    outputType = outputSplit[1];
    System.out.println("Creating output export file of: " + jasperOutput);
    if (outputType.equalsIgnoreCase("pdf")) {
        Reporting.pdf(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("pptx")) {
        Reporting.pptx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("docx")) {
        Reporting.docx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("odt")) {
        Reporting.odt(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("xhtml")) {
        Reporting.xhtml(jrPrintFile, jasperOutput);
    }
    System.out.println("Done creating output export file of: " + jasperOutput);
}

From source file:de.tu.darmstadt.lt.ner.preprocessing.GermaNERMain.java

public static void main(String[] arg) throws Exception {
    long startTime = System.currentTimeMillis();
    String usage = "USAGE: java -jar germanner.jar [-c config.properties] \n"
            + " [-f trainingFileName] -t testFileName -d ModelOutputDirectory-o outputFile";
    long start = System.currentTimeMillis();

    ChangeColon c = new ChangeColon();

    List<String> argList = Arrays.asList(arg);
    try {/*from  w  w w  .ja v  a  2s. co m*/

        if (argList.contains("-c") && argList.get(argList.indexOf("-c") + 1) != null) {
            if (!new File(argList.get(argList.indexOf("-c") + 1)).exists()) {
                LOG.error("Default configuration is read from the system\n");
            } else {
                configFile = new FileInputStream(argList.get(argList.indexOf("-c") + 1));
            }

        }

        if (argList.contains("-t") && argList.get(argList.indexOf("-t") + 1) != null) {
            if (!new File(argList.get(argList.indexOf("-t") + 1)).exists()) {
                LOG.error("There is no test file to tag");
                System.exit(1);
            }
            Configuration.testFileName = argList.get(argList.indexOf("-t") + 1);
        }

        if (argList.contains("-f") && argList.get(argList.indexOf("-f") + 1) != null) {
            if (!new File(argList.get(argList.indexOf("-f") + 1)).exists()) {
                LOG.error("The system is running in tagging mode. No training data provided");
            } else {
                Configuration.trainFileName = argList.get(argList.indexOf("-f") + 1);
            }
        }

        if (argList.contains("-d") && argList.get(argList.indexOf("-d") + 1) != null) {
            if (new File(argList.get(argList.indexOf("-d") + 1)).exists()) {
                Configuration.modelDir = argList.get(argList.indexOf("-d") + 1);
            } else {
                File dir = new File(argList.get(argList.indexOf("-d") + 1));
                dir.mkdirs();
                Configuration.modelDir = dir.getAbsolutePath();
            }
        }
        // load a properties file
        initNERModel();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    try {
        setModelDir();

        File outputtmpFile = new File(modelDirectory, "result.tmp");
        File outputFile = null;
        if (argList.contains("-o") && argList.get(argList.indexOf("-o") + 1) != null) {
            outputFile = new File(argList.get(argList.indexOf("-o") + 1));
        } else {
            LOG.error("The directory for this output file does not exist. Output file "
                    + "will be found in the current directury under folder \"output\"");
            outputFile = new File(modelDirectory, "result.tsv");
        }

        if (Configuration.mode.equals("ft")
                && (Configuration.trainFileName == null || Configuration.testFileName == null)) {
            LOG.error(usage);
            System.exit(1);
        }
        if (Configuration.mode.equals("f") && Configuration.trainFileName == null) {
            LOG.error(usage);
            System.exit(1);
        }
        if (Configuration.mode.equals("t") && Configuration.testFileName == null) {
            LOG.error(usage);
            System.exit(1);
        }

        if (Configuration.mode.equals("f") && Configuration.trainFileName != null) {
            c.normalize(Configuration.trainFileName, Configuration.trainFileName + ".normalized");
            System.out.println("Start model generation");
            writeModel(new File(Configuration.trainFileName + ".normalized"), modelDirectory);
            System.out.println("Start model generation -- done");
            System.out.println("Start training");
            trainModel(modelDirectory);
            System.out.println("Start training ---done");
        } else if (Configuration.mode.equals("ft") && Configuration.trainFileName != null
                && Configuration.testFileName != null) {
            c.normalize(Configuration.trainFileName, Configuration.trainFileName + ".normalized");
            c.normalize(Configuration.testFileName, Configuration.testFileName + ".normalized");
            System.out.println("Start model generation");
            writeModel(new File(Configuration.trainFileName + ".normalized"), modelDirectory);
            System.out.println("Start model generation -- done");
            System.out.println("Start training");
            trainModel(modelDirectory);
            System.out.println("Start training ---done");
            System.out.println("Start tagging");
            classifyTestFile(modelDirectory, new File(Configuration.testFileName + ".normalized"),
                    outputtmpFile, null, null);
            System.out.println("Start tagging ---done");

            // re-normalized the colon changed text
            c.deNormalize(outputtmpFile.getAbsolutePath(), outputFile.getAbsolutePath());
        } else {
            c.normalize(Configuration.testFileName, Configuration.testFileName + ".normalized");
            System.out.println("Start tagging");
            classifyTestFile(modelDirectory, new File(Configuration.testFileName + ".normalized"),
                    outputtmpFile, null, null);
            // re-normalized the colon changed text
            c.deNormalize(outputtmpFile.getAbsolutePath(), outputFile.getAbsolutePath());

            System.out.println("Start tagging ---done");
        }
        long now = System.currentTimeMillis();
        UIMAFramework.getLogger().log(Level.INFO, "Time: " + (now - start) + "ms");
    } catch (Exception e) {
        LOG.error(usage);
        e.printStackTrace();
    }
    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    System.out.println("NER tarin/test done in " + totalTime / 1000 + " seconds");

}

From source file:com.linkedin.pinot.perf.MultiValueReaderWriterBenchmark.java

public static void main(String[] args) throws Exception {
    List<String> lines = IOUtils.readLines(new FileReader(new File(args[0])));
    int totalDocs = lines.size();
    int max = Integer.MIN_VALUE;
    int maxNumberOfMultiValues = Integer.MIN_VALUE;
    int totalNumValues = 0;
    int data[][] = new int[totalDocs][];
    for (int i = 0; i < lines.size(); i++) {
        String line = lines.get(i);
        String[] split = line.split(",");
        totalNumValues = totalNumValues + split.length;
        if (split.length > maxNumberOfMultiValues) {
            maxNumberOfMultiValues = split.length;
        }/* www .j a  va2s.c  om*/
        data[i] = new int[split.length];
        for (int j = 0; j < split.length; j++) {
            String token = split[j];
            int val = Integer.parseInt(token);
            data[i][j] = val;
            if (val > max) {
                max = val;
            }
        }
    }
    int maxBitsNeeded = (int) Math.ceil(Math.log(max) / Math.log(2));
    int size = 2048;
    int[] offsets = new int[size];
    int bitMapSize = 0;
    File outputFile = new File("output.mv.fwd");

    FixedBitSkipListSCMVWriter fixedBitSkipListSCMVWriter = new FixedBitSkipListSCMVWriter(outputFile,
            totalDocs, totalNumValues, maxBitsNeeded);

    for (int i = 0; i < totalDocs; i++) {
        fixedBitSkipListSCMVWriter.setIntArray(i, data[i]);
        if (i % size == size - 1) {
            MutableRoaringBitmap rr1 = MutableRoaringBitmap.bitmapOf(offsets);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bos);
            rr1.serialize(dos);
            dos.close();
            //System.out.println("Chunk " + i / size + " bitmap size:" + bos.size());
            bitMapSize += bos.size();
        } else if (i == totalDocs - 1) {
            MutableRoaringBitmap rr1 = MutableRoaringBitmap.bitmapOf(Arrays.copyOf(offsets, i % size));
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bos);
            rr1.serialize(dos);
            dos.close();
            //System.out.println("Chunk " + i / size + " bitmap size:" + bos.size());
            bitMapSize += bos.size();
        }
    }
    fixedBitSkipListSCMVWriter.close();
    System.out.println("Output file size:" + outputFile.length());
    System.out.println("totalNumberOfDoc\t\t\t:" + totalDocs);
    System.out.println("totalNumberOfValues\t\t\t:" + totalNumValues);
    System.out.println("chunk size\t\t\t\t:" + size);
    System.out.println("Num chunks\t\t\t\t:" + totalDocs / size);
    int numChunks = totalDocs / size + 1;
    int totalBits = (totalNumValues * maxBitsNeeded);
    int dataSizeinBytes = (totalBits + 7) / 8;

    System.out.println("Raw data size with fixed bit encoding\t:" + dataSizeinBytes);
    System.out.println("\nPer encoding size");
    System.out.println();
    System.out.println("size (offset + length)\t\t\t:" + ((totalDocs * (4 + 4)) + dataSizeinBytes));
    System.out.println();
    System.out.println("size (offset only)\t\t\t:" + ((totalDocs * (4)) + dataSizeinBytes));
    System.out.println();
    System.out.println("bitMapSize\t\t\t\t:" + bitMapSize);
    System.out.println("size (with bitmap)\t\t\t:" + (bitMapSize + (numChunks * 4) + dataSizeinBytes));

    System.out.println();
    System.out.println("Custom Bitset\t\t\t\t:" + (totalNumValues + 7) / 8);
    System.out.println("size (with custom bitset)\t\t\t:"
            + (((totalNumValues + 7) / 8) + (numChunks * 4) + dataSizeinBytes));

}