List of usage examples for java.util Optional map
public <U> Optional<U> map(Function<? super T, ? extends U> mapper)
From source file:org.jbb.members.impl.security.DefaultUserDetailsService.java
@Override @Transactional(readOnly = true)//from w w w . j a va 2s. c om public UserDetails loadUserByUsername(String usernameString) { if (StringUtils.isEmpty(usernameString)) { throwUserNotFoundException("Username cannot be blank"); } Username username = Username.builder().value(usernameString).build(); Optional<Member> memberData = memberService.getMemberWithUsername(username); return memberData.map(member -> getUserDetails(username, member)) .orElseGet(() -> throwUserNotFoundException( String.format("Member with username '%s' not found", username.getValue()))); }
From source file:org.lanternpowered.server.command.element.GenericArguments2.java
public static CommandElement targetedVector3d(Text key, @Nullable Vector3d defaultValue) { return delegateCompleter(vector3d(key), new Vector3dElementCompleter() { private List<String> complete(CommandContext context, Function<Vector3d, Double> function) { final Optional<Location<World>> location = context .<Location<World>>getOne(CommandContext.TARGET_BLOCK_ARG); if (location.isPresent() || defaultValue != null) { final Vector3d pos = location.map(Location::getPosition).orElse(defaultValue); return Collections.singletonList(Double.toString(function.apply(pos))); }//from w w w . ja va 2 s . com return Collections.emptyList(); } @Override protected List<String> completeX(CommandSource src, CommandContext context) { return this.complete(context, Vector3d::getX); } @Override protected List<String> completeY(CommandSource src, CommandContext context) { return this.complete(context, Vector3d::getY); } @Override protected List<String> completeZ(CommandSource src, CommandContext context) { return this.complete(context, Vector3d::getZ); } }); }
From source file:org.lanternpowered.server.command.element.GenericArguments2.java
public static CommandElement targetedRelativeVector3d(Text key, @Nullable Vector3d defaultValue) { return delegateCompleter(relativeVector3d(key), new Vector3dElementCompleter() { private List<String> complete(CommandContext context, Function<Vector3d, Double> function) { final Optional<Location<World>> location = context .<Location<World>>getOne(CommandContext.TARGET_BLOCK_ARG); if (location.isPresent() || defaultValue != null) { final Vector3d pos = location.map(Location::getPosition).orElse(defaultValue); return Collections.singletonList(Double.toString(function.apply(pos))); }//from w w w . j ava2 s .c o m return Collections.emptyList(); } @Override protected List<String> completeX(CommandSource src, CommandContext context) { return this.complete(context, Vector3d::getX); } @Override protected List<String> completeY(CommandSource src, CommandContext context) { return this.complete(context, Vector3d::getY); } @Override protected List<String> completeZ(CommandSource src, CommandContext context) { return this.complete(context, Vector3d::getZ); } }); }
From source file:org.omegat.gui.issues.IssuesPanelController.java
void viewSelectedIssueDetail() { Optional<IIssue> issue = getSelectedIssue(); issue.map(IIssue::getDetailComponent).ifPresent(comp -> { if (Preferences.isPreference(Preferences.PROJECT_FILES_USE_FONT)) { Font font = Core.getMainWindow().getApplicationFont(); StaticUIUtils.visitHierarchy(comp, c -> c instanceof JTextComponent, c -> c.setFont(font)); }// ww w .ja va 2 s . c om panel.outerSplitPane.setBottomComponent(comp); }); panel.jumpButton.setEnabled(issue.isPresent()); }
From source file:org.onosproject.net.intent.impl.compiler.PathCompiler.java
/** * Compiles an intent down to flows.// w ww . j ava 2 s.c o m * * @param creator how to create the flows * @param intent intent to process * @param flows list of generated flows * @param devices list of devices that correspond to the flows */ public void compile(PathCompilerCreateFlow<T> creator, PathIntent intent, List<T> flows, List<DeviceId> devices) { // Note: right now recompile is not considered // TODO: implement recompile behavior List<Link> links = intent.path().links(); Optional<EncapsulationConstraint> encapConstraint = intent.constraints().stream() .filter(constraint -> constraint instanceof EncapsulationConstraint) .map(x -> (EncapsulationConstraint) x).findAny(); //if no encapsulation or is involved only a single switch use the default behaviour if (!encapConstraint.isPresent() || links.size() == 2) { for (int i = 0; i < links.size() - 1; i++) { ConnectPoint ingress = links.get(i).dst(); ConnectPoint egress = links.get(i + 1).src(); creator.createFlow(intent.selector(), intent.treatment(), ingress, egress, intent.priority(), isLast(links, i), flows, devices); } return; } encapConstraint.map(EncapsulationConstraint::encapType).map(type -> { switch (type) { case VLAN: manageVlanEncap(creator, flows, devices, intent); break; case MPLS: manageMplsEncap(creator, flows, devices, intent); break; default: // Nothing to do } return 0; }); }
From source file:org.onosproject.net.intent.impl.IntentInstaller.java
/** * Tests if one of {@code toUninstall} or {@code toInstall} contains * installable Intent of type specified by {@code intentClass}. * * @param toUninstall IntentData to test * @param toInstall IntentData to test * @param intentClass installable Intent class * @return true if at least one of IntentData contains installable specified. *//*from w w w.jav a 2 s .c o m*/ private boolean isInstallable(Optional<IntentData> toUninstall, Optional<IntentData> toInstall, Class<? extends Intent> intentClass) { return Stream .concat(toInstall.map(IntentData::installables).map(Collection::stream).orElse(Stream.empty()), toUninstall.map(IntentData::installables).map(Collection::stream).orElse(Stream.empty())) .anyMatch(i -> intentClass.isAssignableFrom(i.getClass())); }
From source file:org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler.java
/** * Transform received command using the transformation. * * In case of JSON as transformation output, the output processed using {@link processJsonTransform}. * * @param channelUID channel UID corresponding to received command * @param command command to be transformed * @return transformed command. Null is returned with JSON transformation outputs and configuration errors * * @see processJsonTransform/*from w ww . j a va 2 s . co m*/ */ private @Nullable Optional<Command> transformCommandAndProcessJSON(ChannelUID channelUID, Command command) { String transformOutput; Optional<Command> transformedCommand; Transformation writeTransformation = this.writeTransformation; if (writeTransformation == null || writeTransformation.isIdentityTransform()) { transformedCommand = Optional.of(command); } else { transformOutput = writeTransformation.transform(bundleContext, command.toString()); if (transformOutput.contains("[")) { processJsonTransform(command, transformOutput); return null; } else if (transformationOnlyInWrite) { logger.error( "Thing {} seems to have writeTransformation but no other write parameters. Since the transformation did not return a JSON for command '{}' (channel {}), this is a configuration error.", getThing().getUID(), command, channelUID); updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format( "Seems to have writeTransformation but no other write parameters. Since the transformation did not return a JSON for command '%s' (channel %s), this is a configuration error", command, channelUID)); return null; } else { transformedCommand = Transformation.tryConvertToCommand(transformOutput); logger.trace("Converted transform output '{}' to command '{}' (type {})", transformOutput, transformedCommand.map(c -> c.toString()).orElse("<conversion failed>"), transformedCommand.map(c -> c.getClass().getName()).orElse("<conversion failed>")); } } return transformedCommand; }
From source file:org.opensingular.form.wicket.feedback.SValidationFeedbackPanel.java
protected Component newMessageDisplayComponent(String id, IModel<IValidationError> error) { final Component component = new Label(id, $m.map(error, IValidationError::getMessage)); component.setEscapeModelStrings(SValidationFeedbackPanel.this.getEscapeModelStrings()); component.add($b.classAppender($m.map(error, this::getCSSClass))); final Label label = (Label) component; if (error instanceof SFeedbackMessage) { final SFeedbackMessage bfm = (SFeedbackMessage) error; final SInstance instance = bfm.getInstanceModel().getObject(); final SInstance parentContext = WicketFormUtils.resolveInstance(getFence().getMainContainer()) .orElse(null);/* w w w. j av a 2 s.c o m*/ final Optional<Component> reporter = WicketFormUtils.findChildByInstance(getFence().getMainContainer(), instance); final String labelPath = StringUtils.defaultString( reporter.map(it -> WicketFormUtils.generateTitlePath(getFence().getMainContainer(), parentContext, it, instance)).orElse(null), SFormUtil.generatePath(instance, it -> Objects.equals(it, parentContext))); label.setDefaultModelObject(labelPath + " : " + bfm.getMessage()); } return component; }
From source file:org.sakaiproject.gradebookng.tool.actions.GradeUpdateAction.java
@Override public ActionResponse handleEvent(final JsonNode params, final AjaxRequestTarget target) { final GradebookPage page = (GradebookPage) target.getPage(); // clear the feedback message at the top of the page target.addChildren(page, FeedbackPanel.class); final String rawOldGrade = params.get("oldScore").textValue(); final String rawNewGrade = params.get("newScore").textValue(); if (StringUtils.isNotBlank(rawNewGrade) && (!NumberUtil.isValidLocaleDouble(rawNewGrade) || FormatHelper.validateDouble(rawNewGrade) < 0)) { target.add(page.updateLiveGradingMessage(page.getString("feedback.error"))); return new ArgumentErrorResponse("Grade not valid"); }/*from ww w .ja v a 2 s .c om*/ final String oldGrade = FormatHelper.formatGradeFromUserLocale(rawOldGrade); final String newGrade = FormatHelper.formatGradeFromUserLocale(rawNewGrade); final String assignmentId = params.get("assignmentId").asText(); final String studentUuid = params.get("studentId").asText(); final String categoryId = params.has("categoryId") ? params.get("categoryId").asText() : null; // We don't pass the comment from the use interface, // but the service needs it otherwise it will assume 'null' // so pull it back from the service and poke it in there! final String comment = businessService.getAssignmentGradeComment(Long.valueOf(assignmentId), studentUuid); // for concurrency, get the original grade we have in the UI and pass it into the service as a check final GradeSaveResponse result = businessService.saveGrade(Long.valueOf(assignmentId), studentUuid, oldGrade, newGrade, comment); if (result.equals(GradeSaveResponse.NO_CHANGE)) { target.add(page.updateLiveGradingMessage(page.getString("feedback.saved"))); return new SaveGradeNoChangeResponse(); } if (!result.equals(GradeSaveResponse.OK) && !result.equals(GradeSaveResponse.OVER_LIMIT)) { target.add(page.updateLiveGradingMessage(page.getString("feedback.error"))); return new SaveGradeErrorResponse(result); } final CourseGrade studentCourseGrade = businessService.getCourseGrade(studentUuid); boolean isOverride = false; String grade = "-"; String points = "0"; if (studentCourseGrade != null) { final GradebookUiSettings uiSettings = page.getUiSettings(); final Gradebook gradebook = businessService.getGradebook(); final CourseGradeFormatter courseGradeFormatter = new CourseGradeFormatter(gradebook, page.getCurrentRole(), businessService.isCourseGradeVisible(businessService.getCurrentUser().getId()), uiSettings.getShowPoints(), true); grade = courseGradeFormatter.format(studentCourseGrade); if (studentCourseGrade.getPointsEarned() != null) { points = FormatHelper.formatDoubleToDecimal(studentCourseGrade.getPointsEarned()); } if (studentCourseGrade.getEnteredGrade() != null) { isOverride = true; } } Optional<CategoryScoreData> catData = categoryId == null ? Optional.empty() : businessService.getCategoryScoreForStudent(Long.valueOf(categoryId), studentUuid, true); String categoryScore = catData.map(c -> String.valueOf(c.score)).orElse("-"); List<Long> droppedItems = catData.map(c -> c.droppedItems).orElse(Collections.emptyList()); target.add(page.updateLiveGradingMessage(page.getString("feedback.saved"))); return new GradeUpdateResponse(result.equals(GradeSaveResponse.OVER_LIMIT), grade, points, isOverride, categoryScore, droppedItems); }
From source file:org.sakaiproject.sitestats.impl.event.detailed.refresolvers.AssignmentReferenceResolver.java
/** * Resolves an event reference into meaningful details * @param ref the event reference//from w w w . ja v a 2 s . co m * @param asnServ the assignment service * @param siteServ the site service * @return one of the AssignmentsData variants, or ResolvedEventData.ERROR/PERM_ERROR */ public static ResolvedEventData resolveReference(String ref, AssignmentService asnServ, SiteService siteServ) { if (StringUtils.isBlank(ref) || asnServ == null || siteServ == null) { log.warn("Cannot resolve reference. Reference is null/empty or service(s) are not initialized."); return ResolvedEventData.ERROR; } AssignmentReferenceReckoner.AssignmentReference asnRef = AssignmentReferenceReckoner.reckoner() .reference(ref).reckon(); try { if (AssignmentServiceConstants.REF_TYPE_ASSIGNMENT.equals(asnRef.getSubtype())) { Assignment asn = asnServ.getAssignment(asnRef.getId()); if (asn != null) { boolean anon = asnServ.assignmentUsesAnonymousGrading(asn); return new AssignmentData(asn.getTitle(), anon, asn.getDeleted()); } } else if (AssignmentServiceConstants.REF_TYPE_SUBMISSION.equals(asnRef.getSubtype())) { AssignmentSubmission sub = asnServ.getSubmission(asnRef.getId()); if (sub == null) { return ResolvedEventData.ERROR; } Assignment asn = sub.getAssignment(); boolean anon = asnServ.assignmentUsesAnonymousGrading(asn); AssignmentData asnData = new AssignmentData(asn.getTitle(), anon, asn.getDeleted()); Set<AssignmentSubmissionSubmitter> submitters = sub.getSubmitters(); boolean byInstructor = false; if (submitters.isEmpty()) { log.warn("No submitters found for submission id " + sub.getId()); return ResolvedEventData.ERROR; } String submitter = submitters.stream().filter(s -> s.getSubmittee()).findFirst() .map(s -> s.getSubmitter()).orElse(""); if (submitter.isEmpty()) { byInstructor = true; if (submitters.size() == 1) { submitter = submitters.stream().findFirst().map(s -> s.getSubmitter()).orElse(""); } } String group = ""; String groupId = StringUtils.trimToEmpty(sub.getGroupId()); if (!groupId.isEmpty()) { // get the group title Optional<Site> site = RefResolverUtils.getSiteByID(asnRef.getContext(), siteServ, log); group = site.map(s -> s.getGroup(groupId)).map(g -> g.getTitle()).orElse(""); } if (group.isEmpty()) { if (submitter.isEmpty()) { log.warn("No submitter found for submission id " + sub.getId()); return ResolvedEventData.ERROR; } return new SubmissionData(asnData, submitter, byInstructor); } else { return new GroupSubmissionData(asnData, group, submitter, byInstructor); } } } catch (IdUnusedException iue) { log.warn("Unable to retrieve assignment/submission.", iue); } catch (PermissionException pe) { log.warn("Permission exception trying to retrieve assignment/submssion.", pe); return ResolvedEventData.PERM_ERROR; } log.warn("Unable to retrieve data; ref = " + ref); return ResolvedEventData.ERROR; }