List of usage examples for java.util Optional ifPresent
public void ifPresent(Consumer<? super T> action)
From source file:gov.ca.cwds.cals.util.PlacementHomeUtil.java
private static StringBuilder composeSecondPartOfFacilityName(Optional<ApplicantDTO> firstApplicant, ApplicantDTO secondApplicant) {//from w w w .j a v a 2 s.c o m StringBuilder sbForSecondApplicant = new StringBuilder(); Optional<String> secondLastName = Optional.ofNullable(secondApplicant.getLastName()); Optional<String> secondFirstName = Optional.ofNullable(secondApplicant.getFirstName()); if (firstApplicant.isPresent() && secondLastName.isPresent() && !secondLastName.get().equals(firstApplicant.get().getLastName())) { sbForSecondApplicant.append(secondLastName.get()); if (secondFirstName.isPresent()) { sbForSecondApplicant.append(", "); } } secondFirstName.ifPresent(sbForSecondApplicant::append); return sbForSecondApplicant; }
From source file:ai.grakn.graql.GraqlShell.java
private static void sendBatchRequest(BatchMutatorClient batchMutatorClient, String graqlPath, Optional<Integer> activeTasks, Optional<Integer> batchSize) throws IOException { AtomicInteger numberBatchesCompleted = new AtomicInteger(0); activeTasks.ifPresent(batchMutatorClient::setNumberActiveTasks); batchSize.ifPresent(batchMutatorClient::setBatchSize); batchMutatorClient.setTaskCompletionConsumer((json) -> { TaskStatus status = TaskStatus.valueOf(json.at("status").asString()); numberBatchesCompleted.incrementAndGet(); System.out.println(format("Status of batch: %s", status)); System.out.println(format("Number batches completed: %s", numberBatchesCompleted.get())); System.out.println(format("Approximate queries executed: %s", numberBatchesCompleted.get() * batchMutatorClient.getBatchSize())); });/*w w w.ja v a 2 s.com*/ String queries = loadQuery(graqlPath); Graql.parseList(queries).forEach(batchMutatorClient::add); batchMutatorClient.waitToFinish(); }
From source file:net.sf.jabref.JabRef.java
/** * Will open a file (like importFile), but will also request JabRef to focus on this database * * @param argument See importFile./* w ww. j a va 2 s . c o m*/ * @return ParserResult with setToOpenTab(true) */ private static Optional<ParserResult> importToOpenBase(String argument) { Optional<ParserResult> result = JabRef.importFile(argument); result.ifPresent(x -> x.setToOpenTab(true)); return result; }
From source file:com.flozano.socialauth.util.HttpUtil.java
/** * Makes HTTP request using java.net.HTTPURLConnection and optional settings * for the connection/*from w w w .j a v a 2 s .c om*/ * * @param urlStr * the URL String * @param requestMethod * Method type * @param body * Body to pass in request. * @param header * Header parameters * @param connectionSettings * The connection settings to apply * @return Response Object * @throws SocialAuthException */ public static Response doHttpRequest(final String urlStr, final String requestMethod, final String body, final Map<String, String> header, Optional<ConnectionSettings> connectionSettings) throws SocialAuthException { HttpURLConnection conn; try { URL url = new URL(urlStr); if (proxyObj != null) { conn = (HttpURLConnection) url.openConnection(proxyObj); } else { conn = (HttpURLConnection) url.openConnection(); } connectionSettings.ifPresent(settings -> settings.apply(conn)); if (MethodType.POST.toString().equalsIgnoreCase(requestMethod) || MethodType.PUT.toString().equalsIgnoreCase(requestMethod)) { conn.setDoOutput(true); } conn.setDoInput(true); conn.setInstanceFollowRedirects(true); if (timeoutValue > 0) { LOG.debug("Setting connection timeout : " + timeoutValue); conn.setConnectTimeout(timeoutValue); } if (requestMethod != null) { conn.setRequestMethod(requestMethod); } if (header != null) { for (String key : header.keySet()) { conn.setRequestProperty(key, header.get(key)); } } // If use POST or PUT must use this OutputStream os = null; if (body != null) { if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod) && !MethodType.DELETE.toString().equals(requestMethod)) { os = conn.getOutputStream(); DataOutputStream out = new DataOutputStream(os); out.write(body.getBytes("UTF-8")); out.flush(); } } conn.connect(); } catch (Exception e) { throw new SocialAuthException(e); } return new Response(conn); }
From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_LibraryJars.java
/** Create a new library bean * @param id/* ww w . java 2 s . c o m*/ * @param bucket_mgmt * @param create_not_update - true if create, false if update * @param share_db * @return */ protected static ManagementFuture<Supplier<Object>> createLibraryBean(final String id, final IManagementCrudService<SharedLibraryBean> library_mgmt, final IStorageService aleph2_fs, final boolean create_not_update, final ICrudService<JsonNode> share_db, final GridFS share_fs, final IServiceContext context) { if (create_not_update) { _logger.info(ErrorUtils.get("Found new share {0}, creating library bean", id)); } else { _logger.info(ErrorUtils.get("Share {0} was modified, updating library bean", id)); } // Create a status bean: final SingleQueryComponent<JsonNode> v1_query = CrudUtils.allOf().when(JsonUtils._ID, new ObjectId(id)); return FutureUtils.denestManagementFuture(share_db.getObjectBySpec(v1_query) .<ManagementFuture<Supplier<Object>>>thenApply(Lambdas.wrap_u(jsonopt -> { final SharedLibraryBean new_object = getLibraryBeanFromV1Share(jsonopt.get()); // Try to copy the file across before going crazy (going to leave this as single threaded for now, we'll live) final String binary_id = safeJsonGet("binaryId", jsonopt.get()).asText(); if (!binary_id.isEmpty()) { copyFile(binary_id, new_object.path_name(), aleph2_fs, share_fs); } else { // Check if it's a reference and if so copy from local to HDFS final Optional<String> maybe_local_path = JsonUtils .getProperty("documentLocation.collection", jsonopt.get()) .filter(j -> j.isTextual()).map(j -> j.asText()); maybe_local_path.ifPresent(Lambdas.wrap_consumer_u( local_path -> copyFile(local_path, new_object.path_name(), aleph2_fs))); } final AuthorizationBean auth = new AuthorizationBean(new_object.owner_id()); final ManagementFuture<Supplier<Object>> ret = library_mgmt.secured(context, auth) .storeObject(new_object, !create_not_update); return ret; })).exceptionally(e -> { return FutureUtils .<Supplier<Object>>createManagementFuture( FutureUtils.returnError(new RuntimeException(e)), CompletableFuture.completedFuture(Arrays.asList(new BasicMessageBean(new Date(), false, "IkanowV1SyncService_LibraryJars", "createLibraryBean", null, ErrorUtils.getLongForm("{0}", e), null)))); })); }
From source file:com.flozano.socialauth.util.HttpUtil.java
/** * * @param urlStr// w w w . ja va 2s . c o m * the URL String * @param requestMethod * Method type * @param params * Parameters to pass in request * @param header * Header parameters * @param inputStream * Input stream of image * @param fileName * Image file name * @param fileParamName * Image Filename parameter. It requires in some provider. * @return Response object * @throws SocialAuthException */ public static Response doHttpRequest(final String urlStr, final String requestMethod, final Map<String, String> params, final Map<String, String> header, final InputStream inputStream, final String fileName, final String fileParamName, Optional<ConnectionSettings> connectionSettings) throws SocialAuthException { HttpURLConnection conn; try { URL url = new URL(urlStr); if (proxyObj != null) { conn = (HttpURLConnection) url.openConnection(proxyObj); } else { conn = (HttpURLConnection) url.openConnection(); } connectionSettings.ifPresent(settings -> settings.apply(conn)); if (requestMethod.equalsIgnoreCase(MethodType.POST.toString()) || requestMethod.equalsIgnoreCase(MethodType.PUT.toString())) { conn.setDoOutput(true); } conn.setDoInput(true); conn.setInstanceFollowRedirects(true); if (timeoutValue > 0) { LOG.debug("Setting connection timeout : " + timeoutValue); conn.setConnectTimeout(timeoutValue); } if (requestMethod != null) { conn.setRequestMethod(requestMethod); } if (header != null) { for (String key : header.keySet()) { conn.setRequestProperty(key, header.get(key)); } } // If use POST or PUT must use this OutputStream os = null; if (inputStream != null) { if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod) && !MethodType.DELETE.toString().equals(requestMethod)) { LOG.debug(requestMethod + " request"); String boundary = "----Socialauth-posting" + System.currentTimeMillis(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); boundary = "--" + boundary; os = conn.getOutputStream(); DataOutputStream out = new DataOutputStream(os); write(out, boundary + "\r\n"); if (fileParamName != null) { write(out, "Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\"" + fileName + "\"\r\n"); } else { write(out, "Content-Disposition: form-data; filename=\"" + fileName + "\"\r\n"); } write(out, "Content-Type: " + "multipart/form-data" + "\r\n\r\n"); int b; while ((b = inputStream.read()) != -1) { out.write(b); } // out.write(imageFile); write(out, "\r\n"); Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); write(out, boundary + "\r\n"); write(out, "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"); // write(out, // "Content-Type: text/plain;charset=UTF-8 \r\n\r\n"); LOG.debug(entry.getValue()); out.write(entry.getValue().getBytes("UTF-8")); write(out, "\r\n"); } write(out, boundary + "--\r\n"); write(out, "\r\n"); } } conn.connect(); } catch (Exception e) { throw new SocialAuthException(e); } return new Response(conn); }
From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java
/** Inserts one of a few different of property into an edge or vertex * TODO (ALEPH-15): Doesn't currently handle a few things: eg multi cardinality, permissions * @param mutable_element/*from w ww . j a v a 2 s .co m*/ * @param maybe_props */ protected static void insertProperties(final Element mutable_element, final Optional<ObjectNode> maybe_props) { maybe_props.ifPresent(props -> { Optionals.streamOf(props.fields(), false).forEach(prop -> { Optional.ofNullable(denestProperties(prop.getValue())).ifPresent(val -> val.either(o -> { return mutable_element.property(prop.getKey(), o); }, oo -> { if (oo.length > 0) { Patterns.match(oo[0]).andAct() // (see jsonNodeToObject - these are the only possibilities) .when(String.class, __ -> mutable_element.property(prop.getKey(), Arrays.stream(oo).toArray(String[]::new))) .when(Long.class, __ -> mutable_element.property(prop.getKey(), Arrays.stream(oo).toArray(Long[]::new))) .when(Double.class, __ -> mutable_element.property(prop.getKey(), Arrays.stream(oo).toArray(Double[]::new))) .when(Boolean.class, __ -> mutable_element.property(prop.getKey(), Arrays.stream(oo).toArray(Boolean[]::new))); } return null; })); }); }); }
From source file:nu.yona.server.subscriptions.service.migration.MoveVpnPasswordToDevice.java
@Override public void upgrade(User user) { Optional<String> vpnPassword = user.getAndClearVpnPassword(); vpnPassword.ifPresent(p -> setPasswordOnDefaultDevice(user, p)); }
From source file:com.ikanow.aleph2.analytics.spark.utils.SparkTechnologyUtils.java
/** Builds a multimap of named inputs * @param context the analytic context retrieved from the * @return A multi map of Java RDDs against name (with input name built as resource_name:data_service if not present) */// w w w. ja va 2 s . c o m public static Multimap<String, JavaPairRDD<Object, Tuple2<Long, IBatchRecord>>> buildBatchSparkInputs( final IAnalyticsContext context, final Optional<ProcessingTestSpecBean> maybe_test_spec, final JavaSparkContext spark_context, final Set<String> exclude_names) { final DataBucketBean bucket = context.getBucket().get(); final AnalyticThreadJobBean job = context.getJob().get(); final Configuration config = HadoopTechnologyUtils .getHadoopConfig(context.getServiceContext().getGlobalProperties()); config.set(HadoopBatchEnrichmentUtils.BE_BUCKET_SIGNATURE, BeanTemplateUtils.toJson(bucket).toString()); maybe_test_spec.ifPresent(test_spec -> Optional.ofNullable(test_spec.requested_num_objects()) .ifPresent(num -> config.set(HadoopBatchEnrichmentUtils.BE_DEBUG_MAX_SIZE, Long.toString(num)))); final Multimap<String, JavaPairRDD<Object, Tuple2<Long, IBatchRecord>>> mutable_builder = HashMultimap .create(); buildAleph2Inputs(context, bucket, job, maybe_test_spec, config, exclude_names, (input, input_job) -> { try { @SuppressWarnings("unchecked") final JavaPairRDD<Object, Tuple2<Long, IBatchRecord>> rdd = spark_context.newAPIHadoopRDD( input_job.getConfiguration(), (Class<InputFormat<Object, Tuple2<Long, IBatchRecord>>>) input_job.getInputFormatClass(), Object.class, (Class<Tuple2<Long, IBatchRecord>>) (Class<?>) Tuple2.class); mutable_builder.put(input.name(), rdd); } catch (Throwable t) { System.out.println(ErrorUtils.getLongForm("ERROR: building aleph2 inputs: {0}", t)); } }); return mutable_builder; }
From source file:org.openmhealth.shim.runkeeper.mapper.RunkeeperCaloriesBurnedDataPointMapper.java
private Optional<CaloriesBurned> getMeasure(JsonNode itemNode) { Optional<Double> calorieValue = asOptionalDouble(itemNode, "total_calories"); if (!calorieValue.isPresent()) { // Not all activity datapoints have the "total_calories" property return Optional.empty(); }/* w ww . j av a 2s . c om*/ CaloriesBurned.Builder caloriesBurnedBuilder = new CaloriesBurned.Builder( new KcalUnitValue(KcalUnit.KILOCALORIE, calorieValue.get())); setEffectiveTimeFrameIfPresent(itemNode, caloriesBurnedBuilder); Optional<String> activityType = asOptionalString(itemNode, "type"); activityType.ifPresent(at -> caloriesBurnedBuilder.setActivityName(at)); return Optional.of(caloriesBurnedBuilder.build()); }