Example usage for java.util Optional isPresent

List of usage examples for java.util Optional isPresent

Introduction

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

Prototype

public boolean isPresent() 

Source Link

Document

If a value is present, returns true , otherwise false .

Usage

From source file:io.github.retz.scheduler.MesosHTTPFetcher.java

public static Optional<String> sandboxUri(String t, String master, String slaveId, String frameworkId,
        String executorId) {/* www  .  j  ava2 s  .  c  om*/

    Optional<String> slaveAddr = fetchSlaveAddr(master, slaveId); // get master:5050/slaves with slaves/pid, cut with '@'
    LOG.debug("Agent address of executor {}: {}", executorId, slaveAddr);

    if (!slaveAddr.isPresent()) {
        return Optional.empty();
    }

    Optional<String> dir = fetchDirectory(slaveAddr.get(), frameworkId, executorId);
    if (!dir.isPresent()) {
        return Optional.empty();
    }

    try {
        return Optional.of(String.format("http://%s/files/%s?path=%s", slaveAddr.get(), t,
                java.net.URLEncoder.encode(dir.get(), //builder.toString(),
                        java.nio.charset.StandardCharsets.UTF_8.toString())));
    } catch (UnsupportedEncodingException e) {
        return Optional.empty();
    }
}

From source file:io.github.retz.web.JobRequestHandler.java

private static Optional<Job> getJobAndVerify(Request req) throws IOException {
    int id = Integer.parseInt(req.params(":id"));
    Optional<AuthHeader> authHeaderValue = WebConsole.getAuthInfo(req);

    if (!authHeaderValue.isPresent()) {
        LOG.debug("Authorization header lacking?");
        return Optional.empty();
    }//from  w  w w  . j  a  v a2 s.c  o m
    LOG.debug("get-xxx id={}, user={}", id, authHeaderValue.get().key());

    Optional<AppJobPair> maybePair = Database.getInstance().getAppJob(id);
    if (maybePair.isPresent()) {
        AppJobPair pair = maybePair.get();
        if (pair.application().getOwner().equals(authHeaderValue.get().key())) {
            return Optional.of(pair.job());
        }
    }
    return Optional.empty();
}

From source file:com.spectralogic.ds3contractcomparator.print.htmlprinter.generators.row.ModifiedHtmlRowGenerator.java

/**
 * Recursively traverses two objects using reflection and constructs the modified
 * rows that represent the changes and differences between the objects.
 *///from ww  w. j  a  va 2  s .c o  m
public static <T> ImmutableList<Row> createModifiedRows(final T oldObject, final T newObject,
        final int indent) {
    if (oldObject == null && newObject == null) {
        return ImmutableList.of();
    }
    final Field[] fields = getFields(oldObject, newObject);
    final ImmutableList.Builder<Row> builder = ImmutableList.builder();

    for (final Field field : fields) {
        final String property = field.getName();

        final Optional<String> oldValue = getPropertyValue(oldObject, property);
        final Optional<String> newValue = getPropertyValue(newObject, property);

        if (oldValue.isPresent() || newValue.isPresent()) {
            final int fieldIndent = toModifiedFieldIndent(indent, oldObject, newObject, field);
            if (field.getType() == ImmutableList.class) {
                //Field is a list, recursively print each element in the list
                builder.add(new NoChangeRow(fieldIndent, property, ""));

                final ImmutableList<Object> oldObjList = getListPropertyFromObject(field, oldObject);
                final ImmutableList<Object> newObjList = getListPropertyFromObject(field, newObject);

                if (hasContent(oldObjList) || hasContent(newObjList)) {
                    final String uniqueProperty = getPropertyNameFromList(oldObjList, newObjList);

                    final ImmutableSet<String> parameterUnion = toPropertyUnion(oldObjList, newObjList,
                            uniqueProperty);
                    final ImmutableMap<String, Object> oldMap = toPropertyMap(oldObjList, uniqueProperty);
                    final ImmutableMap<String, Object> newMap = toPropertyMap(newObjList, uniqueProperty);

                    parameterUnion.forEach(param -> builder
                            .addAll(createModifiedRows(oldMap.get(param), newMap.get(param), fieldIndent + 1)));
                }
            } else if (oldValue.isPresent() && newValue.isPresent() && oldValue.get().equals(newValue.get())) {
                //Element is the same in both contracts
                builder.add(new NoChangeRow(fieldIndent, property, oldValue.get()));
            } else {
                //Element is different between old and new contracts
                builder.add(new ModifiedRow(fieldIndent, property, oldValue.orElse(RowConstants.NA),
                        newValue.orElse(RowConstants.NA)));
            }
        }
    }
    return builder.build();
}

From source file:com.skelril.skree.content.registry.item.zone.ZoneItemUtil.java

public static boolean playerAlreadyHasInvite(ItemStack stack, Player target) {
    UUID zoneID = getZoneID(stack).orElseThrow(() -> new IllegalArgumentException("Illegal zone ItemStack"));
    ItemStack[] inv = tf(target).inventory.mainInventory;
    for (ItemStack aStack : inv) {
        Optional<UUID> optZoneID = getZoneID(aStack);
        if (optZoneID.isPresent()) {
            if (zoneID.equals(optZoneID.get())) {
                return true;
            }/*from w ww .ja  v  a  2s  .  c om*/
        }
    }
    return false;
}

From source file:com.skelril.skree.content.registry.item.zone.ZoneItemUtil.java

public static boolean notifyGroupOwner(ItemStack stack, Player holder, boolean joined) {
    Validate.isTrue(isZoneSlaveItem(stack));
    Optional<Player> optPlayer = getGroupOwner(stack);
    if (optPlayer.isPresent()) {
        Player player = optPlayer.get();
        if (joined) {
            if (incrementCount(stack, player)) {
                player.sendMessage(//from   w  ww .j  a v  a 2s.co m
                        Text.of(TextColors.GOLD, holder.getName() + " has accepted your invitation."));
            }
        } else {
            if (!isAttuned(stack) || decrementCount(stack, player)) {
                player.sendMessage(
                        Text.of(TextColors.RED, holder.getName() + " has declined your invitation."));
            }
        }
        return true;
    }
    return false;
}

From source file:net.fabricmc.loom.task.DownloadTask.java

public static void downloadMcJson(LoomGradleExtension extension, Logger logger) throws IOException {
    if (!Constants.MINECRAFT_JSON.get(extension).exists()) {
        logger.lifecycle(":downloading minecraft json");
        FileUtils.copyURLToFile(new URL("https://launchermeta.mojang.com/mc/game/version_manifest.json"),
                Constants.VERSION_MANIFEST.get(extension));
        ManifestVersion mcManifest = new GsonBuilder().create().fromJson(
                FileUtils.readFileToString(Constants.VERSION_MANIFEST.get(extension), "UTF-8"),
                ManifestVersion.class);

        Optional<ManifestVersion.Versions> optionalVersion = mcManifest.versions.stream()
                .filter(versions -> versions.id.equalsIgnoreCase(extension.version)).findFirst();
        if (optionalVersion.isPresent()) {
            FileUtils.copyURLToFile(new URL(optionalVersion.get().url),
                    Constants.MINECRAFT_JSON.get(extension));
        } else {/*from  ww w .  j  a v  a 2  s. c  o  m*/
            logger.info(":failed downloading minecraft json");
            throw new RuntimeException("Failed downloading Minecraft json");
        }
    }
}

From source file:com.spotify.styx.docker.KubernetesPodEventTranslator.java

private static Optional<Event> isInErrorState(WorkflowInstance workflowInstance, Pod pod) {
    final PodStatus status = pod.getStatus();
    final String phase = status.getPhase();

    switch (phase) {
    case "Pending":
        // check if one or more docker contains failed to pull their image, a possible silent error
        return status.getContainerStatuses().stream()
                .filter(IS_STYX_CONTAINER.and(KubernetesPodEventTranslator::hasPullImageError)).findAny()
                .map((x) -> Event.runError(workflowInstance,
                        "One or more containers failed to pull their image"));

    case "Succeeded":
    case "Failed":
        final Optional<ContainerStatus> containerStatusOpt = pod.getStatus().getContainerStatuses().stream()
                .filter(IS_STYX_CONTAINER).findFirst();

        if (!containerStatusOpt.isPresent()) {
            return Optional.of(Event.runError(workflowInstance, "Could not find our container in pod"));
        }// w  w  w  .  j av a  2 s.  c o m

        final ContainerStatus containerStatus = containerStatusOpt.get();
        final ContainerStateTerminated terminated = containerStatus.getState().getTerminated();
        if (terminated == null) {
            return Optional.of(Event.runError(workflowInstance, "Unexpected null terminated status"));
        }
        return Optional.empty();

    case "Unknown":
        return Optional.of(Event.runError(workflowInstance, "Pod entered Unknown phase"));

    default:
        return Optional.empty();
    }
}

From source file:info.archinnov.achilles.internals.parser.CodecFactory.java

public static CodecContext buildCodecContext(AptUtils aptUtils, AnnotationMirror codecFromType) {
    Optional<Class<Codec>> codecClassO = getElementValueClass(codecFromType, "value", false);
    if (codecClassO.isPresent()) {
        Class<Codec> codecClass = codecClassO.get();
        List<Type> genericTypes = Arrays.asList(codecClass.getGenericInterfaces());

        final List<TypeName> codecTypes = genericTypes.stream().filter(x -> x instanceof ParameterizedType)
                .map(x -> (ParameterizedType) x)
                .filter(x -> x.getRawType().getTypeName()
                        .equals(info.archinnov.achilles.type.codec.Codec.class.getCanonicalName()))
                .flatMap(x -> Arrays.asList(x.getActualTypeArguments()).stream()).map(TypeName::get)
                .collect(Collectors.toList());
        aptUtils.validateTrue(codecTypes.size() == 2,
                "Codec class '%s' should have 2 parameters: Codec<FROM, TO>", codecClass);
        return new CodecContext(ClassName.get(codecClass), codecTypes.get(0), codecTypes.get(1));
    } else {/*from  www.j a v a  2  s. c  om*/
        return buildCodecContext(aptUtils, getElementValueClassName(codecFromType, "value", false).toString());
    }
}

From source file:io.github.retz.web.JobRequestRouter.java

public static String getFile(spark.Request req, spark.Response res) throws IOException {
    int id = Integer.parseInt(req.params(":id"));

    String file = req.queryParams("path");
    long offset = Long.parseLong(req.queryParams("offset"));
    long length = Long.parseLong(req.queryParams("length"));
    Optional<Job> job = JobQueue.getJob(id);

    LOG.debug("get-file: id={}, path={}, offset={}, length={}", id, file, offset, length);
    res.type("application/json");

    Optional<FileContent> fileContent;
    if (job.isPresent() && job.get().url() != null // If url() is null, the job hasn't yet been started at Mesos
            && statHTTPFile(job.get().url(), file)) {
        String payload = fetchHTTPFile(job.get().url(), file, offset, length);
        LOG.debug("Payload length={}, offset={}", payload.length(), offset);
        // TODO: what the heck happens when a file is not UTF-8 encodable???? How Mesos works?
        fileContent = Optional.ofNullable(MAPPER.readValue(payload, FileContent.class));
    } else {//  w  w  w.  j  a v  a 2  s. c  o m
        fileContent = Optional.empty();
    }
    GetFileResponse getFileResponse = new GetFileResponse(job, fileContent);
    getFileResponse.ok();
    res.status(200);

    return MAPPER.writeValueAsString(getFileResponse);
}

From source file:com.github.horrorho.inflatabledonkey.file.FileStreamWriter.java

public static boolean copy(InputStream in, OutputStream out, Optional<XFileKey> keyCipher,
        Optional<byte[]> signature, Optional<IOFunction<InputStream, InputStream>> decompress)
        throws IOException {

    Digest digest = signature.flatMap(FileSignature::type).orElse(FileSignature.ONE).newDigest();

    DigestInputStream dis = new DigestInputStream(in, digest);

    InputStream fis = decryptStream(dis, keyCipher);

    if (decompress.isPresent()) {
        logger.info("-- copy() - decompressing");
        fis = decompress.get().apply(fis);
    }//from  ww  w  .  ja  v a 2  s  .c om

    IOUtils.copyLarge(fis, out, new byte[BUFFER_SIZE]);
    out.flush();

    return testSignature(dis.getDigest(), signature);
}