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:info.archinnov.achilles.internals.parser.FunctionParser.java

public static List<FunctionSignature> parseFunctionRegistryAndValidateTypes(AptUtils aptUtils, TypeElement elm,
        GlobalParsingContext context) {/*from w  w  w.  j  av a  2s.c  o m*/
    final List<ExecutableElement> methods = ElementFilter.methodsIn(elm.getEnclosedElements());
    final Optional<String> keyspace = AnnotationTree.findKeyspaceForFunctionRegistry(aptUtils, elm);
    final FunctionParamParser paramParser = new FunctionParamParser(aptUtils);

    final TypeName parentType = TypeName.get(aptUtils.erasure(elm));

    //Not allow to declare function in system keyspaces
    if (keyspace.isPresent()) {
        final String keyspaceName = keyspace.get();
        aptUtils.validateFalse(
                FORBIDDEN_KEYSPACES.contains(keyspaceName)
                        || FORBIDDEN_KEYSPACES.contains(keyspaceName.toLowerCase()),
                "The provided keyspace '%s' on function registry class '%s' is forbidden because it is a system keyspace",
                keyspaceName, parentType);
    }

    aptUtils.validateFalse(keyspace.isPresent() && isBlank(keyspace.get()),
            "The declared keyspace for function registry '%s' should not be blank",
            elm.getSimpleName().toString());

    return methods.stream().map(method -> {
        final String methodName = method.getSimpleName().toString();
        final List<AnnotationTree> annotationTrees = AnnotationTree.buildFromMethodForParam(aptUtils, method);
        final List<? extends VariableElement> parameters = method.getParameters();
        final List<FunctionParamSignature> parameterSignatures = new ArrayList<>(parameters.size());
        for (int i = 0; i < parameters.size(); i++) {
            final VariableElement parameter = parameters.get(i);
            context.nestedTypesStrategy.validate(aptUtils, annotationTrees.get(i), method.toString(),
                    parentType);
            final FunctionParamSignature functionParamSignature = paramParser.parseParam(context,
                    annotationTrees.get(i), parentType, methodName, parameter.getSimpleName().toString());
            parameterSignatures.add(functionParamSignature);
        }

        //Validate return type
        final TypeMirror returnType = method.getReturnType();
        aptUtils.validateFalse(returnType.getKind() == TypeKind.VOID,
                "The return type for the method '%s' on class '%s' should not be VOID", method.toString(),
                elm.getSimpleName().toString());

        aptUtils.validateFalse(returnType.getKind().isPrimitive(),
                "Due to internal JDK API limitations, UDF/UDA return types cannot be primitive. "
                        + "Use their Object counterpart instead for method '%s' " + "in function registry '%s'",
                method.toString(), elm.getQualifiedName());

        final FunctionParamSignature returnTypeSignature = paramParser.parseParam(context,
                AnnotationTree.buildFromMethodForReturnType(aptUtils, method), parentType, methodName,
                "returnType");

        // Validate NOT system function comparing only name lowercase
        aptUtils.validateFalse(SYSTEM_FUNCTIONS_NAME.contains(methodName.toLowerCase()),
                "The name of the function '%s' in class '%s' is reserved for system functions", method,
                parentType);

        return new FunctionSignature(keyspace, parentType, methodName, returnTypeSignature,
                parameterSignatures);
    }).collect(toList());
}

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

public static void setMasterToZone(ItemStack stack, String zone) {
    Optional<ZoneService> optService = Sponge.getServiceManager().provide(ZoneService.class);

    if (optService.isPresent()) {
        ZoneService service = optService.get();

        if (stack.getTagCompound() == null) {
            stack.setTagCompound(new NBTTagCompound());
        }//from w  w w. jav  a2  s . c o  m

        if (!stack.getTagCompound().hasKey("skree_zone_data")) {
            stack.getTagCompound().setTag("skree_zone_data", new NBTTagCompound());
        }

        NBTTagCompound tag = stack.getTagCompound().getCompoundTag("skree_zone_data");
        tag.setString("zone", zone);
        tag.setInteger("zone_player_count", 1);
        tag.setInteger("zone_max_players", service.getMaxGroupSize(zone).orElse(-1));
        tag.setString("zone_id", UUID.randomUUID().toString());

        attune(stack);
    }
}

From source file:io.github.lxgaming.teleportbow.managers.CommandManager.java

public static CommandResult process(AbstractCommand abstractCommand, CommandSource commandSource,
        String message) {/*  w w  w . j av a 2  s .c  o  m*/
    Optional<List<String>> arguments = getArguments(message).map(Toolbox::newArrayList);
    if (!arguments.isPresent()) {
        commandSource
                .sendMessage(Text.of(Toolbox.getTextPrefix(), TextColors.RED, "Failed to collect arguments"));
        return CommandResult.empty();
    }

    Optional<AbstractCommand> command = getCommand(abstractCommand, arguments.get());
    if (!command.isPresent()) {
        return CommandResult.empty();
    }

    if (!command.get().testPermission(commandSource)) {
        commandSource.sendMessage(Text.of(Toolbox.getTextPrefix(), TextColors.RED,
                "You do not have permission to execute this command"));
        return CommandResult.empty();
    }

    TeleportBow.getInstance().getLogger().debug("Processing {} for {}",
            command.get().getPrimaryAlias().orElse("Unknown"), commandSource.getName());
    return command.get().execute(commandSource, arguments.get());
}

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);
    }// ww  w  .  j  ava2 s  . c  o  m

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

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

From source file:net.sf.jabref.gui.desktop.JabRefDesktop.java

/**
 * Open a http/pdf/ps viewer for the given link string.
 *///from   w  w w .  ja  va  2s . c o m
public static void openExternalViewer(BibDatabaseContext databaseContext, String initialLink,
        String initialFieldName) throws IOException {
    String link = initialLink;
    String fieldName = initialFieldName;
    if ("ps".equals(fieldName) || "pdf".equals(fieldName)) {
        // Find the default directory for this field type:
        List<String> dir = databaseContext.getFileDirectory(fieldName);

        Optional<File> file = FileUtil.expandFilename(link, dir);

        // Check that the file exists:
        if (!file.isPresent() || !file.get().exists()) {
            throw new IOException("File not found (" + fieldName + "): '" + link + "'.");
        }
        link = file.get().getCanonicalPath();

        // Use the correct viewer even if pdf and ps are mixed up:
        String[] split = file.get().getName().split("\\.");
        if (split.length >= 2) {
            if ("pdf".equalsIgnoreCase(split[split.length - 1])) {
                fieldName = "pdf";
            } else if ("ps".equalsIgnoreCase(split[split.length - 1])
                    || ((split.length >= 3) && "ps".equalsIgnoreCase(split[split.length - 2]))) {
                fieldName = "ps";
            }
        }
    } else if (FieldName.DOI.equals(fieldName)) {
        Optional<DOI> doiUrl = DOI.build(link);
        if (doiUrl.isPresent()) {
            link = doiUrl.get().getURIAsASCIIString();
        }
        // should be opened in browser
        fieldName = FieldName.URL;
    } else if ("eprint".equals(fieldName)) {
        fieldName = FieldName.URL;

        // Check to see if link field already contains a well formated URL
        if (!link.startsWith("http://")) {
            link = ARXIV_LOOKUP_PREFIX + link;
        }
    }

    if (FieldName.URL.equals(fieldName)) { // html
        try {
            openBrowser(link);
        } catch (IOException e) {
            LOGGER.error("Error opening file '" + link + "'", e);
            // TODO: should we rethrow the exception?
            // In BasePanel.java, the exception is catched and a text output to the frame
            // throw e;
        }
    } else if ("ps".equals(fieldName)) {
        try {
            NATIVE_DESKTOP.openFile(link, "ps");
        } catch (IOException e) {
            LOGGER.error("An error occured on the command: " + link, e);
        }
    } else if ("pdf".equals(fieldName)) {
        try {
            NATIVE_DESKTOP.openFile(link, "pdf");
        } catch (IOException e) {
            LOGGER.error("An error occured on the command: " + link, e);
        }
    } else {
        LOGGER.info("Message: currently only PDF, PS and HTML files can be opened by double clicking");
    }
}

From source file:gmailclientfx.core.GmailClient.java

public static void authorizeUser() throws IOException {

    FLOW = new GoogleAuthorizationCodeFlow.Builder(TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, SCOPES)
            //.setApprovalPrompt("select_account")
            .setAccessType("offline").build();

    String url = FLOW.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
    String txtURI = url + "&prompt=select_account";
    String code = "";

    if (Desktop.isDesktopSupported()) {
        try {//from w w w  . j a  v  a2s  . c o  m
            Desktop.getDesktop().browse(new URI(txtURI));

            TextInputDialog dialog = new TextInputDialog();
            dialog.setTitle("Verifikacija");
            dialog.setHeaderText(null);
            dialog.setContentText("Unesite verifikacijski kod: ");

            Optional<String> result = dialog.showAndWait();
            if (result.isPresent()) {
                code = result.get();
            }
        } catch (URISyntaxException ex) {
            Logger.getLogger(GmailClient.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Greska prilikom logiranja!");
        }
    }

    GoogleTokenResponse tokenResponse = FLOW.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
    CREDENTIAL = new GoogleCredential.Builder().setTransport(TRANSPORT).setJsonFactory(JSON_FACTORY)
            .setClientSecrets(CLIENT_ID, CLIENT_SECRET).addRefreshListener(new CredentialRefreshListener() {
                @Override
                public void onTokenResponse(Credential credential, TokenResponse tokenResponse) {
                    // Handle success.
                }

                @Override
                public void onTokenErrorResponse(Credential credential, TokenErrorResponse tokenErrorResponse) {
                    // Handle error.
                }
            }).build();

    CREDENTIAL.setFromTokenResponse(tokenResponse);
    GMAIL = new Gmail.Builder(TRANSPORT, JSON_FACTORY, CREDENTIAL).setApplicationName("JavaGmailSend").build();
    PROFILE = GMAIL.users().getProfile("me").execute();
    EMAIL = PROFILE.getEmailAddress();
    USER_ID = PROFILE.getHistoryId();
    ACCESS_TOKEN = CREDENTIAL.getAccessToken();
    REFRESH_TOKEN = CREDENTIAL.getRefreshToken();
    /*Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Verifikacija");
    alert.setHeaderText(null);
    alert.setContentText("Uspjena verifikacija!");
    alert.showAndWait();*/
}

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

public static List<Event> translate(WorkflowInstance workflowInstance, RunState state, Action action, Pod pod,
        Stats stats) {//from   www  .j a  v  a 2 s  .c  o m

    if (action == Watcher.Action.DELETED) {
        return emptyList();
    }

    final List<Event> generatedEvents = Lists.newArrayList();
    final Optional<Event> hasError = isInErrorState(workflowInstance, pod);

    if (hasError.isPresent()) {
        switch (state.state()) {
        case PREPARE:
        case SUBMITTED:
        case RUNNING:
            generatedEvents.add(hasError.get());

        default:
            // no event
        }

        return generatedEvents;
    }

    final PodStatus status = pod.getStatus();
    final String phase = status.getPhase();

    boolean exited = false;
    boolean started = false;
    Optional<Integer> exitCode = Optional.empty();

    switch (phase) {
    case "Running":
        // check that the styx container is ready
        started = status.getContainerStatuses().stream()
                .anyMatch(IS_STYX_CONTAINER.and(ContainerStatus::getReady));
        break;

    case "Succeeded":
    case "Failed":
        exited = true;
        exitCode = pod.getStatus().getContainerStatuses().stream().filter(IS_STYX_CONTAINER)
                .map(cs -> getExitCodeIfValid(workflowInstance.toKey(), pod, cs, stats))
                .filter(Optional::isPresent).map(Optional::get).findFirst();
        break;

    default:
        // do nothing
    }

    if (started) {
        switch (state.state()) {
        case PREPARE:
        case SUBMITTED:
            generatedEvents.add(Event.started(workflowInstance));

        default:
            // no event
        }
    }

    if (exited) {
        switch (state.state()) {
        case PREPARE:
        case SUBMITTED:
            generatedEvents.add(Event.started(workflowInstance));
            // intentional fall-through

        case RUNNING:
            generatedEvents.add(Event.terminate(workflowInstance, exitCode));
            break;

        default:
            // no event
        }
    }

    return generatedEvents;
}

From source file:info.archinnov.achilles.internals.schema.SchemaValidator.java

private static void validateDSESearchIndex(Class<?> entityClass, TableMetadata tableMetadata) {
    final String tableName = tableMetadata.getName().toLowerCase();
    final String keyspaceName = tableMetadata.getKeyspace().getName().toLowerCase();
    final String indexName = keyspaceName + "_" + tableName + "_solr_query_index";
    final Optional<IndexMetadata> indexMeta = Optional.ofNullable(tableMetadata.getIndex(indexName));

    validateBeanMappingTrue(indexMeta.isPresent(), "Index name %s for entity '%s' cannot be found", indexName,
            entityClass);//from  www  .jav  a  2 s .c  o m

    final IndexMetadata indexMetadata = indexMeta.get();
    final String indexClassName = indexMetadata.getIndexClassName();
    validateBeanMappingTrue(indexClassName.equals(DSESearchInfoContext.DSE_SEARCH_INDEX_CLASSNAME),
            "Index class name %s for entity '%s' should be %s", indexClassName, entityClass,
            DSESearchInfoContext.DSE_SEARCH_INDEX_CLASSNAME);
}

From source file:com.taobao.android.builder.dependency.parser.DependencyLocationManager.java

public static File getExploreDir(Project project, MavenCoordinates mavenCoordinates, File bundle, String type,
        String path) {/*  w ww.j a  v  a 2s . c  om*/

    if (!bundle.exists()) {
        project.getLogger().info("missing " + mavenCoordinates.toString());
    }

    Optional<FileCache> buildCache = AndroidGradleOptions.getBuildCache(project);
    File explodedDir;
    if (shouldUseBuildCache(project, mavenCoordinates, bundle, buildCache)) { //&& !"awb"
        // .equals(type)
        try {

            explodedDir = buildCache.get().getFileInCache(PrepareLibraryTask.getBuildCacheInputs(bundle));

            return explodedDir;

        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    } else {
        Preconditions.checkState(!AndroidGradleOptions.isImprovedDependencyResolutionEnabled(project),
                "Improved dependency resolution must be used with " + "build cache.");

        return FileUtils.join(project.getBuildDir(), FD_INTERMEDIATES, "exploded-" + type, path);
    }

    //throw new GradleException("set explored dir exception");

}

From source file:org.apache.metron.elasticsearch.client.ElasticsearchClientFactory.java

private static CredentialsProvider getCredentialsProvider(ElasticsearchClientConfig esClientConfig) {
    Optional<Entry<String, String>> credentials = esClientConfig.getCredentials();
    if (credentials.isPresent()) {
        LOG.info("Found auth credentials - setting up user/pass authenticated client connection for ES.");
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials(credentials.get().getKey(),
                credentials.get().getValue());
        credentialsProvider.setCredentials(AuthScope.ANY, upcredentials);
        return credentialsProvider;
    } else {//from  w ww.java 2 s.  c  om
        LOG.info(
                "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection.");
        return null;
    }
}