use of org.apache.commons.lang3.ObjectUtils.defaultIfNull in project nem2-sdk-java by nemtech.
the class RestrictionMosaicRepositoryVertxImpl method toMosaicAddressRestriction.
private MosaicAddressRestriction toMosaicAddressRestriction(MosaicAddressRestrictionDTO mosaicAddressRestrictionDTO) {
MosaicAddressRestrictionEntryWrapperDTO dto = mosaicAddressRestrictionDTO.getMosaicRestrictionEntry();
Map<BigInteger, BigInteger> restrictions = dto.getRestrictions().stream().collect(Collectors.toMap(e -> new BigInteger(e.getKey()), e -> toBigInteger(e.getValue())));
return new MosaicAddressRestriction(mosaicAddressRestrictionDTO.getId(), ObjectUtils.defaultIfNull(dto.getVersion(), 1), dto.getCompositeHash(), MosaicRestrictionEntryType.rawValueOf(dto.getEntryType().getValue()), MapperUtils.toMosaicId(dto.getMosaicId()), MapperUtils.toAddress(dto.getTargetAddress()), restrictions);
}
use of org.apache.commons.lang3.ObjectUtils.defaultIfNull in project midpoint by Evolveum.
the class ReportServiceImpl method evaluateSubreportParameters.
public VariablesMap evaluateSubreportParameters(PrismObject<ReportType> report, VariablesMap variables, Task task, OperationResult result) {
VariablesMap subreportVariable = new VariablesMap();
if (report != null && report.asObjectable().getObjectCollection() != null && report.asObjectable().getObjectCollection().getSubreport() != null && !report.asObjectable().getObjectCollection().getSubreport().isEmpty()) {
Collection<SubreportParameterType> subreports = report.asObjectable().getObjectCollection().getSubreport();
List<SubreportParameterType> sortedSubreports = new ArrayList<>(subreports);
sortedSubreports.sort(Comparator.comparingInt(s -> ObjectUtils.defaultIfNull(s.getOrder(), Integer.MAX_VALUE)));
for (SubreportParameterType subreport : sortedSubreports) {
if (subreport.getExpression() == null || subreport.getName() == null) {
continue;
}
ExpressionType expression = subreport.getExpression();
try {
Collection<? extends PrismValue> subreportParameter = evaluateScript(report, expression, variables, "subreport parameter", task, result);
Class<?> subreportParameterClass;
if (subreport.getType() != null) {
subreportParameterClass = getPrismContext().getSchemaRegistry().determineClassForType(subreport.getType());
} else {
if (subreportParameter != null && !subreportParameter.isEmpty()) {
subreportParameterClass = subreportParameter.iterator().next().getRealClass();
} else {
subreportParameterClass = Object.class;
}
}
subreportVariable.put(subreport.getName(), subreportParameter, subreportParameterClass);
} catch (Exception e) {
LOGGER.error("Couldn't execute expression " + expression, e);
}
}
return subreportVariable;
}
return subreportVariable;
}
use of org.apache.commons.lang3.ObjectUtils.defaultIfNull in project plugin-prov by ligoj.
the class ProvQuoteUploadResource method persist.
/**
* Validate the input object, do a lookup, then create the {@link ProvQuoteInstance} and the
* {@link ProvQuoteStorage} entities.
*/
private <V extends AbstractQuoteVmEditionVo> void persist(final VmUpload upload, final int subscription, final BiFunction<V, UploadContext, Integer> merger, final UploadContext context, final V vo, final ObjIntConsumer<QuoteStorageEditionVo> diskConsumer, final ResourceType resourceType) {
// Create the quote instance from the validated inputs
final var id = merger.apply(vo, context);
if (id == null) {
// Do not continue
return;
}
// Storage part
final var disks = IntStream.range(0, upload.getDisk().size()).filter(index -> upload.getDisk().get(index) > 0).mapToObj(index -> {
final var size = upload.getDisk().get(index).intValue();
final var sizeMax = upload.getDiskMax().size() > index ? upload.getDiskMax().get(index).intValue() : null;
// Size is provided, propagate the upload properties
final var svo = new QuoteStorageEditionVo();
svo.setName(vo.getName() + (index == 0 ? "" : index));
diskConsumer.accept(svo, id);
svo.setSize(size);
svo.setSizeMax(sizeMax);
svo.setLatency(getItem(upload.getLatency(), index));
svo.setOptimized(getItem(upload.getOptimized(), index));
// Find the nicest storage
svo.setType(storageResource.lookup(context.quote, svo).stream().findFirst().orElseThrow(() -> new ValidationJsonException("storage", "NotNull")).getPrice().getType().getCode());
// Default the storage name to the instance name
svo.setSubscription(subscription);
return storageResource.create(svo).getId();
}).collect(Collectors.toList());
// Tags part
Arrays.stream(StringUtils.split(ObjectUtils.defaultIfNull(upload.getTags(), ""), ",;")).map(StringUtils::trimToNull).filter(Objects::nonNull).forEach(t -> {
// Instance tags
final var tag = new TagEditionVo();
final var parts = StringUtils.splitPreserveAllTokens(t + ":", ':');
tag.setName(parts[0].trim());
tag.setValue(StringUtils.trimToNull(parts[1]));
tag.setResource(id);
tag.setType(resourceType);
tagResource.create(subscription, tag);
// Storage tags
tag.setType(ResourceType.STORAGE);
disks.forEach(d -> {
tag.setResource(d);
tagResource.create(subscription, tag);
});
});
}
use of org.apache.commons.lang3.ObjectUtils.defaultIfNull in project plugin-prov by ligoj.
the class ProvQuoteUploadResource method upload.
/**
* Upload a file of quote.
*
* @param subscription The subscription identifier, will be used to filter the locations from the associated
* provider.
* @param uploadedFile Instance entries files to import. Currently support only CSV format.
* @param headers the CSV header names. When <code>null</code> or empty, the default headers are used.
* @param headersIncluded When <code>true</code>, the first line is the headers and the given <code>headers</code>
* parameter is ignored. Otherwise the <code>headers</code> parameter is used.
* @param defaultUsage The optional usage name. When not <code>null</code>, each quote instance without defined
* usage will be associated to this usage.
* @param mode The merge option indicates how the entries are inserted.
* @param ramMultiplier The multiplier for imported RAM values. Default is 1.
* @param encoding CSV encoding. Default is UTF-8.
* @param errorContinue When <code>true</code> errors do not block the upload.
* @param createUsage When <code>true</code>, missing usage are automatically created.
* @param separator CSV separator. Default is ";".
* @throws IOException When the CSV stream cannot be written.
*/
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("{subscription:\\d+}/upload")
public void upload(@PathParam("subscription") final int subscription, @Multipart(value = CSV_FILE) final InputStream uploadedFile, @Multipart(value = "headers", required = false) final String[] headers, @Multipart(value = "headers-included", required = false) final boolean headersIncluded, @Multipart(value = "usage", required = false) final String defaultUsage, @Multipart(value = "mergeUpload", required = false) final MergeMode mode, @Multipart(value = "memoryUnit", required = false) final Integer ramMultiplier, @Multipart(value = "errorContinue", required = false) final boolean errorContinue, @Multipart(value = "encoding", required = false) final String encoding, @Multipart(value = "createMissingUsage", required = false) final boolean createUsage, @Multipart(value = "separator", required = false) final String separator) throws IOException {
log.info("Upload provisioning requested...");
subscriptionResource.checkVisible(subscription);
final var quote = resource.getRepository().findBy("subscription.id", subscription);
final var safeEncoding = ObjectUtils.defaultIfNull(encoding, DEFAULT_ENCODING);
// Check headers validity
final String[] headersArray;
final InputStream fileNoHeader;
if (headersIncluded) {
// Header at first line
final var br = new BufferedReader(new StringReader(IOUtils.toString(uploadedFile, safeEncoding)));
headersArray = StringUtils.defaultString(br.readLine()).split(separator);
fileNoHeader = new ByteArrayInputStream(IOUtils.toByteArray(br, safeEncoding));
} else {
// Headers are provided separately
headersArray = ArrayUtils.isEmpty(headers) ? DEFAULT_HEADERS : headers;
fileNoHeader = uploadedFile;
}
final var headersArray2 = checkHeaders(headersArray);
final var headersString = StringUtils.chop(ArrayUtils.toString(headersArray2)).substring(1).replace(",", separator) + "\n";
final var reader = new InputStreamReader(new SequenceInputStream(new ByteArrayInputStream(headersString.getBytes(safeEncoding)), fileNoHeader), safeEncoding);
// Build entries
log.info("Upload provisioning : reading, using header {}", headersString);
final var list = csvForBean.toBean(VmUpload.class, reader);
log.info("Upload provisioning : importing {} entries", list.size());
final var cursor = new AtomicInteger(0);
final var previousQi = qiRepository.findAll(quote).stream().collect(Collectors.toConcurrentMap(ProvQuoteInstance::getName, Function.identity()));
final var previousQb = qbRepository.findAll(quote).stream().collect(Collectors.toConcurrentMap(ProvQuoteDatabase::getName, Function.identity()));
// Initialization for parallel process
Hibernate.initialize(quote.getUsages());
Hibernate.initialize(quote.getBudgets());
final var context = new UploadContext();
context.quote = quote;
context.previousQi = previousQi;
context.previousQb = previousQb;
list.stream().filter(Objects::nonNull).filter(i -> i.getName() != null).forEach(i -> {
try {
persist(subscription, defaultUsage, mode, ramMultiplier, list.size(), cursor, context, createUsage, i);
} catch (final ValidationJsonException e) {
handleUploadError(errorContinue, handleValidationError(i, e));
} catch (final ConstraintViolationException e) {
handleUploadError(errorContinue, handleValidationError(i, new ValidationJsonException(e)));
} catch (final RuntimeException e) {
log.error("Unmanaged error during import of " + i.getName(), e);
handleUploadError(errorContinue, e);
}
});
log.info("Upload provisioning : flushing");
}
Aggregations