Example usage for java.util Optional orElseThrow

List of usage examples for java.util Optional orElseThrow

Introduction

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

Prototype

public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X 

Source Link

Document

If a value is present, returns the value, otherwise throws an exception produced by the exception supplying function.

Usage

From source file:org.apache.james.sieve.jpa.JPASieveRepository.java

@Override
public ZonedDateTime getActivationDateForActiveScript(User user)
        throws StorageException, ScriptNotFoundException {
    Optional<JPASieveScript> script = findActiveSieveScript(user);
    JPASieveScript activeSieveScript = script.orElseThrow(
            () -> new ScriptNotFoundException("Unable to find active script for user " + user.asString()));
    return activeSieveScript.getActivationDateTime().toZonedDateTime();
}

From source file:org.apache.james.sieve.jpa.JPASieveRepository.java

@Override
public InputStream getActive(User user) throws ScriptNotFoundException, StorageException {
    Optional<JPASieveScript> script = findActiveSieveScript(user);
    JPASieveScript activeSieveScript = script.orElseThrow(
            () -> new ScriptNotFoundException("Unable to find active script for user " + user.asString()));
    return IOUtils.toInputStream(activeSieveScript.getScriptContent(), StandardCharsets.UTF_8);
}

From source file:org.apache.james.sieve.jpa.JPASieveRepository.java

@Override
public InputStream getScript(User user, ScriptName name) throws ScriptNotFoundException, StorageException {
    Optional<JPASieveScript> script = findSieveScript(user, name);
    JPASieveScript sieveScript = script.orElseThrow(() -> new ScriptNotFoundException(
            "Unable to find script " + name.getValue() + " for user " + user.asString()));
    return IOUtils.toInputStream(sieveScript.getScriptContent(), StandardCharsets.UTF_8);
}

From source file:org.codice.ddf.registry.federationadmin.impl.FederationAdmin.java

@Override
public String createLocalEntry(Map<String, Object> registryMap) throws FederationAdminException {

    Optional<RegistryPackageType> registryPackageOptional = registryTypeConverter.convert(registryMap);
    RegistryPackageType registryPackage = registryPackageOptional
            .orElseThrow(() -> new FederationAdminException(
                    "Error creating local registry entry. Couldn't convert registry map to a registry package."));

    if (!registryPackage.isSetHome()) {
        registryPackage.setHome(SystemBaseUrl.EXTERNAL.getBaseUrl());
    }// w  ww.j  ava 2s. com

    if (!registryPackage.isSetObjectType()) {
        registryPackage.setObjectType(RegistryConstants.REGISTRY_NODE_OBJECT_TYPE);
    }

    if (!registryPackage.isSetId()) {
        String registryPackageId = RegistryConstants.GUID_PREFIX
                + UUID.randomUUID().toString().replaceAll("-", "");
        registryPackage.setId(registryPackageId);
    }

    updateDateFields(registryPackage);

    Metacard metacard = getRegistryMetacardFromRegistryPackage(registryPackage);
    metacard.setAttribute(new AttributeImpl(RegistryObjectMetacardType.REGISTRY_LOCAL_NODE, true));
    return federationAdminService.addRegistryEntry(metacard);
}

From source file:org.codice.ddf.registry.federationadmin.impl.FederationAdmin.java

@Override
public void updateLocalEntry(Map<String, Object> registryObjectMap) throws FederationAdminException {

    Optional<RegistryPackageType> registryPackageOptional = registryTypeConverter.convert(registryObjectMap);
    RegistryPackageType registryPackage = registryPackageOptional
            .orElseThrow(() -> new FederationAdminException(
                    "Error updating local registry entry. Couldn't convert registry map to a registry package."));

    updateDateFields(registryPackage);//from ww w . j  a  va 2 s  .  c  o  m

    List<Metacard> existingMetacards = federationAdminService
            .getLocalRegistryMetacardsByRegistryIds(Collections.singletonList(registryPackage.getId()));

    if (CollectionUtils.isEmpty(existingMetacards)) {
        String message = "Error updating local registry entry. Registry metacard not found.";
        LOGGER.debug("{} Registry ID: {}", message, registryPackage.getId());
        throw new FederationAdminException(message);
    }

    if (existingMetacards.size() > 1) {
        throw new FederationAdminException(
                "Error updating local registry entry. Multiple registry metacards found.");
    }
    Metacard existingMetacard = existingMetacards.get(0);

    Metacard updateMetacard = getRegistryMetacardFromRegistryPackage(registryPackage);
    updateMetacard.setAttribute(new AttributeImpl(Metacard.ID, existingMetacard.getId()));

    federationAdminService.updateRegistryEntry(updateMetacard);
}

From source file:org.exist.launcher.Launcher.java

private void checkInstalledApps() {
    try {//w  w w .  ja  va 2 s  .co  m
        final BrokerPool pool = BrokerPool.getInstance();
        try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) {

            final XQuery xquery = pool.getXQueryService();
            final Sequence pkgs = xquery.execute(broker, "repo:list()", null);
            for (final SequenceIterator i = pkgs.iterate(); i.hasNext();) {
                final ExistRepository.Notification notification = new ExistRepository.Notification(
                        ExistRepository.Action.INSTALL, i.nextItem().getStringValue());
                Optional<ExistRepository> expathRepo = pool.getExpathRepo();
                if (expathRepo.isPresent()) {
                    update(expathRepo.get(), notification);
                    utilityPanel.update(expathRepo.get(), notification);
                }
                expathRepo.orElseThrow(() -> new XPathException("expath repository is not available."));
            }
        }
    } catch (final EXistException e) {
        System.err.println("Failed to check installed packages: " + e.getMessage());
        e.printStackTrace();
    } catch (final XPathException e) {
        System.err.println("Failed to check installed packages: " + e.getMessage());
        e.printStackTrace();
    } catch (final PermissionDeniedException e) {
        System.err.println("Failed to check installed packages: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.haiku.haikudepotserver.pkg.PkgIconServiceImpl.java

@Override
public PkgIcon storePkgIconImage(InputStream input, MediaType mediaType, Integer expectedSize,
        ObjectContext context, Pkg pkg) throws IOException, BadPkgIconException {

    Preconditions.checkArgument(null != context, "the context is not supplied");
    Preconditions.checkArgument(null != input, "the input must be provided");
    Preconditions.checkArgument(null != mediaType, "the mediaType must be provided");
    Preconditions.checkArgument(null != pkg, "the pkg must be provided");

    byte[] imageData = ByteStreams.toByteArray(new BoundedInputStream(input, ICON_SIZE_LIMIT));

    Optional<PkgIcon> pkgIconOptional;
    Integer size = null;//from  w w  w . ja  v a2 s.com

    switch (mediaType.getCode()) {

    case MediaType.MEDIATYPE_PNG:
        ImageHelper.Size pngSize = imageHelper.derivePngSize(imageData);

        if (null == pngSize) {
            LOGGER.warn(
                    "attempt to set the bitmap (png) package icon for package {}, but the size was invalid; it is not a valid png image",
                    pkg.getName());
            throw new BadPkgIconException("invalid png");
        }

        if (!pngSize.areSides(16) && !pngSize.areSides(32) && !pngSize.areSides(64)) {
            LOGGER.warn(
                    "attempt to set the bitmap (png) package icon for package {}, but the size was invalid; it must be either 32x32 or 16x16 px, but was {}",
                    pkg.getName(), pngSize.toString());
            throw new BadPkgIconException("non-square sizing or unexpected sizing");
        }

        if (null != expectedSize && !pngSize.areSides(expectedSize)) {
            LOGGER.warn(
                    "attempt to set the bitmap (png) package icon for package {}, but the size did not match the expected size",
                    pkg.getName());
            throw new BadPkgIconException("size of image was not as expected");
        }

        try {
            imageData = pngOptimizationService.optimize(imageData);
        } catch (IOException ioe) {
            throw new RuntimeException("the png optimization process has failed; ", ioe);
        }

        size = pngSize.width;
        pkgIconOptional = pkg.getPkgIcon(mediaType, pngSize.width);
        break;

    case MediaType.MEDIATYPE_HAIKUVECTORICONFILE:
        if (!imageHelper.looksLikeHaikuVectorIconFormat(imageData)) {
            LOGGER.warn(
                    "attempt to set the vector (hvif) package icon for package {}, but the data does not look like hvif",
                    pkg.getName());
            throw new BadPkgIconException();
        }
        pkgIconOptional = pkg.getPkgIcon(mediaType, null);
        break;

    default:
        throw new IllegalStateException("unhandled media type; " + mediaType.getCode());

    }

    PkgIconImage pkgIconImage;

    if (pkgIconOptional.isPresent()) {
        pkgIconImage = pkgIconOptional.get().getPkgIconImage();
    } else {
        PkgIcon pkgIcon = context.newObject(PkgIcon.class);
        pkg.addToManyTarget(Pkg.PKG_ICONS.getName(), pkgIcon, true);
        pkgIcon.setMediaType(mediaType);
        pkgIcon.setSize(size);
        pkgIconImage = context.newObject(PkgIconImage.class);
        pkgIcon.addToManyTarget(PkgIcon.PKG_ICON_IMAGES.getName(), pkgIconImage, true);
        pkgIconOptional = Optional.of(pkgIcon);
    }

    pkgIconImage.setData(imageData);
    pkg.setModifyTimestamp();
    pkg.setIconModifyTimestamp(new java.sql.Timestamp(Clock.systemUTC().millis()));
    renderedPkgIconRepository.evict(context, pkg);

    if (null != size) {
        LOGGER.info("the icon {}px for package {} has been updated", size, pkg.getName());
    } else {
        LOGGER.info("the icon for package {} has been updated", pkg.getName());
    }

    PkgIcon pkgIcon = pkgIconOptional.orElseThrow(IllegalStateException::new);

    for (Pkg subordinatePkg : pkgService.findSubordinatePkgsForMainPkg(context, pkg.getName())) {
        replicatePkgIcon(context, pkgIcon, subordinatePkg);
    }

    return pkgIcon;
}

From source file:org.kaaproject.kaa.server.control.service.DefaultControlService.java

@Override
public EndpointSpecificConfigurationDto findEndpointSpecificConfiguration(byte[] endpointKeyHash,
        Integer confSchemaVersion) {
    Optional<EndpointSpecificConfigurationDto> result;
    if (confSchemaVersion == null) {
        result = endpointSpecificConfigurationService.findActiveConfigurationByEndpointKeyHash(endpointKeyHash);
    } else {//from  www . j  ava2s.  co m
        result = endpointSpecificConfigurationService.findByEndpointKeyHashAndConfSchemaVersion(endpointKeyHash,
                confSchemaVersion);
    }
    return result.orElseThrow(() -> new NotFoundException("Endpoint specific configuration not found"));
}

From source file:org.kaaproject.kaa.server.control.service.DefaultControlService.java

@Override
public EndpointSpecificConfigurationDto deleteEndpointSpecificConfiguration(byte[] endpointKeyHash,
        Integer confSchemaVersion) {
    Optional<EndpointSpecificConfigurationDto> result;
    if (confSchemaVersion == null) {
        result = endpointSpecificConfigurationService
                .deleteActiveConfigurationByEndpointKeyHash(endpointKeyHash);
    } else {//from ww w  .j a  v  a 2s .  c  o  m
        result = endpointSpecificConfigurationService
                .deleteByEndpointKeyHashAndConfSchemaVersion(endpointKeyHash, confSchemaVersion);
    }
    EndpointSpecificConfigurationDto configuration = result
            .orElseThrow(() -> new NotFoundException("Endpoint specific configuration not found"));
    sendEndpointConfigurationRefreshMessage(configuration);
    return configuration;
}

From source file:org.kitodo.dataaccess.storage.memory.MemoryNode.java

@Override
public MemoryResult getFirst() {
    Optional<Long> first = first();
    if (first.isPresent()) {
        return get(first.orElseThrow(() -> {
            return new IllegalStateException();
        }));//  ww w  .  j  a  va 2 s  . co  m
    } else {
        return MemoryResult.EMPTY;
    }
}