List of usage examples for org.springframework.util Assert notEmpty
public static void notEmpty(@Nullable Map<?, ?> map, Supplier<String> messageSupplier)
From source file:com.massabot.codesender.connection.JSSCConnection.java
@Override public List<String> getReceivedGcodes() { Assert.notEmpty(receivedGcodes, "??Gcode?"); List<String> gcodes = receivedGcodes; receivedGcodes = null;// ww w. j a v a 2s . c o m return gcodes; }
From source file:org.devgateway.ocds.web.rest.controller.AwardsWonLostController.java
@ApiOperation(value = "Number of tenders grouped by procuring entities. All filters apply. " + "procuringEntityId filter is mandatory.") @RequestMapping(value = "/api/procuringEntitiesTendersCount", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public List<DBObject> procuringEntitiesTendersCount( @ModelAttribute @Valid final YearFilterPagingRequest filter) { Assert.notEmpty(filter.getProcuringEntityId(), "procuringEntityId must not be empty!"); Aggregation agg = newAggregation(match(getYearDefaultFilterCriteria(filter, TENDER_PERIOD_START_DATE)), group(TENDER_PROCURING_ENTITY_ID).count().as("tenderCount")); return releaseAgg(agg); }
From source file:com.flipkart.aesop.runtime.relay.DefaultRelayFactory.java
/** * Interface method implementation. Checks for mandatory dependencies and initializes this Relay * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() *///from ww w . j av a2s .c o m public void afterPropertiesSet() throws Exception { Assert.notNull(this.relayConfig, "'relayConfig' cannot be null. This Relay will not be initialized"); Assert.notEmpty(this.producerRegistrationList, "'producerRegistrationList' cannot be empty. No Event producers registered"); }
From source file:de.extra.client.plugins.responseprocessplugin.filesystem.FileSystemResultPackageDataResponseProcessPlugin.java
/** * Erwartet Ergebnisse als Daten in den Felder * ResponseTransportBody.Package.PackageBody in dem Data-Fragment * /*from ww w.j a v a 2 s.c o m*/ * @see de.extra.client.core.plugin.IResponsePlugin#processResponse(de.drv.dsrv * .extrastandard.namespace.response.XMLTransport) */ @Override public IResponseData processResponse(final ResponseTransport extraResponse) { final IResponseData responseData = new ResponseData(); try { // Ausgabe der Response im log // ExtraMessageReturnDataExtractor.printResult(marshaller, // extraResponse); logger.info("ResponsePlugin. ProcessResponse"); final ResponseTransportHeader transportHeader = extraResponse.getTransportHeader(); final ITransportInfo transportInfo = transportInfoBuilder.createTransportInfo(transportHeader); transportObserver.responseFilled(transportInfo); final ResponseDetailsType responseDetails = transportHeader.getResponseDetails(); final RequestDetailsType requestDetails = transportHeader.getRequestDetails(); if (isBodyEmpty(extraResponse.getTransportBody())) { // (21.11.12) Keine Ergebnisse ermoeglichen! // (04.01.13) Warnung signalisieren! responseData.setWarning(true); return responseData; // throw new ExtraResponseProcessPluginRuntimeException( // ExceptionCode.UNEXPECTED_INTERNAL_EXCEPTION, // "Keine Daten vorhanden. Body Element ist leer"); } // -- Fehler/Status aus TransportHeader auswerten -- final String responseId = responseDetails.getResponseID().getValue(); final ReportType report = responseDetails.getReport(); final SingleReportData reportData = returnCodeExtractor.extractReportData(report); final String returnCode = reportData.getReturnCode(); final boolean returnCodeSuccessful = extraReturnCodeAnalyser.isReturnCodeSuccessful(returnCode); if (returnCodeSuccessful == false) { // Falls ein Fehler im Header angezeigt wird, wird der Body (= // Einzelergebnisse) // nicht mehr ausgewertet! Fehler wird hier zugeordnet // final String outputIdentifier = responseId; final ISingleResponseData singleResponseData = new SingleResponseData( requestDetails.getRequestID().getValue(), returnCode, reportData.getReturnText(), responseId, returnCodeSuccessful, PersistentStatus.FAIL, responseId); responseData.addSingleResponse(singleResponseData); } else { // Einzelergebnisse auswerten final ResponseTransportBody transportBody = extraResponse.getTransportBody(); Assert.notNull(transportBody, "ResponseTransportBody is null"); final List<ResponsePackage> packages = transportBody.getPackage(); Assert.notEmpty(packages, "ResponseTransportBody.Package() is empty"); for (final ResponsePackage transportBodyPackage : packages) { final ResponsePackageBody packageBody = transportBodyPackage.getPackageBody(); Assert.notNull(packageBody, "PackageBody is null"); final DataType data = packageBody.getData(); Assert.notNull(data, "PackageBody.data is null"); final Base64CharSequenceType base64CharSequence = data.getBase64CharSequence(); Assert.notNull(base64CharSequence, "Base64CharSequenceType.data is null"); final DataHandler packageBodyDataHandler = base64CharSequence.getValue(); // final byte[] decodedpackageBodyData = Base64 // .decodeBase64(packageBodyData); final ResponsePackageHeader packageHeader = transportBodyPackage.getPackageHeader(); final ResponseDetailsType packageHeaderResponseDetails = packageHeader.getResponseDetails(); final String packageHeaderResponseId = packageHeaderResponseDetails.getResponseID().getValue(); final String incomingFileName = extractIncomingFileNameFromDataSource( transportBodyPackage.getPackagePlugIns()); final String savedFileName = saveBodyToFilesystem(incomingFileName, packageHeaderResponseId, packageBodyDataHandler); final ISingleResponseData singlePackageResponseData = extractResponseDetail(packageHeader, extraReturnCodeAnalyser, savedFileName); responseData.addSingleResponse(singlePackageResponseData); } } logger.info("ReponseData processed. {}", responseData); return responseData; } catch (final XmlMappingException xmlMappingException) { throw new ExtraResponseProcessPluginRuntimeException(xmlMappingException); } }
From source file:org.devgateway.ocds.web.rest.controller.AwardsWonLostController.java
@ApiOperation(value = "Number of awards grouped by procuring entities. All filters apply. " + "procuringEntityId filter is mandatory.") @RequestMapping(value = "/api/procuringEntitiesAwardsCount", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public List<DBObject> procuringEntitiesAwardsCount( @ModelAttribute @Valid final YearFilterPagingRequest filter) { Assert.notEmpty(filter.getProcuringEntityId(), "procuringEntityId must not be empty!"); Aggregation agg = newAggregation(match(getYearDefaultFilterCriteria(filter, TENDER_PERIOD_START_DATE)), unwind("awards"), match(where(MongoConstants.FieldNames.AWARDS_STATUS).is(Award.Status.active.toString())), group(TENDER_PROCURING_ENTITY_ID).count().as("awardCount")); return releaseAgg(agg); }
From source file:org.bremersee.common.security.acls.jdbc.BasicLookupStrategy.java
/** * Locates the primary key IDs specified in "findNow", adding AclImpl instances with * StubAclParents to the "acls" Map./*from w w w .jav a 2 s .c o m*/ * * @param acls the AclImpls (with StubAclParents) * @param findNow Long-based primary keys to retrieve * @param sids the sids */ private void lookupPrimaryKeys(final Map<Serializable, Acl> acls, final Set<Long> findNow, final List<Sid> sids) { Assert.notNull(acls, "ACLs are required"); Assert.notEmpty(findNow, "Items to find now required"); String sql = computeRepeatingSql(lookupPrimaryKeysWhereClause, findNow.size()); Set<Long> parentsToLookup = jdbcTemplate.query(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { int i = 0; for (Long toFind : findNow) { i++; ps.setLong(i, toFind); } } }, new ProcessResultSet(acls, sids)); // Lookup the parents, now that our JdbcTemplate has released the database // connection (SEC-547) if (!parentsToLookup.isEmpty()) { lookupPrimaryKeys(acls, parentsToLookup, sids); } }
From source file:net.sf.gazpachoquest.repository.dynamic.QuestionnaireAnswersRepositoryImpl.java
private void processQuestion(final JPADynamicTypeBuilder builder, final Question question) { QuestionType questionType = question.getType(); if (!questionType.hasSubquestions()) { if (questionType.hasMultipleAnswers()) { String baseFieldName = new StringBuilder().append(question.getCode()).toString(); List<QuestionOption> questionOptions = question.getQuestionOptions(); for (QuestionOption questionOption : questionOptions) { String fieldName = new StringBuilder(baseFieldName).append("_").append(questionOption.getCode()) .toString().toLowerCase(Locale.ENGLISH); builder.addDirectMapping(fieldName, questionType.getAnswerType(), fieldName); }/* ww w. ja v a 2 s. co m*/ } else { String fieldName = new StringBuilder().append(question.getCode().replace(".", "_")).toString() .toLowerCase(Locale.ENGLISH); builder.addDirectMapping(fieldName, questionType.getAnswerType(), fieldName); } } else { Question example = Question.with().parent(Question.with().id(question.getId()).build()).build(); List<Question> subquestions = questionRepository.findByExample(example, new SearchParameters()); Assert.notEmpty(subquestions, String.format("Type %s requires subquestion", questionType)); for (Question subquestion : subquestions) { processQuestion(builder, subquestion); } } }
From source file:org.devgateway.ocds.web.rest.controller.AwardsWonLostController.java
@ApiOperation(value = "Counts the won, lost procurements, flags and amounts. Receives any filters, " + "but most important here is the supplierId and bidderId. Requires bid extension. Use bidderId instead " + "of supplierId.") @RequestMapping(value = "/api/procurementsWonLost", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public List<ProcurementsWonLost> procurementsWonLost( @ModelAttribute @Valid final YearFilterPagingRequest filter) { Assert.notEmpty(filter.getBidderId(), "bidderId must not be empty!"); Assert.isTrue(CollectionUtils.isEmpty(filter.getSupplierId()), "supplierId is not allowed here! Use bidderId to show results!"); //supplier is the same thing as bidder for this particular query filter.setSupplierId(filter.getBidderId()); Map<String, CriteriaDefinition> noSupplierCriteria = createDefaultFilterCriteriaMap(filter); noSupplierCriteria.remove(MongoConstants.Filters.SUPPLIER_ID); Aggregation agg1 = newAggregation(/*ww w .ja v a2 s . c o m*/ match(getYearDefaultFilterCriteria(filter, noSupplierCriteria, TENDER_PERIOD_START_DATE)), unwind("bids.details"), unwind("bids.details.tenderers"), match(getYearDefaultFilterCriteria(filter, noSupplierCriteria, TENDER_PERIOD_START_DATE)), group(BIDS_DETAILS_TENDERERS_ID).count().as("count").sum(BIDS_DETAILS_VALUE_AMOUNT) .as("totalAmount").sum(FLAGS_TOTAL_FLAGGED).as("countFlags"), project("count", "totalAmount", "countFlags")); List<CountAmountFlags> applied = releaseAgg(agg1, CountAmountFlags.class); Aggregation agg2 = newAggregation( match(where(AWARDS_STATUS).is(Award.Status.active.toString()) .andOperator(getYearDefaultFilterCriteria(filter, TENDER_PERIOD_START_DATE))), unwind("awards"), unwind("awards.suppliers"), match(where(AWARDS_STATUS).is(Award.Status.active.toString()).andOperator( getYearDefaultFilterCriteria(filter.awardFiltering(), TENDER_PERIOD_START_DATE))), group(MongoConstants.FieldNames.AWARDS_SUPPLIERS_ID).count().as("count") .sum(MongoConstants.FieldNames.AWARDS_VALUE_AMOUNT).as("totalAmount") .sum(FLAGS_TOTAL_FLAGGED).as("countFlags"), project("count", "totalAmount", "countFlags")); List<CountAmountFlags> won = releaseAgg(agg2, CountAmountFlags.class); ArrayList<ProcurementsWonLost> ret = new ArrayList<>(); applied.forEach(a -> { ProcurementsWonLost r = new ProcurementsWonLost(); r.setApplied(a); Optional<CountAmountFlags> optWon = won.stream().filter(w -> w.getId().equals(a.getId())).findFirst(); if (optWon.isPresent()) { r.setWon(optWon.get()); r.setLostAmount(r.getApplied().getTotalAmount().subtract(r.getWon().getTotalAmount())); r.setLostCount(r.getApplied().getCount() - r.getWon().getCount()); } else { r.setLostAmount(r.getApplied().getTotalAmount()); r.setLostCount(r.getLostCount()); } ret.add(r); }); return ret; }
From source file:com.emc.ecs.sync.target.EcsS3Target.java
@Override public void configure(SyncSource source, Iterator<SyncFilter> filters, SyncTarget target) { Assert.hasText(accessKey, "accessKey is required"); Assert.hasText(secretKey, "secretKey is required"); Assert.hasText(bucketName, "bucketName is required"); Assert.isTrue(bucketName.matches("[A-Za-z0-9._-]+"), bucketName + " is not a valid bucket name"); S3Config s3Config;//from w w w .ja va 2 s . c om if (enableVHosts) { Assert.notNull(endpoint, "endpoint is required"); s3Config = new S3Config(endpoint); } else { // try to infer from endpoint if (endpoint != null) { if (vdcs == null && endpoint.getHost() != null) { vdcs = new ArrayList<>(); for (String host : endpoint.getHost().split(",")) { vdcs.add(new Vdc(host)); } } if (port <= 0 && endpoint.getPort() > 0) port = endpoint.getPort(); if (protocol == null && endpoint.getScheme() != null) protocol = endpoint.getScheme(); } Assert.hasText(protocol, "protocol is required"); Assert.notEmpty(vdcs, "at least one VDC is required"); s3Config = new S3Config(com.emc.object.Protocol.valueOf(protocol.toUpperCase()), vdcs.toArray(new Vdc[vdcs.size()])); if (port > 0) s3Config.setPort(port); s3Config.setSmartClient(smartClientEnabled); } s3Config.withIdentity(accessKey).withSecretKey(secretKey); if (apacheClientEnabled) { s3 = new S3JerseyClient(s3Config); } else { System.setProperty("http.maxConnections", "100"); s3 = new S3JerseyClient(s3Config, new URLConnectionClientHandler()); } // TODO: generalize uri translation EcsS3Util.S3Uri s3Uri = new EcsS3Util.S3Uri(); s3Uri.protocol = protocol; s3Uri.vdcs = vdcs; s3Uri.port = port; s3Uri.accessKey = accessKey; s3Uri.secretKey = secretKey; s3Uri.rootKey = rootKey; if (targetUri == null) targetUri = s3Uri.toUri(); // for version support. TODO: genericize version support if (source instanceof EcsS3Source) { s3Source = (EcsS3Source) source; if (!s3Source.isVersioningEnabled()) includeVersions = false; // don't include versions if source versioning is off } else if (includeVersions) { throw new ConfigurationException( "Object versions are currently only supported with the S3 source & target plugins."); } if (!s3.bucketExists(bucketName)) { if (createBucket) { s3.createBucket(bucketName); if (includeVersions) s3.setBucketVersioning(bucketName, new VersioningConfiguration().withStatus(VersioningConfiguration.Status.Enabled)); } else { throw new ConfigurationException("The bucket " + bucketName + " does not exist."); } } if (rootKey == null) rootKey = ""; // make sure rootKey isn't null if (includeVersions) { VersioningConfiguration.Status status = s3.getBucketVersioning(bucketName).getStatus(); if (status == null || status == VersioningConfiguration.Status.Suspended) throw new ConfigurationException("The specified bucket does not have versioning enabled."); } if (!mpuDisabled && mpuPartSizeMB < EcsS3Util.MIN_PART_SIZE_MB) { log.warn("{}MB is below the minimum MPU part size of {}MB. the minimum will be used instead", mpuPartSizeMB, EcsS3Util.MIN_PART_SIZE_MB); mpuPartSizeMB = EcsS3Util.MIN_PART_SIZE_MB; } }
From source file:org.bremersee.common.security.acls.jdbc.BasicLookupStrategy.java
/** * The main method./*w ww . ja va 2 s . c o m*/ * <p> * WARNING: This implementation completely disregards the "sids" argument! Every item * in the cache is expected to contain all SIDs. If you have serious performance needs * (e.g. a very large number of SIDs per object identity), you'll probably want to * develop a custom {@link LookupStrategy} implementation instead. * <p> * The implementation works in batch sizes specified by {@link #batchSize}. * * @param objects the identities to lookup (required) * @param sids the SIDs for which identities are required (ignored by this * implementation) * * @return a <tt>Map</tt> where keys represent the {@link ObjectIdentity} of the * located {@link Acl} and values are the located {@link Acl} (never <tt>null</tt> * although some entries may be missing; this method should not throw * {@link NotFoundException}, as a chain of {@link LookupStrategy}s may be used to * automatically create entries if required) */ @Override public final Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, // NOSONAR List<Sid> sids) { Assert.isTrue(batchSize >= 1, "BatchSize must be >= 1"); Assert.notEmpty(objects, "Objects to lookup required"); // Map<ObjectIdentity,Acl> Map<ObjectIdentity, Acl> result = new HashMap<>(); // contains // FULLY // loaded // Acl // objects Set<ObjectIdentity> currentBatchToLoad = new HashSet<>(); for (int i = 0; i < objects.size(); i++) { final ObjectIdentity oid = objects.get(i); boolean aclFound = false; // Check we don't already have this ACL in the results if (result.containsKey(oid)) { aclFound = true; } // Check cache for the present ACL entry if (!aclFound) { Acl acl = aclCache.getFromCache(oid); // Ensure any cached element supports all the requested SIDs // (they should always, as our base impl doesn't filter on SID) if (acl != null) { if (acl.isSidLoaded(sids)) { // NOSONAR result.put(acl.getObjectIdentity(), acl); aclFound = true; } else { throw new IllegalStateException( "Error: SID-filtered element detected when implementation does not perform SID filtering " + "- have you added something to the cache manually?"); } } } // Load the ACL from the database if (!aclFound) { currentBatchToLoad.add(oid); } // Is it time to load from JDBC the currentBatchToLoad? if ((currentBatchToLoad.size() == this.batchSize) || ((i + 1) == objects.size())) { if (!currentBatchToLoad.isEmpty()) { // NOSONAR Map<ObjectIdentity, Acl> loadedBatch = lookupObjectIdentities(currentBatchToLoad, sids); // Add loaded batch (all elements 100% initialized) to results result.putAll(loadedBatch); // Add the loaded batch to the cache for (Acl loadedAcl : loadedBatch.values()) { // NOSONAR aclCache.putInCache((AclImpl) loadedAcl); } currentBatchToLoad.clear(); } } } return result; }