Example usage for java.util Optional ifPresent

List of usage examples for java.util Optional ifPresent

Introduction

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

Prototype

public void ifPresent(Consumer<? super T> action) 

Source Link

Document

If a value is present, performs the given action with the value, otherwise does nothing.

Usage

From source file:com.spotify.heroic.suggest.elasticsearch.SuggestBackendKV.java

@Override
public AsyncFuture<TagSuggest> tagSuggest(TagSuggest.Request request) {
    return connection.doto((final Connection c) -> {
        final BoolQueryBuilder bool = boolQuery();

        final Optional<String> key = request.getKey();
        final Optional<String> value = request.getValue();

        // special case: key and value are equal, which indicates that _any_ match should be
        // in effect.
        // XXX: Enhance API to allow for this to be intentional instead of this by
        // introducing an 'any' field.
        if (key.isPresent() && value.isPresent() && key.equals(value)) {
            bool.should(matchTermKey(key.get()));
            bool.should(matchTermValue(value.get()));
        } else {//w  w  w .  j  av a  2 s .co  m
            key.ifPresent(k -> {
                if (!k.isEmpty()) {
                    bool.must(matchTermKey(k).boost(2.0f));
                }
            });

            value.ifPresent(v -> {
                if (!v.isEmpty()) {
                    bool.must(matchTermValue(v));
                }
            });
        }

        QueryBuilder query = bool.hasClauses() ? bool : matchAllQuery();

        if (!(request.getFilter() instanceof TrueFilter)) {
            query = new BoolQueryBuilder().must(query).filter(filter(request.getFilter()));
        }

        final SearchRequestBuilder builder = c.search(TAG_TYPE).setSize(0).setQuery(query).setTimeout(TIMEOUT);

        // aggregation
        {
            final TopHitsAggregationBuilder hits = AggregationBuilders.topHits("hits").size(1)
                    .fetchSource(TAG_SUGGEST_SOURCES, new String[0]);

            final TermsAggregationBuilder terms = AggregationBuilders.terms("terms").field(TAG_KV)
                    .subAggregation(hits);

            request.getLimit().asInteger().ifPresent(terms::size);

            builder.addAggregation(terms);
        }

        return bind(builder.execute()).directTransform((SearchResponse response) -> {
            final ImmutableList.Builder<Suggestion> suggestions = ImmutableList.builder();

            final Aggregations aggregations = response.getAggregations();

            if (aggregations == null) {
                return TagSuggest.of();
            }

            final StringTerms terms = aggregations.get("terms");

            for (final Terms.Bucket bucket : terms.getBuckets()) {
                final TopHits topHits = bucket.getAggregations().get("hits");
                final SearchHits hits = topHits.getHits();
                final SearchHit hit = hits.getAt(0);
                final Map<String, Object> doc = hit.getSource();

                final String k = (String) doc.get(TAG_SKEY);
                final String v = (String) doc.get(TAG_SVAL);

                suggestions.add(new Suggestion(hits.getMaxScore(), k, v));
            }

            return TagSuggest.of(suggestions.build());
        });
    });
}

From source file:io.bitsquare.btc.WalletService.java

public void swapTradeEntryToAvailableEntry(String offerId, AddressEntry.Context context) {
    Optional<AddressEntry> addressEntryOptional = getAddressEntryListAsImmutableList().stream()
            .filter(e -> offerId.equals(e.getOfferId())).filter(e -> context == e.getContext()).findAny();
    addressEntryOptional.ifPresent(e -> {
        addressEntryList.swapToAvailable(e);
        saveAddressEntryList();//from   w  w w.  ja  v a2 s  .c  o  m
    });
}

From source file:alfio.manager.PaymentManager.java

TransactionAndPaymentInfo getInfo(TicketReservation reservation, Event event) {
    Optional<TransactionAndPaymentInfo> maybeTransaction = transactionRepository
            .loadOptionalByReservationId(reservation.getId()).map(transaction -> {
                switch (reservation.getPaymentMethod()) {
                case PAYPAL:
                    return new TransactionAndPaymentInfo(reservation.getPaymentMethod(), transaction,
                            paypalManager.getInfo(transaction, event).orElse(null));
                case STRIPE:
                    return new TransactionAndPaymentInfo(reservation.getPaymentMethod(), transaction,
                            stripeManager.getInfo(transaction, event).orElse(null));
                default:
                    return new TransactionAndPaymentInfo(reservation.getPaymentMethod(), transaction,
                            new PaymentInformation(reservation.getPaidAmount(), null,
                                    String.valueOf(transaction.getGatewayFee()),
                                    String.valueOf(transaction.getPlatformFee())));
                }//from w w  w.j  av a  2  s . c om
            });
    maybeTransaction.ifPresent(info -> {
        try {
            Transaction transaction = info.getTransaction();
            String transactionId = transaction.getTransactionId();
            PaymentInformation paymentInformation = info.getPaymentInformation();
            if (paymentInformation != null) {
                transactionRepository.updateFees(transactionId, reservation.getId(),
                        safeParseLong(paymentInformation.getPlatformFee()),
                        safeParseLong(paymentInformation.getFee()));
            }
        } catch (Exception e) {
            log.warn("cannot update fees", e);
        }
    });
    return maybeTransaction.orElseGet(() -> new TransactionAndPaymentInfo(reservation.getPaymentMethod(), null,
            new PaymentInformation(reservation.getPaidAmount(), null, null, null)));
}

From source file:blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.java

public Set<AbstractConnection> getIndirectEnergyConnections(BlockPos node, World world,
        boolean ignoreIsEnergyOutput) {
    int dimension = world.provider.getDimension();
    if (!ignoreIsEnergyOutput && indirectConnections.containsKey(dimension)
            && indirectConnections.get(dimension).containsKey(node))
        return indirectConnections.get(dimension).get(node);
    else if (ignoreIsEnergyOutput && indirectConnectionsIgnoreOut.containsKey(dimension)
            && indirectConnectionsIgnoreOut.get(dimension).containsKey(node))
        return indirectConnectionsIgnoreOut.get(dimension).get(node);

    PriorityQueue<Pair<IImmersiveConnectable, Float>> queue = new PriorityQueue<>(
            Comparator.comparingDouble(Pair::getRight));
    Set<AbstractConnection> closedList = newSetFromMap(new ConcurrentHashMap<AbstractConnection, Boolean>());
    List<BlockPos> checked = new ArrayList<>();
    HashMap<BlockPos, BlockPos> backtracker = new HashMap<>();

    checked.add(node);/*from  w  ww .  j a  v  a 2 s.c o m*/
    Set<Connection> conL = getConnections(world, node);
    if (conL != null)
        for (Connection con : conL) {
            IImmersiveConnectable end = toIIC(con.end, world);
            if (end != null) {
                queue.add(new ImmutablePair<>(end, con.getBaseLoss()));
                backtracker.put(con.end, node);
            }
        }

    IImmersiveConnectable next;
    final int closedListMax = 1200;

    while (closedList.size() < closedListMax && !queue.isEmpty()) {
        Pair<IImmersiveConnectable, Float> pair = queue.poll();
        next = pair.getLeft();
        float loss = pair.getRight();
        BlockPos nextPos = toBlockPos(next);
        if (!checked.contains(nextPos) && queue.stream().noneMatch((p) -> p.getLeft().equals(nextPos))) {
            boolean isOutput = next.isEnergyOutput();
            if (ignoreIsEnergyOutput || isOutput) {
                BlockPos last = toBlockPos(next);
                WireType minimumType = null;
                int distance = 0;
                List<Connection> connectionParts = new ArrayList<>();
                while (last != null) {
                    BlockPos prev = last;
                    last = backtracker.get(last);
                    if (last != null) {

                        Set<Connection> conLB = getConnections(world, last);
                        if (conLB != null)
                            for (Connection conB : conLB)
                                if (conB.end.equals(prev)) {
                                    connectionParts.add(0, conB);
                                    distance += conB.length;
                                    if (minimumType == null
                                            || conB.cableType.getTransferRate() < minimumType.getTransferRate())
                                        minimumType = conB.cableType;
                                    break;
                                }
                    }
                }
                closedList.add(new AbstractConnection(toBlockPos(node), toBlockPos(next), minimumType, distance,
                        isOutput, connectionParts.toArray(new Connection[connectionParts.size()])));
            }

            Set<Connection> conLN = getConnections(world, toBlockPos(next));
            if (conLN != null)
                for (Connection con : conLN)
                    if (next.allowEnergyToPass(con)) {
                        IImmersiveConnectable end = toIIC(con.end, world);

                        Optional<Pair<IImmersiveConnectable, Float>> existing = queue.stream()
                                .filter((p) -> p.getLeft() == end).findAny();
                        float newLoss = con.getBaseLoss() + loss;
                        if (end != null && !checked.contains(con.end)
                                && existing.map(Pair::getRight).orElse(Float.MAX_VALUE) > newLoss) {
                            existing.ifPresent(p1 -> queue.removeIf((p2) -> p1.getLeft() == p2.getLeft()));
                            queue.add(new ImmutablePair<>(end, newLoss));
                            backtracker.put(con.end, toBlockPos(next));
                        }
                    }
            checked.add(toBlockPos(next));
        }
    }
    if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) {
        if (ignoreIsEnergyOutput) {
            if (!indirectConnectionsIgnoreOut.containsKey(dimension))
                indirectConnectionsIgnoreOut.put(dimension, new ConcurrentHashMap<>());
            Map<BlockPos, Set<AbstractConnection>> conns = indirectConnectionsIgnoreOut.get(dimension);
            if (!conns.containsKey(node))
                conns.put(node, newSetFromMap(new ConcurrentHashMap<>()));
            conns.get(node).addAll(closedList);
        } else {
            if (!indirectConnections.containsKey(dimension))
                indirectConnections.put(dimension, new ConcurrentHashMap<>());
            Map<BlockPos, Set<AbstractConnection>> conns = indirectConnections.get(dimension);
            if (!conns.containsKey(node))
                conns.put(node, newSetFromMap(new ConcurrentHashMap<>()));
            conns.get(node).addAll(closedList);
        }
    }
    return closedList;
}

From source file:alfio.manager.system.MailjetMailer.java

@Override
public void send(Event event, String to, List<String> cc, String subject, String text, Optional<String> html,
        Attachment... attachment) {//from   w  w w . j av  a2s .c o m
    String apiKeyPublic = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(),
            event.getId(), ConfigurationKeys.MAILJET_APIKEY_PUBLIC));
    String apiKeyPrivate = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(),
            event.getId(), ConfigurationKeys.MAILJET_APIKEY_PRIVATE));

    String fromEmail = configurationManager.getRequiredValue(
            Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAILJET_FROM));

    //https://dev.mailjet.com/guides/?shell#sending-with-attached-files
    Map<String, Object> mailPayload = new HashMap<>();

    List<Map<String, String>> recipients = new ArrayList<>();
    recipients.add(Collections.singletonMap("Email", to));
    if (cc != null && !cc.isEmpty()) {
        recipients.addAll(cc.stream().map(email -> Collections.singletonMap("Email", email))
                .collect(Collectors.toList()));
    }

    mailPayload.put("FromEmail", fromEmail);
    mailPayload.put("FromName", event.getDisplayName());
    mailPayload.put("Subject", subject);
    mailPayload.put("Text-part", text);
    html.ifPresent(h -> mailPayload.put("Html-part", h));
    mailPayload.put("Recipients", recipients);

    String replyTo = configurationManager.getStringConfigValue(
            Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAIL_REPLY_TO), "");
    if (StringUtils.isNotBlank(replyTo)) {
        mailPayload.put("Headers", Collections.singletonMap("Reply-To", replyTo));
    }

    if (attachment != null && attachment.length > 0) {
        mailPayload.put("Attachments",
                Arrays.stream(attachment).map(MailjetMailer::fromAttachment).collect(Collectors.toList()));
    }

    RequestBody body = RequestBody.create(MediaType.parse("application/json"), Json.GSON.toJson(mailPayload));
    Request request = new Request.Builder().url("https://api.mailjet.com/v3/send")
            .header("Authorization", Credentials.basic(apiKeyPublic, apiKeyPrivate)).post(body).build();
    try (Response resp = client.newCall(request).execute()) {
        if (!resp.isSuccessful()) {
            log.warn("sending email was not successful:" + resp);
        }
    } catch (IOException e) {
        log.warn("error while sending email", e);
    }

}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Creates a list of JsonNodes containing the mapping for fields that will _enable_ or _disable_ field data depending on fielddata_info is present 
 *  (note this can convert a property to a dynamic template, but never the other way round)
 * @param instream/*from w w w  .j  av  a  2s  .c  o m*/
 * @param f
 * @param field_lookups
 * @param fielddata_info 3tuple containing not_analyzed, analyzed, and override
 * @param mapper
 * @return
 */
protected static Stream<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>> createFieldLookups(
        final Stream<String> instream, final Function<String, Either<String, Tuple2<String, String>>> f,
        final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> field_lookups,
        final Optional<Tuple3<JsonNode, JsonNode, Boolean>> fielddata_info,
        final SearchIndexSchemaDefaultBean search_index_schema_override,
        final Map<Either<String, Tuple2<String, String>>, String> type_override, final ObjectMapper mapper,
        final String index_type) {
    return instream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>map(Lambdas.wrap_u(fn -> {
        final Either<String, Tuple2<String, String>> either_tmp = f.apply(fn);
        final Optional<String> maybe_type = Optional.ofNullable(type_override.get(either_tmp));

        // add type if present
        final Either<String, Tuple2<String, String>> either = maybe_type
                .<Either<String, Tuple2<String, String>>>map(type -> {
                    return either_tmp.<Either<String, Tuple2<String, String>>>either(s -> Either.left(s),
                            t2 -> Either.right(Tuples._2T(t2._1(), type)));
                }).orElse(either_tmp);

        final ObjectNode mutable_field_metadata = (ObjectNode) Optional.ofNullable(field_lookups.get(either))
                .map(j -> j.deepCopy())
                .orElse(either.either(Lambdas.wrap_fj_u(__ -> mapper.readTree(BACKUP_FIELD_MAPPING_PROPERTIES)),
                        Lambdas.wrap_fj_u(__ -> mapper.readTree(BACKUP_FIELD_MAPPING_TEMPLATES))));
        //(note that these 2 mappings don't have "type"s - therefore they will result in default_templates not properties - you need the type to generate a property)

        final ObjectNode mutable_field_mapping_tmp = either.isLeft() ? mutable_field_metadata
                : (ObjectNode) mutable_field_metadata.get("mapping");

        //(override with type if set)
        maybe_type.ifPresent(type -> mutable_field_mapping_tmp.put("type", type));

        final boolean has_type = mutable_field_mapping_tmp.has("type");

        final Tuple2<ObjectNode, Either<String, Tuple2<String, String>>> toplevel_eithermod = Lambdas
                .get(() -> {
                    if (either.isLeft() && !has_type) {
                        final ObjectNode top_level = (ObjectNode) mapper.createObjectNode().set("mapping",
                                mutable_field_metadata);
                        return Tuples._2T(top_level,
                                Either.<String, Tuple2<String, String>>right(Tuples._2T(fn, "*")));
                    } else { // right[dynamic] *OR* (left[properties] and has-type)
                        return Tuples._2T(mutable_field_metadata, either);
                    }
                });

        final ObjectNode mutable_field_mapping = toplevel_eithermod._2().isLeft() ? toplevel_eithermod._1()
                : (ObjectNode) toplevel_eithermod._1().get("mapping");

        // Special case ... if we're columnar and we're merging with tokenized and non-dual then convert to untokenized instead 
        if (fielddata_info.filter(t3 -> t3._3()).isPresent() && mutable_field_mapping.equals(
                mapper.convertValue(search_index_schema_override.tokenized_string_field(), JsonNode.class))) {
            mutable_field_mapping.removeAll();
            mutable_field_mapping.setAll((ObjectNode) mapper
                    .convertValue(search_index_schema_override.untokenized_string_field(), ObjectNode.class));
        }

        if (toplevel_eithermod._2().isRight()) {
            if (!toplevel_eithermod._1().has(PATH_MATCH_NAME) && !toplevel_eithermod._1().has(RAW_MATCH_NAME)) {
                toplevel_eithermod._1().put(PATH_MATCH_NAME, toplevel_eithermod._2().right().value()._1());

                if (!toplevel_eithermod._1().has(TYPE_MATCH_NAME))
                    toplevel_eithermod._1().put(TYPE_MATCH_NAME, toplevel_eithermod._2().right().value()._2());
            }
            if (!has_type) {
                if (toplevel_eithermod._2().right().value()._2().equals("*")) { // type is mandatory
                    mutable_field_mapping.put("type", "{dynamic_type}");
                } else {
                    mutable_field_mapping.put("type", toplevel_eithermod._2().right().value()._2());
                }
            }
        }
        handleMappingFields(mutable_field_mapping, fielddata_info, mapper, index_type);
        setMapping(mutable_field_mapping, fielddata_info, mapper, index_type);
        return Tuples._2T(toplevel_eithermod._2(), toplevel_eithermod._1());
    }));

}

From source file:com.github.lukaszbudnik.dqueue.QueueClientImpl.java

@Override
public Future<UUID> publish(Item item) {
    if (item.getStartTime() == null || item.getStartTime().version() != 1) {
        throw new IllegalArgumentException("Start time must be a valid UUID version 1 identifier");
    }//from   w w  w  .jav a  2 s.co m
    if (item.getContents() == null) {
        throw new IllegalArgumentException("Contents must not be null");
    }
    if (item.getFilters() == null) {
        throw new IllegalArgumentException(
                "Filters cannot be null, if no filters are to be used pass an empty map");
    }

    Future<UUID> publishResult = executorService.submit(() -> {
        String filterNames;
        if (item.getFilters().isEmpty()) {
            filterNames = NO_FILTERS;
        } else {
            filterNames = String.join("_", item.getFilters().keySet());
        }
        String wholeOperationMetricName = "dqueue.publish." + filterNames + ".whole.timer";
        Optional<Timer.Context> publishTimer = Optional.ofNullable(metricRegistry)
                .map(m -> m.timer(wholeOperationMetricName).time());

        try {
            String tableName = createTableIfNotExists("publish", filterNames, item.getFilters());

            QueryBuilder queryBuilder = new QueryBuilder(cluster);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String primaryKey = df.format(new Date(UUIDs.unixTimestamp(item.getStartTime())));
            final Insert insert = queryBuilder.insertInto(cassandraKeyspace, tableName).value("key", primaryKey)
                    .value("start_time", item.getStartTime()).value("contents", item.getContents());

            if (item.getFilters() != null && !item.getFilters().isEmpty()) {
                for (String key : item.getFilters().keySet()) {
                    insert.value(key, item.getFilters().get(key));
                }
            }

            String cassandraInsertMetricName = "dqueue.publish." + filterNames + ".cassandraInsert.timer";
            executeAndMeasureTime(() -> session.executeAsync(insert).getUninterruptibly(),
                    cassandraInsertMetricName);

            return item.getStartTime();
        } finally {
            publishTimer.ifPresent(Timer.Context::stop);
        }
    });

    return publishResult;
}

From source file:com.hubrick.vertx.s3.client.S3Client.java

private S3ClientRequest createPutAclRequest(String bucket, String key,
        Optional<AclHeadersRequest> aclHeadersRequest, Handler<HttpClientResponse> handler) {
    HttpClientRequest httpRequest = client.put("/" + bucket + "/" + key + "?acl", handler);
    final S3ClientRequest s3ClientRequest = new S3ClientRequest("PUT", awsRegion, awsServiceName, httpRequest,
            awsAccessKey, awsSecretKey, clock, signPayload).setTimeout(globalTimeout).putHeader(Headers.HOST,
                    hostname);/*from   w ww.j a  v a2 s  . c o  m*/

    aclHeadersRequest.ifPresent(e -> s3ClientRequest.headers().addAll(populateAclHeadersRequest(e)));
    return s3ClientRequest;
}

From source file:com.ikanow.aleph2.analytics.spark.services.SparkCompilerService.java

/** Compiles a scala class
 * @param script//from  ww  w.  j  ava 2  s .  c  om
 * @param clazz_name
 * @return
 * @throws IOException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 */
public Tuple2<ClassLoader, Object> buildClass(final String script, final String clazz_name,
        final Optional<IBucketLogger> logger)
        throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    final String relative_dir = "./script_classpath/";
    new File(relative_dir).mkdirs();

    final File source_file = new File(relative_dir + clazz_name + ".scala");
    FileUtils.writeStringToFile(source_file, script);

    final String this_path = LiveInjector.findPathJar(this.getClass(), "./dummy.jar");
    final File f = new File(this_path);
    final File fp = new File(f.getParent());
    final String classpath = Arrays.stream(fp.listFiles()).map(ff -> ff.toString())
            .filter(ff -> ff.endsWith(".jar")).collect(Collectors.joining(":"));

    // Need this to make the URL classloader be used, not the system classloader (which doesn't know about Aleph2..)

    final Settings s = new Settings();
    s.classpath().value_$eq(System.getProperty("java.class.path") + classpath);
    s.usejavacp().scala$tools$nsc$settings$AbsSettings$AbsSetting$$internalSetting_$eq(true);
    final StoreReporter reporter = new StoreReporter();
    final Global g = new Global(s, reporter);
    final Run r = g.new Run();
    r.compile(JavaConverters.asScalaBufferConverter(Arrays.<String>asList(source_file.toString())).asScala()
            .toList());

    if (reporter.hasErrors() || reporter.hasWarnings()) {
        final String errors = "Compiler: Errors/warnings (**to get to user script line substract 22**): "
                + JavaConverters.asJavaSetConverter(reporter.infos()).asJava().stream()
                        .map(info -> info.toString()).collect(Collectors.joining(" ;; "));
        logger.ifPresent(l -> l.log(reporter.hasErrors() ? Level.ERROR : Level.DEBUG, false, () -> errors,
                () -> "SparkScalaInterpreterTopology", () -> "compile"));

        //ERROR:
        if (reporter.hasErrors()) {
            System.err.println(errors);
        }
    }
    // Move any class files (eg including sub-classes)
    Arrays.stream(fp.listFiles()).filter(ff -> ff.toString().endsWith(".class"))
            .forEach(Lambdas.wrap_consumer_u(ff -> {
                FileUtils.moveFile(ff, new File(relative_dir + ff.getName()));
            }));

    // Create a JAR file...

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    final JarOutputStream target = new JarOutputStream(new FileOutputStream("./script_classpath.jar"),
            manifest);
    Arrays.stream(new File(relative_dir).listFiles()).forEach(Lambdas.wrap_consumer_i(ff -> {
        JarEntry entry = new JarEntry(ff.getName());
        target.putNextEntry(entry);
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(ff))) {
            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        }
    }));
    target.close();

    final String created = "Created = " + new File("./script_classpath.jar").toURI().toURL() + " ... "
            + Arrays.stream(new File(relative_dir).listFiles()).map(ff -> ff.toString())
                    .collect(Collectors.joining(";"));
    logger.ifPresent(l -> l.log(Level.DEBUG, true, () -> created, () -> "SparkScalaInterpreterTopology",
            () -> "compile"));

    final Tuple2<ClassLoader, Object> o = Lambdas.get(Lambdas.wrap_u(() -> {
        _cl.set(new java.net.URLClassLoader(
                Arrays.asList(new File("./script_classpath.jar").toURI().toURL()).toArray(new URL[0]),
                Thread.currentThread().getContextClassLoader()));
        Object o_ = _cl.get().loadClass("ScriptRunner").newInstance();
        return Tuples._2T(_cl.get(), o_);
    }));
    return o;
}

From source file:com.rcn.controller.ResourceController.java

@RequestMapping(value = "/create-certificate", method = RequestMethod.POST)
public String createCertPost(@RequestParam("resourceType") String resourceType,
        @RequestParam("certName") String certName, @RequestParam("validDays") int validDays,
        @RequestParam("certDesc") String certDesc, @RequestParam("certType") String certType,
        @RequestParam("taPemCert") String taPemCert, @RequestParam("taPkcs10") String taPkcs10,
        @RequestParam("ca") String ca, @RequestParam("caPassword") String caPassword,
        @RequestParam("password1") String password1, @RequestParam("password2") String password2,
        Authentication principal, Model model) {

    Optional<String> optError = !password1.equals(password2) ? Optional.of(l("password.does.not.match"))
            : Optional.empty();//from  w  w  w  .jav  a 2  s  . c o  m

    if (!optError.isPresent()) {
        try {
            String type = ResoureMapping.computeIfAbsent(resourceType, a -> {
                throw new IllegalArgumentException("could not map a resource key:" + a);
            });

            RcnUserDetail user = (RcnUserDetail) principal.getPrincipal();
            Long targetUserId = user.getTargetUser().getId();

            Optional<String> caCert = ca.trim().length() > 0
                    ? Optional.ofNullable(
                            resourceRepository.certById(targetUserId, user.getId(), Long.valueOf(ca)))
                    : Optional.empty();

            Optional<String> clientCert = Optional.ofNullable("certImport".equals(certType) ? taPemCert : null);
            Optional<String> pkcs10Req = Optional
                    .ofNullable("certGeneratePkcs10".equals(certType) ? taPkcs10 : null);
            String cnName = certName.startsWith("cn=") ? certName : "cn=" + certName;
            String certPem = clientCert.orElseGet(() -> certificateService.generateCert(cnName, password1,
                    validDays, caCert, caPassword, TYPE_CA.equals(type), pkcs10Req));

            Long resourceId = resourceRepository.createResource(targetUserId, type, certName, certDesc);
            certificateService.storeCert(resourceId, certPem, password1);
        } catch (Exception e) {
            log.error("createCertPost", e);
            optError = Optional.of(e.getMessage());
        }
    }

    optError.ifPresent(e -> model.addAttribute("error", e));
    return optError.map(a -> "create-certificate").orElse("redirect:/resources");
}