List of usage examples for java.util Optional orElse
public T orElse(T other)
From source file:tds.itemrenderer.data.ITSDocument.java
public ITSContent getContent(String language) { if (StringUtils.isEmpty(language)) return null; // get language Optional<ITSContent> maybeContent = Optional.ofNullable(contents.get(language)); // if language does not exist try splitting language if (!maybeContent.isPresent() && language.indexOf('-') != -1) { final String[] langTags = StringUtils.split(language, '-'); if (langTags.length > 1) { maybeContent = Optional.ofNullable(contents.get(langTags[0])); }//from w ww .j ava2 s.c o m } return maybeContent.orElse(null); }
From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceImpl.java
private OwncloudLocalResourceExtension createOwncloudResourceOf(Path path) { Path rootPath = getRootLocationOfAuthenticatedUser(); Path relativePath = rootPath.toAbsolutePath().relativize(path.toAbsolutePath()); URI href = URI.create(UriComponentsBuilder.fromPath("/").path(relativePath.toString()).toUriString()); String name = path.getFileName().toString(); MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM; if (Files.isDirectory(path)) { href = URI.create(UriComponentsBuilder.fromUri(href).path("/").toUriString()); mediaType = OwncloudUtils.getDirectoryMediaType(); } else {//from ww w .jav a 2s. c om FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentType = fileNameMap.getContentTypeFor(path.getFileName().toString()); if (StringUtils.isNotBlank(contentType)) { mediaType = MediaType.valueOf(contentType); } } try { LocalDateTime lastModifiedAt = LocalDateTime.ofInstant(Files.getLastModifiedTime(path).toInstant(), ZoneId.systemDefault()); Optional<String> checksum = checksumService.getChecksum(path); if (Files.isSameFile(rootPath, path)) { name = "/"; checksum = Optional.empty(); } OwncloudLocalResourceExtension resource = OwncloudLocalResourceImpl.builder().href(href).name(name) .eTag(checksum.orElse(null)).mediaType(mediaType).lastModifiedAt(lastModifiedAt).build(); if (Files.isDirectory(path)) { return resource; } return OwncloudLocalFileResourceImpl.fileBuilder().owncloudResource(resource) .contentLength(Files.size(path)).build(); } catch (NoSuchFileException e) { throw new OwncloudResourceNotFoundException(href, getUsername()); } catch (IOException e) { val logMessage = String.format("Cannot create OwncloudResource from Path %s", path); log.error(logMessage, e); throw new OwncloudLocalResourceException(logMessage, e); } }
From source file:org.ow2.proactive.connector.iaas.cloud.provider.azure.AzureProvider.java
@Override public Set<Instance> createInstance(Infrastructure infrastructure, Instance instance) { Azure azureService = azureServiceCache.getService(infrastructure); String instanceTag = Optional.ofNullable(instance.getTag()).orElseThrow( () -> new RuntimeException("ERROR missing instance tag/name from instance: '" + instance + "'")); // Check for Image by name first and then by id String imageNameOrId = Optional.ofNullable(instance.getImage()).orElseThrow( () -> new RuntimeException("ERROR missing Image name/id from instance: '" + instance + "'")); VirtualMachineCustomImage image = getImageByName(azureService, imageNameOrId) .orElseGet(() -> getImageById(azureService, imageNameOrId).orElseThrow(() -> new RuntimeException( "ERROR unable to find custom Image: '" + instance.getImage() + "'"))); // Get the options (Optional by design) Optional<Options> options = Optional.ofNullable(instance.getOptions()); // Try to retrieve the resourceGroup from provided name, otherwise get it from image ResourceGroup resourceGroup = azureProviderUtils .searchResourceGroupByName(azureService, options.map(Options::getResourceGroup).orElseGet(image::resourceGroupName)) .orElseThrow(() -> new RuntimeException( "ERROR unable to find a suitable resourceGroup from instance: '" + instance + "'")); // Try to get region from provided name, otherwise get it from image Region region = options.map(presentOptions -> Region.findByLabelOrName(presentOptions.getRegion())) .orElseGet(image::region);// w w w . ja v a 2 s. c o m // Prepare a new virtual private network (same for all VMs) Optional<String> optionalPrivateNetworkCIDR = options.map(Options::getPrivateNetworkCIDR); Creatable<Network> creatableVirtualNetwork = azureProviderUtils.prepareVirtualNetwork(azureService, region, resourceGroup, createUniqueVirtualNetworkName(instanceTag), optionalPrivateNetworkCIDR.orElse(DEFAULT_PRIVATE_NETWORK_CIDR)); // Prepare a new security group (same for all VMs) Creatable<NetworkSecurityGroup> creatableNetworkSecurityGroup = azureProviderUtils .prepareSSHNetworkSecurityGroup(azureService, region, resourceGroup, createUniqueSecurityGroupName(instance.getTag())); // Prepare the VM(s) Optional<Boolean> optionalStaticPublicIP = options.map(Options::getStaticPublicIP); List<Creatable<VirtualMachine>> creatableVirtualMachines = IntStream .rangeClosed(1, Integer.valueOf(Optional.ofNullable(instance.getNumber()).orElse(SINGLE_INSTANCE_NUMBER))) .mapToObj(instanceNumber -> { // Create a new public IP address (one per VM) String publicIPAddressName = createUniquePublicIPName( createUniqueInstanceTag(instanceTag, instanceNumber)); Creatable<PublicIpAddress> creatablePublicIPAddress = azureProviderUtils.preparePublicIPAddress( azureService, region, resourceGroup, publicIPAddressName, optionalStaticPublicIP.orElse(DEFAULT_STATIC_PUBLIC_IP)); // Prepare a new network interface (one per VM) String networkInterfaceName = createUniqueNetworkInterfaceName( createUniqueInstanceTag(instanceTag, instanceNumber)); Creatable<NetworkInterface> creatableNetworkInterface = azureProviderUtils .prepareNetworkInterfaceFromScratch(azureService, region, resourceGroup, networkInterfaceName, creatableVirtualNetwork, creatableNetworkSecurityGroup, creatablePublicIPAddress); return prepareVirtualMachine(instance, azureService, resourceGroup, region, createUniqueInstanceTag(instanceTag, instanceNumber), image, creatableNetworkInterface); }).collect(Collectors.toList()); // Create all VMs in parallel and collect IDs return azureService.virtualMachines().create(creatableVirtualMachines).values().stream() .map(vm -> instance.withTag(vm.name()).withId(vm.vmId()).withNumber(SINGLE_INSTANCE_NUMBER)) .collect(Collectors.toSet()); }
From source file:com.ikanow.aleph2.management_db.services.DataBucketStatusCrudService.java
@Override public ManagementFuture<Boolean> updateObjectBySpec(final QueryComponent<DataBucketStatusBean> unique_spec, final Optional<Boolean> upsert, final UpdateComponent<DataBucketStatusBean> update) { final MethodNamingHelper<DataBucketStatusBean> helper = BeanTemplateUtils.from(DataBucketStatusBean.class); if (upsert.orElse(false)) { throw new RuntimeException("This method is not supported with upsert set and true"); }/*from w w w .j a va2s. c o m*/ final Collection<BasicMessageBean> errors = validateUpdateCommand(update); if (!errors.isEmpty()) { return FutureUtils.createManagementFuture(CompletableFuture.completedFuture(false), CompletableFuture.completedFuture(errors)); } // Now perform the update and based on the results we may need to send out instructions // to any listening buckets final CompletableFuture<Optional<DataBucketStatusBean>> update_reply = _underlying_data_bucket_status_db .get().updateAndReturnObjectBySpec(unique_spec, Optional.of(false), update, Optional.of(false), Arrays.asList(helper.field(DataBucketStatusBean::_id), helper.field(DataBucketStatusBean::confirmed_suspended), helper.field(DataBucketStatusBean::confirmed_multi_node_enabled), helper.field(DataBucketStatusBean::confirmed_master_enrichment_type), helper.field(DataBucketStatusBean::suspended), helper.field(DataBucketStatusBean::quarantined_until), helper.field(DataBucketStatusBean::node_affinity)), true); try { // What happens now depends on the contents of the message // Maybe the user wanted to suspend/resume the bucket: final CompletableFuture<Collection<BasicMessageBean>> suspend_future = Lambdas .<CompletableFuture<Collection<BasicMessageBean>>>get(() -> { if (update.getAll().containsKey(helper.field(DataBucketStatusBean::suspended))) { // (note this handles suspending the bucket if no handlers are available) return getOperationFuture(update_reply, sb -> sb.suspended(), _underlying_data_bucket_db.get(), _underlying_data_bucket_status_db.get(), _actor_context, _bucket_action_retry_store.get()); } else { // (this isn't an error, just nothing to do here) return CompletableFuture.completedFuture(Collections.<BasicMessageBean>emptyList()); } }); // Maybe the user wanted to set quarantine on/off: final CompletableFuture<Collection<BasicMessageBean>> quarantine_future = Lambdas .<CompletableFuture<Collection<BasicMessageBean>>>get(() -> { if (update.getAll().containsKey(helper.field(DataBucketStatusBean::quarantined_until))) { // (note this handles suspending the bucket if no handlers are available) return getOperationFuture(update_reply, sb -> { // (this predicate is slightly more complex) return (null != sb.quarantined_until()) || (new Date().getTime() < sb.quarantined_until().getTime()); }, _underlying_data_bucket_db.get(), _underlying_data_bucket_status_db.get(), _actor_context, _bucket_action_retry_store.get()); } else { // (this isn't an error, just nothing to do here) return CompletableFuture.completedFuture(Collections.<BasicMessageBean>emptyList()); } }); return FutureUtils.createManagementFuture(update_reply.thenApply(o -> o.isPresent()), // whether we updated suspend_future.thenCombine(quarantine_future, (f1, f2) -> Stream.concat(f1.stream(), f2.stream()).collect(Collectors.toList()))); //(+combine error messages from suspend/quarantine operations) } catch (Exception e) { // This is a serious enough exception that we'll just leave here return FutureUtils.createManagementFuture(FutureUtils.returnError(e)); } }
From source file:org.jboss.tools.openshift.internal.core.preferences.OCBinaryValidator.java
/** * Returns the version of the OC binary by running the version command. * // w ww. j a v a 2 s. c o m * @param monitor the progress monitor * * @return the OSGi version of the binary */ public Version getVersion(IProgressMonitor monitor) { Optional<Version> version = Optional.empty(); if (path != null) { try { ProcessBuilder builder = new ProcessBuilder(path, "version"); Process process = builder.start(); String line; try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { while (!monitor.isCanceled() && (!version.isPresent()) && ((line = reader.readLine()) != null)) { version = parseVersion(line); } } } catch (IOException e) { OpenShiftCoreActivator.logError(e.getLocalizedMessage(), e); } } return version.orElse(Version.emptyVersion); }
From source file:com.teradata.benchto.service.BenchmarkService.java
@Retryable(value = { TransientDataAccessException.class, DataIntegrityViolationException.class }) @Transactional//from w w w. j ava 2 s.com public String startBenchmarkRun(String uniqueName, String name, String sequenceId, Optional<String> environmentName, Map<String, String> variables, Map<String, String> attributes) { String generatedUniqueName = generateBenchmarkUniqueName(name, variables); checkArgument(uniqueName.equals(generatedUniqueName), "Passed unique benchmark name (%s) does not match generated one: (%s) - name: %s, variables: %s", uniqueName, generatedUniqueName, name, variables); BenchmarkRun benchmarkRun = benchmarkRunRepo.findForUpdateByUniqueNameAndSequenceId(uniqueName, sequenceId); if (benchmarkRun == null) { Environment environment = environmentService .findEnvironment(environmentName.orElse(DEFAULT_ENVIRONMENT_NAME)); benchmarkRun = new BenchmarkRun(name, sequenceId, variables, uniqueName); benchmarkRun.setStatus(STARTED); benchmarkRun.setEnvironment(environment); benchmarkRun.getAttributes().putAll(attributes); benchmarkRun.setStarted(currentDateTime()); benchmarkRunRepo.save(benchmarkRun); } LOG.debug("Starting benchmark - {}", benchmarkRun); return benchmarkRun.getUniqueName(); }
From source file:uk.jamierocks.zinc.ZincDispatcher.java
@Override public Optional<Text> getHelp(CommandSource source) { if (this.commands.isEmpty()) { return Optional.empty(); }/*w w w . ja v a 2 s .c o m*/ Text.Builder build = t("Available commands:\n").toBuilder(); for (Iterator<String> it = filterCommands(source).iterator(); it.hasNext();) { final Optional<CommandMapping> mappingOpt = get(it.next(), source); if (!mappingOpt.isPresent()) { continue; } CommandMapping mapping = mappingOpt.get(); @SuppressWarnings("unchecked") final Optional<Text> description = (Optional<Text>) mapping.getCallable().getShortDescription(source); build.append( Text.builder(mapping.getPrimaryAlias()).color(TextColors.GREEN).style(TextStyles.UNDERLINE) .onClick(TextActions.suggestCommand("/" + mapping.getPrimaryAlias())).build(), SPACE_TEXT, description.orElse(mapping.getCallable().getUsage(source))); if (it.hasNext()) { build.append(Text.NEW_LINE); } } return Optional.of(build.build()); }
From source file:com.ikanow.aleph2.distributed_services.services.CoreDistributedServices.java
@Override public synchronized boolean waitForAkkaJoin(Optional<FiniteDuration> timeout) { joinAkkaCluster(); // (does nothing if already joined) try {/*from w w w.j a v a 2s . c o m*/ if (_joined_akka_cluster.isDone()) { return true; } else { logger.info("Waiting for cluster to start up"); _joined_akka_cluster.get(timeout.orElse(_default_akka_join_timeout).toMillis(), TimeUnit.MILLISECONDS); } return true; } catch (Exception e) { logger.info("Cluster timed out: " + timeout.orElse(_default_akka_join_timeout) + ", throw_error=" + !timeout.isPresent()); if (!timeout.isPresent()) { throw new RuntimeException("waitForAkkaJoin timeout"); } return false; } }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.java
/** * Attempts to compile a script and cache it in the request {@link javax.script.ScriptEngine}. This is only * possible if the {@link javax.script.ScriptEngine} implementation implements {@link javax.script.Compilable}. * In the event that the requested {@link javax.script.ScriptEngine} does not implement it, the method will * return empty./*from w w w . j a va2s.c o m*/ */ public Optional<CompiledScript> compile(final String script, final Optional<String> language) throws ScriptException { final String lang = language.orElse("gremlin-groovy"); try { return Optional.of(scriptEngines.compile(script, lang)); } catch (UnsupportedOperationException uoe) { return Optional.empty(); } }
From source file:io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder.java
public Swagger2MarkupConfigBuilder(Configuration configuration) { CompositeConfiguration compositeConfiguration = new CompositeConfiguration(); compositeConfiguration.addConfiguration(new SystemConfiguration()); compositeConfiguration.addConfiguration(configuration); compositeConfiguration.addConfiguration(getDefaultConfiguration()); Swagger2MarkupProperties swagger2MarkupProperties = new Swagger2MarkupProperties(compositeConfiguration); config.markupLanguage = swagger2MarkupProperties.getRequiredMarkupLanguage(MARKUP_LANGUAGE); config.swaggerMarkupLanguage = swagger2MarkupProperties.getRequiredMarkupLanguage(SWAGGER_MARKUP_LANGUAGE); config.generatedExamplesEnabled = swagger2MarkupProperties.getRequiredBoolean(GENERATED_EXAMPLES_ENABLED); config.basePathPrefixEnabled = swagger2MarkupProperties.getRequiredBoolean(BASE_PATH_PREFIX_ENABLED); config.separatedDefinitionsEnabled = swagger2MarkupProperties .getRequiredBoolean(SEPARATED_DEFINITIONS_ENABLED); config.separatedOperationsEnabled = swagger2MarkupProperties .getRequiredBoolean(SEPARATED_OPERATIONS_ENABLED); config.pathsGroupedBy = swagger2MarkupProperties.getGroupBy(PATHS_GROUPED_BY); config.outputLanguage = swagger2MarkupProperties.getLanguage(OUTPUT_LANGUAGE); config.inlineSchemaEnabled = swagger2MarkupProperties.getRequiredBoolean(INLINE_SCHEMA_ENABLED); config.interDocumentCrossReferencesEnabled = swagger2MarkupProperties .getRequiredBoolean(INTER_DOCUMENT_CROSS_REFERENCES_ENABLED); config.interDocumentCrossReferencesPrefix = swagger2MarkupProperties .getString(INTER_DOCUMENT_CROSS_REFERENCES_PREFIX, null); config.flatBodyEnabled = swagger2MarkupProperties.getRequiredBoolean(FLAT_BODY_ENABLED); config.pathSecuritySectionEnabled = swagger2MarkupProperties .getRequiredBoolean(PATH_SECURITY_SECTION_ENABLED); config.anchorPrefix = swagger2MarkupProperties.getString(ANCHOR_PREFIX, null); config.overviewDocument = swagger2MarkupProperties.getRequiredString(OVERVIEW_DOCUMENT); config.pathsDocument = swagger2MarkupProperties.getRequiredString(PATHS_DOCUMENT); config.definitionsDocument = swagger2MarkupProperties.getRequiredString(DEFINITIONS_DOCUMENT); config.securityDocument = swagger2MarkupProperties.getRequiredString(SECURITY_DOCUMENT); config.separatedOperationsFolder = swagger2MarkupProperties.getRequiredString(SEPARATED_OPERATIONS_FOLDER); config.separatedDefinitionsFolder = swagger2MarkupProperties .getRequiredString(SEPARATED_DEFINITIONS_FOLDER); config.tagOrderBy = swagger2MarkupProperties.getOrderBy(TAG_ORDER_BY); config.operationOrderBy = swagger2MarkupProperties.getOrderBy(OPERATION_ORDER_BY); config.definitionOrderBy = swagger2MarkupProperties.getOrderBy(DEFINITION_ORDER_BY); config.parameterOrderBy = swagger2MarkupProperties.getOrderBy(PARAMETER_ORDER_BY); config.propertyOrderBy = swagger2MarkupProperties.getOrderBy(PROPERTY_ORDER_BY); config.responseOrderBy = swagger2MarkupProperties.getOrderBy(RESPONSE_ORDER_BY); Optional<String> lineSeparator = swagger2MarkupProperties.getString(LINE_SEPARATOR); if (lineSeparator.isPresent() && StringUtils.isNoneBlank(lineSeparator.get())) { config.lineSeparator = LineSeparator.valueOf(lineSeparator.get()); }/*w w w . j ava2s. c o m*/ config.pageBreakLocations = swagger2MarkupProperties.getPageBreakLocations(PAGE_BREAK_LOCATIONS); Optional<Pattern> headerPattern = swagger2MarkupProperties.getHeaderPattern(HEADER_REGEX); config.headerPattern = headerPattern.orElse(null); Configuration swagger2markupConfiguration = compositeConfiguration.subset(PROPERTIES_PREFIX); Configuration extensionsConfiguration = swagger2markupConfiguration.subset(EXTENSION_PREFIX); config.extensionsProperties = new Swagger2MarkupProperties(extensionsConfiguration); }