Example usage for org.apache.commons.lang.time StopWatch getTime

List of usage examples for org.apache.commons.lang.time StopWatch getTime

Introduction

In this page you can find the example usage for org.apache.commons.lang.time StopWatch getTime.

Prototype

public long getTime() 

Source Link

Document

Get the time on the stopwatch.

This is either the time between the start and the moment this method is called, or the amount of time between start and stop.

Usage

From source file:org.trend.hgraph.util.test.GetGeneratedGraphData.java

private static void doBFSGetGeneratedGraphData(Configuration conf, int levelToTraverse,
        LoopRowKeysStrategy rowKeysStrategy) throws Exception {
    StopWatch timerAll = new StopWatch();
    StopWatch timerRowKey = null;
    Graph graph = null;/*from w  w w  .java  2  s . c om*/
    Vertex vertex = null;
    List<Vertex> curVertices = null;
    List<Vertex> subVertices = null;
    Iterable<Edge> subEdges = null;
    int level = 0;
    long totalVertexCount = 0;
    long perVertexCount = 0;
    String rowKey = null;
    try {
        timerAll.start();
        graph = HBaseGraphFactory.open(conf);
        while (rowKeysStrategy.hasNext()) {
            rowKey = rowKeysStrategy.next();
            LOG.info("***HEAD:Start to process rowKey:" + rowKey + "***");
            timerRowKey = new StopWatch();
            timerRowKey.start();
            vertex = graph.getVertex(rowKey);
            curVertices = Arrays.asList(vertex);
            perVertexCount = 0;
            level = 0;
            while (level < levelToTraverse) {
                level++;
                LOG.info("***HEAD:level:" + level + "***");
                totalVertexCount += curVertices.size();
                perVertexCount += curVertices.size();
                subVertices = new ArrayList<Vertex>();
                for (Vertex tmpVertex : curVertices) {
                    LOG.info("processing vertex:" + tmpVertex.getId());
                    tmpVertex.getPropertyKeys();
                    subEdges = ((org.trend.hgraph.Vertex) vertex).getEdges();
                    for (Edge edge : subEdges) {
                        LOG.info("processing edge:" + edge.getId());
                        edge.getPropertyKeys();
                        subVertices.add(edge.getVertex(Direction.OUT));
                    }
                }
                curVertices = null;
                if (subVertices.size() == 0) {
                    LOG.info("reach last level:" + level);
                    break;
                }
                curVertices = subVertices;
            }
            timerRowKey.stop();
            LOG.info("Time elapsed:" + timerRowKey.toString() + ", " + timerRowKey.getTime()
                    + " for processing rowKey:" + rowKey + " for " + perVertexCount + " of vertices");
            LOG.info("***TAIL:Stop to process rowKey:" + rowKey + "***");
        }
        timerAll.stop();
        LOG.info("Time elapsed:" + timerAll.toString() + ", " + timerAll.getTime() + " for getting "
                + totalVertexCount + " of vertices");
    } catch (Exception e) {
        LOG.error("Processing vertex failed for rowKey:" + rowKey, e);
        throw e;
    } finally {
        try {
            rowKeysStrategy.close();
        } catch (Exception e) {
            LOG.error("Close rowKeysStrategy faiiled", e);
            throw e;
        }
        graph.shutdown();
    }
}

From source file:org.wso2.carbon.esb.samples.test.mediation.Sample9TestCase.java

@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = { "wso2.esb" }, description = "Introduction to Dynamic Sequences with the Registry")
public void testDynamicSequenceWithRegistry() throws Exception {

    LogViewerClient logViewerClient = new LogViewerClient(contextUrls.getBackEndUrl(), getSessionCookie());

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();//  w  w w .j  av a  2  s .  c  o  m

    boolean foundFirstMessage = false;
    boolean foundSecondMessage = false;
    int round = 1;
    while (!foundSecondMessage && stopWatch.getTime() < 20000L) {

        logViewerClient.clearLogs();
        axis2Client.sendSimpleStockQuoteRequest(getMainSequenceURL(),
                getBackEndServiceUrl(ESBTestConstant.SIMPLE_STOCK_QUOTE_SERVICE), "WSO2");

        LogEvent[] getLogsInfo = logViewerClient.getAllSystemLogs();
        for (LogEvent event : getLogsInfo) {
            if (event.getMessage().contains("message = *** Test Message 1 ***")) {
                foundFirstMessage = true;
                log.info("Message [message = *** Test Message 1 ***] found at : " + stopWatch.getTime());
            }
            if (event.getMessage().contains("message = *** Test Message 2 ***")) {
                log.info("Message [message = *** Test Message 2 ***] found at : " + stopWatch.getTime());
                foundSecondMessage = true;
                break;
            }
        }
        if (round == 1) {
            updateSequenceFile();
        }
        round++;
        Thread.sleep(4000);
    }

    stopWatch.stop();
    Assert.assertTrue(foundFirstMessage, "Message [message = *** Test Message 1 ***] not found");
    Assert.assertTrue(foundSecondMessage, "Message [message = *** Test Message 2 ***] not found");
}

From source file:pt.ua.tm.gimli.reader.BCReader.java

/**
 * Main program to read BioCreative corpora and store the result in a file.
 * @param args Command line arguments./*from  w w w  .  j  a v  a2 s . c  o  m*/
 */
public static void main(String[] args) {

    // Start stopwatch
    StopWatch watch = new StopWatch();
    watch.start();

    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("h", "help", false, "Print this usage information.");
    options.addOption("c", "corpus", true, "File with the corpus.");

    Option o = new Option("a", "annotations", true, "File with the annotations of the corpus.");
    o.setRequired(false);
    options.addOption(o);

    options.addOption("g", "gdep", true, "File to load/save the GDep output.");
    options.addOption("o", "output", true, "File to save the annotated corpus.");
    CommandLine commandLine = null;
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments.", ex);
        return;
    }

    // Show help text
    if (commandLine.hasOption('h')) {
        printHelp(options, "");
        return;
    }

    // Get corpus
    String corpus = null;
    if (commandLine.hasOption('c')) {
        corpus = commandLine.getOptionValue('c');
    } else {
        printHelp(options, "Please specify the corpus file.");
        return;
    }

    // Get annotations
    String annotations = null;
    if (commandLine.hasOption('a')) {
        annotations = commandLine.getOptionValue('a');
    }

    // Get GDep output
    String gdep = null;
    if (commandLine.hasOption('g')) {
        gdep = commandLine.getOptionValue('g');
    } else {
        printHelp(options, "Please specify the file to load/save the GDep output.");
        return;
    }

    // Get output
    String output = null;
    if (commandLine.hasOption('o')) {
        output = commandLine.getOptionValue('o');
    } else {
        printHelp(options, "Please specify the output file.");
        return;
    }

    // Create corpus reader
    BCReader reader = new BCReader(corpus, annotations, gdep);

    // Load corpus and write it to a file
    Corpus c = null;
    try {
        c = reader.read(LabelFormat.BIO);
        c.writeToFile(output);
    } catch (GimliException ex) {
        logger.error("There was a problem loading the corpus.", ex);
    }

    // Time feedback
    watch.stop();
    logger.info("Done!");
    logger.info("Total time: {}", watch.toString());

    double time = (double) watch.getTime();
    double size = (double) c.size();

    double perSentence = time / size;
    double perAbstract = time / (size / 10.0);
    double perHundred = time / (size / 100.0);

    logger.info("Per sentence: {} seconds", String.format("%2.4f", perSentence / 1000.0));
    logger.info("Per abstract: {} seconds", String.format("%2.4f", perAbstract / 1000.0));
    logger.info("10 abstracts: {} seconds", String.format("%2.4f", perHundred / 1000.0));
}

From source file:pt.ua.tm.gimli.reader.JNLPBAReader.java

/**
 * Main program to read JNLPBA corpora and store the result in a file.
 * @param args Command line arguments./*  w ww  . j av  a  2  s .  com*/
 */
public static void main(String[] args) {

    // Start stopwatch
    StopWatch watch = new StopWatch();
    watch.start();

    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("h", "help", false, "Print this usage information.");
    options.addOption("c", "corpus", true, "File with the corpus.");
    options.addOption("g", "gdep", true, "File to load/save the GDep output.");

    Option o = new Option("e", "entity", true,
            "Target entity, should be protein, dna, rna, cell_line or cell_type.");
    o.setRequired(false);
    options.addOption(o);

    options.addOption("o", "output", true, "File to save the annotated corpus.");
    CommandLine commandLine = null;

    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments.", ex);
        return;
    }

    // Show help text
    if (commandLine.hasOption('h')) {
        printHelp(options, "");
        return;
    }

    String str;

    // Get corpus
    String corpus = null;
    if (commandLine.hasOption('c')) {
        corpus = commandLine.getOptionValue('c');
    } else {
        printHelp(options, "Please specify the corpus file.");
        return;
    }

    // Get entity
    EntityType entity = null;
    if (commandLine.hasOption('e')) {
        str = commandLine.getOptionValue('e');
        try {
            entity = EntityType.valueOf(str);
        } catch (IllegalArgumentException ex) {
            printHelp(options, "Entity must be protein, dna, rna, cell_line or cell_type.");
            return;
        }
    }

    // Get GDep output
    String gdep = null;
    if (commandLine.hasOption('g')) {
        gdep = commandLine.getOptionValue('g');
    } else {
        printHelp(options, "Please specify the file to load/save the GDep output.");
        return;
    }

    // Get output
    String output = null;
    if (commandLine.hasOption('o')) {
        output = commandLine.getOptionValue('o');
    } else {
        printHelp(options, "Please specify the output file.");
        return;
    }

    // Create corpus reader
    JNLPBAReader reader;
    if (entity != null) {
        reader = new JNLPBAReader(corpus, gdep, entity);
    } else {
        reader = new JNLPBAReader(corpus, gdep);
    }

    // Load corpus and write it to a file
    Corpus c = null;
    try {
        c = reader.read(LabelFormat.BIO);
        c.writeToFile(output);
    } catch (GimliException ex) {
        logger.error("There was a problem loading the corpus.", ex);
    }

    // Time feedback
    watch.stop();
    logger.info("Done!");
    logger.info("Total time: {}", watch.toString());

    double time = (double) watch.getTime();
    double size = (double) c.size();

    double perSentence = time / size;
    double perAbstract = time / (size / 10.0);
    double perHundred = time / (size / 100.0);

    logger.info("Per sentence: {} seconds", String.format("%2.4f", perSentence / 1000.0));
    logger.info("Per abstract: {} seconds", String.format("%2.4f", perAbstract / 1000.0));
    logger.info("10 abstracts: {} seconds", String.format("%2.4f", perHundred / 1000.0));
}

From source file:pt.ua.tm.gimli.writer.BCWriter.java

/**
 * Main program annotate a corpus using one or several models, and save the
 * result in the BioCreative format.//ww w .  j a va  2 s .  c  o m
 * @param args Command line arguments.
 */
public static void main(String[] args) {
    // Start stopwatch
    StopWatch watch = new StopWatch();
    watch.start();

    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("h", "help", false, "Print this usage information.");

    options.addOption("c", "corpus", true, "File with the corpus in the CoNNL format.");

    Option o = new Option("m", "model", true, MODEL_HELP);
    o.setArgs(Integer.MAX_VALUE);

    options.addOption(o);

    options.addOption("o", "output", true, "File to save the annotated corpus.");
    CommandLine commandLine = null;
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments.", ex);
        return;
    }

    // Show help text
    if (commandLine.hasOption('h')) {
        printHelp(options, "");
        return;
    }

    // Get corpus
    String corpus = null;
    if (commandLine.hasOption('c')) {
        corpus = commandLine.getOptionValue('c');
    } else {
        printHelp(options, "Please specify the corpus file.");
        return;
    }

    // Get models
    String[] input = null;
    if (commandLine.hasOption('m')) {
        input = commandLine.getOptionValues('m');
    } else {
        printHelp(options, "Please specify the models.");
        return;
    }

    // Parse models characteristics
    String[] models = new String[input.length];
    String[] features = new String[input.length];
    Parsing[] parsing = new Parsing[input.length];

    String[] strs;
    for (int i = 0; i < input.length; i++) {
        strs = input[i].split(",");

        if (strs.length != 3) {
            printHelp(options, "Wrong input format for models.");
            return;
        }

        models[i] = strs[0].trim();
        parsing[i] = Parsing.valueOf(strs[1].trim().toUpperCase());
        features[i] = strs[2].trim();
    }

    // Get output
    String output = null;
    if (commandLine.hasOption('o')) {
        output = commandLine.getOptionValue('o');
    } else {
        printHelp(options, "Please specify the output file.");
        return;
    }

    // Check length consistency
    if ((features.length != models.length) || (features.length != parsing.length)) {
        logger.error(
                "The number of feature files, parsing, entities and models are different from each other.");
        return;
    }

    // Give user feedback
    logger.info("Corpus: {}", corpus);
    logger.info("Models:");
    for (int i = 0; i < models.length; i++) {
        logger.info("\t{}: {}, {}, {}", new Object[] { i + 1, models[i], features[i], parsing[i] });
    }
    logger.info("Output: {}", output);

    // Load model configurations
    ModelConfig[] mc = new ModelConfig[features.length];
    for (int i = 0; i < features.length; i++) {
        mc[i] = new ModelConfig(features[i]);
    }

    // Load Corpus
    Corpus c = null;
    try {
        c = new Corpus(LabelFormat.BIO, EntityType.protein, corpus);
    } catch (GimliException ex) {
        logger.error("There was a problem loading the corpus", ex);
        return;
    }

    // Load models
    CRFModel[] crfmodels = new CRFModel[models.length];
    try {
        for (int i = 0; i < models.length; i++) {
            crfmodels[i] = new CRFModel(mc[i], parsing[i], models[i]);
        }
    } catch (GimliException ex) {
        logger.error("There was a problem loading the model(s)", ex);
        return;
    }

    Annotator a = new Annotator(c);
    if (crfmodels.length > 1) {
        // Annotate combining the models
        logger.info("Annotating the corpus by combining {} models... ", crfmodels.length);
        a.annotate(crfmodels);

    } else {
        // Annotate using only one model
        logger.info("Annotating the corpus using 1 model...");
        a.annotate(crfmodels[0]);
    }

    // Post-process annotations
    Parentheses.processRemoving(c);
    Abbreviation.process(c);

    // Write to file in the BC format
    BCWriter writer = new BCWriter();
    try {
        logger.info("Wrtiting annotated corpus into file: {}", output);
        writer.write(c, output);
    } catch (GimliException ex) {
        logger.error("There was a problem writing the corpus to file", ex);
    }

    // Time feedback
    watch.stop();
    logger.info("Done!");
    logger.info("Total time: {}", watch.toString());

    double time = (double) watch.getTime();
    double size = (double) c.size();

    double perSentence = time / size;
    double perAbstract = time / (size / 10.0);
    double perHundred = time / (size / 100.0);

    logger.info("Per sentence: {} seconds", String.format("%2.4f", perSentence / 1000.0));
    logger.info("Per abstract: {} seconds", String.format("%2.4f", perAbstract / 1000.0));
    logger.info("10 abstracts: {} seconds", String.format("%2.4f", perHundred / 1000.0));
}

From source file:pt.ua.tm.gimli.writer.JNLPBAWriter.java

/**
 * Main program annotate a corpus using one or several models, and save the
 * result in the JNLPBA format.//from   ww  w. ja v  a 2 s  . co m
 * @param args Command line arguments.
 */
public static void main(String[] args) {
    // Start stopwatch
    StopWatch watch = new StopWatch();
    watch.start();

    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("h", "help", false, "Print this usage information.");

    options.addOption("c", "corpus", true, "File with the corpus in the CoNNL format.");

    Option o = new Option("m", "model", true, MODEL_HELP);
    o.setArgs(Integer.MAX_VALUE);

    options.addOption(o);

    options.addOption("o", "output", true, "File to save the annotated corpus.");
    CommandLine commandLine = null;
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments.", ex);
        return;
    }

    // Show help text
    if (commandLine.hasOption('h')) {
        printHelp(options, "");
        return;
    }

    // Get corpus
    String corpus = null;
    if (commandLine.hasOption('c')) {
        corpus = commandLine.getOptionValue('c');
    } else {
        printHelp(options, "Please specify the corpus file.");
        return;
    }

    // Get models
    String[] input = null;
    if (commandLine.hasOption('m')) {
        input = commandLine.getOptionValues('m');
    } else {
        printHelp(options, "Please specify the models.");
        return;
    }

    // Parse models characteristics
    String[] models = new String[input.length];
    EntityType[] entities = new EntityType[input.length];
    String[] features = new String[input.length];
    Parsing[] parsing = new Parsing[input.length];

    String[] strs;
    for (int i = 0; i < input.length; i++) {
        strs = input[i].split(",");

        if (strs.length != 4) {
            printHelp(options, "Wrong input format for models.");
            return;
        }

        models[i] = strs[0].trim();
        entities[i] = EntityType.valueOf(strs[1].trim());
        parsing[i] = Parsing.valueOf(strs[2].trim().toUpperCase());
        features[i] = strs[3].trim();
    }

    // Get output
    String output = null;
    if (commandLine.hasOption('o')) {
        output = commandLine.getOptionValue('o');
    } else {
        printHelp(options, "Please specify the output file.");
        return;
    }

    // Check length consistency
    if ((features.length != models.length) || (features.length != entities.length)
            || (features.length != parsing.length)) {
        logger.error(
                "The number of feature files, parsing, entities and models are different from each other.");
        return;
    }

    // Give feedback
    logger.info("Corpus: {}", corpus);
    logger.info("Models:");
    for (int i = 0; i < models.length; i++) {
        logger.info("\t{}: {}, {}, {}, {}",
                new Object[] { i + 1, models[i], entities[i], features[i], parsing[i] });
    }
    logger.info("Output: {}", output);

    // Load model configurations
    ModelConfig[] mc = new ModelConfig[features.length];
    for (int i = 0; i < features.length; i++) {
        mc[i] = new ModelConfig(features[i]);
    }

    // Get unique entities
    ArrayList<EntityType> uniqueEntities = new ArrayList<EntityType>();
    for (int i = 0; i < entities.length; i++) {
        if (!uniqueEntities.contains(entities[i])) {
            uniqueEntities.add(entities[i]);
        }
    }

    // Load Corpus
    Corpus[] c = new Corpus[uniqueEntities.size()];
    try {
        for (int i = 0; i < uniqueEntities.size(); i++) {
            c[i] = new Corpus(LabelFormat.BIO, uniqueEntities.get(i), corpus);
        }
    } catch (GimliException ex) {
        logger.error("There was a problem loading the corpus.", ex);
        return;
    }

    // Combine models of the same entity
    for (int j = 0; j < uniqueEntities.size(); j++) {
        ArrayList<CRFModel> crfmodels = new ArrayList<CRFModel>();

        try {
            for (int i = 0; i < entities.length; i++) {
                if (entities[i].equals(uniqueEntities.get(j))) {
                    crfmodels.add(new CRFModel(mc[i], parsing[i], models[i]));
                }
            }
        } catch (GimliException ex) {
            logger.error("There was a problem loading a model.", ex);
            return;
        }

        Annotator a = new Annotator(c[j]);
        if (crfmodels.size() > 1) {

            logger.info("Annotating the corpus by combining {} models for {}...", crfmodels.size(),
                    uniqueEntities.get(j));
            a.annotate(crfmodels.toArray(new CRFModel[0]));
        } else {
            logger.info("Annotating the corpus using 1 model for {}...", uniqueEntities.get(j));
            a.annotate(crfmodels.get(0));
        }
    }

    // Post-processing
    for (int i = 0; i < c.length; i++) {
        Parentheses.processRemoving(c[i]);
        Abbreviation.process(c[i]);
    }

    // Write annotations to file
    logger.info("Writing the corpus in the JNLPBA format...");
    JNLPBAWriter writer = new JNLPBAWriter();

    try {
        if (c.length > 1) {
            //Annotator.writeJNLPBACombined(c, output);
            writer.write(c, output);
        } else {
            writer.write(c[0], output);
            //Annotator.writeJNLPBA(c[0], output);
        }
    } catch (GimliException ex) {
        logger.error("There was a problem writing the corpus to file.", ex);
        return;
    }

    // Time feedback
    watch.stop();
    logger.info("Done!");
    logger.info("Total time: {}", watch.toString());

    double time = (double) watch.getTime();
    double size = (double) c[0].size();

    double perSentence = time / size;
    double perAbstract = time / (size / 10.0);
    double perHundred = time / (size / 100.0);

    logger.info("Per sentence: {} seconds", String.format("%2.4f", perSentence / 1000.0));
    logger.info("Per abstract: {} seconds", String.format("%2.4f", perAbstract / 1000.0));
    logger.info("10 abstracts: {} seconds", String.format("%2.4f", perHundred / 1000.0));
}

From source file:seava.j4e.web.controller.data.AbstractAsgnController.java

/**
 * Default handler for find action.//from ww w  .ja  v  a2 s  .  co  m
 * 
 * @param resourceName
 * @param dataformat
 * @param dataString
 * @param paramString
 * @param resultStart
 * @param resultSize
 * @param orderByCol
 * @param orderBySense
 * @return
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.POST, params = Constants.REQUEST_PARAM_ACTION + "="
        + Constants.ASGN_ACTION_QUERY_LEFT)
@ResponseBody
public String findLeft(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_ASGN_OBJECT_ID, required = true) String objectId,
        @RequestParam(value = Constants.REQUEST_PARAM_ASGN_SELECTION_ID, required = true) String selectionId,
        @RequestParam(value = Constants.REQUEST_PARAM_FILTER, required = false, defaultValue = "{}") String dataString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        @RequestParam(value = Constants.REQUEST_PARAM_START, required = false, defaultValue = "0") int resultStart,
        @RequestParam(value = Constants.REQUEST_PARAM_SIZE, required = false, defaultValue = "500") int resultSize,
        @RequestParam(value = Constants.REQUEST_PARAM_SORT, required = false, defaultValue = "") String orderByCol,
        @RequestParam(value = Constants.REQUEST_PARAM_SENSE, required = false, defaultValue = "") String orderBySense,
        @RequestParam(value = Constants.REQUEST_PARAM_ORDERBY, required = false, defaultValue = "") String orderBy,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        if (logger.isInfoEnabled()) {
            logger.info("Processing request: {}.{} -> action = {} ",
                    new Object[] { resourceName, dataFormat, Constants.ASGN_ACTION_QUERY_LEFT });
        }

        if (logger.isDebugEnabled()) {
            logger.debug("  --> request-filter: objectId={}, selectionId={} data={}",
                    new Object[] { objectId, selectionId, dataString });
            logger.debug("  --> request-params: {} ", new Object[] { paramString });
            logger.debug("  --> request-orderBy: sort={}, sense={}, orderBy={}",
                    new Object[] { orderByCol, orderBySense, orderBy });
            logger.debug("  --> request-result-range: {} ",
                    new Object[] { resultStart + "", (resultStart + resultSize) + "" });
        }

        this.prepareRequest(request, response);

        this.authorizeAsgnAction(resourceName, "find");

        IAsgnService<M, F, P> service = this.findAsgnService(this.serviceNameFromResourceName(resourceName));
        IDsMarshaller<M, F, P> marshaller = service.createMarshaller(dataFormat);

        IQueryBuilder<M, F, P> builder = service.createQueryBuilder().addFetchLimit(resultStart, resultSize);

        if (orderBy != null && !orderBy.equals("")) {
            List<ISortToken> sortTokens = marshaller.readSortTokens(orderBy);
            builder.addSortInfo(sortTokens);
        } else {
            builder.addSortInfo(orderByCol, orderBySense);
        }

        F filter = marshaller.readFilterFromString(dataString);
        P params = marshaller.readParamsFromString(paramString);

        List<M> list = service.findLeft(selectionId, filter, params, builder);
        long totalCount = service.countLeft(selectionId, filter, params, builder);

        IActionResultFind result = this.packfindResult(list, params, totalCount);
        stopWatch.stop();
        result.setExecutionTime(stopWatch.getTime());

        return marshaller.writeResultToString(result);
    } catch (Exception e) {
        return this.handleManagedException(ErrorCode.DB_QUERY_ERROR, e, response);
    } finally {
        this.finishRequest();
    }

}

From source file:seava.j4e.web.controller.data.AbstractAsgnController.java

/**
 * Default handler for find action.//from ww  w  .  ja va2  s .  co  m
 * 
 * @param resourceName
 * @param dataformat
 * @param dataString
 * @param paramString
 * @param resultStart
 * @param resultSize
 * @param orderByCol
 * @param orderBySense
 * @return
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.POST, params = Constants.REQUEST_PARAM_ACTION + "="
        + Constants.ASGN_ACTION_QUERY_RIGHT)
@ResponseBody
public String findRight(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_ASGN_OBJECT_ID, required = true) String objectId,
        @RequestParam(value = Constants.REQUEST_PARAM_ASGN_SELECTION_ID, required = true) String selectionId,
        @RequestParam(value = Constants.REQUEST_PARAM_FILTER, required = false, defaultValue = "{}") String dataString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        @RequestParam(value = Constants.REQUEST_PARAM_START, required = false, defaultValue = "0") int resultStart,
        @RequestParam(value = Constants.REQUEST_PARAM_SIZE, required = false, defaultValue = "500") int resultSize,
        @RequestParam(value = Constants.REQUEST_PARAM_SORT, required = false, defaultValue = "") String orderByCol,
        @RequestParam(value = Constants.REQUEST_PARAM_SENSE, required = false, defaultValue = "") String orderBySense,
        @RequestParam(value = Constants.REQUEST_PARAM_ORDERBY, required = false, defaultValue = "") String orderBy,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        if (logger.isInfoEnabled()) {
            logger.info("Processing request: {}.{} -> action = {} ",
                    new Object[] { resourceName, dataFormat, Constants.ASGN_ACTION_QUERY_RIGHT });
        }

        if (logger.isDebugEnabled()) {
            logger.debug("  --> request-filter: objectId={}, selectionId={} data={}",
                    new Object[] { objectId, selectionId, dataString });
            logger.debug("  --> request-params: {} ", new Object[] { paramString });
            logger.debug("  --> request-orderBy: sort={}, sense={}, orderBy={}",
                    new Object[] { orderByCol, orderBySense, orderBy });
            logger.debug("  --> request-result-range: {} ",
                    new Object[] { resultStart + "", (resultStart + resultSize) + "" });
        }

        this.prepareRequest(request, response);

        this.authorizeAsgnAction(resourceName, "find");

        IAsgnService<M, F, P> service = this.findAsgnService(this.serviceNameFromResourceName(resourceName));

        IDsMarshaller<M, F, P> marshaller = service.createMarshaller(dataFormat);

        IQueryBuilder<M, F, P> builder = service.createQueryBuilder().addFetchLimit(resultStart, resultSize);

        if (orderBy != null && !orderBy.equals("")) {
            List<ISortToken> sortTokens = marshaller.readSortTokens(orderBy);
            builder.addSortInfo(sortTokens);
        } else {
            builder.addSortInfo(orderByCol, orderBySense);
        }

        F filter = marshaller.readFilterFromString(dataString);
        P params = marshaller.readParamsFromString(paramString);

        List<M> list = service.findRight(selectionId, filter, params, builder);
        long totalCount = service.countRight(selectionId, filter, params, builder);

        IActionResultFind result = this.packfindResult(list, params, totalCount);
        stopWatch.stop();
        result.setExecutionTime(stopWatch.getTime());

        return marshaller.writeResultToString(result);
    } catch (Exception e) {
        return this.handleManagedException(ErrorCode.DB_QUERY_ERROR, e, response);
    } finally {
        this.finishRequest();
    }
}

From source file:seava.j4e.web.controller.data.AbstractDsReadController.java

/**
 * Default handler for find action./*from w w w  .  ja  va  2  s  .  c o m*/
 * 
 * @param resourceName
 * @param dataformat
 * @param dataString
 * @param paramString
 * @param resultStart
 * @param resultSize
 * @param orderByCol
 * @param orderBySense
 * @param orderBy
 * @return
 * @throws Exception
 */
@RequestMapping(params = Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_QUERY)
@ResponseBody
public String find(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_FILTER, required = false, defaultValue = "{}") String filterString,
        @RequestParam(value = Constants.REQUEST_PARAM_ADVANCED_FILTER, required = false, defaultValue = "") String filterRulesString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        @RequestParam(value = Constants.REQUEST_PARAM_START, required = false, defaultValue = DEFAULT_RESULT_START) int resultStart,
        @RequestParam(value = Constants.REQUEST_PARAM_SIZE, required = false, defaultValue = DEFAULT_RESULT_SIZE) int resultSize,
        @RequestParam(value = Constants.REQUEST_PARAM_SORT, required = false, defaultValue = "") String orderByCol,
        @RequestParam(value = Constants.REQUEST_PARAM_SENSE, required = false, defaultValue = "") String orderBySense,
        @RequestParam(value = Constants.REQUEST_PARAM_ORDERBY, required = false, defaultValue = "") String orderBy,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        if (logger.isInfoEnabled()) {
            logger.info("Processing request: {}.{} -> action = {} ",
                    new Object[] { resourceName, dataFormat, Constants.DS_ACTION_QUERY });
        }

        if (logger.isDebugEnabled()) {
            logger.debug("  --> request-filter: {} ", new Object[] { filterString });
            logger.debug("  --> request-params: {} ", new Object[] { paramString });
            logger.debug("  --> request-orderBy: sort={}, sense={}, orderBy={}",
                    new Object[] { orderByCol, orderBySense, orderBy });
            logger.debug("  --> request-result-range: {} ",
                    new Object[] { resultStart + "", (resultStart + resultSize) + "" });
        }
        this.prepareRequest(request, response);

        this.authorizeDsAction(resourceName, Constants.DS_ACTION_QUERY, null);

        IDsService<M, F, P> service = this.findDsService(resourceName);
        IDsMarshaller<M, F, P> marshaller = service.createMarshaller(IDsMarshaller.JSON);

        F filter = marshaller.readFilterFromString(filterString);
        P params = marshaller.readParamsFromString(paramString);

        IQueryBuilder<M, F, P> builder = service.createQueryBuilder().addFetchLimit(resultStart, resultSize)
                .addFilter(filter).addParams(params);

        if (orderBy != null && !orderBy.equals("")) {
            List<ISortToken> sortTokens = marshaller.readSortTokens(orderBy);
            builder.addSortInfo(sortTokens);
        } else {
            builder.addSortInfo(orderByCol, orderBySense);
        }

        if (filterRulesString != null && !filterRulesString.equals("")) {
            List<IFilterRule> filterRules = marshaller.readFilterRules(filterRulesString);
            builder.addFilterRules(filterRules);
        }

        List<M> list = service.find(builder);
        long totalCount = service.count(builder);

        IActionResultFind result = this.packfindResult(list, params, totalCount);
        stopWatch.stop();
        result.setExecutionTime(stopWatch.getTime());

        String out = null;

        if (dataFormat.equals(IDsMarshaller.XML)) {
            IDsMarshaller<M, F, P> resultMarshaller = service.createMarshaller(dataFormat);
            out = resultMarshaller.writeResultToString(result);
            response.setContentType("text/xml; charset=UTF-8");
        } else {
            out = marshaller.writeResultToString(result);
            response.setContentType("text/plain; charset=UTF-8");
        }

        return out;
    } catch (Exception e) {
        return this.handleManagedException(ErrorCode.DB_QUERY_ERROR, e, response);
    } finally {
        this.finishRequest();
    }

}

From source file:seava.j4e.web.controller.data.AbstractDsRpcController.java

/**
 * Default handler for remote procedure call on a single value-object.
 * //  w w  w.j av a  2  s . c o m
 * @param resourceName
 * @param dataformat
 * @param dataString
 * @param paramString
 * @return
 * @throws Exception
 */
@RequestMapping(params = { Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_RPC,
        Constants.DS_ACTION_RPC_TYPE + "=" + Constants.DS_ACTION_RPC_TYPE_DATA })
@ResponseBody
public String rpcData(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_SERVICE_NAME_PARAM, required = true) String rpcName,
        @RequestParam(value = Constants.REQUEST_PARAM_DATA, required = false, defaultValue = "{}") String dataString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        if (logger.isInfoEnabled()) {
            logger.info("Processing request: {}.{} -> action = {}-data / {}",
                    new Object[] { resourceName, dataFormat, Constants.DS_ACTION_RPC, rpcName });
        }

        if (logger.isDebugEnabled()) {
            logger.debug("  --> request-data: {} ", new Object[] { dataString });
            logger.debug("  --> request-params: {} ", new Object[] { paramString });
        }

        this.prepareRequest(request, response);

        this.authorizeDsAction(resourceName, Constants.DS_ACTION_RPC, rpcName);

        if (dataFormat.equals("stream")) {
            IDsService<M, F, P> service = this.findDsService(resourceName);
            IDsMarshaller<M, F, P> marshaller = service.createMarshaller("json");

            M data = marshaller.readDataFromString(dataString);
            P params = marshaller.readParamsFromString(paramString);

            InputStream s = service.rpcDataStream(rpcName, data, params);
            this.sendFile(s, response.getOutputStream());
            return "";
        } else {
            IDsService<M, F, P> service = this.findDsService(resourceName);
            IDsMarshaller<M, F, P> marshaller = service.createMarshaller(dataFormat);

            M data = marshaller.readDataFromString(dataString);
            P params = marshaller.readParamsFromString(paramString);

            service.rpcData(rpcName, data, params);
            IActionResultRpc result = this.packRpcDataResult(data, params);
            stopWatch.stop();
            result.setExecutionTime(stopWatch.getTime());
            return marshaller.writeResultToString(result);
        }

    } catch (Exception e) {
        return this.handleManagedException(null, e, response);
    } finally {
        this.finishRequest();
    }
}