List of usage examples for java.util Optional orElse
public T orElse(T other)
From source file:io.klerch.alexa.state.handler.AWSIotStateHandler.java
/** * {@inheritDoc}// ww w . j av a 2 s . c om */ @Override public <TModel extends AlexaStateModel> Optional<TModel> readModel(final Class<TModel> modelClass, final String id) throws AlexaStateException { // if there is nothing for this model in the session ... final Optional<TModel> modelSession = super.readModel(modelClass, id); // create new model with given id. for now we assume a model exists for this id. we find out by // reading file from the bucket in the following lines. only if this is true model will be written back to session final TModel model = modelSession.orElse(createModel(modelClass, id)); // we need to remember if there will be something from thing shadow to be written to the model // in order to write those values back to the session at the end of this method Boolean modelChanged = false; // and if there are user-scoped fields ... if (model.hasUserScopedField() && fromThingShadowToModel(model, AlexaScope.USER)) { modelChanged = true; } // and if there are app-scoped fields ... if (model.hasApplicationScopedField() && fromThingShadowToModel(model, AlexaScope.APPLICATION)) { modelChanged = true; } // so if model changed from within something out of the shadow we want this to be in the speechlet as well // this gives you access to user- and app-scoped attributes throughout a session without reading from S3 over and over again if (modelChanged) { super.writeModel(model); return Optional.of(model); } else { // if there was nothing received from IOT and there is nothing to return from session // then its not worth return the model. better indicate this model does not exist return modelSession.isPresent() ? Optional.of(model) : Optional.empty(); } }
From source file:org.exist.launcher.ServiceManager.java
ServiceManager(Launcher launcher) { this.launcher = launcher; if (SystemUtils.IS_OS_WINDOWS) { canUseServices = true;//from w ww . j a v a2 s . c o m } else { isRoot((root) -> canUseServices = root); } final Optional<Path> eXistHome = ConfigurationHelper.getExistHome(); if (eXistHome.isPresent()) { wrapperDir = eXistHome.get().resolve("tools/yajsw"); } else { wrapperDir = Paths.get("tools/yajsw"); } final Path wrapperConfig = wrapperDir.resolve("conf/wrapper.conf"); System.setProperty("wrapper.config", wrapperConfig.toString()); wrapperProperties = new Properties(); wrapperProperties.setProperty("wrapper.working.dir", eXistHome.orElse(Paths.get(".")).toString()); wrapperProperties.setProperty("wrapper.config", wrapperConfig.toString()); }
From source file:org.ops4j.pax.web.resources.jsf.OsgiResourceHandler.java
@Override public Resource createResource(final String resourceName, String libraryName, String contentType) { // first, use default ResourceHandler for lookup Resource standardResource = super.createResource(resourceName, libraryName, contentType); if (standardResource != null) { return standardResource; }/*from w ww . jav a2 s. co m*/ String workResourceName = resourceName; // nothing found, continue with OsgiResourceHandler final FacesContext facesContext = FacesContext.getCurrentInstance(); if (workResourceName.charAt(0) == PATH_SEPARATOR) { // If resourceName starts with '/', remove that character because it // does not have any meaning (with and without should point to the // same resource). workResourceName = workResourceName.substring(1); } if (!ResourceValidationUtils.isValidResourceName(workResourceName)) { logger.debug("Invalid resourceName '{}'", workResourceName); return null; } if (libraryName != null && !ResourceValidationUtils.isValidLibraryName(libraryName)) { logger.debug("Invalid libraryName '{}'", libraryName); return null; } final Optional<String> localePrefix = ResourceHandlerUtils.getLocalePrefixForLocateResource(facesContext); // Contract currently not supported: final List<String> contracts = facesContext.getResourceLibraryContracts(); final JsfResourceQuery query = new JsfResourceQuery(localePrefix.orElse(null), libraryName, workResourceName, contentType); final Optional<JsfResourceQueryResult> matchedQueryResult = getServiceAndExecute( service -> matchResources(service, query)); if (matchedQueryResult.isPresent()) { JsfResourceQueryResult queryResult = matchedQueryResult.get(); return new OsgiResource(queryResult.getResourceInformation().getUrl(), queryResult.isMatchedLocalePrefix() ? localePrefix.orElseGet(null) : null, workResourceName, queryResult.getResourceVersion(), libraryName, queryResult.getLibraryVersion(), queryResult.getResourceInformation().getLastModified()); } else { return null; } // inspect final resource for contentType // FIXME deal with content-type // if (contentType == null) // { // try(InputStream is = resourceInfo.getUrl().openConnection().getInputStream()){ // contentType = URLConnection.guessContentTypeFromStream(is); // }catch(IOException e){ // logger.error("Could not determine contentType from url-resource!", e); // } // } }
From source file:alfio.manager.system.MockMailer.java
@Override public void send(Event event, String to, String subject, String text, Optional<String> html, Attachment... attachments) {// w w w . j a v a2 s . co m String printedAttachments = Optional.ofNullable(attachments).map(Arrays::asList) .orElse(Collections.emptyList()).stream() .map(a -> "{filename:" + a.getFilename() + ", contentType: " + a.getContentType() + "}") .collect(Collectors.joining(", ")); log.info("Email: from: {}, replyTo: {}, to: {}, subject: {}, text: {}, html: {}, attachments: {}", event.getDisplayName(), configurationManager.getStringConfigValue( Configuration.from(event.getOrganizationId(), event.getId(), MAIL_REPLY_TO), ""), to, subject, text, html.orElse("no html"), printedAttachments); }
From source file:zipkin.server.ZipkinServerConfiguration.java
@Bean @ConditionalOnMissingBean(CollectorMetrics.class) CollectorMetrics metrics(Optional<CounterBuffers> counterBuffers, Optional<GaugeBuffers> gaugeBuffers) { // it is not guaranteed that BufferCounterService/CounterBuffers will be used, // for ex., com.datastax.cassandra:cassandra-driver-core brings com.codahale.metrics.MetricRegistry // and as result DropwizardMetricServices is getting instantiated instead of standard Java8 BufferCounterService. // On top of it Cassandra driver heavily relies on Dropwizard metrics and manually excluding it from pom.xml is not an option. // MetricsDropwizardAutoConfiguration can be manually excluded either, as Cassandra metrics won't be recorded. return new ActuateCollectorMetrics(counterBuffers.orElse(new CounterBuffers()), gaugeBuffers.orElse(new GaugeBuffers())); }
From source file:org.kontalk.view.ThreadDetails.java
ThreadDetails(final Component focusGainer, KonThread thread) { mThread = thread;//from w ww.j a v a2 s . co m GroupPanel groupPanel = new GroupPanel(View.GAP_BIG, false); groupPanel.setMargin(View.MARGIN_BIG); groupPanel.add(new WebLabel(Tr.tr("Edit Chat")).setBoldFont()); groupPanel.add(new WebSeparator(true, true)); // editable fields groupPanel.add(new WebLabel(Tr.tr("Subject:"))); String subj = mThread.getSubject(); mSubjectField = new WebTextField(subj, 22); mSubjectField.setInputPrompt(subj); mSubjectField.setHideInputPromptOnFocus(false); groupPanel.add(mSubjectField); groupPanel.add(new WebSeparator(true, true)); final WebSlider colorSlider = new WebSlider(WebSlider.HORIZONTAL); groupPanel.add(new WebLabel(Tr.tr("Custom Background"))); mColorOpt = new WebRadioButton(Tr.tr("Color:") + " "); Optional<Color> optBGColor = mThread.getViewSettings().getBGColor(); mColorOpt.setSelected(optBGColor.isPresent()); mColorOpt.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { colorSlider.setEnabled(e.getStateChange() == ItemEvent.SELECTED); } }); mColor = new WebButton(); mColor.setMinimumHeight(25); Color oldColor = optBGColor.orElse(DEFAULT_BG); mColor.setBottomBgColor(oldColor); groupPanel.add(new GroupPanel(GroupingType.fillLast, mColorOpt, mColor)); colorSlider.setMinimum(0); colorSlider.setMaximum(100); colorSlider.setPaintTicks(false); colorSlider.setPaintLabels(false); colorSlider.setEnabled(optBGColor.isPresent()); final GradientData gradientData = GradientData.getDefaultValue(); // TODO set location for color gradientData.getColor(0); colorSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { float v = colorSlider.getValue() / (float) 100; Color c = gradientData.getColorForLocation(v); mColor.setBottomBgColor(c); mColor.repaint(); } }); groupPanel.add(colorSlider); mImgOpt = new WebRadioButton(Tr.tr("Image:") + " "); String imgPath = mThread.getViewSettings().getImagePath(); mImgOpt.setSelected(!imgPath.isEmpty()); mImgOpt.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { mImgChooser.setEnabled(e.getStateChange() == ItemEvent.SELECTED); mImgChooser.getChooseButton().setEnabled(e.getStateChange() == ItemEvent.SELECTED); } }); mImgChooser = Utils.createImageChooser(!imgPath.isEmpty(), imgPath); groupPanel.add(new GroupPanel(GroupingType.fillLast, mImgOpt, mImgChooser)); UnselectableButtonGroup.group(mColorOpt, mImgOpt); groupPanel.add(new WebSeparator()); // groupPanel.add(new WebLabel(Tr.tr("Participants:"))); // mParticipantsList = new WebCheckBoxList(); // mParticipantsList.setVisibleRowCount(10); // for (User oneUser : UserList.getInstance().getAll()) { // boolean selected = mThread.getUser().contains(oneUser); // mParticipantsList.getCheckBoxListModel().addCheckBoxElement( // new UserElement(oneUser), // selected); // } final WebButton saveButton = new WebButton(Tr.tr("Save")); // mParticipantsList.getModel().addListDataListener(new ListDataListener() { // @Override // public void intervalAdded(ListDataEvent e) { // } // @Override // public void intervalRemoved(ListDataEvent e) { // } // @Override // public void contentsChanged(ListDataEvent e) { // saveButton.setEnabled(!mParticipantsList.getCheckedValues().isEmpty()); // } // }); // // groupPanel.add(new WebScrollPane(mParticipantsList)); // groupPanel.add(new WebSeparator(true, true)); this.add(groupPanel, BorderLayout.CENTER); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // if (mParticipantsList.getCheckedValues().size() > 1) { // String infoText = Tr.t/r("More than one receiver not supported (yet)."); // WebOptionPane.showMessageDialog(ThreadListView.this, // infoText, // Tr.t/r("Sorry"), // WebOptionPane.INFORMATION_MESSAGE); // return; // } ThreadDetails.this.save(); // close popup focusGainer.requestFocus(); } }); //this.getRootPane().setDefaultButton(saveButton); GroupPanel buttonPanel = new GroupPanel(2, saveButton); buttonPanel.setLayout(new FlowLayout(FlowLayout.TRAILING)); this.add(buttonPanel, BorderLayout.SOUTH); }
From source file:org.ow2.proactive.connector.iaas.cloud.provider.azure.AzureProvider.java
private Creatable<VirtualMachine> prepareVirtualMachine(Instance instance, Azure azureService, ResourceGroup resourceGroup, Region region, String instanceTag, VirtualMachineCustomImage image, Creatable<NetworkInterface> creatableNetworkInterface) { // Configure the VM depending on the OS type VirtualMachine.DefinitionStages.WithFromImageCreateOptionsManaged creatableVirtualMachineWithImage; OperatingSystemTypes operatingSystemType = image.osDiskImage().osType(); if (operatingSystemType.equals(OperatingSystemTypes.LINUX)) { creatableVirtualMachineWithImage = configureLinuxVirtualMachine(azureService, instanceTag, region, resourceGroup, instance.getCredentials(), image, creatableNetworkInterface); } else if (operatingSystemType.equals(OperatingSystemTypes.WINDOWS)) { creatableVirtualMachineWithImage = configureWindowsVirtualMachine(azureService, instanceTag, region, resourceGroup, instance.getCredentials(), image, creatableNetworkInterface); } else {// w w w. j av a 2s . co m throw new RuntimeException( "ERROR Operating System of type '" + operatingSystemType.toString() + "' is not yet supported"); } // Set VM size (or type) and name of OS' disk Optional<String> optionalHardwareType = Optional.ofNullable(instance.getHardware()).map(Hardware::getType); VirtualMachine.DefinitionStages.WithCreate creatableVMWithSize = creatableVirtualMachineWithImage .withSize(new VirtualMachineSizeTypes(optionalHardwareType.orElse(DEFAULT_VM_SIZE.toString()))) .withOsDiskName(createUniqOSDiskName(instanceTag)); // Add init script(s) using dedicated Microsoft extension Optional.ofNullable(instance.getInitScript()).map(InstanceScript::getScripts).ifPresent(scripts -> { if (scripts.length > 0) { StringBuilder concatenatedScripts = new StringBuilder(); Lists.newArrayList(scripts) .forEach(script -> concatenatedScripts.append(script).append(SCRIPT_SEPARATOR)); creatableVMWithSize.defineNewExtension(createUniqueScriptName(instanceTag)) .withPublisher(SCRIPT_EXTENSION_PUBLISHER).withType(SCRIPT_EXTENSION_TYPE) .withVersion(SCRIPT_EXTENSION_VERSION).withMinorVersionAutoUpgrade() .withPublicSetting(SCRIPT_EXTENSION_CMD_KEY, concatenatedScripts.toString()).attach(); } }); return creatableVMWithSize; }
From source file:org.onosproject.store.cluster.messaging.impl.NettyMessagingManager.java
private void sendReply(InternalMessage message, Status status, Optional<byte[]> responsePayload) { InternalMessage response = new InternalMessage(preamble, clockService.timeNow(), message.id(), localEp, REPLY_MESSAGE_TYPE, responsePayload.orElse(new byte[0]), status); sendAsync(message.sender(), response).whenComplete((result, error) -> { if (error != null) { log.debug("Failed to respond", error); }/*from ww w. ja v a 2 s.c om*/ }); }
From source file:com.smoketurner.notification.api.Notification.java
/** * Constructor//from w w w. j a v a2 s .c o m * * @param id * @param idStr * @param category * @param message * @param createdAt * @param unseen * @param properties * @param notifications */ @JsonCreator private Notification(@JsonProperty("id") final Optional<Long> id, @JsonProperty("id_str") final Optional<String> idStr, @JsonProperty("category") final String category, @JsonProperty("message") final String message, @JsonProperty("created_at") final Optional<DateTime> createdAt, @JsonProperty("unseen") final Optional<Boolean> unseen, @JsonProperty("properties") final Optional<Map<String, String>> properties, @JsonProperty("notifications") final Optional<Collection<Notification>> notifications) { this.id = id.orElse(null); this.idStr = idStr.orElse(null); this.category = category; this.message = message; this.createdAt = createdAt.orElse(DateTime.now(DateTimeZone.UTC)); this.unseen = unseen.orElse(null); this.properties = properties.orElse(Collections.<String, String>emptyMap()); this.notifications = notifications.orElse(null); }
From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java
/** Creates a mapping for the bucket - columnar elements * ALSO INCLUDES THE PER-FIELD CONFIGURATION FROM THE SEARCH_INDEX_SCHEMA AND TEMPORAL_SCHMEA * @param bucket//w ww .j a va2 s .c o m * @return * @throws IOException */ public static XContentBuilder getColumnarMapping(final DataBucketBean bucket, Optional<XContentBuilder> to_embed, final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> field_lookups, final JsonNode enabled_not_analyzed, final JsonNode enabled_analyzed, final JsonNode default_not_analyzed, final JsonNode default_analyzed, final Optional<JsonNode> doc_schema, final SearchIndexSchemaDefaultBean search_index_schema_override, final ObjectMapper mapper, final String index_type) { try { final XContentBuilder start = to_embed.orElse(XContentFactory.jsonBuilder().startObject()); final boolean columnar_enabled = Optional.ofNullable(bucket.data_schema()) .map(DataSchemaBean::columnar_schema).filter(s -> Optional.ofNullable(s.enabled()).orElse(true)) .isPresent(); final Map<Either<String, Tuple2<String, String>>, String> type_override = Optionals .of(() -> bucket.data_schema().search_index_schema().type_override()).map(m -> buildTypeMap(m)) .orElse(Collections.emptyMap()); // If no columnar settings are specified then go with a sensible default final Optional<DataSchemaBean.ColumnarSchemaBean> maybe_user_columnar_schema = Optionals .of(() -> bucket.data_schema().columnar_schema()); final DataSchemaBean.ColumnarSchemaBean columnar_schema = maybe_user_columnar_schema .filter(__ -> columnar_enabled).filter(schema -> (null == schema.field_include_list()) && // ie the entire thing is empty (null == schema.field_exclude_list()) && (null == schema.field_include_pattern_list()) && (null == schema.field_type_include_list()) && (null == schema.field_exclude_pattern_list()) && (null == schema.field_type_exclude_list())) .map(schema -> BeanTemplateUtils.clone(schema) .with(DataSchemaBean.ColumnarSchemaBean::field_type_include_list, Arrays.asList("string", "number", "date")) .done()) .orElseGet(() -> maybe_user_columnar_schema.orElse(null)) // (NOTE: can only be null if columnar_enabled is false) ; final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> column_lookups_pretypes = Stream .of(columnar_enabled ? createFieldIncludeLookups( Optionals.ofNullable(columnar_schema.field_include_list()).stream(), fn -> getKey(fn), field_lookups, enabled_not_analyzed, enabled_analyzed, true, search_index_schema_override, type_override, mapper, index_type) : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(), columnar_enabled ? createFieldExcludeLookups( Optionals.ofNullable(columnar_schema.field_exclude_list()).stream(), fn -> getKey(fn), field_lookups, search_index_schema_override, type_override, mapper, index_type) : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(), columnar_enabled ? createFieldIncludeLookups( Optionals.ofNullable(columnar_schema.field_include_pattern_list()) .stream(), fn -> Either.right(Tuples._2T(fn, "*")), field_lookups, enabled_not_analyzed, enabled_analyzed, true, search_index_schema_override, type_override, mapper, index_type) : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(), columnar_enabled ? createFieldIncludeLookups( Optionals.ofNullable(columnar_schema.field_type_include_list()) .stream(), fn -> Either.right(Tuples._2T("*", fn)), field_lookups, enabled_not_analyzed, enabled_analyzed, true, search_index_schema_override, type_override, mapper, index_type) : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(), columnar_enabled ? createFieldExcludeLookups( Optionals.ofNullable(columnar_schema.field_exclude_pattern_list()) .stream(), fn -> Either.right(Tuples._2T(fn, "*")), field_lookups, search_index_schema_override, type_override, mapper, index_type) : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(), columnar_enabled ? createFieldExcludeLookups( Optionals.ofNullable(columnar_schema.field_type_exclude_list()) .stream(), fn -> Either.right(Tuples._2T("*", fn)), field_lookups, search_index_schema_override, type_override, mapper, index_type) : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(), // Finally add the default columnar lookups to the unmentioned strings (ensures that *_* is at the end) field_lookups.entrySet().stream() .flatMap(kv -> createFieldIncludeLookups(Stream.of(kv.getKey().toString()), __ -> kv.getKey(), field_lookups, default_not_analyzed, default_analyzed, false, search_index_schema_override, type_override, mapper, index_type))) .flatMap(x -> x).collect(Collectors.toMap(t2 -> t2._1(), t2 -> t2._2(), (v1, v2) -> v1, // (ie ignore duplicates) () -> new LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode>())); ; // Also any types that didn't map onto one of the fields or tokens: final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> column_lookups_types = type_override .entrySet().stream() // (filter - convert name/* to name/type and check if I've already created such an entry using the type map) .filter(kv -> !column_lookups_pretypes .containsKey(kv.getKey().either(s -> s, t2 -> Tuples._2T(t2._1(), kv.getValue())))) .flatMap(kv -> createFieldIncludeLookups(Stream.of(kv.getKey().toString()), __ -> kv.getKey().<Either<String, Tuple2<String, String>>>either(s -> Either.left(s), t2 -> Either.right(Tuples._2T(t2._1(), kv.getValue()))), field_lookups, default_not_analyzed, default_analyzed, false, search_index_schema_override, type_override, mapper, index_type)) .collect(Collectors.toMap(t2 -> t2._1(), t2 -> t2._2(), (v1, v2) -> v1, () -> new LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode>())); final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> column_lookups = Stream .concat(column_lookups_pretypes.entrySet().stream(), column_lookups_types.entrySet().stream()) .sorted((a, b) -> Integer.compare(sortKey(a.getKey()), sortKey(b.getKey()))) .collect(Collectors.toMap(t2 -> t2.getKey(), t2 -> t2.getValue(), (v1, v2) -> v1, () -> new LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode>())); final XContentBuilder properties = column_lookups.entrySet().stream() // properties not dynamic_templates .filter(kv -> kv.getKey().isLeft()) // overwrite with version built using columns if it exists .map(kv -> Tuples._2T(kv.getKey(), column_lookups.getOrDefault(kv.getKey(), kv.getValue()))) .reduce(Optional.of(start.startObject("properties")) // add doc_schema if it exists .map(props -> doc_schema .map(ds -> Optionals.streamOf(ds.fields(), false) .reduce(props, Lambdas.wrap_u((acc, kv) -> acc.rawField(kv.getKey(), kv.getValue().toString().getBytes())), (acc1, acc2) -> acc1 // shouldn't be possible )).orElse(props)).get(), Lambdas.wrap_u((acc, t2) -> acc.rawField(t2._1().left().value(), t2._2().toString().getBytes())), // (left by construction) (acc1, acc2) -> acc1) // (not actually possible) .endObject(); final XContentBuilder templates = column_lookups.entrySet().stream() // properties not dynamic_templates .filter(kv -> kv.getKey().isRight()) // overwrite with version built using columns if it exists .map(kv -> Tuples._2T(kv.getKey(), column_lookups.getOrDefault(kv.getKey(), kv.getValue()))) .reduce(properties.startArray("dynamic_templates"), Lambdas.wrap_u((acc, t2) -> acc.startObject() .rawField(getFieldNameFromMatchPair(t2._1().right().value()), t2._2().toString().getBytes()) // (right by construction) .endObject()), (acc1, acc2) -> acc1) // (not actually possible) .endArray(); return templates; } catch (IOException e) { //Handle in-practice-impossible "IOException" return null; } }