List of usage examples for org.apache.commons.lang.time StopWatch stop
public void stop()
Stop the stopwatch.
This method ends a new timing session, allowing the time to be retrieved.
From source file:com.nridge.connector.fs.con_fs.core.RunPublishFS.java
/** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread./*w ww. j a v a 2 s .c o m*/ * * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see Thread#run() */ @Override public void run() { Document conDoc; DocumentXML documentXML; String docId, queueItem, srcPathFileName; Logger appLogger = mAppMgr.getLogger(this, "run"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); boolean isPublisherInitialized = true; DataBag schemaBag = (DataBag) mAppMgr.getProperty(Connector.PROPERTY_SCHEMA_NAME); Publishers indexPublishers = new Publishers(mAppMgr, mCrawlQueue, Constants.CFG_PROPERTY_PREFIX); try { indexPublishers.initialize(schemaBag); } catch (NSException e) { isPublisherInitialized = false; appLogger.error("Publisher initialization: " + e.getMessage()); } if (isPublisherInitialized) { BlockingQueue transformQueue = (BlockingQueue) mAppMgr.getProperty(Connector.QUEUE_TRANSFORM_NAME); BlockingQueue publishQueue = (BlockingQueue) mAppMgr.getProperty(Connector.QUEUE_PUBLISH_NAME); long queueWaitTimeout = mAppMgr.getLong(Constants.CFG_PROPERTY_PREFIX + ".queue.wait_timeout", Constants.QUEUE_POLL_TIMEOUT_DEFAULT); do { try { queueItem = (String) transformQueue.poll(queueWaitTimeout, TimeUnit.SECONDS); if (mCrawlQueue.isQueueItemDocument(queueItem)) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); docId = Connector.docIdFromQueueItem(queueItem); appLogger.debug(String.format("Transform Queue Item: %s", docId)); srcPathFileName = mCrawlQueue.docPathFileName(Connector.QUEUE_TRANSFORM_NAME, docId); try { documentXML = new DocumentXML(); documentXML.load(srcPathFileName); conDoc = documentXML.getDocument(); indexPublishers.send(conDoc); File srcFile = new File(srcPathFileName); if (!srcFile.delete()) appLogger.warn(String.format("%s: Unable to delete.", srcPathFileName)); stopWatch.stop(); queueItem = Connector.queueItemIdPhaseTime(queueItem, Connector.PHASE_PUBLISH, stopWatch.getTime()); try { // If queue is full, this thread may block. publishQueue.put(queueItem); } catch (InterruptedException e) { // Restore the interrupted status so parent can handle (if it wants to). Thread.currentThread().interrupt(); } } catch (Exception e) { String msgStr = String.format("%s: %s", docId, e.getMessage()); appLogger.error(msgStr, e); MailManager mailManager = (MailManager) mAppMgr .getProperty(Connector.PROPERTY_MAIL_NAME); mailManager.addMessage(Connector.PHASE_PUBLISH, Connector.STATUS_MAIL_ERROR, msgStr, Constants.MAIL_DETAIL_MESSAGE); } } } catch (InterruptedException e) { queueItem = StringUtils.EMPTY; } } while (!mCrawlQueue.isPhaseComplete(Connector.PHASE_TRANSFORM, queueItem)); // Forward the marker queue item to the next queue. if (mCrawlQueue.isQueueItemMarker(queueItem)) { try { // If queue is full, this thread may block. publishQueue.put(queueItem); } catch (InterruptedException e) { // Restore the interrupted status so parent can handle (if it wants to). Thread.currentThread().interrupt(); } } // Now we can shutdown our search indexer publisher. try { indexPublishers.shutdown(); } catch (NSException e) { appLogger.error("Publisher shutdown: " + e.getMessage()); } } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:com.intellij.lang.jsgraphql.ide.project.JSGraphQLLanguageUIProjectService.java
public void executeGraphQL(Editor editor, VirtualFile virtualFile) { final JSGraphQLEndpointsModel endpointsModel = editor.getUserData(JS_GRAPH_QL_ENDPOINTS_MODEL); if (endpointsModel != null) { final JSGraphQLEndpoint selectedEndpoint = endpointsModel.getSelectedItem(); if (selectedEndpoint != null && selectedEndpoint.url != null) { final JSGraphQLQueryContext context = JSGraphQLQueryContextHighlightVisitor .getQueryContextBufferAndHighlightUnused(editor); final Map<String, Object> requestData = Maps.newLinkedHashMap(); requestData.put("query", context.query); try { requestData.put("variables", getQueryVariables(editor)); } catch (JsonSyntaxException jse) { if (myToolWindowManagerInitialized) { myToolWindowManager.logCurrentErrors(ContainerUtil.immutableList( new JSGraphQLErrorResult("Failed to parse variables as JSON: " + jse.getMessage(), virtualFile.getPath(), "Error", 0, 0)), true);//from www . j a va 2 s.c o m } return; } final String requestJson = new Gson().toJson(requestData); final HttpClient httpClient = new HttpClient(new HttpClientParams()); try { final PostMethod method = new PostMethod(selectedEndpoint.url); setHeadersFromOptions(selectedEndpoint, method); method.setRequestEntity(new StringRequestEntity(requestJson, "application/json", "UTF-8")); ApplicationManager.getApplication().executeOnPooledThread(() -> { try { try { editor.putUserData(JS_GRAPH_QL_EDITOR_QUERYING, true); StopWatch sw = new StopWatch(); sw.start(); httpClient.executeMethod(method); final String responseJson = Optional.fromNullable(method.getResponseBodyAsString()) .or(""); sw.stop(); final Integer errorCount = getErrorCount(responseJson); if (fileEditor instanceof TextEditor) { final TextEditor textEditor = (TextEditor) fileEditor; UIUtil.invokeLaterIfNeeded(() -> { ApplicationManager.getApplication().runWriteAction(() -> { final Document document = textEditor.getEditor().getDocument(); document.setText(responseJson); if (requestJson.startsWith("{")) { final PsiFile psiFile = PsiDocumentManager.getInstance(myProject) .getPsiFile(document); if (psiFile != null) { new ReformatCodeProcessor(psiFile, false).run(); } } }); final StringBuilder queryResultText = new StringBuilder( virtualFile.getName()).append(": ").append(sw.getTime()) .append(" ms execution time, ") .append(bytesToDisplayString(responseJson.length())) .append(" response"); if (errorCount != null && errorCount > 0) { queryResultText.append(", ").append(errorCount).append(" error") .append(errorCount > 1 ? "s" : ""); if (context.onError != null) { context.onError.run(); } } queryResultLabel.setText(queryResultText.toString()); queryResultLabel.putClientProperty(FILE_URL_PROPERTY, virtualFile.getUrl()); if (!queryResultLabel.isVisible()) { queryResultLabel.setVisible(true); } querySuccessLabel.setVisible(errorCount != null); if (querySuccessLabel.isVisible()) { if (errorCount == 0) { querySuccessLabel .setBorder(BorderFactory.createEmptyBorder(2, 8, 0, 0)); querySuccessLabel.setIcon(AllIcons.General.InspectionsOK); } else { querySuccessLabel .setBorder(BorderFactory.createEmptyBorder(2, 12, 0, 4)); querySuccessLabel.setIcon(AllIcons.Ide.ErrorPoint); } } showToolWindowContent(myProject, fileEditor.getComponent().getClass()); textEditor.getEditor().getScrollingModel().scrollVertically(0); }); } } finally { editor.putUserData(JS_GRAPH_QL_EDITOR_QUERYING, null); } } catch (IOException e) { Notifications.Bus.notify( new Notification("GraphQL", "GraphQL Query Error", selectedEndpoint.url + ": " + e.getMessage(), NotificationType.WARNING), myProject); } }); } catch (UnsupportedEncodingException | IllegalStateException | IllegalArgumentException e) { Notifications.Bus.notify( new Notification("GraphQL", "GraphQL Query Error", selectedEndpoint.url + ": " + e.getMessage(), NotificationType.ERROR), myProject); } } } }
From source file:com.liferay.portal.search.solr.SolrIndexSearcher.java
public long searchCount(SearchContext searchContext, Query query) throws SearchException { StopWatch stopWatch = new StopWatch(); stopWatch.start();/*from w ww . j a va2s. co m*/ try { QueryResponse queryResponse = search(searchContext, query, searchContext.getStart(), searchContext.getEnd(), true); SolrDocumentList solrDocumentList = queryResponse.getResults(); return solrDocumentList.getNumFound(); } catch (Exception e) { if (_log.isWarnEnabled()) { _log.warn(e, e); } if (!_swallowException) { throw new SearchException(e.getMessage()); } return 0; } finally { if (_log.isInfoEnabled()) { stopWatch.stop(); _log.info("Searching " + query.toString() + " took " + stopWatch.getTime() + " ms"); } } }
From source file:com.liferay.portal.search.elasticsearch.internal.ElasticsearchIndexSearcher.java
@Override public long searchCount(SearchContext searchContext, Query query) throws SearchException { StopWatch stopWatch = new StopWatch(); stopWatch.start();/*from w w w .j ava2s . c o m*/ try { return doSearchCount(searchContext, query); } catch (Exception e) { if (_log.isWarnEnabled()) { _log.warn(e, e); } if (!_logExceptionsOnly) { throw new SearchException(e.getMessage(), e); } return 0; } finally { if (_log.isInfoEnabled()) { stopWatch.stop(); _log.info(StringBundler.concat("Searching ", query.toString(), " took ", String.valueOf(stopWatch.getTime()), " ms")); } } }
From source file:com.qualogy.qafe.mgwt.server.RPCServiceImpl.java
public GDataObject executeEvent(EventDataGVO eventData) throws GWTServiceException { StopWatch stopWatch = new StopWatch(); try {//from www . ja v a2s. co m stopWatch.start(); String appIdUUID = eventData.getUuid().substring(eventData.getUuid().lastIndexOf('|') + 1);// uuid.substring(uuid.lastIndexOf('|')+1); ApplicationIdentifier appId = service.getApplicationId(appIdUUID); GDataObject gDataObject = null; if (appId != null) { eventData.setContext(appId.toString()); resolveRequest(eventData); gDataObject = eventProcessor.execute(eventData, appId, new SessionContainer(getLocale(), eventData.getParameters())); } stopWatch.stop(); if (gDataObject != null) { gDataObject.setTime(Long.valueOf(stopWatch.getTime())); } return gDataObject; } catch (Exception e) { GWTServiceException gWTServiceException = handleException(e); gWTServiceException.setGDataObject(ExceptionProcessor.handle(eventData, e)); stopWatch.stop(); if (gWTServiceException.getGDataObject() != null) { gWTServiceException.getGDataObject().setTime(Long.valueOf(stopWatch.getTime())); } throw gWTServiceException; } }
From source file:com.nridge.connector.fs.con_fs.core.FileCrawler.java
private void saveAddQueueDocument(Document aDocument, StopWatch aStopWatch) throws IOException { Logger appLogger = mAppMgr.getLogger(this, "saveAddQueueDocument"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (!mIsValidationOnly) { DataBag dataBag = aDocument.getBag(); DataField dataField = dataBag.getPrimaryKeyField(); if (dataField == null) appLogger.error("Primary key field is missing from bag - cannot add to queue."); else {/*from www .j a v a 2s. co m*/ String docId = dataField.getValueAsString(); String queueBagPathFileName = mCrawlQueue.docPathFileName(Connector.QUEUE_EXTRACT_NAME, docId); DocumentXML documentXML = new DocumentXML(aDocument); documentXML.save(queueBagPathFileName); aStopWatch.stop(); String queueItem = Connector.queueItemIdPhaseTime(docId, Connector.PHASE_EXTRACT, aStopWatch.getTime()); try { // If queue is full, this thread may block. mExtractQueue.put(queueItem); } catch (InterruptedException e) { // Restore the interrupted status so parent can handle (if it wants to). Thread.currentThread().interrupt(); } } } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:hrider.hbase.Scanner.java
/** * Gets the total number of rows in the table. This value is calculated by scanning throughout the whole table to count the rows. This value is then cached * for future uses./*from w ww . j a v a 2 s . c om*/ * * @return A total number of rows in the table. * @throws IOException Error accessing hbase. */ public long getRowsCount(long timeout) throws IOException { if (this.rowsCount == 0) { this.partialRowsCount = 0; Scan scan = getScanner(); FilterList filters = new FilterList(); if (scan.getFilter() != null) { filters.addFilter(scan.getFilter()); } filters.addFilter(new FirstKeyOnlyFilter()); scan.setFilter(filters); scan.setCaching(GlobalConfig.instance().getBatchSizeForRead()); HTable table = this.connection.getTableFactory().get(this.tableName); ResultScanner scanner = table.getScanner(scan); StopWatch stopWatch = new StopWatch(); stopWatch.start(); try { int count = 0; for (Result rr = scanner.next(); rr != null; rr = scanner.next(), count++) { if (stopWatch.getTime() > timeout) { this.partialRowsCount = count; break; } } this.rowsCount = count; } finally { stopWatch.stop(); scanner.close(); } } return this.rowsCount; }
From source file:eagle.storage.jdbc.entity.impl.JdbcEntityUpdaterImpl.java
@Override public int update(List<E> entities) throws Exception { ConnectionManager cm = ConnectionManagerFactory.getInstance(); TorqueStatementPeerImpl<E> peer = cm.getStatementExecutor(this.jdbcEntityDefinition.getJdbcTableName()); Connection connection = cm.getConnection(); connection.setAutoCommit(false);/*from w ww .j a v a 2s . c o m*/ StopWatch stopWatch = new StopWatch(); stopWatch.start(); int num = 0; try { for (E entity : entities) { String primaryKey = entity.getEncodedRowkey(); PrimaryKeyCriteriaBuilder pkBuilder = new PrimaryKeyCriteriaBuilder(Arrays.asList(primaryKey), this.jdbcEntityDefinition.getJdbcTableName()); Criteria selectCriteria = pkBuilder.build(); if (LOG.isDebugEnabled()) LOG.debug("Updating by query: " + SqlBuilder.buildQuery(selectCriteria).getDisplayString()); ColumnValues columnValues = JdbcEntitySerDeserHelper.buildColumnValues(entity, this.jdbcEntityDefinition); num += peer.delegate().doUpdate(selectCriteria, columnValues, connection); } if (LOG.isDebugEnabled()) LOG.debug("Committing updates"); connection.commit(); } catch (Exception ex) { LOG.error("Failed to update, rolling back", ex); connection.rollback(); throw ex; } finally { stopWatch.stop(); if (LOG.isDebugEnabled()) LOG.debug("Closing connection"); connection.close(); } LOG.info(String.format("Updated %s records in %s ms", num, stopWatch.getTime())); return num; }
From source file:com.liferay.portal.search.elasticsearch.ElasticsearchQuerySuggester.java
@Override public String[] suggestKeywordQueries(SearchContext searchContext, int max) { StopWatch stopWatch = null; if (_log.isInfoEnabled()) { stopWatch = new StopWatch(); stopWatch.start();/*w w w .jav a 2s .com*/ } SuggestBuilder.SuggestionBuilder<PhraseSuggestionBuilder> suggestionBuilder = SuggestBuilder .phraseSuggestion(_REQUEST_TYPE_KEYWORD_QUERY); Suggest.Suggestion<?> suggestion = getSuggestion(searchContext, suggestionBuilder, DocumentTypes.KEYWORD_QUERY, Field.KEYWORD_SEARCH, _REQUEST_TYPE_KEYWORD_QUERY, max); List<?> entries = suggestion.getEntries(); Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option> suggestionEntry = (Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>) entries .get(0); List<String> keywordQueries = new ArrayList<String>(); for (Suggest.Suggestion.Entry.Option option : suggestionEntry.getOptions()) { String optionText = String.valueOf(option.getText()); keywordQueries.add(optionText); } if (_log.isInfoEnabled()) { stopWatch.stop(); _log.info("Suggested keyword queries in " + stopWatch.getTime() + "ms"); } return keywordQueries.toArray(new String[keywordQueries.size()]); }
From source file:net.nan21.dnet.core.web.controller.data.AbstractAsgnController.java
/** * /*from w w w. j av a2s . co m*/ * @param resourceName * @param dataFormat * @param selectionId * @param request * @param response * @return * @throws Exception */ @RequestMapping(method = RequestMethod.POST, params = Constants.REQUEST_PARAM_ACTION + "=" + Constants.ASGN_ACTION_CLEANUP) @ResponseBody public String delete(@PathVariable String resourceName, @PathVariable String dataFormat, @RequestParam(value = Constants.REQUEST_PARAM_ASGN_SELECTION_ID, required = true) String selectionId, HttpServletRequest request, HttpServletResponse response) throws Exception { try { StopWatch stopWatch = new StopWatch(); stopWatch.start(); if (logger.isInfoEnabled()) { logger.info("Processing request: {}.{} -> action = {} ", new String[] { resourceName, dataFormat, Constants.ASGN_ACTION_CLEANUP }); } if (logger.isDebugEnabled()) { logger.debug(" --> request-filter: selectionId={} ", new String[] { selectionId }); } this.prepareRequest(request, response); IAsgnService<M, F, P> service = this.findAsgnService(this.serviceNameFromResourceName(resourceName)); service.cleanup(selectionId); stopWatch.stop(); return ""; } catch (Exception e) { return this.handleException(e, response); } finally { this.finishRequest(); } }