Example usage for java.util Optional ifPresent

List of usage examples for java.util Optional ifPresent

Introduction

In this page you can find the example usage for java.util Optional ifPresent.

Prototype

public void ifPresent(Consumer<? super T> action) 

Source Link

Document

If a value is present, performs the given action with the value, otherwise does nothing.

Usage

From source file:org.silverpeas.core.admin.service.Admin.java

/**
 * Add the space profile instance from Silverpeas.
 *
 * @param spaceProfile/*from   www  .  java  2 s .c om*/
 * @param userId
 * @return
 * @throws AdminException
 */
@Override
public String addSpaceProfileInst(SpaceProfileInst spaceProfile, String userId) throws AdminException {
    try {
        Integer spaceId = getDriverComponentId(spaceProfile.getSpaceFatherId());
        String sSpaceProfileId = spaceProfileManager.createSpaceProfileInst(spaceProfile, spaceId);
        spaceProfile.setId(sSpaceProfileId);
        if (StringUtil.isDefined(userId)) {
            SpaceInst spaceInstFather = getSpaceInstById(spaceId);
            spaceInstFather.setUpdaterUserId(userId);
            updateSpaceInst(spaceInstFather);
        }
        // add new profile in spaces cache
        Optional<SpaceInst> spaceInst = cache.getSpaceInst(spaceId);
        spaceInst.ifPresent(s -> s.addSpaceProfileInst(spaceProfile));

        // profile 'Manager' does not need to be spread
        if (!spaceProfile.isManager()) {
            spreadInheritedSpaceProfile(spaceProfile, spaceId);
        }

        cache.opAddSpaceProfile(spaceProfile);
        return sSpaceProfileId;
    } catch (Exception e) {
        throw new AdminException(failureOnAdding(SPACE_PROFILE, spaceProfile.getName()), e);
    }
}

From source file:org.silverpeas.core.admin.service.Admin.java

@Override
public List<SpaceInstLight> getUserSpaceTreeview(String userId) throws AdminException {

    Set<String> componentsId = new HashSet<>(Arrays.asList(getAvailCompoIds(userId)));
    Set<Integer> authorizedIds = new HashSet<>(100);
    if (!componentsId.isEmpty()) {
        String componentId = componentsId.iterator().next();
        componentsId.remove(componentId);
        filterSpaceFromComponents(authorizedIds, componentsId, componentId);
    }//from   w w  w. java  2 s  . c  o  m
    String[] rootSpaceIds = getAllRootSpaceIds(userId);
    List<SpaceInstLight> treeview = new ArrayList<>(authorizedIds.size());
    for (String spaceId : rootSpaceIds) {
        int currentSpaceId = getDriverSpaceId(spaceId);
        if (authorizedIds.contains(currentSpaceId)) {
            Optional<SpaceInstLight> optionalSpace = treeCache.getSpaceInstLight(currentSpaceId);
            optionalSpace.ifPresent(s -> {
                treeview.add(s);
                addAuthorizedSpaceToTree(treeview, authorizedIds, currentSpaceId, 1);
            });
        }
    }
    return treeview;
}

From source file:org.silverpeas.core.admin.service.Admin.java

/**
 * @param spaces list of authorized spaces built by this method
 * @param componentsId list of components' id (base to get authorized spaces)
 * @param space a space candidate to be in authorized spaces list
 *///from  ww w .j  a v a 2 s .co  m
private void addAuthorizedSpace(Set<Integer> spaces, Set<String> componentsId, SpaceInstLight space) {
    if (!SpaceInst.STATUS_REMOVED.equals(space.getStatus()) && !spaces.contains(space.getLocalId())) {
        int spaceId = space.getLocalId();
        spaces.add(spaceId);
        componentsId.removeAll(treeCache.getComponentIds(spaceId));
        if (!space.isRoot()) {
            int fatherId = getDriverSpaceId(space.getFatherId());
            if (!spaces.contains(fatherId)) {
                Optional<SpaceInstLight> parent = treeCache.getSpaceInstLight(fatherId);
                parent.ifPresent(p -> addAuthorizedSpace(spaces, componentsId, p));
            }
        }
    }
}

From source file:org.silverpeas.core.admin.service.Admin.java

private void filterSpaceFromComponents(Set<Integer> spaces, Set<String> componentsId, String componentId) {
    Optional<SpaceInstLight> space = treeCache.getSpaceContainingComponent(componentId);
    space.ifPresent(s -> addAuthorizedSpace(spaces, componentsId, s));
    if (!componentsId.isEmpty()) {
        String newComponentId = componentsId.iterator().next();
        componentsId.remove(newComponentId);
        filterSpaceFromComponents(spaces, componentsId, newComponentId);
    }// w  w  w.j  av  a 2  s  . c  om
}

From source file:org.silverpeas.core.admin.service.Admin.java

@Override
public String[] getCompoId(String sComponentName) throws AdminException {
    try {/*from  ww  w .j  a v  a2 s .  com*/
        // Build the list of instanciated components with given componentName
        String[] matchingComponentIds = componentManager.getAllCompoIdsByComponentName(sComponentName);

        // check TreeCache to know if component is not removed neither into a removed space
        List<String> shortIds = new ArrayList<>();
        for (String componentId : matchingComponentIds) {
            Optional<ComponentInstLight> component = treeCache.getComponent(sComponentName + componentId);
            component.ifPresent(c -> shortIds.add(componentId));
        }
        return shortIds.toArray(new String[0]);
    } catch (Exception e) {
        throw new AdminException(failureOnGetting("instances of component", sComponentName), e);
    }
}

From source file:org.silverpeas.core.calendar.CalendarComponentDiffDescriptor.java

/**
 * Merges the detected differences into the given component.
 * @param component the component to merge.
 * @return true if something has been merged, false otherwise.
 *//*from  w  w  w.ja v a 2s .c  om*/
@SuppressWarnings("unchecked")
boolean mergeInto(CalendarComponent component) {
    Mutable<Boolean> dataMerged = Mutable.of(false);
    if (diff.containsKey(TITLE_ATTR)) {
        component.setTitle((String) diff.get(TITLE_ATTR));
        dataMerged.set(true);
    }
    if (diff.containsKey(DESCRIPTION_ATTR)) {
        component.setDescription((String) diff.get(DESCRIPTION_ATTR));
        dataMerged.set(true);
    }
    if (diff.containsKey(LOCATION_ATTR)) {
        component.setLocation((String) diff.get(LOCATION_ATTR));
        dataMerged.set(true);
    }
    if (diff.containsKey(PRIORITY_ATTR)) {
        component.setPriority((Priority) diff.get(PRIORITY_ATTR));
        dataMerged.set(true);
    }
    if (diff.containsKey(SAVE_ATTRIBUTE_ATTR)) {
        Map<String, String> attributesToSave = (Map) diff.get(SAVE_ATTRIBUTE_ATTR);
        attributesToSave.forEach((key, value) -> component.getAttributes().set(key, value));
        dataMerged.set(true);
    }
    if (diff.containsKey(REMOVE_ATTRIBUTE_ATTR)) {
        Set<String> attributesToRemove = (Set) diff.get(REMOVE_ATTRIBUTE_ATTR);
        attributesToRemove.forEach(a -> component.getAttributes().remove(a));
        dataMerged.set(true);
    }
    if (diff.containsKey(SAVE_ATTENDEE_ATTR)) {
        Set<Attendee> attendeesToSave = (Set) diff.get(SAVE_ATTENDEE_ATTR);
        attendeesToSave.forEach(a -> {
            Optional<Attendee> attendee = component.getAttendees().get(a.getId());
            if (attendee.isPresent()) {
                attendee.get().setPresenceStatus(a.getPresenceStatus());
            } else {
                component.getAttendees().add(a.cloneFor(component));
            }
        });
        dataMerged.set(true);
    }
    if (diff.containsKey(REMOVE_ATTENDEE_ATTR)) {
        Set<Attendee> attendeesToRemove = (Set) diff.get(REMOVE_ATTENDEE_ATTR);
        attendeesToRemove.forEach(atr -> component.getAttendees().removeIf(a -> a.getId().equals(atr.getId())));
        dataMerged.set(true);
    }
    if (diff.containsKey(UPDATE_ATTENDEE_STATUS_ATTR)) {
        Set<Attendee> attendeeStatusesToUpdate = (Set) diff.get(UPDATE_ATTENDEE_STATUS_ATTR);
        attendeeStatusesToUpdate.forEach(aS -> {
            Optional<Attendee> attendee = component.getAttendees().get(aS.getId());
            attendee.ifPresent(a -> a.setParticipationStatus(aS.getParticipationStatus()));
            dataMerged.set(attendee.isPresent());
        });
    }
    return dataMerged.is(true);
}

From source file:org.silverpeas.core.calendar.CalendarEventOccurrence.java

/**
 * Gets optionally an event occurrence by its identifier.
 * <p>If the occurrence exists into the persistence, it is returned. Otherwise it is generated.
 * <p>Otherwise and if start date is valid, the occurrence is generated.
 * @param id the identifier of the aimed occurrence.
 * @return an optional calendar event occurrence.
 *//*from w  ww  . j a  va2s. c  om*/
public static Optional<CalendarEventOccurrence> getById(final String id) {
    final CalendarEventOccurrenceRepository repository = CalendarEventOccurrenceRepository.get();
    final Mutable<CalendarEventOccurrence> occurrence = Mutable.ofNullable(repository.getById(id));
    if (!occurrence.isPresent()) {
        final Pair<String, Temporal> explodedId = explodeId(id);
        final String eventId = explodedId.getLeft();
        final Temporal startDate = explodedId.getRight();
        final Optional<CalendarEvent> event = Optional.ofNullable(CalendarEvent.getById(eventId));
        event.ifPresent(e -> {
            if (e.isRecurrent()) {
                final LocalDate occStartDate;
                final LocalDate occEndDate;
                if (startDate instanceof LocalDate) {
                    final LocalDate date = (LocalDate) startDate;
                    occStartDate = date.minusDays(1);
                    occEndDate = date.plusDays(1);
                } else {
                    final OffsetDateTime dateTime = (OffsetDateTime) startDate;
                    occStartDate = dateTime.minusDays(1).toLocalDate();
                    occEndDate = dateTime.plusDays(1).toLocalDate();
                }
                final List<CalendarEventOccurrence> occurrences = e.getCalendar()
                        .between(occStartDate, occEndDate).getEventOccurrences();
                occurrences.removeIf(o -> !o.getCalendarEvent().getId().equals(eventId)
                        || (!o.getStartDate().equals(startDate)));
                if (occurrences.size() == 1) {
                    occurrence.set(occurrences.get(0));
                }
            } else {
                occurrence.set(new CalendarEventOccurrence(e, e.getStartDate(), e.getEndDate()));
            }
        });
    }
    return Optional.ofNullable(occurrence.orElse(null));
}

From source file:org.silverpeas.core.importexport.ical.ical4j.ICal4JICalCodec.java

@Override
@SuppressWarnings("unchecked")
public String encode(List<CalendarEvent> events) {

    if (events == null || events.isEmpty()) {
        throw new IllegalArgumentException("The calendar events must be defined to encode them");
    }/*from   w  w w  .j  a v  a  2 s  .  c o m*/

    Calendar calendarIcs = new Calendar();
    calendarIcs.getProperties().add(new ProdId("-//Silverpeas//iCal4j 1.1//FR"));
    calendarIcs.getProperties().add(Version.VERSION_2_0);
    calendarIcs.getProperties().add(CalScale.GREGORIAN);

    // adding VTimeZone component (mandatory with Outlook)
    TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    VTimeZone tz = registry.getTimeZone("Europe/Paris").getVTimeZone();
    calendarIcs.getComponents().add(tz);

    List<VEvent> iCalEvents = new ArrayList<>();
    ByteArrayOutputStream output = new ByteArrayOutputStream(10240);
    for (CalendarEvent event : events) {
        Date startDate = iCal4JDateCodec.encode(event.getStartDate());
        Date endDate = iCal4JDateCodec.encode(event.getEndDate());
        VEvent iCalEvent;
        if (event.isOnAllDay() && startDate.equals(endDate)) {
            iCalEvent = new VEvent(startDate, event.getTitle());
        } else {
            iCalEvent = new VEvent(startDate, endDate, event.getTitle());
        }

        // Generate UID
        iCalEvent.getProperties().add(generateUid(event));

        // Add recurring data if any
        if (event.isRecurrent()) {
            Recur recur = iCal4JRecurrenceCodec.encode(event);
            iCalEvent.getProperties().add(new RRule(recur));
            iCalEvent.getProperties().add(new ExDate(iCal4JRecurrenceCodec.convertExceptionDates(event)));
        }

        // Add Description if any
        if (StringUtil.isDefined(event.getDescription())) {
            HtmlCleaner cleaner = new HtmlCleaner();
            String plainText = "";
            try {
                plainText = cleaner.cleanHtmlFragment(event.getDescription());
            } catch (Exception e) {
                // do nothing
            }
            iCalEvent.getProperties().add(new Description(plainText));
            iCalEvent.getProperties().add(new HtmlProperty(event.getDescription()));
        }

        // Add Classification
        iCalEvent.getProperties().add(new Clazz(event.getVisibilityLevel().name()));
        // Add Priority
        iCalEvent.getProperties().add(new Priority(event.getPriority().getICalLevel()));

        // Add location if any
        Optional<String> location = Optional.ofNullable(event.getLocation());
        location.ifPresent(s -> iCalEvent.getProperties().add(new Location(s)));

        // Add event URL if any
        Optional<String> url = event.getAttributes().get("url");
        if (url.isPresent()) {
            try {
                iCalEvent.getProperties().add(new Url(new URI(url.get())));
            } catch (URISyntaxException ex) {
                throw new EncodingException(ex.getMessage(), ex);
            }
        }

        // Add Categories
        TextList categoryList = new TextList(event.getCategories().asArray());
        if (!categoryList.isEmpty()) {
            iCalEvent.getProperties().add(new Categories(categoryList));
        }
        // Add attendees
        event.getAttendees().forEach(a -> {
            try {
                iCalEvent.getProperties().add(new Attendee(a.getId()));
            } catch (URISyntaxException ex) {
                throw new EncodingException("Malformed attendee URI: " + a, ex);
            }
        });

        iCalEvents.add(iCalEvent);
    }
    calendarIcs.getComponents().addAll(iCalEvents);
    CalendarOutputter outputter = new CalendarOutputter();
    try {
        outputter.output(calendarIcs, output);
        return output.toString(CharEncoding.UTF_8);
    } catch (Exception ex) {
        throw new EncodingException("The encoding of the events in iCal formatted text has failed!", ex);
    } finally {
        IOUtils.closeQuietly(output);
    }
}

From source file:org.silverpeas.core.webapi.calendar.CalendarEventRecurrenceEntity.java

protected CalendarEventRecurrenceEntity decorate(final CalendarEvent event, final ZoneId zoneId) {
    final Recurrence recurrence = event.getRecurrence();
    frequency = FrequencyEntity.from(recurrence.getFrequency());
    count = recurrence.getRecurrenceCount();
    Optional<Temporal> optionalDateTime = recurrence.getRecurrenceEndDate();
    endDate = null;//from   www .  ja v  a2s .com
    optionalDateTime.ifPresent(t -> endDate = TemporalConverter.applyByType(t, LocalDate::toString,
            dateTime -> formatDateWithOffset(event.asCalendarComponent(), dateTime, zoneId)));
    daysOfWeek = recurrence.getDaysOfWeek().stream()
            .sorted(Comparator.comparing(DayOfWeekOccurrence::dayOfWeek)).map(DayOfWeekOccurrenceEntity::from)
            .collect(Collectors.toList());
    return this;
}

From source file:org.silverpeas.core.webapi.calendar.CalendarWebManager.java

/**
 * Saves an event occurrence.<br>// w w  w. j a v a 2  s.  co m
 * This method handles also a common behavior the UI must have between each way an event is
 * saved (from a controller, a WEB service...)
 * @param occurrence the occurrence to save.
 * @param updateMethodType indicates the method of the occurrence update.
 * @param zoneId the zoneId into which dates are displayed (optional).  @return the calendar
 * event.
 */
List<CalendarEvent> saveOccurrence(final CalendarEventOccurrence occurrence,
        OccurrenceEventActionMethodType updateMethodType, final ZoneId zoneId) {
    if (!occurrence.getCalendarEvent().canBeModifiedBy(User.getCurrentRequester())) {
        throw new WebApplicationException(Response.Status.FORBIDDEN);
    }
    OccurrenceEventActionMethodType methodType = updateMethodType == null ? ALL : updateMethodType;

    final String originalTitle = occurrence.getCalendarEvent().getTitle();
    final Temporal originalStartDate = occurrence.getOriginalStartDate();

    final EventOperationResult result;
    switch (methodType) {
    case FROM:
        result = occurrence.updateSinceMe();
        break;
    case UNIQUE:
        result = occurrence.update();
        break;
    default:
        final CalendarEvent event = occurrence.getCalendarEvent();
        occurrence.asCalendarComponent().copyTo(event.asCalendarComponent());
        result = event.update();
        break;
    }

    final List<CalendarEvent> events = new ArrayList<>();
    Optional<CalendarEvent> createdEvent = result.created();
    Optional<CalendarEvent> updatedEvent = result.updated();
    Optional<CalendarEventOccurrence> updatedOccurrence = result.instance();

    updatedOccurrence.ifPresent(o -> {
        final CalendarEvent event = o.getCalendarEvent();
        successMessage("calendar.message.event.occurrence.updated.unique", originalTitle, getMessager()
                .formatDate(getDateWithOffset(event.asCalendarComponent(), originalStartDate, zoneId)));
        events.add(event);
    });

    updatedEvent.ifPresent(e -> {
        if (!createdEvent.isPresent()) {
            successMessage("calendar.message.event.updated", e.getTitle());
        } else {
            //noinspection OptionalGetWithoutIsPresent
            final Temporal endDate = e.getRecurrence().getRecurrenceEndDate().get();
            successMessage("calendar.message.event.occurrence.updated.from", e.getTitle(),
                    getMessager().formatDate(getDateWithOffset(e.asCalendarComponent(), endDate, zoneId)));
        }
        events.add(e);
    });

    createdEvent.ifPresent(e -> {
        events.add(e);
        successMessage("calendar.message.event.created", e.getTitle());
    });

    return events;
}