Example usage for java.util Optional get

List of usage examples for java.util Optional get

Introduction

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

Prototype

public T get() 

Source Link

Document

If a value is present, returns the value, otherwise throws NoSuchElementException .

Usage

From source file:com.liferay.blade.cli.util.Prompter.java

private static String _buildQuestionWithPrompt(String question, Optional<Boolean> defaultAnswer) {
    String yesDefault = "y";
    String noDefault = "n";

    if (defaultAnswer.isPresent()) {
        if (defaultAnswer.get()) {
            yesDefault = "Y";
        } else {//from  www . ja va 2 s.  c  o m
            noDefault = "N";
        }
    }

    return question + " (" + yesDefault + "/" + noDefault + ")";
}

From source file:net.fabricmc.installer.installer.LocalVersionInstaller.java

public static void install(File mcDir, IInstallerProgress progress) throws Exception {
    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle(Translator.getString("install.client.selectCustomJar"));
    fc.setFileFilter(new FileNameExtensionFilter("Jar Files", "jar"));
    if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        File inputFile = fc.getSelectedFile();

        JarFile jarFile = new JarFile(inputFile);
        Attributes attributes = jarFile.getManifest().getMainAttributes();
        String mcVersion = attributes.getValue("MinecraftVersion");
        Optional<String> stringOptional = ClientInstaller.isValidInstallLocation(mcDir, mcVersion);
        jarFile.close();/*from  www  . jav a2s  .  c om*/
        if (stringOptional.isPresent()) {
            throw new Exception(stringOptional.get());
        }
        ClientInstaller.install(mcDir, mcVersion, progress, inputFile);
    } else {
        throw new Exception("Failed to find jar");
    }

}

From source file:io.github.lxgaming.teleportbow.util.Toolbox.java

public static boolean isValidBow(ItemStack itemStack) {
    if (itemStack == null || itemStack.getType() != ItemTypes.BOW) {
        return false;
    }//from   w ww .  j a v a 2  s .  co m

    Optional<List<Enchantment>> enchantments = itemStack.get(Keys.ITEM_ENCHANTMENTS);
    if (!enchantments.isPresent() || enchantments.get().isEmpty()) {
        return false;
    }

    for (Enchantment enchantment : enchantments.get()) {
        if (enchantment.getType() == EnchantmentTypes.INFINITY && enchantment.getLevel() == 10) {
            return true;
        }
    }

    return false;
}

From source file:com.synopsys.integration.blackduck.service.model.RequestFactory.java

public static Request.Builder addBlackDuckQuery(Request.Builder requestBuilder,
        Optional<BlackDuckQuery> blackDuckQuery) {
    if (blackDuckQuery.isPresent()) {
        requestBuilder.addQueryParameter(RequestFactory.Q_PARAMETER, blackDuckQuery.get().getParameter());
    }/*from   w w  w. ja v  a2 s . c o m*/
    return requestBuilder;
}

From source file:io.github.jeddict.jpa.spec.OrderBy.java

public static OrderBy load(MemberExplorer member) {
    Optional<AnnotationExplorer> orderByOpt = member.getAnnotation(javax.persistence.OrderBy.class);
    if (orderByOpt.isPresent()) {
        OrderBy orderBy = new OrderBy();
        orderByOpt.get().getString("value")
                .ifPresent(value -> orderBy.getAttributes().addAll(OrderbyItem.process(value)));
        return orderBy;
    }/*from w  w  w  . ja  v  a2 s  .  c  om*/
    return null;
}

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

static String getApp(Request req, Response res) throws JsonProcessingException {
    LOG.debug(LoadAppRequest.resourcePattern());
    Optional<AuthHeader> authHeaderValue = getAuthInfo(req);

    String appname = req.params(":name");
    LOG.debug("deleting app {} requested by {}", appname, authHeaderValue.get().key());
    Optional<Application> maybeApp = Applications.get(appname);
    res.type("application/json");
    if (maybeApp.isPresent()) {
        // Compare application owner and requester
        validateOwner(req, maybeApp.get());

        res.status(200);//www .  j a  va 2  s.c o  m
        GetAppResponse getAppResponse = new GetAppResponse(maybeApp.get());
        getAppResponse.ok();
        String r = MAPPER.writeValueAsString(getAppResponse);
        LOG.info(r);
        return r;

    } else {
        ErrorResponse response = new ErrorResponse("No such application: " + appname);
        res.status(404);
        return MAPPER.writeValueAsString(response);
    }
}

From source file:com.ejisto.util.ContainerUtils.java

public static String extractAgentJar(String classPath) {
    String systemProperty = System.getProperty("ejisto.agent.jar.path");
    if (StringUtils.isNotBlank(systemProperty)) {
        return systemProperty;
    }/*w w  w. jav  a  2 s  .co  m*/

    final Optional<String> agentPath = Arrays.stream(classPath.split(Pattern.quote(File.pathSeparator)))
            .filter(e -> AGENT_JAR.matcher(e).matches()).findFirst();
    if (agentPath.isPresent()) {
        return Paths.get(System.getProperty("user.dir"), agentPath.get()).toString();
    }
    throw new IllegalStateException("unable to find agent jar");
}

From source file:br.com.blackhubos.eventozero.updater.assets.uploader.Uploader.java

@SuppressWarnings("unchecked")
public static Optional<Uploader> parseJsonObject(JSONObject parse, MultiTypeFormatter formatter) {

    long id = Long.MIN_VALUE;
    String name = null;//from  w  ww  .j av a  2s .com
    boolean admin = false;
    // Loop em todas entradas do JSON
    for (Map.Entry entries : (Set<Map.Entry>) parse.entrySet()) {

        Object key = entries.getKey();
        Object value = entries.getValue();
        String valueString = String.valueOf(value);
        /** Transforma o objeto em um {@link AssetUploaderInput) para usar com switch **/
        switch (AssetUploaderInput.parseObject(key)) {
        case ADMIN: {
            // Obtem o valor que indica se quem enviou era administrador
            if (formatter.canFormat(Boolean.class)) {
                Optional<Boolean> result = formatter.format(value, Boolean.class);
                if (result.isPresent())
                    admin = result.get();
            }
            break;
        }
        case ID: {
            // Obtm o ID do usurio
            id = Long.parseLong(valueString);
            break;
        }
        case LOGIN: {
            // Obtm o nome/login do usurio
            name = valueString;
            break;
        }

        default: {
            break;
        }
        }
    }
    if (id == Long.MIN_VALUE || name == null) {
        return Optional.empty();
    }
    return Optional.of(new Uploader(name, admin, id));
}

From source file:com.ejisto.core.classloading.javassist.ObjectEditor.java

private static boolean hasAlreadyBeenProcessed(FieldAccess f, String fieldName) {
    Optional<String> fieldMarker = getFieldMarker(fieldName);
    return !fieldMarker.isPresent() || Arrays.stream(f.getEnclosingClass().getDeclaredFields())
            .anyMatch(field -> field.getName().equals(fieldMarker.get()));
}

From source file:com.netflix.spinnaker.halyard.config.model.v1.security.AuthnMethod.java

public static Class<? extends AuthnMethod> translateAuthnMethodName(String authnMethodName) {
    Optional<? extends Class<?>> res = Arrays.stream(Authn.class.getDeclaredFields())
            .filter(f -> f.getName().equals(authnMethodName)).map(Field::getType).findFirst();

    if (res.isPresent()) {
        return (Class<? extends AuthnMethod>) res.get();
    } else {//from   www  . j  av  a  2 s  .  co m
        throw new IllegalArgumentException(
                "No authn method with name \"" + authnMethodName + "\" handled by halyard");
    }
}