List of usage examples for org.apache.commons.lang.time StopWatch start
public void start()
Start the stopwatch.
This method starts a new timing session, clearing any previous values.
From source file:com.yahoo.flowetl.core.Plumber.java
/** * Translates a set of roots into a runnable object. * //from w w w.j a v a 2 s . c om * @param roots * * @return the pipe runner * * @throws PipeException */ public PipeRunner translate(final Set<Pipe> roots) throws PipeException { if (roots == null || roots.isEmpty()) { throw new IllegalArgumentException("No valid pipes provided"); } // first translate to a graph final DefaultDirectedGraph<Pipe, PipeEdge> runGraph = new DefaultDirectedGraph<Pipe, PipeEdge>( new EdgeFactory<Pipe, PipeEdge>() { @Override public PipeEdge createEdge(Pipe src, Pipe tgt) { StringBuilder tmp = new StringBuilder(); tmp.append("{" + src.getName() + "}"); tmp.append("->"); tmp.append("{" + tgt.getName() + "}"); return new PipeEdge(tmp.toString()); } }); // find all reachable pipes from the given roots final Set<Pipe> reachableInputs = new HashSet<Pipe>(); Set<Pipe> reachablePipesTmp = new HashSet<Pipe>(); for (Pipe p : roots) { discoverReachable(p, reachablePipesTmp); reachableInputs.addAll(reachablePipesTmp); reachableInputs.add(p); reachablePipesTmp.clear(); } // add as vertexes.. for (Pipe p : reachableInputs) { runGraph.addVertex(p); } // connect together for (Pipe v : reachableInputs) { List<Pipe> outs = v.getOutputs(); if (outs != null) { int max = v.maxOutputs(); int cur = outs.size(); if (max != -1 && (max < cur)) { throw new PipeException( "Pipe " + v + " is only allowed " + max + " outputs but it has " + cur + " outputs"); } for (Pipe t : outs) { if (t == null) { continue; } PipeEdge edgeName = runGraph.addEdge(v, t); if (logger.isEnabled(Level.INFO)) { logger.log(Level.INFO, "Connected " + v + " to " + t + " with edge " + edgeName); } } } } // do cycle detection CycleDetector<Pipe, PipeEdge> cycleDetect = new CycleDetector<Pipe, PipeEdge>(runGraph); Set<Pipe> cycleNodes = cycleDetect.findCycles(); if (cycleNodes != null && cycleNodes.isEmpty() == false) { StringBuilder msg = new StringBuilder("The following pipes are causing cycles ["); msg.append(StringUtils.join(cycleNodes, ",")); msg.append("]"); throw new PipeException(msg.toString()); } // check connected components ConnectivityInspector<Pipe, PipeEdge> cInspector = new ConnectivityInspector<Pipe, PipeEdge>(runGraph); if (cInspector.isGraphConnected() == false) { throw new PipeException( "The pipes provided have occurences which do not actually connect to other pipes"); } // display if (logger.isEnabled(Level.DEBUG)) { StringWriter w = new StringWriter(); DOTExporter<Pipe, PipeEdge> d = new DOTExporter<Pipe, PipeEdge>(new VertexNameProvider<Pipe>() { @Override public String getVertexName(Pipe p) { return p.getName(); } }, new VertexNameProvider<Pipe>() { @Override public String getVertexName(Pipe p) { return p.getName(); } }, new EdgeNameProvider<PipeEdge>() { @Override public String getEdgeName(PipeEdge e) { return String.valueOf(e); } }); d.export(w, runGraph); try { w.close(); } catch (IOException e1) { // should be ok to ignore this... } logger.log(Level.DEBUG, w.toString()); } // all verified, yippe PipeRunner out = new PipeRunner() { @Override public void run() { // use topological order to figure out // how to run this graph in a way // that will ensure the inputs are satisfied // before a vertex is ran... GraphIterator<Pipe, PipeEdge> it = makeTraversalIterator(runGraph); // get the ordering first // which doesn't involve activating any of the pipes // just seeing what the iteration order will be... final List<Pipe> order = IterUtils.toList(it, ArrayList.class); // now make the real run iterator it = makeTraversalIterator(runGraph); it.addTraversalListener(new TraversalListenerAdapter<Pipe, PipeEdge>() { @Override public void vertexTraversed(VertexTraversalEvent<Pipe> v) { if (logger.isEnabled(Level.INFO)) { logger.log(Level.INFO, "Vertex " + v.getVertex() + " was visited"); } } }); StopWatch overallTimer = new StopWatch(); overallTimer.start(); notifyStart(order); // keep track of which ones we exec'ed // maybe for use later?? final List<Pipe> curExecd = new ArrayList<Pipe>(order.size()); // iterate StopWatch perRunTimer = new StopWatch(); List<Pipe> pipeOutputs = null; PipeResult pipeRes = null; while (it.hasNext()) { Pipe toRun = it.next(); perRunTimer.reset(); perRunTimer.start(); notifyStartGenerate(toRun); { pipeRes = toRun.generateOutput(); } perRunTimer.stop(); curExecd.add(toRun); pipeOutputs = toRun.getOutputs(); if (pipeOutputs != null) { for (Pipe tmp : pipeOutputs) { if (tmp == null) { continue; } tmp.attachInput(pipeRes); } } notifyFinishGenerate(toRun, pipeRes, perRunTimer.getTime()); // now clear it toRun.clearInputs(); } overallTimer.stop(); notifyComplete(overallTimer.getTime()); } }; return out; }
From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserExporterImpl.java
@Override public void exportUser(Contact contact, Map<String, Serializable> contactExpandoAttributes) throws Exception { long companyId = contact.getCompanyId(); StopWatch stopWatch = new StopWatch(); if (_log.isDebugEnabled()) { stopWatch.start(); _log.debug("Exporting contact " + contact); }/* w w w .j av a 2s.com*/ if (!_ldapSettings.isExportEnabled(companyId)) { return; } User user = _userLocalService.getUserByContactId(contact.getContactId()); if (user.isDefaultUser() || (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) { return; } long ldapServerId = _portalLDAP.getLdapServerId(companyId, user.getScreenName(), user.getEmailAddress()); LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId); try { if (ldapContext == null) { return; } Properties contactMappings = _ldapSettings.getContactMappings(ldapServerId, companyId); Properties contactExpandoMappings = _ldapSettings.getContactExpandoMappings(ldapServerId, companyId); Binding binding = _portalLDAP.getUser(ldapServerId, contact.getCompanyId(), user.getScreenName(), user.getEmailAddress()); if (binding == null) { Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId); binding = addUser(ldapServerId, ldapContext, user, userMappings); } Name name = new CompositeName(); name.add(binding.getNameInNamespace()); Modifications modifications = _portalToLDAPConverter.getLDAPContactModifications(contact, contactExpandoAttributes, contactMappings, contactExpandoMappings); if (modifications == null) { return; } ModificationItem[] modificationItems = modifications.getItems(); ldapContext.modifyAttributes(name, modificationItems); } finally { if (ldapContext != null) { ldapContext.close(); } if (_log.isDebugEnabled()) { _log.debug(StringBundler.concat("Finished exporting contact ", String.valueOf(contact), " in ", String.valueOf(stopWatch.getTime()), "ms")); } } }
From source file:com.liferay.portal.search.elasticsearch.internal.connection.EmbeddedElasticsearchConnection.java
@Override protected Client createClient() { StopWatch stopWatch = new StopWatch(); stopWatch.start(); if (_log.isWarnEnabled()) { StringBundler sb = new StringBundler(6); sb.append("Liferay is configured to use embedded Elasticsearch "); sb.append("as its search engine. Do NOT use embedded "); sb.append("Elasticsearch in production. Embedded Elasticsearch "); sb.append("is useful for development and demonstration purposes. "); sb.append("Remote Elasticsearch connections can be configured in "); sb.append("the Control Panel."); _log.warn(sb.toString());//from w w w .j a v a2 s .com } if (_log.isDebugEnabled()) { _log.debug("Starting embedded Elasticsearch cluster " + elasticsearchConfiguration.clusterName()); } _node = createNode(settingsBuilder.build()); _node.start(); Client client = _node.client(); if (_log.isDebugEnabled()) { stopWatch.stop(); _log.debug(StringBundler.concat("Finished starting ", elasticsearchConfiguration.clusterName(), " in ", String.valueOf(stopWatch.getTime()), " ms")); } return client; }
From source file:com.mothsoft.alexis.engine.predictive.OpenNLPMaxentModelExecutorTask.java
private boolean doExecute(final Model model) { final StopWatch stopWatch = new StopWatch(); stopWatch.start(); boolean result = false; try {/* ww w. jav a 2s. co m*/ logger.info(String.format("Executing model %d", model.getId())); // load model file final File userDirectory = new File(baseDirectory, "" + model.getUserId()); final File modelFile = new File(userDirectory, model.getId() + BIN_GZ_EXT); final AbstractModel maxentModel = new SuffixSensitiveGISModelReader(modelFile).getModel(); final Date now = new Date(); final TimeUnits timeUnits = model.getTimeUnits(); final Timestamp topOfPeriod = new Timestamp(TimeUnits.floor(now, timeUnits).getTime()); final Timestamp endOfPeriod = new Timestamp(topOfPeriod.getTime() + timeUnits.getDuration() - 1); // first position: sum of changes predicted, second position: number // of samples--will calculate a boring old mean... final double[][] changeByPeriod = new double[model.getLookahead()][2]; // initialize for (int i = 0; i < changeByPeriod.length; i++) { changeByPeriod[i][0] = 0.0d; changeByPeriod[i][1] = 0.0d; } // find the most recent point value // FIXME - some sparse data sets may require executing the model on // all documents since that point or applying some sort of // dead-reckoning logic for smoothing final DataSetPoint initial = this.dataSetPointDao.findLastPointBefore(model.getTrainingDataSet(), endOfPeriod); // let's get the corner cases out of the way if (initial == null) { logger.warn("Insufficient data to execute model!"); return false; } // happy path // build consolidated context of events in this period // find current value of training data set for this period final double[] probs = eval(model, topOfPeriod, endOfPeriod, maxentModel); // predict from the last available point, adjusted for time // remaining in period final double y0 = initial.getY(); // map outcomes to periods in the future (at least no earlier than // this period) for (int i = 0; i < probs.length; i++) { // in the form +nU:+/-x, where n is the number of periods, U is // the unit type for the period, +/- is the direction, and x is // a discrete value from Model.OUTCOME_ARRAY final String outcome = maxentModel.getOutcome(i); final Matcher matcher = OUTCOME_PATTERN.matcher(outcome); if (!matcher.matches()) { logger.warn("Can't process outcome: " + outcome + "; skipping"); continue; } final int period = Integer.valueOf(matcher.group(1)); final String units = matcher.group(2); final double percentChange = Double.valueOf(matcher.group(3)); // record the observation and the count of observations changeByPeriod[period][0] += percentChange; changeByPeriod[period][1] += 1.0d; if (logger.isDebugEnabled()) { final double yi = y0 * (1 + percentChange); logger.debug(String.format("Outcome: %s, %s: +%d, change: %f, new value: %f, probability: %f", outcome, units, period, percentChange, yi, probs[i])); } } // build points for predictive data set double yn = y0; // we need to track the points and remove any that were not // predicted by this execution of the model final Timestamp endOfPredictionRange = new Timestamp( topOfPeriod.getTime() + (changeByPeriod.length * timeUnits.getDuration())); final List<DataSetPoint> existingPoints = this.dataSetPointDao .findByTimeRange(model.getPredictionDataSet(), topOfPeriod, endOfPredictionRange); for (int period = 0; period < changeByPeriod.length; period++) { final double totalPercentChange = changeByPeriod[period][0]; final double sampleCount = changeByPeriod[period][1]; double percentChange; if (totalPercentChange == 0.0d || sampleCount == 0.0d) { percentChange = 0.0d; } else { percentChange = totalPercentChange / sampleCount; } // apply adjustments only if the initial point is within the // time period, and only for the first time period boolean applyAdjustment = period == 0 && topOfPeriod.before(initial.getX()); if (applyAdjustment) { final double adjustmentFactor = findAdjustmentFactor(initial.getX(), timeUnits); percentChange = (totalPercentChange / sampleCount) * adjustmentFactor; } // figure out the next value and coerce to a sane number of // decimal places (2); final double newValue = (double) Math.round(yn * (1.0d + percentChange) * 100) / 100; final Timestamp timestamp = new Timestamp( topOfPeriod.getTime() + (period * timeUnits.getDuration())); if (logger.isDebugEnabled()) { logger.debug(String.format("Model %d for data set %d predicted point: (%s, %f)", model.getId(), model.getTrainingDataSet().getId(), DateFormat.getInstance().format(timestamp), newValue)); } DataSetPoint ithPoint = this.dataSetPointDao.findByTimestamp(model.getPredictionDataSet(), timestamp); // conditionally create if (ithPoint == null) { ithPoint = new DataSetPoint(model.getPredictionDataSet(), timestamp, newValue); this.dataSetPointDao.add(ithPoint); } else { // or update ithPoint.setY(newValue); // updated points retained, other existing removed existingPoints.remove(ithPoint); } // store current and use as starting point for next iteration yn = newValue; } // remove stale points from an old model execution for (final DataSetPoint toRemove : existingPoints) { this.dataSetPointDao.remove(toRemove); } result = true; } catch (final Exception e) { logger.warn("Model " + model.getId() + " failed with: " + e, e); result = false; } finally { stopWatch.stop(); logger.info(String.format("Executing model %d took %s", model.getId(), stopWatch.toString())); } return result; }
From source file:net.craigstars.game.services.GameControllerImpl.java
/** * Put a game in the Game Cache To improve speeds we cache all the games as they are loaded from * the database. We have to load all the game planets/fleets/etc from the DB now because the * session will be gone after this request. * // w w w . j av a 2 s .c om * @param game The game to put in the cache */ private void putInCache(Game game) { StopWatch timer = new StopWatch(); timer.start(); // init planets for (Planet planet : game.getPlanets()) { planet.getOwner(); planet.getOrbitingFleets().size(); planet.getQueue().getItems().size(); } // init fleets for (Fleet fleet : game.getFleets()) { fleet.getOwner(); fleet.getShipStacks().size(); for (Waypoint wp : fleet.getWaypoints()) { if (wp.getTarget() != null) { wp.getTarget().getName(); } } } // init players for (Player player : game.getPlayers().values()) { // init the planet knowledges for (PlanetKnowledge knowledge : player.getPlanetKnowledges().values()) { knowledge.getOwner(); } // init the fleet knowledges player.getFleetKnowledges().size(); // init the race hab widths if (player.getRace() != null) player.getRace().init(); // init the homeworld if (player.getHomeworld() != null) player.getHomeworld().getQueue().getItems().size(); // init the ship designs with the tech store for (ShipDesign design : player.getDesigns()) { techStore.initShipDesign(design); } // init the player techs player.getTechs().init(player, techStore); // init the messages for the player player.getMessages().size(); } // put the game in the cache gameCache.put(new Element(game.getId(), game)); log.info("Put game {}({}) in cache, took {} ms", new Object[] { game.getName(), game.getId(), timer.getTime() }); }
From source file:de.griffel.confluence.plugins.plantuml.PlantUmlMacro.java
protected final String executeInternal(Map<String, String> params, final String body, final RenderContext renderContext) throws MacroException, IOException, UnauthorizedDownloadResourceException, DownloadResourceNotFoundException { final StopWatch stopWatch = new StopWatch(); stopWatch.start(); final PlantUmlMacroParams macroParams = new PlantUmlMacroParams(params); if (!(renderContext instanceof PageContext)) { throw new MacroException("This macro can only be used in Confluence pages. (ctx=" + renderContext.getClass().getName() + ")"); }//from w ww . ja v a 2 s .c o m final PageContext pageContext = (PageContext) renderContext; final UmlSourceLocator umlSourceLocator = new UmlSourceLocatorConfluence(pageContext); final PreprocessingContext preprocessingContext = new MyPreprocessingContext(pageContext); final DiagramType diagramType = macroParams.getDiagramType(); final boolean dropShadow = macroParams.getDropShadow(); final boolean separation = macroParams.getSeparation(); final PlantUmlConfiguration configuration = configurationManager.load(); final UmlSourceBuilder builder = new UmlSourceBuilder(diagramType, dropShadow, separation, configuration) .append(new StringReader(body)); final PlantUmlPreprocessor preprocessor = new PlantUmlPreprocessor(builder.build(), umlSourceLocator, preprocessingContext); final String umlBlock = preprocessor.toUmlBlock(); final String result = render(umlBlock, pageContext, macroParams, preprocessor); stopWatch.stop(); logger.info(String.format("Rendering %s diagram on page %s:%s took %d ms.", diagramType, pageContext.getSpaceKey(), pageContext.getPageTitle(), stopWatch.getTime())); return result; }
From source file:com.liferay.portal.jsonwebservice.JSONWebServiceConfigurator.java
private void _configure(File... classPathFiles) throws PortalException { StopWatch stopWatch = null; if (_log.isDebugEnabled()) { _log.debug("Configure JSON web service actions"); stopWatch = new StopWatch(); stopWatch.start(); }//w ww . ja va2 s . com try { scanPaths(classPathFiles); } catch (Exception e) { throw new PortalException(e.getMessage(), e); } if (_log.isDebugEnabled()) { _log.debug("Configured " + _registeredActionsCount + " actions in " + stopWatch.getTime() + " ms"); } }
From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserExporterImpl.java
@Override public void exportUser(long userId, long userGroupId, UserOperation userOperation) throws Exception { User user = _userLocalService.getUser(userId); long companyId = user.getCompanyId(); StopWatch stopWatch = new StopWatch(); if (_log.isDebugEnabled()) { stopWatch.start(); _log.debug(StringBundler.concat("Exporting user ", String.valueOf(user), " in user group ", String.valueOf(userGroupId))); }// ww w. ja v a 2s . c o m if (!_ldapSettings.isExportEnabled(companyId) || !_ldapSettings.isExportGroupEnabled(companyId)) { return; } long ldapServerId = _portalLDAP.getLdapServerId(companyId, user.getScreenName(), user.getEmailAddress()); LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId); if (ldapContext == null) { return; } UserGroup userGroup = _userGroupLocalService.getUserGroup(userGroupId); Properties groupMappings = _ldapSettings.getGroupMappings(ldapServerId, companyId); Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId); Binding binding = _portalLDAP.getGroup(ldapServerId, companyId, userGroup.getName()); if (binding == null) { if (userOperation == UserOperation.ADD) { addGroup(ldapServerId, ldapContext, userGroup, user, groupMappings, userMappings); } else { if (_log.isWarnEnabled()) { _log.warn("Unable to get or add LDAP bindings for user group " + userGroup.getName()); } } return; } try { Name name = new CompositeName(); name.add(binding.getNameInNamespace()); Modifications modifications = _portalToLDAPConverter.getLDAPGroupModifications(ldapServerId, userGroup, user, groupMappings, userMappings, userOperation); ModificationItem[] modificationItems = modifications.getItems(); ldapContext.modifyAttributes(name, modificationItems); } catch (SchemaViolationException sve) { if (_log.isInfoEnabled()) { _log.info("Unable to update LDAP bindings for user group " + userGroup.getName(), sve); } String fullGroupDN = binding.getNameInNamespace(); Attributes attributes = _portalLDAP.getGroupAttributes(ldapServerId, companyId, ldapContext, fullGroupDN, true); Attribute groupMembers = attributes.get(groupMappings.getProperty(GroupConverterKeys.USER)); if ((groupMembers != null) && (groupMembers.size() == 1)) { ldapContext.unbind(fullGroupDN); } } finally { if (ldapContext != null) { ldapContext.close(); } if (_log.isDebugEnabled()) { _log.debug(StringBundler.concat("Finished exporting user ", String.valueOf(user), " in user group ", String.valueOf(userGroupId), " in ", String.valueOf(stopWatch.getTime()), "ms")); } } }
From source file:com.liferay.portal.search.solr.internal.SolrIndexSearcher.java
public long searchCount(SearchContext searchContext, Query query) throws SearchException { StopWatch stopWatch = new StopWatch(); stopWatch.start(); try {//from w w w .ja v a2s. com return doSearchCount(searchContext, query); } catch (Exception e) { if (_log.isWarnEnabled()) { _log.warn(e, e); } if (!_swallowException) { throw new SearchException(e.getMessage(), e); } return 0; } finally { if (_log.isInfoEnabled()) { stopWatch.stop(); _log.info("Searching " + query.toString() + " took " + stopWatch.getTime() + " ms"); } } }
From source file:com.liferay.portal.search.solr.internal.SolrIndexSearcher.java
@Override public Hits search(SearchContext searchContext, Query query) throws SearchException { StopWatch stopWatch = new StopWatch(); stopWatch.start(); try {/*from ww w . j av a 2s . c o m*/ int total = (int) searchCount(searchContext, query); int start = searchContext.getStart(); int end = searchContext.getEnd(); if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS)) { start = 0; end = total; } int[] startAndEnd = SearchPaginationUtil.calculateStartAndEnd(start, end, total); start = startAndEnd[0]; end = startAndEnd[1]; Hits hits = doSearchHits(searchContext, query, start, end); hits.setStart(stopWatch.getStartTime()); return hits; } catch (Exception e) { if (_log.isWarnEnabled()) { _log.warn(e, e); } if (!_swallowException) { throw new SearchException(e.getMessage(), e); } return new HitsImpl(); } finally { if (_log.isInfoEnabled()) { stopWatch.stop(); _log.info("Searching " + query.toString() + " took " + stopWatch.getTime() + " ms"); } } }