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:lumbermill.internal.StringTemplateTest.java

@Test
public void testExtractSentence() {
    try {//from  w ww.j  a v  a  2  s.co m

        StringTemplate t = StringTemplate.compile("Hej hopp {field}");
        Event event = Codecs.BYTES.from("Hello").put("field", "value");
        Optional<String> formattedString = t.format(event);
        assertThat(formattedString.isPresent()).isTrue();
        assertThat(formattedString.get()).isEqualTo("Hej hopp value");

        ObjectNode objectNode = new ObjectNode(JsonNodeFactory.instance);
        JsonEvent jsonEvent = new JsonEvent(objectNode);
        jsonEvent.put("id", "This is a test ID");
        jsonEvent.put("version", "This is a test version");

        StringTemplate key = StringTemplate.compile("{id}/{version}");
        assertThat(key.format(jsonEvent).get()).isEqualTo("This is a test ID/This is a test version");

    } catch (RuntimeException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:se.curity.examples.oauth.jwt.JwtValidatorWithJwk.java

/**
 * JWT: abads.gfdr.htefgy/*from w  ww .java  2  s  .c o m*/
 *
 * @param jwt the original base64 encoded JWT
 * @return A map with the content of the Jwt body if the JWT is valid, otherwise null
 * @throws IllegalArgumentException if alg or kid are not present in the JWT header.
 * @throws RuntimeException         if some environment issue makes it impossible to validate a signature
 */
public @Nullable Map<String, Object> validate(String jwt) throws JwtValidationException {
    String[] jwtParts = jwt.split("\\.");

    if (jwtParts.length != 3) {
        throw new IllegalArgumentException("Incorrect JWT input");
    }

    String header = jwtParts[0];
    String body = jwtParts[1];
    byte[] headerAndPayload = convertToBytes(header + "." + jwtParts[1]);

    Base64 base64 = new Base64(true);

    @SuppressWarnings("unchecked")
    Map<String, String> headerMap = _gson.fromJson(new String(base64.decode(header), Charsets.UTF_8),
            Map.class);

    String alg = headerMap.get("alg");
    String kid = headerMap.get("kid");

    Preconditions.checkArgument(!isNullOrEmpty(alg), "Alg is not present in JWT");
    Preconditions.checkArgument(!isNullOrEmpty(kid), "Key ID is not present in JWT");

    if (canRecognizeAlg(alg)) {
        try {
            Optional<JsonWebKey> maybeWebKey = getJsonWebKeyFor(kid);
            if (maybeWebKey.isPresent()) {
                byte[] signatureData = base64.decode(jwtParts[2]);
                if (validateSignature(headerAndPayload, signatureData,
                        getKeyFromModAndExp(maybeWebKey.get().getModulus(), maybeWebKey.get().getExponent()))) {
                    return _gson.fromJson(new String(base64.decode(body), Charsets.UTF_8), Map.class);
                }
            }
        } catch (Exception e) {
            throw new JwtValidationException("Unable to validate Jwt ", e);
        }
    } else {
        _logger.info("Requested JsonWebKey using unrecognizable alg: {}", headerMap.get("alg"));
    }
    return null;
}

From source file:com.uber.hoodie.common.util.ParquetUtils.java

/**
 * Read the rowKey list matching the given filter, from the given parquet file. If the filter is empty,
 * then this will return all the rowkeys.
 *
 * @param filePath              The parquet file path.
 * @param configuration         configuration to build fs object
 * @param filter                record keys filter
 * @return Set                  Set of row keys matching candidateRecordKeys
 *//*from w  w  w.  j  a  v  a2s . c  om*/
public static Set<String> filterParquetRowKeys(Configuration configuration, Path filePath, Set<String> filter) {
    Optional<RecordKeysFilterFunction> filterFunction = Optional.empty();
    if (CollectionUtils.isNotEmpty(filter)) {
        filterFunction = Optional.of(new RecordKeysFilterFunction(filter));
    }
    Configuration conf = new Configuration(configuration);
    conf.addResource(getFs(filePath.toString(), conf).getConf());
    Schema readSchema = HoodieAvroUtils.getRecordKeySchema();
    AvroReadSupport.setAvroReadSchema(conf, readSchema);
    AvroReadSupport.setRequestedProjection(conf, readSchema);
    ParquetReader reader = null;
    Set<String> rowKeys = new HashSet<>();
    try {
        reader = AvroParquetReader.builder(filePath).withConf(conf).build();
        Object obj = reader.read();
        while (obj != null) {
            if (obj instanceof GenericRecord) {
                String recordKey = ((GenericRecord) obj).get(HoodieRecord.RECORD_KEY_METADATA_FIELD).toString();
                if (!filterFunction.isPresent() || filterFunction.get().apply(recordKey)) {
                    rowKeys.add(recordKey);
                }
            }
            obj = reader.read();
        }
    } catch (IOException e) {
        throw new HoodieIOException("Failed to read row keys from Parquet " + filePath, e);

    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return rowKeys;
}

From source file:com.devicehive.application.security.WebSecurityConfig.java

@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
    return (request, response, authException) -> {
        Optional<String> authHeader = Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION));
        if (authHeader.isPresent() && authHeader.get().startsWith(Constants.TOKEN_SCHEME)) {
            response.addHeader(HttpHeaders.WWW_AUTHENTICATE, Messages.OAUTH_REALM);
        } else {// w  ww  .j  av  a  2  s.com
            response.addHeader(HttpHeaders.WWW_AUTHENTICATE, Messages.BASIC_REALM);
        }
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getOutputStream().println(gson
                .toJson(new ErrorResponse(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage())));
    };
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.op.artifact.KubernetesCleanupArtifactsOperation.java

private List<Artifact> artifactsToDelete(KubernetesManifest manifest) {
    KubernetesManifestStrategy strategy = KubernetesManifestAnnotater.getStrategy(manifest);
    if (strategy.getMaxVersionHistory() == null) {
        return new ArrayList<>();
    }//from   ww w.j  a  va2 s .c  o m

    int maxVersionHistory = strategy.getMaxVersionHistory();
    Optional<Artifact> optional = KubernetesManifestAnnotater.getArtifact(manifest);
    if (!optional.isPresent()) {
        return new ArrayList<>();
    }

    Artifact artifact = optional.get();

    List<Artifact> artifacts = artifactProvider
            .getArtifacts(artifact.getType(), artifact.getName(), artifact.getLocation()).stream()
            .filter(a -> a.getMetadata() != null && accountName.equals(a.getMetadata().get("account")))
            .collect(Collectors.toList());

    if (maxVersionHistory >= artifacts.size()) {
        return new ArrayList<>();
    } else {
        return artifacts.subList(0, artifacts.size() - maxVersionHistory);
    }
}

From source file:it.tidalwave.bluemarine2.metadata.impl.audio.musicbrainz.MusicBrainzAudioMedatataImporter.java

/*******************************************************************************************************************
 *
 * FIXME: DUPLICATED FROM EmbbededAudioMetadataImporter
 *
 ******************************************************************************************************************/
@Nonnull/*from ww  w  .  j a  v  a 2s.c o m*/
private static IRI recordIriOf(final @Nonnull Metadata metadata, final @Nonnull String recordTitle) {
    final Optional<Cddb> cddb = metadata.get(CDDB);
    return BMMO.recordIriFor((cddb.isPresent()) ? createSha1IdNew(cddb.get().getToc())
            : createSha1IdNew("RECORD:" + recordTitle));
}

From source file:com.yfiton.api.Notifier.java

public NotificationResult handle(Parameters parameters) throws NotificationException {
    Optional<String> message = checkParameters(parameters).getMessage();

    if (message.isPresent()) {
        throw new NotificationException(message.get());
    }//  w w  w .j av a  2 s .c  o  m

    stopwatch.start();

    notify(parameters);

    stopwatch.stop();

    return new NotificationResult(getKey(), stopwatch);
}

From source file:com.netflix.spinnaker.orca.clouddriver.tasks.pipeline.MigratePipelineClustersTask.java

private List<Map> getSources(Map<String, Object> pipeline) {
    List<Map> stages = (List<Map>) pipeline.getOrDefault("stages", new ArrayList<>());
    return stages.stream().map(s -> {
        Optional<PipelineClusterExtractor> extractor = PipelineClusterExtractor.getExtractor(s, extractors);
        if (extractor.isPresent()) {
            return extractor.get().extractClusters(s).stream().map(c -> Collections.singletonMap("cluster", c))
                    .collect(Collectors.toList());
        }/*from w  w  w.j a  v a 2 s .  co m*/
        return new ArrayList<Map>();
    }).flatMap(Collection::stream).collect(Collectors.toList());
}

From source file:io.kamax.mxisd.controller.identity.v1.MappingController.java

@RequestMapping(value = "/lookup", method = GET)
String lookup(HttpServletRequest request, @RequestParam String medium, @RequestParam String address) {
    SingleLookupRequest lookupRequest = new SingleLookupRequest();
    setRequesterInfo(lookupRequest, request);
    lookupRequest.setType(medium);/*from ww  w  . j  ava  2s  .  co m*/
    lookupRequest.setThreePid(address);

    log.info("Got single lookup request from {} with client {} - Is recursive? {}",
            lookupRequest.getRequester(), lookupRequest.getUserAgent(), lookupRequest.isRecursive());

    Optional<SingleLookupReply> lookupOpt = strategy.find(lookupRequest);
    if (!lookupOpt.isPresent()) {
        log.info("No mapping was found, return empty JSON object");
        return "{}";
    }

    SingleLookupReply lookup = lookupOpt.get();

    // FIXME signing should be done in the business model, not in the controller
    JsonObject obj = gson.toJsonTree(new SingeLookupReplyJson(lookup)).getAsJsonObject();
    obj.add(EventKey.Signatures.get(), signMgr.signMessageGson(MatrixJson.encodeCanonical(obj)));

    return gson.toJson(obj);
}

From source file:io.mapzone.controller.LoginAppDesign.java

@Override
public Shell createMainWindow(@SuppressWarnings("hiding") Display display) {
    this.display = display;
    mainWindow = new Shell(display, SWT.NO_TRIM);
    mainWindow.setMaximized(true);/*from   w  ww .  j a  v a2  s  . c  om*/
    UIUtils.setVariant(mainWindow, CSS_SHELL);

    mainWindow.setLayout(new FillLayout());

    String handlerId = RWT.getRequest().getParameter("id");

    SimpleDialog dialog = new SimpleDialog(mainWindow);
    dialog.title.set("Login required");
    dialog.setContents(parent -> {
        LoginForm loginForm = new LoginForm() {
            @Override
            protected boolean login(String name, String passwd) {
                Optional<User> loggedIn = tryLogin(name, passwd);
                if (loggedIn.isPresent()) {
                    Consumer<User> handler = handlers.remove(handlerId);
                    handler.accept(loggedIn.get());
                    return true;
                } else {
                    formSite.setFieldValue("password", "");
                    return false;
                }
            }

            @Override
            protected PanelSite panelSite() {
                throw new RuntimeException("not yet implemented.");
            }
        };
        loginForm.showRegisterLink.set(false);
        loginForm.showStoreCheck.set(true);
        loginForm.showLostLink.set(false); // XXX implement!

        new BatikFormContainer(loginForm).createContents(parent);
    });
    dialog.open();

    mainWindow.open();
    return mainWindow;
}