Java Code Examples for org.apache.commons.lang3.time.StopWatch#createStarted()
The following examples show how to use
org.apache.commons.lang3.time.StopWatch#createStarted() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IndyRepositorySession.java From pnc with Apache License 2.0 | 6 votes |
/** * Promote all build dependencies NOT ALREADY CAPTURED to the hosted repository holding store for the shared imports * and return dependency artifacts meta data. * * @param report The tracking report that contains info about artifacts downloaded by the build * @param promote flag if collected dependencies should be promoted * @return List of dependency artifacts meta data * @throws RepositoryManagerException In case of a client API transport error or an error during promotion of * artifacts * @throws PromotionValidationException when the promotion process results in an error due to validation failure */ private List<Artifact> processDownloads(final TrackedContentDTO report, final boolean promote) throws RepositoryManagerException, PromotionValidationException { List<Artifact> deps; logger.info("BEGIN: Process artifacts downloaded by build"); userLog.info("Processing dependencies"); StopWatch stopWatch = StopWatch.createStarted(); Set<TrackedContentEntryDTO> downloads = report.getDownloads(); if (CollectionUtils.isEmpty(downloads)) { deps = Collections.emptyList(); } else { deps = collectDownloadedArtifacts(report); if (promote) { Map<StoreKey, Map<StoreKey, Set<String>>> depMap = collectDownloadsPromotionMap(downloads); promoteDownloads(depMap); } } logger.info("END: Process artifacts downloaded by build, took {} seconds", stopWatch.getTime(TimeUnit.SECONDS)); return deps; }
Example 2
Source File: IndyRepositorySession.java From pnc with Apache License 2.0 | 6 votes |
@Override public void deleteBuildGroup() throws RepositoryManagerException { logger.info("BEGIN: Removing build aggregation group: {}", buildContentId); userLog.info("Removing build aggregation group"); StopWatch stopWatch = StopWatch.createStarted(); try { StoreKey key = new StoreKey(packageType, StoreType.group, buildContentId); serviceAccountIndy.stores().delete(key, "[Post-Build] Removing build aggregation group: " + buildContentId); } catch (IndyClientException e) { throw new RepositoryManagerException( "Failed to retrieve Indy stores module. Reason: %s", e, e.getMessage()); } logger.info( "END: Removing build aggregation group: {}, took: {} seconds", buildContentId, stopWatch.getTime(TimeUnit.SECONDS)); stopWatch.reset(); }
Example 3
Source File: FilesApiServiceImpl.java From multiapps-controller with Apache License 2.0 | 6 votes |
@Override public ResponseEntity<FileMetadata> uploadFile(HttpServletRequest request, String spaceGuid, String namespace) { try { StopWatch stopWatch = StopWatch.createStarted(); LOGGER.trace("Received upload request on URI: {}", ServletUtil.decodeUri(request)); FileEntry fileEntry = uploadFiles(request, spaceGuid, namespace).get(0); FileMetadata file = parseFileEntry(fileEntry); AuditLoggingProvider.getFacade() .logConfigCreate(file); stopWatch.stop(); LOGGER.trace("Uploaded file \"{}\" with name {}, size {} and digest {} (algorithm {}) for {} ms.", file.getId(), file.getName(), file.getSize(), file.getDigest(), file.getDigestAlgorithm(), stopWatch.getTime()); return ResponseEntity.status(HttpStatus.CREATED) .body(file); } catch (FileUploadException | IOException | FileStorageException e) { throw new SLException(e, Messages.COULD_NOT_UPLOAD_FILE_0, e.getMessage()); } }
Example 4
Source File: RESTCallToken.java From egeria with Apache License 2.0 | 6 votes |
/** * Set up the values that will be used in the logging process. * * @param serviceName name of service * @param serverName name of server (or null if it is a platform request) * @param userId calling user * @param methodName calling method */ RESTCallToken(String serviceName, String serverName, String userId, String methodName) { this.serviceName = serviceName; this.userId = userId; this.methodName = methodName; this.threadName = Thread.currentThread().getName(); this.watch = StopWatch.createStarted(); this.callId = getNextCallId(); if (serverName == null) { this.serverName = PLATFORM_NAME; } else { this.serverName = serverName; } }
Example 5
Source File: ElasticSearchServer.java From vind with Apache License 2.0 | 6 votes |
private IndexResult indexMultipleDocuments(List<Document> docs, int withinMs) { log.warn("Parameter 'within' not in use in elastic search backend"); final StopWatch elapsedTime = StopWatch.createStarted(); final List<Map<String,Object>> jsonDocs = docs.parallelStream() .map(DocumentUtil::createInputDocument) .collect(Collectors.toList()); try { if (elasticClientLogger.isTraceEnabled()) { elasticClientLogger.debug(">>> add({})", jsonDocs); } else { elasticClientLogger.debug(">>> add({})", jsonDocs); } final BulkResponse response =this.elasticSearchClient.add(jsonDocs) ; elapsedTime.stop(); return new IndexResult(elapsedTime.getTime()).setElapsedTime(elapsedTime.getTime()); } catch (ElasticsearchException | IOException e) { log.error("Cannot index documents {}", jsonDocs, e); throw new SearchServerException("Cannot index documents", e); } }
Example 6
Source File: ElasticSearchServer.java From vind with Apache License 2.0 | 6 votes |
@Override public boolean execute(Update update, DocumentFactory factory) { try { log.warn("Update script builder does not check for script injection. Ensure values provided are script safe."); final StopWatch elapsedTime = StopWatch.createStarted(); elasticClientLogger.debug(">>> delete({})", update); final PainlessScript.ScriptBuilder updateScript = ElasticQueryBuilder.buildUpdateScript(update.getOptions(), factory, update.getUpdateContext()); final UpdateResponse response = elasticSearchClient.update(update.getId(), updateScript); elapsedTime.stop(); return true; } catch (ElasticsearchException | IOException e) { log.error("Cannot update document {}: {}", update.getId(), e.getMessage() , e); throw new SearchServerException( String.format("Cannot update document %s: %s", update.getId(), e.getMessage()), e); } }
Example 7
Source File: ElasticSearchServer.java From vind with Apache License 2.0 | 6 votes |
private IndexResult indexSingleDocument(Document doc, int withinMs) { log.warn("Parameter 'within' not in use in elastic search backend"); final StopWatch elapsedTime = StopWatch.createStarted(); final Map<String,Object> document = DocumentUtil.createInputDocument(doc); try { if (elasticClientLogger.isTraceEnabled()) { elasticClientLogger.debug(">>> add({})", doc.getId()); } else { elasticClientLogger.debug(">>> add({})", doc.getId()); } final BulkResponse response = this.elasticSearchClient.add(document); elapsedTime.stop(); return new IndexResult(response.getTook().getMillis()).setElapsedTime(elapsedTime.getTime()); } catch (ElasticsearchException | IOException e) { log.error("Cannot index document {}", document.get(FieldUtil.ID) , e); throw new SearchServerException("Cannot index document", e); } }
Example 8
Source File: ElasticSearchServer.java From vind with Apache License 2.0 | 6 votes |
@Override public GetResult execute(RealTimeGet search, DocumentFactory assets) { try { final StopWatch elapsedTime = StopWatch.createStarted(); final MultiGetResponse response = elasticSearchClient.realTimeGet(search.getValues()); elapsedTime.stop(); if(response!=null){ return ResultUtils.buildRealTimeGetResult(response, search, assets, elapsedTime.getTime()).setElapsedTime(elapsedTime.getTime()); }else { log.error("Null result from ElasticClient"); throw new SearchServerException("Null result from ElasticClient"); } } catch (ElasticsearchException | IOException e) { log.error("Cannot execute realTime get query"); throw new SearchServerException("Cannot execute realTime get query", e); } }
Example 9
Source File: Web3SDKConnector.java From WeEvent with Apache License 2.0 | 5 votes |
public static Web3j initWeb3j(Service service) throws BrokerException { // init web3j with given group id try { log.info("begin to initialize web3sdk's Web3j, group id: {}", service.getGroupId()); StopWatch sw = StopWatch.createStarted(); // special thread for TransactionSucCallback.onResponse, callback from IO thread directly if not setting //service.setThreadPool(poolTaskExecutor); service.run(); ChannelEthereumService channelEthereumService = new ChannelEthereumService(); channelEthereumService.setChannelService(service); channelEthereumService.setTimeout(service.getConnectSeconds() * 1000); Web3j web3j = Web3j.build(channelEthereumService, service.getGroupId()); // check connect with getNodeVersion command NodeVersion.Version version = web3j.getNodeVersion().send().getNodeVersion(); String nodeVersion = version.getVersion(); if (StringUtils.isBlank(nodeVersion) || !nodeVersion.contains(FISCO_BCOS_2_X_VERSION_PREFIX)) { log.error("init web3sdk failed, mismatch FISCO-BCOS version in node: {}", nodeVersion); throw new BrokerException(ErrorCode.WEB3SDK_INIT_ERROR); } chainID = version.getChainID(); sw.stop(); log.info("initialize web3sdk success, group id: {} cost: {} ms", service.getGroupId(), sw.getTime()); return web3j; } catch (Exception e) { log.error("init web3sdk failed", e); throw new BrokerException(ErrorCode.WEB3SDK_INIT_ERROR); } }
Example 10
Source File: ElasticsearchStoreTransactionsTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void sparqlTest() throws IOException { SailRepository elasticsearchStore = new SailRepository(this.elasticsearchStore); try (SailRepositoryConnection connection = elasticsearchStore.getConnection()) { connection.begin(IsolationLevels.NONE); connection.add( ElasticsearchStoreTransactionsTest.class.getClassLoader().getResourceAsStream("testFile.ttl"), "", RDFFormat.TURTLE); connection.commit(); StopWatch stopwatch = StopWatch.createStarted(); TupleQuery tupleQuery = connection.prepareTupleQuery(String.join("\n", "", "PREFIX sh: <http://www.w3.org/ns/shacl#>", "select * where {", " ?a a sh:NodeShape ;", " sh:property ?property .", "", " ?property sh:path ?path;", " sh:minCount ?minCount.", "}")); List<BindingSet> bindingSets = Iterations.asList(tupleQuery.evaluate()); stopwatch.stop(); logTime(stopwatch, "query", TimeUnit.MILLISECONDS); assertEquals(1, bindingSets.size()); assertEquals("http://example.com/ns#PersonShape", bindingSets.get(0).getValue("a").stringValue()); assertEquals("http://www.w3.org/2000/01/rdf-schema#label", bindingSets.get(0).getValue("path").stringValue()); assertEquals("1", bindingSets.get(0).getValue("minCount").stringValue()); } }
Example 11
Source File: ElasticsearchStoreTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testAddLargeDataset() { StopWatch stopWatch = StopWatch.createStarted(); SailRepository elasticsearchStore = new SailRepository( new ElasticsearchStore("localhost", embeddedElastic.getTransportTcpPort(), "cluster1", "testindex")); try (SailRepositoryConnection connection = elasticsearchStore.getConnection()) { stopWatch.stop(); ElasticsearchStoreTransactionsTest.logTime(stopWatch, "Creating repo and getting connection", TimeUnit.SECONDS); stopWatch = StopWatch.createStarted(); connection.begin(IsolationLevels.NONE); int count = 100000; for (int i = 0; i < count; i++) { connection.add(RDFS.RESOURCE, RDFS.LABEL, connection.getValueFactory().createLiteral(i)); } connection.commit(); stopWatch.stop(); ElasticsearchStoreTransactionsTest.logTime(stopWatch, "Adding data", TimeUnit.SECONDS); stopWatch = StopWatch.createStarted(); assertEquals(count, connection.size()); stopWatch.stop(); ElasticsearchStoreTransactionsTest.logTime(stopWatch, "Getting size", TimeUnit.SECONDS); } }
Example 12
Source File: ElasticSearchServer.java From vind with Apache License 2.0 | 5 votes |
@Override public DeleteResult execute(Delete delete, DocumentFactory factory) { try { final StopWatch elapsedTime = StopWatch.createStarted(); elasticClientLogger.debug(">>> delete({})", delete); final QueryBuilder deleteQuery = ElasticQueryBuilder.buildFilterQuery(delete.getQuery(), factory, delete.getUpdateContext()); final BulkByScrollResponse response = elasticSearchClient.deleteByQuery(deleteQuery); elapsedTime.stop(); return new DeleteResult(response.getTook().getMillis()).setElapsedTime(elapsedTime.getTime()); } catch (ElasticsearchException | IOException e) { log.error("Cannot delete with query {}", delete.getQuery() , e); throw new SearchServerException( String.format("Cannot delete with query %s", delete.getQuery().toString()), e); } }
Example 13
Source File: ElasticSearchServer.java From vind with Apache License 2.0 | 5 votes |
@Override public DeleteResult deleteWithin(Document doc, int withinMs) { log.warn("Parameter 'within' not in use in elastic search backend"); try { final StopWatch elapsedTime = StopWatch.createStarted(); elasticClientLogger.debug(">>> delete({})", doc.getId()); final DeleteResponse deleteResponse = elasticSearchClient.deleteById(doc.getId()); elapsedTime.stop(); return new DeleteResult(elapsedTime.getTime()).setElapsedTime(elapsedTime.getTime()); } catch (ElasticsearchException | IOException e) { log.error("Cannot delete document {}", doc.getId() , e); throw new SearchServerException("Cannot delete document", e); } }
Example 14
Source File: MetricInterceptor.java From mybatis-boost with MIT License | 5 votes |
@Override public Object intercept(Invocation invocation) throws Throwable { BoundSql boundSql = ((StatementHandler) invocation.getTarget()).getBoundSql(); String sql = boundSql.getSql().replaceAll("\\s*\\n\\s*", " "); List<Object> parameters = new ArrayList<>(); if (configuration.isShowQueryWithParameters()) { List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); Object parameterObject = boundSql.getParameterObject(); MetaObject metaObject = MyBatisUtils.getMetaObject(parameterObject); if (parameterMappings.size() == 1 && !(parameterObject instanceof Map) && !metaObject.hasGetter(parameterMappings.get(0).getProperty())) { parameters.add(parameterObject); } else { parameterMappings.forEach(pm -> parameters.add(metaObject.getValue(pm.getProperty()))); } } StopWatch stopWatch = StopWatch.createStarted(); Object proceed = invocation.proceed(); long time = stopWatch.getTime(); if (time > configuration.getSlowQueryThresholdInMillis()) { if (parameters.isEmpty()) { logger.error(String.format("[SLOW Query took %s ms] %s", time, sql)); } else { logger.error(String.format("[SLOW Query took %s ms, Parameters: %s] %s ", time, parameters, sql)); } BiConsumer<String, Long> slowSqlHandler = configuration.getSlowQueryHandler(); if (slowSqlHandler != null) { slowSqlHandler.accept(sql, time); } } else if (configuration.isShowQuery()) { if (parameters.isEmpty()) { logger.info(String.format("[Query took %s ms] %s", time, sql)); } else { logger.info(String.format("[Query took %s ms, Parameters: %s] %s ", time, parameters, sql)); } } return proceed; }
Example 15
Source File: ElasticSearchServer.java From vind with Apache License 2.0 | 4 votes |
@Override public SuggestionResult execute(ExecutableSuggestionSearch search, DocumentFactory factory) { final StopWatch elapsedtime = StopWatch.createStarted(); final SearchSourceBuilder query = ElasticQueryBuilder.buildSuggestionQuery(search, factory); //query try { elasticClientLogger.debug(">>> query({})", query.toString()); final SearchResponse response = elasticSearchClient.query(query); HashMap<FieldDescriptor, TermFacetResult<?>> suggestionValues = ResultUtils.buildSuggestionResults(response, factory, search.getSearchContext()); String spellcheckText = null; if (!suggestionValues.values().stream() .anyMatch(termFacetResult -> CollectionUtils.isNotEmpty(termFacetResult.getValues())) ) { //if no results, try spellchecker (if defined and if spellchecked query differs from original) final List<String> spellCheckedQuery = ElasticQueryBuilder.getSpellCheckedQuery(response); //query with checked query if(spellCheckedQuery != null && CollectionUtils.isNotEmpty(spellCheckedQuery)) { final Iterator<String> iterator = spellCheckedQuery.iterator(); while(iterator.hasNext()) { final String text = iterator.next(); final SearchSourceBuilder spellcheckQuery = ElasticQueryBuilder.buildSuggestionQuery(search.text(text), factory); final SearchResponse spellcheckResponse = elasticSearchClient.query(spellcheckQuery); final HashMap<FieldDescriptor, TermFacetResult<?>> spellcheckValues = ResultUtils.buildSuggestionResults(spellcheckResponse, factory, search.getSearchContext()); if (spellcheckValues.values().stream() .anyMatch(termFacetResult -> CollectionUtils.isNotEmpty(termFacetResult.getValues())) ) { spellcheckText = text; suggestionValues = spellcheckValues; break; } } } } elapsedtime.stop(); return new SuggestionResult( suggestionValues, spellcheckText, response.getTook().getMillis(), factory) .setElapsedTime(elapsedtime.getTime(TimeUnit.MILLISECONDS)); } catch (ElasticsearchException | IOException e) { throw new SearchServerException(String.format("Cannot issue query: %s",e.getMessage()), e); } }
Example 16
Source File: ElasticSearchServer.java From vind with Apache License 2.0 | 4 votes |
@Override public SearchResult execute(FulltextSearch search, DocumentFactory factory) { final StopWatch elapsedtime = StopWatch.createStarted(); final SearchSourceBuilder query = ElasticQueryBuilder.buildQuery(search, factory); //query try { elasticClientLogger.debug(">>> query({})", query.toString()); final SearchResponse response = elasticSearchClient.query(query); if(Objects.nonNull(response) && Objects.nonNull(response.getHits()) && Objects.nonNull(response.getHits().getHits())){ //TODO: if nested doc search is implemented //final Map<String,Integer> childCounts = SolrUtils.getChildCounts(response); final List<Document> documents = Arrays.stream(response.getHits().getHits()) .map(hit -> DocumentUtil.buildVindDoc(hit, factory, search.getSearchContext())) .collect(Collectors.toList()); String spellcheckText = null; if ( search.isSpellcheck() && CollectionUtils.isEmpty(documents)) { //if no results, try spellchecker (if defined and if spellchecked query differs from original) final List<String> spellCheckedQuery = ElasticQueryBuilder.getSpellCheckedQuery(response); //query with checked query if(spellCheckedQuery != null && CollectionUtils.isNotEmpty(spellCheckedQuery)) { final Iterator<String> iterator = spellCheckedQuery.iterator(); while(iterator.hasNext()) { final String text = iterator.next(); final SearchSourceBuilder spellcheckQuery = ElasticQueryBuilder.buildQuery(search.text(text).spellcheck(false), factory); final SearchResponse spellcheckResponse = elasticSearchClient.query(spellcheckQuery); documents.addAll(Arrays.stream(spellcheckResponse.getHits().getHits()) .map(hit -> DocumentUtil.buildVindDoc(hit, factory, search.getSearchContext())) .collect(Collectors.toList())); } } } // Building Vind Facet Results final FacetResults facetResults = ResultUtils.buildFacetResults( response.getAggregations(), factory, search.getFacets(), search.getSearchContext()); elapsedtime.stop(); final long totalHits = response.getHits().getTotalHits().value; switch(search.getResultSet().getType()) { case page:{ return new PageResult(totalHits, response.getTook().getMillis(), documents, search, facetResults, this, factory).setElapsedTime(elapsedtime.getTime()); } case slice: { return new SliceResult(totalHits, response.getTook().getMillis(), documents, search, facetResults, this, factory).setElapsedTime(elapsedtime.getTime()); } default: return new PageResult(totalHits, response.getTook().getMillis(), documents, search, facetResults, this, factory).setElapsedTime(elapsedtime.getTime()); } }else { throw new ElasticsearchException("Empty result from ElasticClient"); } } catch (ElasticsearchException | IOException e) { throw new SearchServerException(String.format("Cannot issue query: %s",e.getMessage()), e); } }
Example 17
Source File: IndyRepositorySession.java From pnc with Apache License 2.0 | 4 votes |
/** * Promotes by path downloads captured in given map. The key in the map is promotion target store key. The value is * another map, where key is promotion source store key and value is list of paths to be promoted. * * @param depMap dependencies map * @throws RepositoryManagerException in case of an unexpected error during promotion * @throws PromotionValidationException when the promotion process results in an error due to validation failure */ private void promoteDownloads(Map<StoreKey, Map<StoreKey, Set<String>>> depMap) throws RepositoryManagerException, PromotionValidationException { for (Map.Entry<StoreKey, Map<StoreKey, Set<String>>> targetToSources : depMap.entrySet()) { StoreKey target = targetToSources.getKey(); for (Map.Entry<StoreKey, Set<String>> sourceToPaths : targetToSources.getValue().entrySet()) { StoreKey source = sourceToPaths.getKey(); PathsPromoteRequest req = new PathsPromoteRequest(source, target, sourceToPaths.getValue()) .setPurgeSource(false); // set read-only only the generic http proxy hosted repos, not shared-imports boolean readonly = !isTempBuild && GENERIC_PKG_KEY.equals(target.getPackageType()); StopWatch stopWatchDoPromote = StopWatch.createStarted(); try { logger.info( "BEGIN: doPromoteByPath: source: '{}', target: '{}', readonly: {}", req.getSource().toString(), req.getTarget().toString(), readonly); userLog.info( "Promoting {} dependencies from {} to {}", req.getPaths().size(), req.getSource(), req.getTarget()); doPromoteByPath(req, false, readonly); logger.info( "END: doPromoteByPath: source: '{}', target: '{}', readonly: {}, took: {} seconds", req.getSource().toString(), req.getTarget().toString(), readonly, stopWatchDoPromote.getTime(TimeUnit.SECONDS)); } catch (RepositoryManagerException ex) { logger.info( "END: doPromoteByPath: source: '{}', target: '{}', readonly: {}, took: {} seconds", req.getSource().toString(), req.getTarget().toString(), readonly, stopWatchDoPromote.getTime(TimeUnit.SECONDS)); throw ex; } } } }
Example 18
Source File: FiscoBcos2.java From WeEvent with Apache License 2.0 | 4 votes |
public CompletableFuture<SendResult> publishEvent(String topicName, String eventContent, String extensions) throws BrokerException { if (!isTopicExist(topicName)) { throw new BrokerException(ErrorCode.TOPIC_NOT_EXIST); } log.info("publish async ..."); StopWatch sw = StopWatch.createStarted(); CompletableFuture<SendResult> future = new CompletableFuture<>(); this.topic.publishWeEvent(topicName, eventContent, extensions, new TransactionSucCallback() { @Override public void onResponse(TransactionReceipt receipt) { SendResult sendResult = new SendResult(); sendResult.setTopic(topicName); // success if (receipt.isStatusOK()) { Tuple1<BigInteger> result = topic.getPublishWeEventOutput(receipt); int sequence = result.getValue1().intValue(); if (sequence == 0) { log.error("permission forbid to publish event"); sendResult.setStatus(SendResult.SendResultStatus.NO_PERMISSION); } else { sendResult.setStatus(SendResult.SendResultStatus.SUCCESS); sendResult.setEventId(DataTypeUtils.encodeEventId(topicName, receipt.getBlockNumber().intValue(), sequence)); } } else { // error String detail = StatusCode.getStatusMessage(receipt.getStatus(), receipt.getMessage()); if ("Transaction receipt timeout.".equals(receipt.getStatus())) { log.error("publish event failed due to transaction execution timeout. {}", detail); sendResult.setStatus(SendResult.SendResultStatus.TIMEOUT); } else { log.error("publish event failed due to transaction execution error. {}", detail); sendResult.setStatus(SendResult.SendResultStatus.ERROR); } } sw.stop(); log.info("publish async result, {} cost: {} ms", sendResult, sw.getTime()); future.complete(sendResult); } }); return future; }
Example 19
Source File: ElasticsearchStoreTransactionsTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Test public void testGetDataSailRepositoryContextIRI() { SailRepository elasticsearchStore = new SailRepository(this.elasticsearchStore); try (SailRepositoryConnection connection = elasticsearchStore.getConnection()) { Resource context1 = vf.createIRI("http://example.com/context1"); Resource context2 = vf.createBNode(); Resource context3 = vf.createIRI("http://example.com/context3"); connection.add(RDF.TYPE, RDF.TYPE, RDFS.RESOURCE, context1); connection.add(RDF.TYPE, RDF.TYPE, RDF.PROPERTY, context2); connection.add(RDF.TYPE, RDF.TYPE, RDF.PREDICATE, context3); connection.add(RDF.TYPE, RDF.TYPE, vf.createLiteral("no context")); printAllDocs(); StopWatch stopWatch = StopWatch.createStarted(); Set<Statement> context1Statements = Iterations .asSet(connection.getStatements(null, RDF.TYPE, null, context1)); stopWatch.stop(); logTime(stopWatch, "Query", TimeUnit.MILLISECONDS); stopWatch = StopWatch.createStarted(); Set<Statement> context2Statements = Iterations .asSet(connection.getStatements(null, RDF.TYPE, null, context2)); stopWatch.stop(); logTime(stopWatch, "Query", TimeUnit.MILLISECONDS); stopWatch = StopWatch.createStarted(); Set<Statement> context3Statements = Iterations .asSet(connection.getStatements(null, RDF.TYPE, null, context3)); stopWatch.stop(); logTime(stopWatch, "Query", TimeUnit.MILLISECONDS); stopWatch = StopWatch.createStarted(); Set<Statement> contextNoneStatements = Iterations .asSet(connection.getStatements(null, RDF.TYPE, null, true, (Resource) null)); stopWatch.stop(); logTime(stopWatch, "Query", TimeUnit.MILLISECONDS); stopWatch = StopWatch.createStarted(); Set<Statement> contextAllStatements = Iterations .asSet(connection.getStatements(null, RDF.TYPE, null)); stopWatch.stop(); logTime(stopWatch, "Query", TimeUnit.MILLISECONDS); stopWatch = StopWatch.createStarted(); Set<Statement> contextContext1And2Statements = Iterations .asSet(connection.getStatements(null, RDF.TYPE, null, context1, context2)); stopWatch.stop(); logTime(stopWatch, "Query", TimeUnit.MILLISECONDS); Statement statementContext1 = vf.createStatement(RDF.TYPE, RDF.TYPE, RDFS.RESOURCE, context1); Statement statementContext2 = vf.createStatement(RDF.TYPE, RDF.TYPE, RDF.PROPERTY, context2); Statement statementContext3 = vf.createStatement(RDF.TYPE, RDF.TYPE, RDF.PREDICATE, context3); Statement statementContextNone = vf.createStatement(RDF.TYPE, RDF.TYPE, vf.createLiteral("no context")); assertEquals(asSet(statementContext1), context1Statements); assertEquals(asSet(statementContext2), context2Statements); assertEquals(asSet(statementContext3), context3Statements); assertEquals(asSet(statementContext1, statementContext2), contextContext1And2Statements); assertEquals(asSet(statementContextNone), contextNoneStatements); assertEquals(asSet(statementContext1, statementContext2, statementContext3, statementContextNone), contextAllStatements); } }
Example 20
Source File: IndyRepositorySession.java From pnc with Apache License 2.0 | 4 votes |
/** * Return list of output artifacts for promotion. * * @param report The tracking report that contains info about artifacts uploaded (output) from the build * @return List of output artifacts meta data * @throws RepositoryManagerException In case of a client API transport error or an error during promotion of * artifacts */ private Uploads collectUploads(TrackedContentDTO report) throws RepositoryManagerException { List<Artifact> data; List<String> promotion; logger.info("BEGIN: Process artifacts uploaded from build"); userLog.info("Processing built artifacts"); StopWatch stopWatch = StopWatch.createStarted(); Set<TrackedContentEntryDTO> uploads = report.getUploads(); if (CollectionUtils.isEmpty(uploads)) { data = Collections.emptyList(); promotion = Collections.emptyList(); } else { data = new ArrayList<>(); Set<String> promotionSet = new HashSet<>(); IndyContentClientModule content; try { content = indy.content(); } catch (IndyClientException e) { throw new RepositoryManagerException( "Failed to retrieve Indy content module. Reason: %s", e, e.getMessage()); } for (TrackedContentEntryDTO upload : uploads) { String path = upload.getPath(); StoreKey storeKey = upload.getStoreKey(); if (artifactFilter.acceptsForData(upload)) { String identifier = computeIdentifier(upload); logger.info("Recording upload: {}", identifier); RepositoryType repoType = toRepoType(storeKey.getPackageType()); TargetRepository targetRepository = getUploadsTargetRepository(repoType, content); ArtifactQuality artifactQuality = getArtifactQuality(isTempBuild); Artifact.Builder artifactBuilder = Artifact.Builder.newBuilder() .md5(upload.getMd5()) .sha1(upload.getSha1()) .sha256(upload.getSha256()) .size(upload.getSize()) .deployPath(upload.getPath()) .filename(new File(path).getName()) .identifier(identifier) .targetRepository(targetRepository) .artifactQuality(artifactQuality); Artifact artifact = validateArtifact(artifactBuilder.build()); data.add(artifact); } if (artifactFilter.acceptsForPromotion(upload, false)) { promotionSet.add(path); if (MAVEN_PKG_KEY.equals(storeKey.getPackageType()) && !isChecksum(path)) { // add the standard checksums to ensure, they are promoted (Maven usually uses only one, so // the other would be missing) but avoid adding checksums of checksums. promotionSet.add(path + ".md5"); promotionSet.add(path + ".sha1"); } } } promotion = new ArrayList<>(promotionSet); } logger.info("END: Process artifacts uploaded from build, took {} seconds", stopWatch.getTime(TimeUnit.SECONDS)); return new Uploads(data, promotion); }