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: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 {/*w  ww. ja  v a2 s.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.ikanow.aleph2.aleph2_rest_utils.RestCrudFunctions.java

private static <T> Response handleDeleteRequest(final Optional<String> query_json,
        final Optional<String> query_id, final ICrudService<T> crud_service, final Class<T> clazz) {
    //get id or a query object that was posted
    if (query_id.isPresent()) {
        //ID delete
        try {/* w ww. j ava  2s.  com*/
            final String id = query_id.get();
            _logger.debug("id: " + id);
            return Response.ok(RestUtils.convertSingleObjectToJson(crud_service.deleteObjectById(id).get(),
                    DELETE_SUCCESS_FIELD_NAME).toString()).build();
        } catch (InterruptedException | ExecutionException e) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build();
        }
    } else if (query_json.isPresent()) {
        //Body delete
        try {
            final String json = query_json.get();
            _logger.debug("query: " + json);
            final QueryComponent<T> query = RestUtils.convertStringToQueryComponent(json, clazz,
                    Optional.empty());
            return Response.ok(RestUtils.convertSingleObjectToJson(crud_service.deleteObjectBySpec(query).get(),
                    DELETE_SUCCESS_FIELD_NAME).toString()).build();
        } catch (Exception e) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build();
        }
    } else {
        //TODO actually we should probably just do something else when this is empty (like return first item, or search all and return limit 10, etc)
        return Response.status(Status.BAD_REQUEST)
                .entity("DELETE requires an id in the url or query in the body").build();
    }
}

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

public static Optional<String> extractDirectory(InputStream stream, String frameworkId, String executorId,
        String containerId) throws IOException {
    // TODO: prepare corresponding object type instead of using java.util.Map
    // Search path: {frameworks|complated_frameworks}/{completed_executors|executors}[.container='containerId'].directory
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Map<String, Object>> map = mapper.readValue(stream, java.util.Map.class);
    List<Map<String, Object>> frameworks = new ArrayList<>();
    if (map.get("frameworks") != null) {
        frameworks.addAll((List) map.get("frameworks"));
    }//  ww  w  .j a va2 s  .  c om
    if (map.get("completed_frameworks") != null) {
        frameworks.addAll((List) map.get("completed_frameworks"));
    }

    // TODO: use json-path for cleaner and flexible code
    for (Map<String, Object> framework : frameworks) {
        List<Map<String, Object>> both = new ArrayList<>();
        List<Map<String, Object>> executors = (List) framework.get("executors");
        if (executors != null) {
            both.addAll(executors);
        }
        List<Map<String, Object>> completedExecutors = (List) framework.get("completed_executors");
        if (completedExecutors != null) {
            both.addAll(completedExecutors);
        }
        Optional<String> s = extractDirectoryFromExecutors(both, executorId, containerId);
        if (s.isPresent()) {
            return s;
        }
    }
    LOG.error("No matching directory at framework={}, executor={}, container={}", frameworkId, executorId,
            containerId);
    return Optional.empty();
}

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

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

    String url = null;//from  w w  w .j  av a  2 s .  com
    String name = null;
    String downloadUrl = null;

    Date createdDate = null;
    Date updatedDate = null;

    long id = Long.MIN_VALUE;
    long size = Long.MIN_VALUE;
    long downloads = Long.MIN_VALUE;

    AssetState state = null;

    Optional<String> label = Optional.empty();

    Optional<Uploader> uploader = Optional.empty();
    // Obtem todos valores do JSON
    for (Map.Entry entries : (Set<Map.Entry>) jsonObject.entrySet()) {

        Object key = entries.getKey();
        Object value = entries.getValue();
        String valueString = String.valueOf(value);

        switch (AssetInput.parseObject(key)) {
        case URL: {
            // URL do Asset
            url = valueString;
            break;
        }
        case ID: {
            // Id do Asset
            id = Long.parseLong(valueString);
            break;
        }
        case BROWSER_DOWNLOAD_URL: {
            // Link de download
            downloadUrl = valueString;
            break;
        }
        case CREATED_AT: {
            // Data de criao
            if (formatter.canFormat(Date.class)) {
                Optional<Date> dateResult = formatter.format(valueString, Date.class);
                if (dateResult.isPresent()) {
                    createdDate = dateResult.get();
                }
            }
            break;
        }
        case UPDATED_AT: {
            // Data de atualizao
            if (formatter.canFormat(Date.class)) {
                Optional<Date> dateResult = formatter.format(valueString, Date.class);
                if (dateResult.isPresent()) {
                    updatedDate = dateResult.get();
                }
            }
            break;
        }
        case NAME: {
            // Nome
            name = valueString;
            break;
        }
        case DOWNLOAD_COUNT: {
            // Quantidade de downloads
            downloads = Long.parseLong(valueString);
            break;
        }

        case LABEL: {
            /** Rtulo (se houver, caso contrrio, {@link Optional#absent()}  **/
            if (value == null) {
                label = Optional.empty();
            } else {
                label = Optional.of(valueString);
            }
            break;
        }

        case STATE: {
            // Estado
            state = AssetState.parseString(valueString);
            break;
        }

        case SIZE: {
            // Tamanho do arquivo (em bytes)
            size = Long.parseLong(valueString);
            break;
        }

        case UPLOADER: {
            // Quem envou (traduzido externalmente)
            uploader = Uploader.parseJsonObject((JSONObject) value, formatter);
            break;
        }

        default: {
        }
        }
    }

    if (id == Long.MIN_VALUE) {
        // Retorna um optional de valor ausente se no for encontrado o Asset.
        return Optional.empty();
    }

    // Cria um novo Asset
    return Optional.of(new Asset(url, name, downloadUrl, createdDate, updatedDate, id, size, downloads, state,
            label, uploader));
}

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

public static Optional<String> sandboxUri(String t, String master, String slaveId, String frameworkId,
        String executorId, String containerId, int retryRemain) {
    if (retryRemain > 0) {
        Optional<String> maybeUri = sandboxUri(t, master, slaveId, frameworkId, executorId, containerId);
        if (maybeUri.isPresent()) {
            return maybeUri;
        } else {/*from  ww w.ja  va  2 s . c  o  m*/
            // NOTE: this sleep is so short because this function may be called in the context of
            // Mesos Scheduler API callback
            // TODO: sole resolution is to remove all these uri fetching but to build it of Job information, including SlaveId
            LOG.warn("{} retry happening for frameworkId={}, executorId={}, containerId={}",
                    RETRY_LIMIT - retryRemain + 1, frameworkId, executorId, containerId);
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
            }
            return sandboxUri(t, master, slaveId, frameworkId, executorId, containerId, retryRemain - 1);
        }
    } else {
        LOG.error("{} retries on fetching sandbox URI failed", RETRY_LIMIT);
        return Optional.empty();
    }
}

From source file:co.runrightfast.vertx.orientdb.verticle.OrientDBVerticleTest.java

private static void initDatabase() {
    Optional<OrientDBService> orientDBService = TypeSafeObjectRegistry.GLOBAL_OBJECT_REGISTRY
            .get(OrientDBService.ORIENTDB_SERVICE);
    while (!orientDBService.isPresent()) {
        log.log(Level.WARNING, "Waiting for OrientDBService ...");
        sleep(Duration.ofSeconds(2));
        orientDBService = TypeSafeObjectRegistry.GLOBAL_OBJECT_REGISTRY.get(OrientDBService.ORIENTDB_SERVICE);
    }//from  www  . j ava  2s.co m

    final OServerAdmin admin = orientDBService.get().getServerAdmin();
    try {
        OrientDBUtils.createDatabase(admin, EventLogRepository.DB);
    } catch (final Exception e) {
        e.printStackTrace();
    } finally {
        admin.close();
    }

    EventLogRepository.initDatabase(
            orientDBService.get().getODatabaseDocumentTxSupplier(EventLogRepository.DB).get().get());
}

From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java

public static List<Artifact> flattenLists(File mcDir) {
    List<Artifact> merged = new ArrayList<>();
    for (ModList list : ModList.getBasicLists(mcDir)) {
        for (Artifact art : list.flatten()) {
            Optional<Artifact> old = merged.stream().filter(art::matchesID).findFirst();
            if (!old.isPresent()) {
                merged.add(art);/*www  .  j a v  a 2  s . c  o  m*/
            } else if (old.get().getVersion().compareTo(art.getVersion()) < 0) {
                merged.add(merged.indexOf(old.get()), art);
                merged.remove(old.get());
            }
        }
    }
    return merged;
}

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

/**
 * Open a http/pdf/ps viewer for the given link string.
 *///ww  w .j av a 2s .c  om
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:io.github.retz.mesosc.MesosHTTPFetcher.java

public static Optional<String> sandboxDownloadUri(String master, String slaveId, String frameworkId,
        String executorId, String containerId, String path) {
    Optional<String> base = sandboxUri("download", master, slaveId, frameworkId, executorId, containerId,
            RETRY_LIMIT);//from   ww w . j a v a  2  s .c  o m
    if (base.isPresent()) {
        try {
            String encodedPath = URLEncoder.encode(path, UTF_8.toString());
            return Optional.of(base.get() + encodedPath);
        } catch (UnsupportedEncodingException e) {
            return Optional.empty();
        }
    }
    return Optional.empty();
}

From source file:com.ikanow.aleph2.data_model.utils.JsonUtils.java

/** Takes a tuple expressed as LinkedHashMap<String, Object> (by convention the Objects are primitives, JsonNode, or POJO), and where one of the objects
 *  is a JSON representation of the original object and creates an object by folding them all together
 *  Note the other fields of the tuple take precedence over the JSON
 * @param in - the tuple/*www  .  ja  v  a2s. com*/
 * @param mapper - the Jackson object mapper
 * @param json_field - optional fieldname of the string representation of the JSON - if not present then the last field is used (set to eg "" if there is no base object)
 * @return
 */
public static JsonNode foldTuple(final LinkedHashMap<String, Object> in, final ObjectMapper mapper,
        final Optional<String> json_field) {
    try {
        // (do this imperatively to handle the "last element can be the base object case"
        final Iterator<Map.Entry<String, Object>> it = in.entrySet().iterator();
        ObjectNode acc = mapper.createObjectNode();
        while (it.hasNext()) {
            final Map.Entry<String, Object> kv = it.next();
            if ((json_field.isPresent() && kv.getKey().equals(json_field.get()))
                    || !json_field.isPresent() && !it.hasNext()) {
                acc = (ObjectNode) ((ObjectNode) mapper.readTree(kv.getValue().toString())).setAll(acc);
            } else {
                final ObjectNode acc_tmp = acc;
                Patterns.match(kv.getValue()).andAct().when(String.class, s -> acc_tmp.put(kv.getKey(), s))
                        .when(Long.class, l -> acc_tmp.put(kv.getKey(), l))
                        .when(Integer.class, l -> acc_tmp.put(kv.getKey(), l))
                        .when(Boolean.class, b -> acc_tmp.put(kv.getKey(), b))
                        .when(Double.class, d -> acc_tmp.put(kv.getKey(), d))
                        .when(JsonNode.class, j -> acc_tmp.set(kv.getKey(), j))
                        .when(Float.class, f -> acc_tmp.put(kv.getKey(), f))
                        .when(BigDecimal.class, f -> acc_tmp.put(kv.getKey(), f))
                        .otherwise(x -> acc_tmp.set(kv.getKey(), BeanTemplateUtils.toJson(x)));
            }
        }
        return acc;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } // (convert to unchecked exception)
}