Example usage for org.springframework.util StopWatch stop

List of usage examples for org.springframework.util StopWatch stop

Introduction

In this page you can find the example usage for org.springframework.util StopWatch stop.

Prototype

public void stop() throws IllegalStateException 

Source Link

Document

Stop the current task.

Usage

From source file:my.adam.smo.client.SocketClient.java

@Inject
public SocketClient(@Value("${client_worker_threads:10}") int workerThreads) {
    bootstrap.setFactory(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool(), workerThreads));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override//  ww w .  ja  v a 2 s .c o  m
        public ChannelPipeline getPipeline() throws Exception {
            StopWatch stopWatch = new StopWatch("getPipeline");
            stopWatch.start();

            ChannelPipeline p = Channels.pipeline();

            if (enableTrafficLogging) {
                InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
                p.addLast("logger", new LoggingHandler(InternalLogLevel.DEBUG));
            }

            p.addLast("frameEncoder", new LengthFieldPrepender(4));//DownstreamHandler
            p.addLast("protobufEncoder", new ProtobufEncoder());//DownstreamHandler

            p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MAX_FRAME_BYTES_LENGTH, 0, 4, 0, 4));//UpstreamHandler
            p.addLast("protobufDecoder", new ProtobufDecoder(RPCommunication.Response.getDefaultInstance()));//UpstreamHandler
            p.addLast("handler", new SimpleChannelUpstreamHandler() {
                @Override
                public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
                    StopWatch stopWatch = new StopWatch("messageReceived");
                    stopWatch.start();

                    RPCommunication.Response response = (RPCommunication.Response) e.getMessage();
                    logger.trace("received response:" + response);

                    //encryption
                    if (enableAsymmetricEncryption) {
                        response = getAsymDecryptedResponse(response);
                        logger.trace(
                                "asymmetric encryption enabled, encrypted request: " + response.toString());
                    }

                    if (enableSymmetricEncryption) {
                        response = getDecryptedResponse(response);
                        logger.trace("symmetric encryption enabled, encrypted request: " + response.toString());
                    }

                    Message msg = descriptorProtoMap.remove(response.getRequestId());
                    Message m = msg.getParserForType().parseFrom(response.getResponse());
                    callbackMap.remove(response.getRequestId()).run(m);

                    super.messageReceived(ctx, e);
                    stopWatch.stop();
                    logger.trace(stopWatch.shortSummary());
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
                    if (!standardExceptionHandling(ctx, e)) {
                        super.exceptionCaught(ctx, e);
                    }
                }
            });
            stopWatch.stop();
            logger.trace(stopWatch.shortSummary());
            return p;
        }
    });
}

From source file:org.dd4t.core.factories.impl.GenericPageFactory.java

private GenericPage getGenericPage(String uri, RequestContext context)
        throws ItemNotFoundException, NotAuthorizedException, NotAuthenticatedException {

    if (context == null && securityFilterPresent()) {
        throw new RuntimeException("use of getPage is not allowed when a SecurityFilter is set");
    }//ww w .ja v a  2  s  .  com

    StopWatch stopWatch = null;
    if (logger.isDebugEnabled()) {
        logger.debug("Enter getGenericPage with uri: " + uri);
        stopWatch = new StopWatch("getGenericPage");
        stopWatch.start();
    }

    GenericPage page = (GenericPage) getCacheProvider().loadFromLocalCache(uri);
    if (page == null) {
        try {
            TCMURI tcmUri = new TCMURI(uri);
            PageMeta pageMeta = getPageProvider().getPageMetaById(tcmUri.getItemId(),
                    tcmUri.getPublicationId());

            if (pageMeta == null)
                throw new ItemNotFoundException("Unable to find page by id " + tcmUri);

            page = getPageFromMeta(pageMeta);

            try {
                // run only the filters where the result is allowed to be
                // cached.
                doFilters(page, context, BaseFilter.RunPhase.BeforeCaching);
            } catch (FilterException e) {
                logger.error("Error in filter. ", e);
                throw new RuntimeException(e);
            }

            getCacheProvider().storeInItemCache(uri, page, tcmUri.getPublicationId(), tcmUri.getItemId());

        } catch (IOException e) {
            logger.error("IOException when processing page: " + uri, e);
            throw new RuntimeException(e);
        } catch (ParseException e) {
            logger.error("ParseException when searching for page: " + uri, e);
            throw new RuntimeException(e);
        } catch (StorageException e) {
            logger.error("StorageException when searching for page: " + uri, e);
            throw new RuntimeException(e);
        }
    }

    try {
        // run only the filters where the result is not allowed to be
        // cached.
        doFilters(page, context, BaseFilter.RunPhase.AfterCaching);
    } catch (FilterException e) {
        logger.error("Error in filter. ", e);
        throw new RuntimeException(e);
    } finally {
        if (logger.isDebugEnabled()) {
            stopWatch.stop();
            logger.debug("Exit getGenericPage (" + stopWatch.getTotalTimeMillis() + " ms)");
        }
    }

    return page;
}

From source file:my.adam.smo.client.HTTPClient.java

@Inject
public HTTPClient(@Value("${client_worker_threads:10}") int workerThreads) {
    bootstrap.setFactory(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool(), workerThreads));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override//from  w w w  . java 2  s.c o m
        public ChannelPipeline getPipeline() throws Exception {
            StopWatch stopWatch = new StopWatch("getPipeline");
            stopWatch.start();

            ChannelPipeline p = Channels.pipeline();

            if (enableTrafficLogging) {
                InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
                p.addLast("logger", new LoggingHandler(InternalLogLevel.DEBUG));
            }

            p.addLast("codec", new HttpClientCodec());
            p.addLast("chunkAggregator", new HttpChunkAggregator(MAX_CONTENT_LENGTH));
            p.addLast("chunkedWriter", new ChunkedWriteHandler());
            p.addLast("decompressor", new HttpContentDecompressor());

            p.addLast("handler", new SimpleChannelUpstreamHandler() {
                @Override
                public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
                    StopWatch stopWatch = new StopWatch("messageReceived");
                    stopWatch.start();

                    HttpResponse httpResponse = (HttpResponse) e.getMessage();

                    ChannelBuffer cb = Base64.decode(httpResponse.getContent(), Base64Dialect.STANDARD);

                    RPCommunication.Response response = RPCommunication.Response
                            .parseFrom(CodedInputStream.newInstance(cb.copy(0, cb.readableBytes()).array()));
                    logger.trace("received response:" + response);

                    //encryption
                    if (enableAsymmetricEncryption) {
                        response = getAsymDecryptedResponse(response);
                        logger.trace(
                                "asymmetric encryption enabled, encrypted request: " + response.toString());
                    }

                    if (enableSymmetricEncryption) {
                        response = getDecryptedResponse(response);
                        logger.trace("symmetric encryption enabled, encrypted request: " + response.toString());
                    }

                    Message msg = descriptorProtoMap.remove(response.getRequestId());
                    Message m = msg.getParserForType().parseFrom(response.getResponse());
                    callbackMap.remove(response.getRequestId()).run(m);

                    super.messageReceived(ctx, e);
                    stopWatch.stop();
                    logger.trace(stopWatch.shortSummary());
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
                    if (!standardExceptionHandling(ctx, e)) {
                        super.exceptionCaught(ctx, e);
                    }
                }
            });

            stopWatch.stop();
            logger.trace(stopWatch.shortSummary());
            return p;
        }
    });
}

From source file:my.adam.smo.server.SocketServer.java

@Inject
public SocketServer(@Value("${server_worker_threads:10}") int workerCount) {
    bootstrap.setFactory(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool(), workerCount));

    ChannelPipelineFactory pipelineFactory = new ChannelPipelineFactory() {
        @Override//w  w  w  .  ja v  a2 s .com
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline p = Channels.pipeline();
            if (enableTrafficLogging) {
                InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
                p.addLast("logger", new LoggingHandler(InternalLogLevel.DEBUG));
            }

            p.addLast("frameEncoder", new LengthFieldPrepender(4));//DownstreamHandler
            p.addLast("protobufEncoder", new ProtobufEncoder());//DownstreamHandler

            p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MAX_FRAME_BYTES_LENGTH, 0, 4, 0, 4));//UpstreamHandler
            p.addLast("protobufDecoder", new ProtobufDecoder(RPCommunication.Request.getDefaultInstance()));//UpstreamHandler
            p.addLast("handler", new SimpleChannelUpstreamHandler() {
                @Override
                public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
                    StopWatch stopWatch = new StopWatch("messageReceived");
                    stopWatch.start();

                    RPCommunication.Request request = (RPCommunication.Request) e.getMessage();
                    logger.trace("received request:" + request.toString());

                    if (enableAsymmetricEncryption) {
                        request = getAsymDecryptedRequest(request);
                        logger.trace("asymmetric encryption enabled, decrypted request: " + request.toString());
                    }

                    if (enableSymmetricEncryption) {
                        request = getDecryptedRequest(request);
                        logger.trace("symmetric encryption enabled, decrypted request: " + request.toString());
                    }

                    final RPCommunication.Request protoRequest = request;

                    RpcController dummyController = new DummyRpcController();
                    Service service = serviceMap.get(request.getServiceName());

                    logger.trace("got service: " + service + " for name " + request.getServiceName());

                    Descriptors.MethodDescriptor methodToCall = service.getDescriptorForType()
                            .findMethodByName(request.getMethodName());

                    logger.trace("got method: " + methodToCall + " for name " + request.getMethodName());

                    Message methodArguments = service.getRequestPrototype(methodToCall).newBuilderForType()
                            .mergeFrom(request.getMethodArgument()).build();

                    logger.trace("get method arguments from request " + methodArguments.toString());

                    RpcCallback<Message> callback = new RpcCallback<Message>() {
                        @Override
                        public void run(Message parameter) {
                            RPCommunication.Response response = RPCommunication.Response.newBuilder()
                                    .setResponse(parameter.toByteString())
                                    .setRequestId(protoRequest.getRequestId()).build();

                            //encryption
                            if (enableSymmetricEncryption) {
                                response = getEncryptedResponse(response);
                                logger.trace("symmetric encryption enabled, encrypted response: "
                                        + response.toString());
                            }

                            if (enableAsymmetricEncryption) {
                                response = getAsymEncryptedResponse(response);
                                logger.trace("asymmetric encryption enabled, encrypted response: "
                                        + response.toString());
                            }

                            e.getChannel().write(response);
                            logger.trace("finishing call, response sent");
                        }
                    };
                    logger.trace("calling " + methodToCall.getFullName());
                    service.callMethod(methodToCall, dummyController, methodArguments, callback);
                    stopWatch.stop();
                    logger.trace(stopWatch.shortSummary());
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
                    if (!standardExceptionHandling(ctx, e)) {
                        super.exceptionCaught(ctx, e);
                    }
                }
            });
            return p;
        }
    };
    bootstrap.setPipelineFactory(pipelineFactory);
}

From source file:com.googlecode.flyway.core.validation.DbValidator.java

/**
 * Validate the checksum of all existing sql migration in the metadata table with the checksum of the sql migrations
 * in the classpath//ww w.  java  2s .  c  o m
 *
 * @param resolvedMigrations All migrations available on the classpath, sorted by version, newest first.
 * @return description of validation error or NULL if no validation error was found
 */
public String validate(List<Migration> resolvedMigrations) {
    if (ValidationMode.NONE.equals(validationMode)) {
        return null;
    }

    LOG.debug(String.format("Validating (mode %s) migrations ...", validationMode));
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    final List<MetaDataTableRow> appliedMigrations = new ArrayList<MetaDataTableRow>(
            metaDataTable.allAppliedMigrations());
    if (appliedMigrations.isEmpty()) {
        LOG.info("No migrations applied yet. No validation necessary.");
        return null;
    }

    List<Migration> migrations = new ArrayList<Migration>(resolvedMigrations);
    // migrations now with newest last
    Collections.reverse(migrations);
    final MetaDataTableRow firstAppliedMigration = appliedMigrations.get(0);
    if (MigrationType.INIT.equals(firstAppliedMigration.getMigrationType())) {
        // if first migration is INIT, just check checksum of following migrations
        final SchemaVersion initVersion = firstAppliedMigration.getVersion();
        appliedMigrations.remove(firstAppliedMigration);

        Iterator<Migration> iterator = migrations.iterator();
        while (iterator.hasNext()) {
            Migration migration = iterator.next();
            if (migration.getVersion().compareTo(initVersion) <= 0) {
                iterator.remove();
            }
        }
    }

    if (appliedMigrations.size() > migrations.size()) {
        List<SchemaVersion> schemaVersions = new ArrayList<SchemaVersion>();
        for (MetaDataTableRow metaDataTableRow : appliedMigrations) {
            schemaVersions.add(metaDataTableRow.getVersion());
        }
        for (Migration migration : migrations) {
            schemaVersions.remove(migration.getVersion());
        }

        String diff = StringUtils.collectionToCommaDelimitedString(schemaVersions);

        return String.format(
                "More applied migrations than classpath migrations: DB=%s, Classpath=%s, Missing migrations=(%s)",
                appliedMigrations.size(), migrations.size(), diff);
    }

    for (int i = 0; i < appliedMigrations.size(); i++) {
        MetaDataTableRow appliedMigration = appliedMigrations.get(i);
        //Migrations are sorted in the opposite order: newest first.
        Migration classpathMigration = migrations.get(i);

        if (!appliedMigration.getVersion().equals(classpathMigration.getVersion())) {
            return String.format("Version mismatch for migration %s: DB=%s, Classpath=%s",
                    appliedMigration.getScript(), appliedMigration.getVersion(),
                    classpathMigration.getVersion());

        }
        if (!appliedMigration.getMigrationType().equals(classpathMigration.getMigrationType())) {
            return String.format("Migration Type mismatch for migration %s: DB=%s, Classpath=%s",
                    appliedMigration.getScript(), appliedMigration.getMigrationType(),
                    classpathMigration.getMigrationType());
        }

        final Integer appliedChecksum = appliedMigration.getChecksum();
        final Integer classpathChecksum = classpathMigration.getChecksum();
        if (!ObjectUtils.nullSafeEquals(appliedChecksum, classpathChecksum)) {
            return String.format("Checksum mismatch for migration %s: DB=%s, Classpath=%s",
                    appliedMigration.getScript(), appliedChecksum, classpathMigration.getChecksum());
        }
    }

    stopWatch.stop();
    if (appliedMigrations.size() == 1) {
        LOG.info(String.format("Validated 1 migration (mode: %s) (execution time %s)", validationMode,
                TimeFormat.format(stopWatch.getTotalTimeMillis())));
    } else {
        LOG.info(String.format("Validated %d migrations (mode: %s) (execution time %s)",
                appliedMigrations.size(), validationMode, TimeFormat.format(stopWatch.getTotalTimeMillis())));
    }

    return null;
}

From source file:org.dd4t.core.factories.impl.GenericComponentFactory.java

/**
 * Get the component by the component uri and template uri.
 * //from  w  w  w.  j  ava  2 s. c  om
 * @return the component
 * @throws ItemNotFoundException
 *             if no item found NotAuthorizedException if the user is not
 *             authorized to get the component
 * @throws NotAuthenticatedException 
 */
public DynamicComponent getComponent(String componentUri, String componentTemplateUri, RequestContext context)
        throws ItemNotFoundException, NotAuthorizedException, NotAuthenticatedException {

    if (context == null && securityFilterPresent()) {
        throw new RuntimeException(
                "use of getComponent without a context is not allowed when a SecurityFilter is set");
    }

    if (!componentUri.endsWith("-16")) {
        componentUri += "-16";
    }

    StopWatch stopWatch = null;
    if (logger.isDebugEnabled()) {
        logger.debug("Enter getComponent with uri: " + componentUri);
        stopWatch = new StopWatch("getComponent");
        stopWatch.start();
    }

    DynamicComponent component = (DynamicComponent) getCacheProvider().loadFromLocalCache(componentUri);
    if (component == null) {
        TCMURI tcmUri;
        ComponentMeta componentMeta;
        com.tridion.dcp.ComponentPresentation dcp;

        try {

            tcmUri = new TCMURI(componentUri);

            componentMeta = getComponentProvider().getComponentMeta(tcmUri.getItemId(),
                    tcmUri.getPublicationId());

            if (componentMeta == null) {
                throw new ItemNotFoundException("Unable to find item with id " + componentUri
                        + " in the broker. Is the item published?");
            }

            if (componentTemplateUri != null) {
                TCMURI ctUri = new TCMURI(componentTemplateUri);

                dcp = getComponentProvider().getDynamicComponentPresentation(tcmUri.getItemId(),
                        ctUri.getItemId(), tcmUri.getPublicationId());
            } else {
                dcp = getComponentProvider().getDynamicComponentPresentation(tcmUri.getItemId(), 0,
                        tcmUri.getPublicationId());
            }
        } catch (ParseException e1) {
            logger.error("No item found with uri: " + componentUri + "; could not parse the URI: " + e1);
            throw new ItemNotFoundException(
                    "No item found with uri: " + componentUri + "; could not parse the URI: " + e1);
        } catch (StorageException e2) {
            logger.error("No item found with uri: " + componentUri + "; broker is down.");
            throw new ItemNotFoundException("No item found with uri: " + componentUri + "; broker is down.");
        }

        if (dcp.getContent() == null) {
            logger.error(
                    "Source is null for item: " + componentUri + " and templateUri: " + componentTemplateUri);
            throw new ItemNotFoundException(
                    "No item found with uri: " + componentUri + " and templateUri: " + componentTemplateUri);
        }

        try {
            component = getDCPFromSource(dcp);

            component.setNativeMetadata(componentMeta);

            // Rogier Oudshoorn, 7/2/2012
            // object size is roughly half the xml string size; 

            ((BasePublishedItem) component).setSourceSize(dcp.getContent().length());

            try {
                doFilters(component, context, BaseFilter.RunPhase.BeforeCaching);
            } catch (FilterException e) {
                logger.error("Error in filter. ", e);
                throw new RuntimeException(e);
            }

            getCacheProvider().storeInItemCache(componentUri, component,
                    component.getNativeMetadata().getPublicationId(),
                    component.getNativeMetadata().getItemId());
        } catch (Exception e) {
            logger.error("error when deserializing component", e);
            throw new RuntimeException(e);
        }
    }

    try {
        doFilters(component, context, BaseFilter.RunPhase.AfterCaching);
    } catch (FilterException e) {
        logger.error("Error in filter. ", e);
        throw new RuntimeException(e);
    }

    if (logger.isDebugEnabled()) {
        stopWatch.stop();
        logger.debug("Exit getComponent (" + stopWatch.getTotalTimeMillis() + " ms)");
    }

    return component;
}

From source file:fr.univrouen.poste.services.GalaxieExcelParser.java

public void process(GalaxieExcel galaxieExcel) throws SQLException {

    StopWatch chrono = new StopWatch();
    chrono.start();//from   ww w  .ja va  2 s  .  co  m

    List<List<String>> cells = excelParser
            .getCells(galaxieExcel.getBigFile().getBinaryFile().getBinaryStream());

    Map<String, Long> cellsPosition = new HashMap<String, Long>();

    int p = 0;
    List<String> cellsHead = cells.remove(0);
    for (String cellName : cellsHead) {
        cellsPosition.put(cellName, new Long(p++));
    }
    galaxieMappingService.checkCellsHead(cellsPosition);

    Map<List<String>, GalaxieEntry> dbGalaxyEntries = new HashMap<List<String>, GalaxieEntry>();
    for (GalaxieEntry galaxieEntry : GalaxieEntry.findAllGalaxieEntrys()) {
        dbGalaxyEntries.put(getList4Id(galaxieEntry), galaxieEntry);
    }

    for (List<String> row : cells) {

        // create a new galaxyEntry
        GalaxieEntry galaxieEntry = new GalaxieEntry();
        for (String cellName : cellsPosition.keySet()) {
            int position = cellsPosition.get(cellName).intValue();
            if (row.size() > position) {
                String cellValue = row.get(position);
                galaxieMappingService.setAttrFromCell(galaxieEntry, cellName, cellValue);
            } else {
                logger.debug("can't get " + cellName + " for this row in excel file ...");
            }
        }

        // Rcupration d'un GalaxieEntry  chaque fois trop gourmand, mme avec l'index ...
        //TypedQuery<GalaxieEntry> query = GalaxieEntry.findGalaxieEntrysByNumEmploiAndNumCandidat(galaxieEntry.getNumEmploi(), galaxieEntry.getNumCandidat(), null, null);
        GalaxieEntry dbGalaxyEntrie = dbGalaxyEntries.get(getList4Id(galaxieEntry));

        if (dbGalaxyEntrie == null) {
            galaxieEntry.persist();
            dbGalaxyEntries.put(getList4Id(galaxieEntry), galaxieEntry);
        } else {
            // This GalaxyEntry exists already, we merge it if needed
            if (!fieldsEquals(dbGalaxyEntrie, galaxieEntry)) {
                dbGalaxyEntrie.setCivilite(galaxieEntry.getCivilite());
                dbGalaxyEntrie.setNom(galaxieEntry.getNom());
                dbGalaxyEntrie.setPrenom(galaxieEntry.getPrenom());
                if (dbGalaxyEntrie.getEmail().isEmpty()) {
                    if (!galaxieEntry.getEmail().isEmpty()) {
                        dbGalaxyEntrie.setEmail(galaxieEntry.getEmail());
                        logger.info("Le candidat " + dbGalaxyEntrie.getNumCandidat()
                                + " a maintenant renseign son email : " + galaxieEntry.getEmail());
                    }
                }
                // si email diffrent et si le candidat n'a pas activ son compte - on rinitialise le compte == on le supprime et on le rcr avec cette nvelle adresse mail
                else if (!dbGalaxyEntrie.getEmail().equals(galaxieEntry.getEmail())) {
                    try {
                        User user = User.findUsersByEmailAddress(dbGalaxyEntrie.getEmail()).getSingleResult();
                        if (user.getActivationDate() == null && !user.isCandidatActif()) {
                            logger.info("Le candidat " + dbGalaxyEntrie.getNumCandidat()
                                    + " a chang d'email alors qu'il n'avait pas encore activ son compte - on relance la procdure de cration de son compte/candidature.");

                            // cas o le candidat postule  plusieurs postes pris en compte ainsi
                            List<GalaxieEntry> userGalaxieEntries = GalaxieEntry
                                    .findGalaxieEntrysByCandidat(user).getResultList();
                            for (GalaxieEntry userGalaxieEntry : userGalaxieEntries) {
                                dbGalaxyEntries.remove(getList4Id(userGalaxieEntry));
                            }

                            user.remove();
                            galaxieEntry.persist();
                            dbGalaxyEntries.put(getList4Id(galaxieEntry), galaxieEntry);
                            continue;
                        }
                        dbGalaxyEntrie.setEmail(galaxieEntry.getEmail());
                    } catch (Exception e) {
                        logger.warn("Pb avec le candidat " + dbGalaxyEntrie.getNumCandidat()
                                + " qui a chang d'email ...", e);
                    }
                }
                dbGalaxyEntrie.setLocalisation(galaxieEntry.getLocalisation());
                dbGalaxyEntrie.setProfil(galaxieEntry.getProfil());
                dbGalaxyEntrie.setEtatDossier(galaxieEntry.getEtatDossier());
                dbGalaxyEntrie.merge();
            }
        }
    }

    chrono.stop();
    logger.info("Le traitement du fichier Excel Galaxie a t effectu en "
            + chrono.getTotalTimeMillis() / 1000.0 + " sec.");

}

From source file:my.adam.smo.server.HTTPServer.java

@Inject
public HTTPServer(@Value("${server_worker_threads:10}") int workerCount) {
    bootstrap.setFactory(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool(), workerCount));

    ChannelPipelineFactory pipelineFactory = new ChannelPipelineFactory() {
        @Override/*from  www .ja  va  2  s.  c  o m*/
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline p = Channels.pipeline();

            if (enableTrafficLogging) {
                InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
                p.addLast("logger", new LoggingHandler(InternalLogLevel.DEBUG));
            }

            p.addLast("codec", new HttpServerCodec());
            p.addLast("chunkAggregator", new HttpChunkAggregator(MAX_CONTENT_LENGTH));
            p.addLast("chunkedWriter", new ChunkedWriteHandler());
            p.addLast("compressor", new HttpContentCompressor());

            p.addLast("handler", new SimpleChannelUpstreamHandler() {
                @Override
                public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
                    StopWatch stopWatch = new StopWatch("messageReceived");
                    stopWatch.start();

                    final DefaultHttpRequest httpRequest = (DefaultHttpRequest) e.getMessage();
                    ChannelBuffer cb = Base64.decode(httpRequest.getContent(), Base64Dialect.STANDARD);

                    RPCommunication.Request request = RPCommunication.Request
                            .parseFrom(cb.copy(0, cb.readableBytes()).array());
                    logger.trace("received request:" + request.toString());

                    if (enableAsymmetricEncryption) {
                        request = getAsymDecryptedRequest(request);
                        logger.trace("asymmetric encryption enabled, decrypted request: " + request.toString());
                    }

                    if (enableSymmetricEncryption) {
                        request = getDecryptedRequest(request);
                        logger.trace("symmetric encryption enabled, decrypted request: " + request.toString());
                    }

                    final RPCommunication.Request protoRequest = request;

                    RpcController dummyController = new DummyRpcController();
                    Service service = serviceMap.get(request.getServiceName());

                    logger.trace("got service: " + service + " for name " + request.getServiceName());

                    Descriptors.MethodDescriptor methodToCall = service.getDescriptorForType()
                            .findMethodByName(request.getMethodName());

                    logger.trace("got method: " + methodToCall + " for name " + request.getMethodName());

                    Message methodArguments = service.getRequestPrototype(methodToCall).newBuilderForType()
                            .mergeFrom(request.getMethodArgument()).build();

                    logger.trace("get method arguments from request " + methodArguments.toString());

                    RpcCallback<Message> callback = new RpcCallback<Message>() {
                        @Override
                        public void run(Message parameter) {
                            HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
                                    HttpResponseStatus.OK);

                            ByteArrayOutputStream paramOutputStream = new ByteArrayOutputStream();
                            CodedOutputStream paramCodedOutputStream = CodedOutputStream
                                    .newInstance(paramOutputStream);
                            try {
                                parameter.writeTo(paramCodedOutputStream);
                                paramCodedOutputStream.flush();
                            } catch (IOException e1) {
                                logger.error("failed to write to output stream");
                            }

                            RPCommunication.Response response = RPCommunication.Response.newBuilder()
                                    .setResponse(ByteString.copyFrom(paramOutputStream.toByteArray()))
                                    .setRequestId(protoRequest.getRequestId()).build();

                            if (enableSymmetricEncryption) {
                                response = getEncryptedResponse(response);
                                logger.trace("symmetric encryption enabled, encrypted response: "
                                        + response.toString());
                            }

                            if (enableAsymmetricEncryption) {
                                response = getAsymEncryptedResponse(response);
                                logger.trace("asymmetric encryption enabled, encrypted response: "
                                        + response.toString());
                            }

                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream);
                            try {
                                response.writeTo(codedOutputStream);
                                codedOutputStream.flush();
                            } catch (IOException e1) {
                                logger.error("unable to write to output stream", e1);
                            }

                            byte[] arr = outputStream.toByteArray();

                            ChannelBuffer resp = Base64.encode(ChannelBuffers.copiedBuffer(arr),
                                    Base64Dialect.STANDARD);

                            httpResponse.setContent(resp);
                            httpResponse.addHeader(HttpHeaders.Names.CONTENT_LENGTH, resp.readableBytes());
                            httpResponse.addHeader(HttpHeaders.Names.CONTENT_TYPE,
                                    HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);

                            e.getChannel().write(httpResponse);
                            logger.trace("finishing call, httpResponse sent");
                        }
                    };
                    logger.trace("calling " + methodToCall.getFullName());
                    service.callMethod(methodToCall, dummyController, methodArguments, callback);
                    stopWatch.stop();
                    logger.trace(stopWatch.shortSummary());
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
                    if (!standardExceptionHandling(ctx, e)) {
                        super.exceptionCaught(ctx, e);
                    }
                }
            });
            return p;
        }
    };
    bootstrap.setPipelineFactory(pipelineFactory);
}

From source file:com.jxt.web.controller.ScatterChartController.java

/**
 * @param applicationName//  w  w  w .jav  a 2 s.  c  om
 * @param from
 * @param to
 * @param limit           max number of data return. if the requested data exceed this limit, we need additional calls to
 *                        fetch the rest of the data
 * @return
 */
@RequestMapping(value = "/getScatterData", method = RequestMethod.GET)
public ModelAndView getScatterData(@RequestParam("application") String applicationName,
        @RequestParam("from") long from, @RequestParam("to") long to,
        @RequestParam("xGroupUnit") int xGroupUnit, @RequestParam("yGroupUnit") int yGroupUnit,
        @RequestParam("limit") int limit,
        @RequestParam(value = "backwardDirection", required = false, defaultValue = "true") boolean backwardDirection,
        @RequestParam(value = "filter", required = false) String filterText,
        @RequestParam(value = "_callback", required = false) String jsonpCallback,
        @RequestParam(value = "v", required = false, defaultValue = "1") int version) {
    limit = LimitUtils.checkRange(limit);

    StopWatch watch = new StopWatch();
    watch.start("getScatterData");

    // TODO range check verification exception occurs. "from" is bigger than "to"
    final Range range = Range.createUncheckedRange(from, to);
    logger.debug(
            "fetch scatter data. RANGE={}, X-Group-Unit:{}, Y-Group-Unit:{}, LIMIT={}, BACKWARD_DIRECTION:{}, FILTER:{}",
            range, xGroupUnit, yGroupUnit, limit, backwardDirection, filterText);

    ModelAndView mv = null;
    if (StringUtils.isEmpty(filterText)) {
        mv = selectScatterData(applicationName, range, xGroupUnit, yGroupUnit, limit, backwardDirection,
                version);
    } else {
        mv = selectFilterScatterData(applicationName, range, xGroupUnit, yGroupUnit, limit, backwardDirection,
                filterText, version);
    }

    if (jsonpCallback == null) {
        mv.setViewName("jsonView");
    } else {
        mv.setViewName("jsonpView");
    }

    watch.stop();

    logger.info("Fetch scatterData time : {}ms", watch.getLastTaskTimeMillis());

    return mv;
}

From source file:com.jxt.web.service.FilteredMapServiceImpl.java

@Override
@Deprecated//from w  w  w  .  j  a  v a  2  s .  c o  m
public LoadFactor linkStatistics(Range range, List<TransactionId> traceIdSet, Application sourceApplication,
        Application destinationApplication, Filter filter) {
    if (sourceApplication == null) {
        throw new NullPointerException("sourceApplication must not be null");
    }
    if (destinationApplication == null) {
        throw new NullPointerException("destApplicationName must not be null");
    }
    if (filter == null) {
        throw new NullPointerException("filter must not be null");
    }

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

    List<List<SpanBo>> originalList = this.traceDao.selectAllSpans(traceIdSet);
    List<SpanBo> filteredTransactionList = filterList(originalList, filter);

    LoadFactor statistics = new LoadFactor(range);

    // TODO need to handle these separately by node type (like fromToFilter)

    // scan transaction list
    for (SpanBo span : filteredTransactionList) {
        if (sourceApplication.equals(span.getApplicationId(),
                registry.findServiceType(span.getApplicationServiceType()))) {
            List<SpanEventBo> spanEventBoList = span.getSpanEventBoList();
            if (spanEventBoList == null) {
                continue;
            }

            // find dest elapsed time
            for (SpanEventBo spanEventBo : spanEventBoList) {
                if (destinationApplication.equals(spanEventBo.getDestinationId(),
                        registry.findServiceType(spanEventBo.getServiceType()))) {
                    // find exception
                    boolean hasException = spanEventBo.hasException();
                    // add sample
                    // TODO : need timeslot value instead of the actual value
                    statistics.addSample(span.getStartTime() + spanEventBo.getStartElapsed(),
                            spanEventBo.getEndElapsed(), 1, hasException);
                    break;
                }
            }
        }
    }

    watch.stop();
    logger.info("Fetch link statistics elapsed. {}ms", watch.getLastTaskTimeMillis());

    return statistics;
}