All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.pincette.jes.util.Util Maven / Gradle / Ivy

There is a newer version: 3.2.1
Show newest version
package net.pincette.jes.util;

import static java.util.concurrent.CompletableFuture.completedFuture;
import static net.pincette.jes.util.JsonFields.ID;
import static net.pincette.jes.util.JsonFields.SEQ;
import static net.pincette.jes.util.JsonFields.TYPE;
import static net.pincette.json.JsonUtil.getString;
import static net.pincette.json.Validate.hasErrors;

import java.util.Optional;
import javax.json.JsonObject;

/**
 * Some general utilities.
 *
 * @author Werner Donn\u00e9
 * @since 1.0
 */
public class Util {
  private Util() {}

  /**
   * Returns a reducer that first calls validator and if the result doesn't contain any
   * errors it calls reducer.
   *
   * @param validator the given validator.
   * @param reducer the given reducer.
   * @return The composed function.
   * @since 1.0
   */
  public static Reducer compose(final Reducer validator, final Reducer reducer) {
    return (aggregate, command) ->
        validator
            .apply(aggregate, command)
            .thenComposeAsync(
                result ->
                    hasErrors(result)
                        ? completedFuture(result)
                        : reducer.apply(aggregate, command));
  }

  /**
   * Returns the username from "/_jwt/sub".
   *
   * @param json the given object.
   * @return The username.
   * @since 1.0
   */
  public static Optional getUsername(final JsonObject json) {
    return getString(json, "/_jwt/sub");
  }

  /**
   * Checks if json is a managed object. This means it has the fields _id,
   * _type and _seq.
   *
   * @param json the given object.
   * @return The check report.
   * @see JsonFields
   * @since 1.0
   */
  public static boolean isManagedObject(final JsonObject json) {
    return json != null && json.containsKey(ID) && json.containsKey(TYPE) && json.containsKey(SEQ);
  }

  /**
   * Checks if json is a managed object with the fields _id and 
   * _type set to id and type respectively.
   *
   * @param json the given object.
   * @param type the aggregate type.
   * @param id the ID of the instance.
   * @return The check report.
   * @since 1.0
   */
  public static boolean isManagedObject(final JsonObject json, final String type, final String id) {
    return json != null
        && type != null
        && id != null
        && type.equals(json.getString(TYPE, null))
        && id.equalsIgnoreCase(json.getString(ID, null))
        && json.containsKey(SEQ);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy