List of usage examples for org.apache.commons.lang.time StopWatch StopWatch
public StopWatch()
Constructor.
From source file:com.yahoo.flowetl.core.Plumber.java
/** * Translates a set of roots into a runnable object. * //from w w w .j av a2s .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:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java
/** * Runs the tests without applying any changes. This method is used to check * if the driver works correctly./* www . ja v a 2s .c o m*/ */ private void runNormalTests() { logger.info("Running tests of project " + configuration.getProjectPrefix()); // addMutationTestListener(new AdabuListener()); addListenersFromProperty(); List<String> allTests = getAllTests(); int counter = 0; int size = allTests.size(); timeout = Integer.MAX_VALUE; boolean allPass = true; List<SingleTestResult> failing = new ArrayList<SingleTestResult>(); testsStart(); StopWatch stopWatch = new StopWatch(); stopWatch.start(); coldRun(allTests); for (String testName : allTests) { counter++; logger.info(DurationFormatUtils.formatDurationHMS(stopWatch.getTime()) + " (" + counter + " / " + size + ") Running test: " + testName); MutationTestRunnable runnable = getTestRunnable(testName); testStart(testName); stopWatch.reset(); stopWatch.start(); runWithTimeout(runnable); SingleTestResult result = runnable.getResult(); logger.info("Test took " + DurationFormatUtils.formatDurationHMS(stopWatch.getTime()) + " " + testName); if (!result.hasPassed()) { allPass = false; failing.add(result); logger.warn("Test has not passed " + result.getTestMessage()); } testEnd(testName); } testsEnd(); if (allPass) { String message = "All " + allTests.size() + " tests passed "; System.out.println(message); logger.info(message); } else { logger.warn("Not all tests passed"); for (SingleTestResult str : failing) { logger.warn(str.getTestMessage().getTestCaseName() + ": " + str.getTestMessage()); } File outFile = new File(configuration.getOutputDir(), "/failed-tests.xml"); XmlIo.toXML(failing, outFile); } }
From source file:com.liferay.portal.lar.PlaytechLayoutExporter.java
protected File doExportLayoutsAsFile(long groupId, boolean privateLayout, long[] layoutIds, Map<String, String[]> parameterMap, Date startDate, Date endDate) throws Exception { boolean exportCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES); boolean exportIgnoreLastPublishDate = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE); boolean exportPermissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS); boolean exportUserPermissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.USER_PERMISSIONS); boolean exportPortletArchivedSetups = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS); boolean exportPortletUserPreferences = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES); boolean exportTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME); boolean exportThemeSettings = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE); boolean exportLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO); boolean exportLayoutSetSettings = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS); //boolean publishToRemote = MapUtil.getBoolean( // parameterMap, PortletDataHandlerKeys.PUBLISH_TO_REMOTE); boolean updateLastPublishDate = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE); if (_log.isDebugEnabled()) { _log.debug("Export categories " + exportCategories); _log.debug("Export permissions " + exportPermissions); _log.debug("Export user permissions " + exportUserPermissions); _log.debug("Export portlet archived setups " + exportPortletArchivedSetups); _log.debug("Export portlet user preferences " + exportPortletUserPreferences); _log.debug("Export theme " + exportTheme); }//from w w w . j a va2 s . c o m LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout); long companyId = layoutSet.getCompanyId(); long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId); ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext(); if (serviceContext == null) { serviceContext = new ServiceContext(); serviceContext.setCompanyId(companyId); serviceContext.setSignedIn(false); serviceContext.setUserId(defaultUserId); ServiceContextThreadLocal.pushServiceContext(serviceContext); } serviceContext.setAttribute("exporting", Boolean.TRUE); long layoutSetBranchId = MapUtil.getLong(parameterMap, "layoutSetBranchId"); serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId); long lastPublishDate = System.currentTimeMillis(); if (endDate != null) { lastPublishDate = endDate.getTime(); } if (exportIgnoreLastPublishDate) { endDate = null; startDate = null; } StopWatch stopWatch = null; if (_log.isInfoEnabled()) { stopWatch = new StopWatch(); stopWatch.start(); } LayoutCache layoutCache = new LayoutCache(); ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter(); PortletDataContext portletDataContext = new PortletDataContextImpl(companyId, groupId, parameterMap, new HashSet<String>(), startDate, endDate, zipWriter); portletDataContext.setPortetDataContextListener(new PortletDataContextListenerImpl(portletDataContext)); Document document = SAXReaderUtil.createDocument(); Element rootElement = document.addElement("root"); Element headerElement = rootElement.addElement("header"); headerElement.addAttribute("available-locales", StringUtil.merge(LanguageUtil.getAvailableLocales())); headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber())); headerElement.addAttribute("export-date", Time.getRFC822()); if (portletDataContext.hasDateRange()) { headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate())); headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate())); } headerElement.addAttribute("group-id", String.valueOf(groupId)); headerElement.addAttribute("private-layout", String.valueOf(privateLayout)); Group group = layoutSet.getGroup(); String type = "layout-set"; if (group.isLayoutPrototype()) { type = "layout-prototype"; LayoutPrototype layoutPrototype = LayoutPrototypeLocalServiceUtil .getLayoutPrototype(group.getClassPK()); headerElement.addAttribute("type-uuid", layoutPrototype.getUuid()); } else if (group.isLayoutSetPrototype()) { type = "layout-set-prototype"; LayoutSetPrototype layoutSetPrototype = LayoutSetPrototypeLocalServiceUtil .getLayoutSetPrototype(group.getClassPK()); headerElement.addAttribute("type-uuid", layoutSetPrototype.getUuid()); } headerElement.addAttribute("type", type); if (exportTheme || exportThemeSettings) { headerElement.addAttribute("theme-id", layoutSet.getThemeId()); headerElement.addAttribute("color-scheme-id", layoutSet.getColorSchemeId()); } if (exportLogo) { Image image = ImageLocalServiceUtil.getImage(layoutSet.getLogoId()); if ((image != null) && (image.getTextObj() != null)) { String logoPath = getLayoutSetLogoPath(portletDataContext); headerElement.addAttribute("logo-path", logoPath); portletDataContext.addZipEntry(logoPath, image.getTextObj()); } } if (exportLayoutSetSettings) { Element settingsElement = headerElement.addElement("settings"); settingsElement.addCDATA(layoutSet.getSettings()); } Element cssElement = headerElement.addElement("css"); cssElement.addCDATA(layoutSet.getCss()); Portlet layoutConfigurationPortlet = PortletLocalServiceUtil .getPortletById(portletDataContext.getCompanyId(), PortletKeys.LAYOUT_CONFIGURATION); Map<String, Object[]> portletIds = new LinkedHashMap<>(); List<Layout> layouts = null; if ((layoutIds == null) || (layoutIds.length == 0)) { String scope = MapUtil.getString(parameterMap, "scope"); if ("no-pages".equals(scope) || "selected-pages".equals(scope)) { layouts = Arrays.asList(); } else { layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout); } } else { layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout, layoutIds); } List<Portlet> portlets = getAlwaysExportablePortlets(companyId); long plid = LayoutConstants.DEFAULT_PLID; if (!layouts.isEmpty()) { Layout firstLayout = layouts.get(0); plid = firstLayout.getPlid(); } if (group.isStagingGroup()) { group = group.getLiveGroup(); } for (Portlet portlet : portlets) { String portletId = portlet.getRootPortletId(); _log.debug("Exporting portlet " + portletId); if (!group.isStagedPortlet(portletId)) { continue; } String key = PortletPermissionUtil.getPrimaryKey(0, portletId); if (portletIds.get(key) == null) { portletIds.put(key, new Object[] { portletId, plid, groupId, StringPool.BLANK, StringPool.BLANK }); } } Element layoutsElement = rootElement.addElement("layouts"); long processedItems = 0; StagingProgressUpdaterThreadLocal.getMonitor().getComponent(PublishProcessProgressMonitor.COMPONENT_LAYOUTS) .setItemsCount(layouts.size()); String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid(); if (Validator.isNotNull(layoutSetPrototypeUuid)) { LayoutSetPrototype layoutSetPrototype = LayoutSetPrototypeLocalServiceUtil .getLayoutSetPrototypeByUuid(layoutSetPrototypeUuid); layoutsElement.addAttribute("layout-set-prototype-uuid", layoutSetPrototypeUuid); layoutsElement.addAttribute("layout-set-prototype-name", layoutSetPrototype.getName(LocaleUtil.getDefault())); } for (Layout layout : layouts) { StagingProgressUpdaterThreadLocal.getMonitor() .getComponent(PublishProcessProgressMonitor.COMPONENT_LAYOUTS) .setItemsProcessed(processedItems++); exportLayout(portletDataContext, layoutConfigurationPortlet, layoutCache, portlets, portletIds, exportPermissions, exportUserPermissions, layout, layoutsElement); } if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM < 5) { Element rolesElement = rootElement.addElement("roles"); if (exportPermissions) { _permissionExporter.exportLayoutRoles(layoutCache, companyId, groupId, rolesElement); } } long previousScopeGroupId = portletDataContext.getScopeGroupId(); Element portletsElement = rootElement.addElement("portlets"); StagingProgressUpdaterThreadLocal.getMonitor() .getComponent(PublishProcessProgressMonitor.COMPONENT_PORTLETS).setItemsCount(portletIds.size()); processedItems = 0; for (Map.Entry<String, Object[]> portletIdsEntry : portletIds.entrySet()) { StagingProgressUpdaterThreadLocal.getMonitor() .getComponent(PublishProcessProgressMonitor.COMPONENT_PORTLETS) .setItemsProcessed(processedItems++); Object[] portletObjects = portletIdsEntry.getValue(); String portletId = null; plid = LayoutConstants.DEFAULT_PLID; long scopeGroupId = 0; String scopeType = StringPool.BLANK; String scopeLayoutUuid = null; if (portletObjects.length == 4) { portletId = (String) portletIdsEntry.getValue()[0]; plid = (Long) portletIdsEntry.getValue()[1]; scopeGroupId = (Long) portletIdsEntry.getValue()[2]; scopeLayoutUuid = (String) portletIdsEntry.getValue()[3]; } else { portletId = (String) portletIdsEntry.getValue()[0]; plid = (Long) portletIdsEntry.getValue()[1]; scopeGroupId = (Long) portletIdsEntry.getValue()[2]; scopeType = (String) portletIdsEntry.getValue()[3]; scopeLayoutUuid = (String) portletIdsEntry.getValue()[4]; } Layout layout = LayoutLocalServiceUtil.fetchLayout(plid); if (layout == null) { if (!group.isCompany() && (plid < LayoutConstants.DEFAULT_PLID)) { continue; } if (_log.isWarnEnabled()) { _log.warn("Assuming global scope because no layout was found"); } layout = new LayoutImpl(); layout.setGroupId(groupId); layout.setCompanyId(companyId); } portletDataContext.setPlid(plid); portletDataContext.setOldPlid(plid); portletDataContext.setScopeGroupId(scopeGroupId); portletDataContext.setScopeType(scopeType); portletDataContext.setScopeLayoutUuid(scopeLayoutUuid); boolean[] exportPortletControls = getExportPortletControls(companyId, portletId, portletDataContext, parameterMap); _portletExporter.exportPortlet(portletDataContext, layoutCache, portletId, layout, portletsElement, defaultUserId, exportPermissions, exportPortletArchivedSetups, exportPortletControls[0], exportPortletControls[1], exportPortletUserPreferences, exportUserPermissions); } portletDataContext.setScopeGroupId(previousScopeGroupId); if (exportCategories || group.isCompany()) { exportAssetCategories(portletDataContext); } _portletExporter.exportAssetLinks(portletDataContext); _portletExporter.exportAssetTags(portletDataContext); _portletExporter.exportComments(portletDataContext); _portletExporter.exportExpandoTables(portletDataContext); _portletExporter.exportLocks(portletDataContext); if (exportPermissions) { _permissionExporter.exportPortletDataPermissions(portletDataContext); } _portletExporter.exportRatingsEntries(portletDataContext, rootElement); if (exportTheme && !portletDataContext.isPerformDirectBinaryImport()) { exportTheme(layoutSet, zipWriter); } if (_log.isInfoEnabled()) { if (stopWatch != null) { _log.info("Exporting layouts takes " + stopWatch.getTime() + " ms"); } else { _log.info("Exporting layouts is finished"); } } portletDataContext.addZipEntry("/manifest.xml", document.formattedString()); try { return zipWriter.getFile(); } finally { if (updateLastPublishDate) { updateLastPublishDate(layoutSet, lastPublishDate); } } }
From source file:eagle.service.generic.GenericEntityServiceResource.java
@PUT @Consumes({ MediaType.MULTIPART_FORM_DATA }) @Produces(MediaType.APPLICATION_JSON)//from w w w. j a v a2 s.co m public GenericServiceAPIResponseEntity update(@FormDataParam("file") InputStream fileInputStream, @FormDataParam("file") FormDataContentDisposition cdh, @QueryParam("serviceName") String serviceName) { GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<String>(); DataStorage dataStorage; Map<String, Object> meta = new HashMap<>(); StopWatch stopWatch = new StopWatch(); try { stopWatch.start(); EntityDefinition entityDefinition = EntityDefinitionManager.getEntityByServiceName(serviceName); if (entityDefinition == null) { throw new IllegalArgumentException("entity definition of service " + serviceName + " not found"); } List<? extends TaggedLogAPIEntity> entities = unmarshalEntitiesByServie(fileInputStream, entityDefinition); dataStorage = DataStorageManager.getDataStorageByEagleConfig(); UpdateStatement updateStatement = new UpdateStatement(entities, entityDefinition); ModifyResult<String> result = updateStatement.execute(dataStorage); if (result.isSuccess()) { List<String> keys = result.getIdentifiers(); if (keys != null) { response.setObj(keys, String.class); meta.put(TOTAL_RESULTS, keys.size()); } else { meta.put(TOTAL_RESULTS, 0); } meta.put(ELAPSEDMS, stopWatch.getTime()); response.setMeta(meta); response.setSuccess(true); } } catch (Exception e) { LOG.error(e.getMessage(), e); response.setException(e); } finally { stopWatch.stop(); } return response; }
From source file:com.redhat.rhn.frontend.action.LoginHelper.java
/** * @param orgIn//from ww w . j ava 2 s .c o m */ private static void publishUpdateErrataCacheEvent(Org orgIn) { StopWatch sw = new StopWatch(); if (log.isDebugEnabled()) { log.debug("Updating errata cache"); sw.start(); } UpdateErrataCacheEvent uece = new UpdateErrataCacheEvent(UpdateErrataCacheEvent.TYPE_ORG); uece.setOrgId(orgIn.getId()); MessageQueue.publish(uece); if (log.isDebugEnabled()) { sw.stop(); log.debug("Finished Updating errata cache. Took [" + sw.getTime() + "]"); } }
From source file:net.craigstars.game.services.GameControllerImpl.java
/** * Generate a new turn for a game./*from ww w . ja v a 2s . co m*/ * * @param gameId The id of the game to generate a turn for */ public void generateTurn(Game game) { StopWatch timer = new StopWatch(); timer.start(); // merge the game from the cache with the session game = dao.getGameDao().merge(game); log.info("Merged turn {}, {}ms", game.getYear(), timer.getTime()); // set our status to generating a turn and put it back in the cache game.setStatus(GameStatus.GeneratingTurn); putInCache(game); // generate the turn TurnGenerator tg = new TurnGenerator(game, fleetController, planetController); tg.generate(); timer.reset(); timer.start(); game = dao.getGameDao().save(game); log.info("Save game {}, {} ms", game.getYear(), timer.getTime()); putInCache(game); }
From source file:eagle.service.generic.ListQueryResource.java
/** * <b>TODO</b> remove the legacy deprecated implementation of listQueryWithoutCoprocessor * * @see #listQuery(String, String, String, int, String, boolean, boolean, long, int, boolean, int, String,Boolean) * * @param query/*from w w w . j a v a2s .c o m*/ * @param startTime * @param endTime * @param pageSize * @param startRowkey * @param treeAgg * @param timeSeries * @param intervalmin * @return */ @GET @Path("/legacy") @Produces({ MediaType.APPLICATION_JSON }) @Deprecated public ListQueryAPIResponseEntity listQueryWithoutCoprocessor(@QueryParam("query") String query, @QueryParam("startTime") String startTime, @QueryParam("endTime") String endTime, @QueryParam("pageSize") int pageSize, @QueryParam("startRowkey") String startRowkey, @QueryParam("treeAgg") boolean treeAgg, @QueryParam("timeSeries") boolean timeSeries, @QueryParam("intervalmin") long intervalmin, @QueryParam("top") int top, @QueryParam("filterIfMissing") boolean filterIfMissing, @QueryParam("parallel") int parallel, @QueryParam("metricName") String metricName, @QueryParam("verbose") Boolean verbose) { StopWatch watch = new StopWatch(); watch.start(); ListQueryAPIResponseEntity result = new ListQueryAPIResponseEntity(); try { validateQueryParameters(startRowkey, pageSize); ListQueryCompiler comp = new ListQueryCompiler(query, filterIfMissing); String serviceName = comp.serviceName(); SearchCondition condition = new SearchCondition(); condition.setFilter(comp.filter()); condition.setQueryExpression(comp.getQueryExpression()); if (comp.sortOptions() == null && top > 0) { LOG.warn( "Parameter \"top\" is only used for sort query! Ignore top parameter this time since it's not a sort query"); } // TODO: For now we don't support one query to query multiple partitions. In future // if partition is defined for the entity, internally We need to spawn multiple // queries and send one query for each search condition for each partition final List<String[]> partitionValues = comp.getQueryPartitionValues(); if (partitionValues != null) { condition.setPartitionValues(Arrays.asList(partitionValues.get(0))); } EntityDefinition ed = EntityDefinitionManager.getEntityByServiceName(serviceName); if (ed.isTimeSeries()) { // TODO check timestamp exists for timeseries or topology data condition.setStartTime(startTime); condition.setEndTime(endTime); } condition.setOutputVerbose(verbose == null || verbose); condition.setOutputAlias(comp.getOutputAlias()); condition.setOutputAll(comp.isOutputAll()); condition.setStartRowkey(startRowkey); condition.setPageSize(pageSize); List<String> outputFields = comp.outputFields(); if (outputFields == null) outputFields = new ArrayList<String>(); /** * TODO ugly logic, waiting for refactoring */ if (!comp.hasAgg() && !serviceName.equals(GenericMetricEntity.GENERIC_METRIC_SERVICE)) { // pure list query // List<String> outputFields = comp.outputFields(); Set<String> filterFields = comp.getFilterFields(); if (filterFields != null) outputFields.addAll(filterFields); condition.setOutputFields(outputFields); if (condition.isOutputAll()) { LOG.info("Output: ALL"); } else { LOG.info("Output: " + StringUtils.join(condition.getOutputFields(), ", ")); } GenericEntityBatchReader reader = new GenericEntityBatchReader(serviceName, condition); List<? extends TaggedLogAPIEntity> entityList = reader.read(); result.setObj(entityList); result.setTotalResults(entityList.size()); result.setSuccess(true); result.setLastTimestamp(reader.getLastTimestamp()); result.setFirstTimestamp(reader.getFirstTimestamp()); } else if (!comp.hasAgg() && serviceName.equals(GenericMetricEntity.GENERIC_METRIC_SERVICE)) { // validate metric name if (metricName == null || metricName.isEmpty()) { throw new IllegalArgumentException("metricName should not be empty for metric list query"); } // List<String> outputFields = comp.outputFields(); Set<String> filterFields = comp.getFilterFields(); if (filterFields != null) outputFields.addAll(filterFields); condition.setOutputFields(outputFields); if (condition.isOutputAll()) { LOG.info("Output: ALL"); } else { LOG.info("Output: " + StringUtils.join(condition.getOutputFields(), ", ")); } GenericMetricEntityBatchReader reader = new GenericMetricEntityBatchReader(metricName, condition); List<? extends TaggedLogAPIEntity> entityList = reader.read(); result.setObj(entityList); result.setTotalResults(entityList.size()); result.setSuccess(true); result.setLastTimestamp(reader.getLastTimestamp()); result.setFirstTimestamp(reader.getFirstTimestamp()); } else if (!treeAgg && !timeSeries && parallel <= 0) { // non time-series based aggregate query, not hierarchical List<String> groupbyFields = comp.groupbyFields(); List<String> aggregateFields = comp.aggregateFields(); Set<String> filterFields = comp.getFilterFields(); // List<String> outputFields = new ArrayList<String>(); if (groupbyFields != null) outputFields.addAll(groupbyFields); if (filterFields != null) outputFields.addAll(filterFields); outputFields.addAll(aggregateFields); if (GenericMetricEntity.GENERIC_METRIC_SERVICE.equals(serviceName) && !outputFields.contains(GenericMetricEntity.VALUE_FIELD)) { outputFields.add(GenericMetricEntity.VALUE_FIELD); } FlatAggregator agg = new FlatAggregator(groupbyFields, comp.aggregateFunctionTypes(), comp.aggregateFields()); StreamReader reader = null; if (ed.getMetricDefinition() == null) { reader = new GenericEntityStreamReader(serviceName, condition); } else { // metric aggregation need metric reader reader = new GenericMetricEntityDecompactionStreamReader(metricName, condition); } condition.setOutputFields(outputFields); if (condition.isOutputAll()) { LOG.info("Output: ALL"); } else { LOG.info("Output: " + StringUtils.join(condition.getOutputFields(), ", ")); } reader.register(agg); reader.readAsStream(); ArrayList<Map.Entry<List<String>, List<Double>>> obj = new ArrayList<Map.Entry<List<String>, List<Double>>>(); obj.addAll(agg.result().entrySet()); if (comp.sortOptions() == null) { result.setObj(obj); } else { // has sort options result.setObj(PostFlatAggregateSort.sort(agg.result(), comp.sortOptions(), top)); } result.setTotalResults(0); result.setSuccess(true); result.setLastTimestamp(reader.getLastTimestamp()); result.setFirstTimestamp(reader.getFirstTimestamp()); } else if (!treeAgg && !timeSeries && parallel > 0) { // TODO ugly branch, let us refactor List<String> groupbyFields = comp.groupbyFields(); List<String> aggregateFields = comp.aggregateFields(); Set<String> filterFields = comp.getFilterFields(); // List<String> outputFields = new ArrayList<String>(); if (groupbyFields != null) outputFields.addAll(groupbyFields); if (filterFields != null) outputFields.addAll(filterFields); outputFields.addAll(aggregateFields); if (GenericMetricEntity.GENERIC_METRIC_SERVICE.equals(serviceName) && !outputFields.contains(GenericMetricEntity.VALUE_FIELD)) { outputFields.add(GenericMetricEntity.VALUE_FIELD); } condition.setOutputFields(outputFields); if (condition.isOutputAll()) { LOG.info("Output: ALL"); } else { LOG.info("Output: " + StringUtils.join(condition.getOutputFields(), ", ")); } FlatAggregator agg = new FlatAggregator(groupbyFields, comp.aggregateFunctionTypes(), comp.aggregateFields()); EntityCreationListener listener = EntityCreationListenerFactory .synchronizedEntityCreationListener(agg); StreamReader reader = new GenericEntityStreamReaderMT(serviceName, condition, parallel); reader.register(listener); reader.readAsStream(); ArrayList<Map.Entry<List<String>, List<Double>>> obj = new ArrayList<Map.Entry<List<String>, List<Double>>>(); obj.addAll(agg.result().entrySet()); if (comp.sortOptions() == null) { result.setObj(obj); } else { // has sort options result.setObj(PostFlatAggregateSort.sort(agg.result(), comp.sortOptions(), top)); } result.setTotalResults(0); result.setSuccess(true); result.setLastTimestamp(reader.getLastTimestamp()); result.setFirstTimestamp(reader.getFirstTimestamp()); } else if (!treeAgg && timeSeries) { // time-series based aggregate query, not hierarchical List<String> groupbyFields = comp.groupbyFields(); List<String> sortFields = comp.sortFields(); List<String> aggregateFields = comp.aggregateFields(); Set<String> filterFields = comp.getFilterFields(); // List<String> outputFields = new ArrayList<String>(); if (groupbyFields != null) outputFields.addAll(groupbyFields); if (filterFields != null) outputFields.addAll(filterFields); if (sortFields != null) outputFields.addAll(sortFields); outputFields.addAll(aggregateFields); if (GenericMetricEntity.GENERIC_METRIC_SERVICE.equals(serviceName) && !outputFields.contains(GenericMetricEntity.VALUE_FIELD)) { outputFields.add(GenericMetricEntity.VALUE_FIELD); } StreamReader reader = null; if (ed.getMetricDefinition() == null) { if (parallel <= 0) { // TODO ugly quick win reader = new GenericEntityStreamReader(serviceName, condition); } else { reader = new GenericEntityStreamReaderMT(serviceName, condition, parallel); } } else { // metric aggregation need metric reader reader = new GenericMetricEntityDecompactionStreamReader(metricName, condition); if (!outputFields.contains(GenericMetricEntity.VALUE_FIELD)) { outputFields.add(GenericMetricEntity.VALUE_FIELD); } } condition.setOutputFields(outputFields); if (condition.isOutputAll()) { LOG.info("Output: ALL"); } else { LOG.info("Output: " + StringUtils.join(condition.getOutputFields(), ", ")); } TimeSeriesAggregator tsAgg = new TimeSeriesAggregator(groupbyFields, comp.aggregateFunctionTypes(), aggregateFields, DateTimeUtil.humanDateToDate(condition.getStartTime()).getTime(), DateTimeUtil.humanDateToDate(condition.getEndTime()).getTime(), intervalmin * 60 * 1000); if (parallel <= 0) { reader.register(tsAgg); } else { EntityCreationListener listener = EntityCreationListenerFactory .synchronizedEntityCreationListener(tsAgg); reader.register(listener); } // for sorting FlatAggregator sortAgg = null; if (comp.sortOptions() != null) { sortAgg = new FlatAggregator(groupbyFields, comp.sortFunctions(), comp.sortFields()); if (parallel <= 0) { reader.register(sortAgg); } else { EntityCreationListener listener = EntityCreationListenerFactory .synchronizedEntityCreationListener(sortAgg); reader.register(listener); } } reader.readAsStream(); ArrayList<Map.Entry<List<String>, List<double[]>>> obj = new ArrayList<Map.Entry<List<String>, List<double[]>>>(); obj.addAll(tsAgg.getMetric().entrySet()); if (comp.sortOptions() == null) { result.setObj(obj); } else { // has sort options result.setObj(TimeSeriesPostFlatAggregateSort.sort(sortAgg.result(), tsAgg.getMetric(), comp.sortOptions(), top)); } result.setTotalResults(0); result.setSuccess(true); result.setLastTimestamp(reader.getLastTimestamp()); result.setFirstTimestamp(reader.getFirstTimestamp()); } else { // use hierarchical aggregate mode List<String> groupbyFields = comp.groupbyFields(); List<String> aggregateFields = comp.aggregateFields(); Set<String> filterFields = comp.getFilterFields(); // List<String> outputFields = new ArrayList<String>(); if (groupbyFields != null) outputFields.addAll(groupbyFields); if (filterFields != null) outputFields.addAll(filterFields); outputFields.addAll(aggregateFields); if (GenericMetricEntity.GENERIC_METRIC_SERVICE.equals(serviceName) && !outputFields.contains(GenericMetricEntity.VALUE_FIELD)) { outputFields.add(GenericMetricEntity.VALUE_FIELD); } condition.setOutputFields(outputFields); if (condition.isOutputAll()) { LOG.info("Output: ALL"); } else { LOG.info("Output: " + StringUtils.join(condition.getOutputFields(), ", ")); } GenericEntityStreamReader reader = new GenericEntityStreamReader(serviceName, condition); HierarchicalAggregator agg = new HierarchicalAggregator(groupbyFields, comp.aggregateFunctionTypes(), comp.aggregateFields()); reader.register(agg); reader.readAsStream(); if (comp.sortOptions() == null) { result.setObj(agg.result()); } else { // has sort options result.setObj(PostHierarchicalAggregateSort.sort(agg.result(), comp.sortOptions())); } result.setTotalResults(0); result.setSuccess(true); result.setLastTimestamp(reader.getLastTimestamp()); result.setFirstTimestamp(reader.getFirstTimestamp()); } } catch (Exception ex) { LOG.error("Fail executing list query: " + query, ex); result.setException(EagleExceptionWrapper.wrap(ex)); result.setSuccess(false); return result; } finally { watch.stop(); result.setElapsedms(watch.getTime()); } LOG.info("Query done " + watch.getTime() + " ms"); return result; }
From source file:com.microsoft.exchange.integration.AbstractIntegrationTest.java
/** * Create 3 {@link CalendarItemType}s and submit with 1 {@link ExchangeWebServicesClient#createItem(CreateItem)} invocation. */// w w w. j av a2 s.com @Test public void testCreate3CalendarItems() { NonEmptyArrayOfBaseItemIdsType createdIds = new NonEmptyArrayOfBaseItemIdsType(); try { initializeCredentials(); CalendarItemType item1 = constructCalendarItem(DateHelp.parseDateTimePhrase("20121109-1300"), DateHelp.parseDateTimePhrase("20121109-1400"), "integration test: testCreate3CalendarItems, item1", "test location", "test ran at " + new Date()); CalendarItemType item2 = constructCalendarItem(DateHelp.parseDateTimePhrase("20121109-1400"), DateHelp.parseDateTimePhrase("20121109-1500"), "integration test: testCreate3CalendarItems, item2", "test location", "test ran at " + new Date()); CalendarItemType item3 = constructCalendarItem(DateHelp.parseDateTimePhrase("20121109-1500"), DateHelp.parseDateTimePhrase("20121109-1600"), "integration test: testCreate3CalendarItems, item3", "test location", "test ran at " + new Date()); CreateItem request = new CreateItem(); request.setSendMeetingInvitations(CalendarItemCreateOrDeleteOperationType.SEND_TO_ALL_AND_SAVE_COPY); NonEmptyArrayOfAllItemsType arrayOfItems = new NonEmptyArrayOfAllItemsType(); arrayOfItems.getItemsAndMessagesAndCalendarItems().add(item1); arrayOfItems.getItemsAndMessagesAndCalendarItems().add(item2); arrayOfItems.getItemsAndMessagesAndCalendarItems().add(item3); request.setItems(arrayOfItems); DistinguishedFolderIdType folder = new DistinguishedFolderIdType(); folder.setId(DistinguishedFolderIdNameType.CALENDAR); TargetFolderIdType target = new TargetFolderIdType(); target.setDistinguishedFolderId(folder); request.setSavedItemFolderId(target); StopWatch stopWatch = new StopWatch(); stopWatch.start(); CreateItemResponse response = ewsClient.createItem(request); stopWatch.stop(); log.debug("CreateItem request (3 CalendarItems) completed in " + stopWatch); Assert.assertNotNull(response); ArrayOfResponseMessagesType responseMessages = response.getResponseMessages(); Assert.assertNotNull(responseMessages); Assert.assertEquals(3, responseMessages .getCreateItemResponseMessagesAndDeleteItemResponseMessagesAndGetItemResponseMessages().size()); for (JAXBElement<? extends ResponseMessageType> m : responseMessages .getCreateItemResponseMessagesAndDeleteItemResponseMessagesAndGetItemResponseMessages()) { Assert.assertEquals(ResponseCodeType.NO_ERROR, m.getValue().getResponseCode()); ItemInfoResponseMessageType itemType = (ItemInfoResponseMessageType) m.getValue(); ArrayOfRealItemsType itemArray = itemType.getItems(); ItemType item = itemArray.getItemsAndMessagesAndCalendarItems().get(0); createdIds.getItemIdsAndOccurrenceItemIdsAndRecurringMasterItemIds().add(item.getItemId()); } } finally { deleteItems(createdIds); } }
From source file:net.nan21.dnet.core.web.controller.data.AbstractDsWriteController.java
/** * Default handler for delete action.//from w w w. ja v a 2 s.c o m * * @param resourceName * @param dataformat * @param idsString * @param paramString * @return * @throws Exception */ @RequestMapping(method = RequestMethod.POST, params = Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_DELETE + "ById") @ResponseBody public String deleteById(@PathVariable String resourceName, @PathVariable String dataFormat, @RequestParam(value = Constants.REQUEST_PARAM_DATA, required = false, defaultValue = "{}") String idsString, @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString, HttpServletRequest request, HttpServletResponse response) throws Exception { try { StopWatch stopWatch = new StopWatch(); stopWatch.start(); this.prepareRequest(request, response); this.authorizeDsAction(resourceName, Constants.DS_ACTION_DELETE, null); if (!idsString.startsWith("[")) { idsString = "[" + idsString + "]"; } IDsService<M, F, P> service = this.findDsService(resourceName); IDsMarshaller<M, F, P> marshaller = service.createMarshaller(IDsMarshaller.JSON); List<Object> list = marshaller.readListFromString(idsString, Object.class); service.deleteByIds(list); IActionResultDelete result = this.packResultDelete(); 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) { this.handleException(e, response); return null; } finally { this.finishRequest(); } }
From source file:com.liferay.portlet.documentlibrary.util.PDFProcessorImpl.java
private void _generateImagesIM(FileVersion fileVersion, File file) throws Exception { if (_isGeneratePreview(fileVersion)) { StopWatch stopWatch = null;//from www.j av a 2 s .co m if (_log.isInfoEnabled()) { stopWatch = new StopWatch(); stopWatch.start(); } _generateImagesIM(fileVersion, file, false); if (_log.isInfoEnabled()) { int previewFileCount = getPreviewFileCount(fileVersion); _log.info("ImageMagick generated " + previewFileCount + " preview pages for " + fileVersion.getTitle() + " in " + stopWatch); } } if (_isGenerateThumbnail(fileVersion)) { StopWatch stopWatch = null; if (_log.isInfoEnabled()) { stopWatch = new StopWatch(); stopWatch.start(); } _generateImagesIM(fileVersion, file, true); if (_log.isInfoEnabled()) { _log.info("ImageMagick generated a thumbnail for " + fileVersion.getTitle() + " in " + stopWatch); } } }