Example usage for java.util Optional orElse

List of usage examples for java.util Optional orElse

Introduction

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

Prototype

public T orElse(T other) 

Source Link

Document

If a value is present, returns the value, otherwise returns other .

Usage

From source file:no.ssb.jsonstat.v2.deser.DatasetDeserializer.java

@Override
public DatasetBuildable deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    if (p.getCurrentToken() == JsonToken.START_OBJECT) {
        p.nextToken();/*w  w w.  j ava2 s. c o  m*/
    }

    Set<String> ids = Collections.emptySet();
    List<Integer> sizes = Collections.emptyList();
    Multimap<String, String> roles = ArrayListMultimap.create();
    Map<String, Dimension.Builder> dims = Collections.emptyMap();
    List<Number> values = Collections.emptyList();

    DatasetBuilder builder = Dataset.create();
    Optional<String> version = Optional.empty();
    Optional<String> clazz = Optional.empty();
    Optional<ObjectNode> extension = Optional.empty();

    while (p.nextValue() != JsonToken.END_OBJECT) {
        switch (p.getCurrentName()) {
        case "label":
            builder.withLabel(_parseString(p, ctxt));
            break;
        case "source":
            builder.withSource(_parseString(p, ctxt));
            break;
        case "href":
            break;
        case "updated":
            Instant updated = parseEcmaDate(_parseString(p, ctxt));
            builder.updatedAt(updated);
            break;
        case "value":
            values = parseValues(p, ctxt);
            break;
        case "dimension":
            if (!version.orElse("1.x").equals("2.0")) {
                dims = Maps.newHashMap();
                // Deal with the id, size and role inside dimension.
                while (p.nextValue() != JsonToken.END_OBJECT) {
                    switch (p.getCurrentName()) {
                    case "id":
                        ids = p.readValueAs(ID_SET);
                        break;
                    case "size":
                        sizes = p.readValueAs(SIZE_LIST);
                        break;
                    case "role":
                        roles = p.readValueAs(ROLE_MULTIMAP);
                        break;
                    default:
                        dims.put(p.getCurrentName(), ctxt.readValue(p, Dimension.Builder.class));
                    }
                }
            } else {
                dims = p.readValueAs(DIMENSION_MAP);
            }
            break;
        case "id":
            ids = p.readValueAs(ID_SET);
            break;
        case "size":
            sizes = p.readValueAs(SIZE_LIST);
            break;
        case "role":
            roles = p.readValueAs(ROLE_MULTIMAP);
            break;
        case "extension":
            extension = Optional.of(ctxt.readValue(p, ObjectNode.class));
            break;
        case "link":
        case "status":
            // TODO
            p.skipChildren();
            break;
        case "version":
            version = Optional.of(_parseString(p, ctxt));
            break;
        case "class":
            // TODO
            clazz = Optional.of(_parseString(p, ctxt));
            break;
        default:
            boolean handled = ctxt.handleUnknownProperty(p, this, Dimension.Builder.class, p.getCurrentName());
            if (!handled)
                p.skipChildren();
            break;
        }
    }

    // Setup roles
    for (Map.Entry<String, String> dimRole : roles.entries()) {
        Dimension.Roles role = Dimension.Roles.valueOf(dimRole.getKey().toUpperCase());
        Dimension.Builder dimension = checkNotNull(dims.get(dimRole.getValue()),
                "could not assign the role {} to the dimension {}. The dimension did not exist", role,
                dimRole.getValue()

        );
        dimension.withRole(role);
    }

    List<Dimension.Builder> orderedDimensions = Lists.newArrayList();
    for (String dimensionName : ids) {
        orderedDimensions.add(dims.get(dimensionName));
    }

    // TODO: Check size?

    // Check ids and add to the data set.
    checkArgument(ids.size() == dims.size(), "dimension and size did not match");

    if (extension.isPresent()) {
        builder.withExtension(extension.get());
    }

    return builder.withDimensions(orderedDimensions).withValues(values);
}

From source file:com.ggvaidya.scinames.model.Dataset.java

/**
 * Set the previous dataset. This is where we calculate implicit changes from the previous
 * dataset that have not been explained in our explicit changes.
 * //w  ww  .  j  a  v  a  2  s  . c o  m
 * @param proj Optionally, the project this dataset is a part of. Used for change filtering.
 * @param tp Optionally, the previous dataset. If null, means there isn't one: we should be considered
 *       the first checklist.
 */
public void setPreviousDataset(Optional<Project> proj, Optional<Dataset> tp) {
    project = proj.orElse(null);
    prevDataset = tp.orElse(null);

    implicitChanges.clear();
    if (isChecklist()) {
        // Implicit changes don't exist for non-checklists. If we're a checklist, figure out what
        // names are new or have been removed in this checklist.

        Set<Name> names = getNamesInAllRows();
        Set<Name> prevNames;

        if (proj.isPresent() && tp.isPresent()) {
            prevNames = prevDataset.getRecognizedNames(proj.get()).collect(Collectors.toSet());
        } else {
            prevNames = new HashSet<>();
        }

        /*
         * Logically, at this point, we need to apply the change filter so that changes that
         * should be filtered out, are filtered out. However, we haven't calculated name clusters
         * at this point, so the filtering wouldn't be correct anyway.
         * 
         * So, instead, we accept all explicit changes and calculate implicit changes on that
         * basis. We then filter changes out of the explicit and implicit changes as needed.
         * 
         */

        // What names do explicit changes add or remove?
        Set<Name> addedByExplicitChanges = explicitChanges.stream().flatMap(ch -> ch.getToStream())
                .collect(Collectors.toSet());
        Set<Name> deletedByExplicitChanges = explicitChanges.stream().flatMap(ch -> ch.getFromStream())
                .collect(Collectors.toSet());

        // Calculate implicit changes that can't be explained by an explicit change.
        Stream<Change> additions = names.stream()
                .filter(n -> !prevNames.contains(n) && !addedByExplicitChanges.contains(n))
                .map(n -> new Change(this, ChangeType.ADDITION, Stream.empty(), Stream.of(n)));
        Stream<Change> deletions = prevNames.stream()
                .filter(n -> !names.contains(n) && !deletedByExplicitChanges.contains(n))
                .map(n -> new Change(this, ChangeType.DELETION, Stream.of(n), Stream.empty()));

        implicitChanges.addAll(additions.collect(Collectors.toList()));
        implicitChanges.addAll(deletions.collect(Collectors.toList()));
    }
}

From source file:org.apache.tajo.storage.hbase.HBaseTablespace.java

@Override
public long getTableVolume(TableDesc table, Optional<EvalNode> filter) {
    long totalVolume;
    try {/*from  www .  j  a v a  2  s.  c  o  m*/
        totalVolume = getRawSplits("", table, filter.orElse(null)).stream().map(f -> f.getLength())
                .filter(size -> size > 0) // eliminate unknown sizes (-1)
                .reduce(0L, Long::sum);
    } catch (TajoException e) {
        throw new TajoRuntimeException(e);
    } catch (Throwable ioe) {
        throw new TajoInternalError(ioe);
    }
    return totalVolume;
}

From source file:com.spectralogic.ds3contractcomparator.print.htmlprinter.generators.row.ModifiedHtmlRowGenerator.java

/**
 * Recursively traverses two objects using reflection and constructs the modified
 * rows that represent the changes and differences between the objects.
 *///from  w  ww  . jav a2 s  .  c  om
public static <T> ImmutableList<Row> createModifiedRows(final T oldObject, final T newObject,
        final int indent) {
    if (oldObject == null && newObject == null) {
        return ImmutableList.of();
    }
    final Field[] fields = getFields(oldObject, newObject);
    final ImmutableList.Builder<Row> builder = ImmutableList.builder();

    for (final Field field : fields) {
        final String property = field.getName();

        final Optional<String> oldValue = getPropertyValue(oldObject, property);
        final Optional<String> newValue = getPropertyValue(newObject, property);

        if (oldValue.isPresent() || newValue.isPresent()) {
            final int fieldIndent = toModifiedFieldIndent(indent, oldObject, newObject, field);
            if (field.getType() == ImmutableList.class) {
                //Field is a list, recursively print each element in the list
                builder.add(new NoChangeRow(fieldIndent, property, ""));

                final ImmutableList<Object> oldObjList = getListPropertyFromObject(field, oldObject);
                final ImmutableList<Object> newObjList = getListPropertyFromObject(field, newObject);

                if (hasContent(oldObjList) || hasContent(newObjList)) {
                    final String uniqueProperty = getPropertyNameFromList(oldObjList, newObjList);

                    final ImmutableSet<String> parameterUnion = toPropertyUnion(oldObjList, newObjList,
                            uniqueProperty);
                    final ImmutableMap<String, Object> oldMap = toPropertyMap(oldObjList, uniqueProperty);
                    final ImmutableMap<String, Object> newMap = toPropertyMap(newObjList, uniqueProperty);

                    parameterUnion.forEach(param -> builder
                            .addAll(createModifiedRows(oldMap.get(param), newMap.get(param), fieldIndent + 1)));
                }
            } else if (oldValue.isPresent() && newValue.isPresent() && oldValue.get().equals(newValue.get())) {
                //Element is the same in both contracts
                builder.add(new NoChangeRow(fieldIndent, property, oldValue.get()));
            } else {
                //Element is different between old and new contracts
                builder.add(new ModifiedRow(fieldIndent, property, oldValue.orElse(RowConstants.NA),
                        newValue.orElse(RowConstants.NA)));
            }
        }
    }
    return builder.build();
}

From source file:com.ikanow.aleph2.enrichment.utils.services.JsScriptEngineService.java

@Override
public void onStageInitialize(IEnrichmentModuleContext context, DataBucketBean bucket,
        EnrichmentControlMetadataBean control, final Tuple2<ProcessingStage, ProcessingStage> previous_next,
        final Optional<List<String>> grouping_fields) {
    // This is currently fixed:
    java_api.set(true);/* w  w  w.j av  a2 s .  c o  m*/

    final JsScriptEngineBean config_bean = BeanTemplateUtils
            .from(Optional.ofNullable(control.config()).orElse(Collections.emptyMap()),
                    JsScriptEngineBean.class)
            .get();
    _config.trySet(config_bean);
    _context.trySet(context);
    _control.trySet(control);

    // Initialize script engine:
    ScriptEngineManager manager = new ScriptEngineManager();
    _engine.trySet(manager.getEngineByName("JavaScript"));
    _script_context.trySet(_engine.get().getContext()); // (actually not needed since we're compiling things)

    _bucket_logger.set(context.getLogger(Optional.of(bucket)));

    // Load globals:
    _engine.get().put("_a2_global_context", _context.get());
    _engine.get().put("_a2_global_grouping_fields", grouping_fields.orElse(Collections.emptyList()));
    _engine.get().put("_a2_global_previous_stage", previous_next._1().toString());
    _engine.get().put("_a2_global_next_stage", previous_next._2().toString());
    _engine.get().put("_a2_global_bucket", bucket);
    _engine.get().put("_a2_global_config", BeanTemplateUtils.configureMapper(Optional.empty())
            .convertValue(config_bean.config(), JsonNode.class));
    _engine.get().put("_a2_global_mapper", BeanTemplateUtils.configureMapper(Optional.empty()));
    _engine.get().put("_a2_bucket_logger", _bucket_logger.optional().orElse(null));
    _engine.get().put("_a2_enrichment_name", Optional.ofNullable(control.name()).orElse("no_name"));

    // Load the resources:
    Stream.concat(config_bean.imports().stream(),
            Stream.of("aleph2_js_globals_before.js", "", "aleph2_js_globals_after.js"))
            .flatMap(Lambdas.flatWrap_i(import_path -> {
                try {
                    if (import_path.equals("")) { // also import the user script just before here
                        return config_bean.script();
                    } else
                        return IOUtils.toString(
                                JsScriptEngineService.class.getClassLoader().getResourceAsStream(import_path),
                                "UTF-8");
                } catch (Throwable e) {
                    _bucket_logger.optional().ifPresent(l -> l.log(Level.ERROR, ErrorUtils.lazyBuildMessage(
                            false, () -> this.getClass().getSimpleName(),
                            () -> Optional.ofNullable(control.name()).orElse("no_name") + ".onStageInitialize",
                            () -> null,
                            () -> ErrorUtils.get("Error initializing stage {0} (script {1}): {2}",
                                    Optional.ofNullable(control.name()).orElse("(no name)"), import_path,
                                    e.getMessage()),
                            () -> ImmutableMap.<String, Object>of("full_error",
                                    ErrorUtils.getLongForm("{0}", e)))));

                    _logger.error(ErrorUtils.getLongForm("onStageInitialize: {0}", e));
                    throw e; // ignored
                }
            })).forEach(Lambdas.wrap_consumer_i(script -> {
                try {
                    _engine.get().eval(script);
                } catch (Throwable e) {
                    _bucket_logger.optional().ifPresent(l -> l.log(Level.ERROR, ErrorUtils.lazyBuildMessage(
                            false, () -> this.getClass().getSimpleName(),
                            () -> Optional.ofNullable(control.name()).orElse("no_name") + ".onStageInitialize",
                            () -> null,
                            () -> ErrorUtils.get("Error initializing stage {0} (main script): {1}",
                                    Optional.ofNullable(control.name()).orElse("(no name)"), e.getMessage()),
                            () -> ImmutableMap.<String, Object>of("full_error",
                                    ErrorUtils.getLongForm("{0}", e)))));

                    _logger.error(ErrorUtils.getLongForm("onStageInitialize: {0}", e));
                    throw e; // ignored
                }
            }));
    ;
}

From source file:org.exist.launcher.Launcher.java

public Launcher(final String[] args) {
    if (SystemTray.isSupported()) {
        tray = SystemTray.getSystemTray();
    }//from ww  w. j av  a 2  s.  c  om

    captureConsole();

    this.jettyConfig = getJettyConfig();
    final Optional<Path> eXistHome = ConfigurationHelper.getExistHome();
    final Path wrapperConfig;
    if (eXistHome.isPresent()) {
        wrapperConfig = eXistHome.get().resolve("tools/yajsw/conf/wrapper.conf");
    } else {
        wrapperConfig = Paths.get("tools/yajsw/conf/wrapper.conf");
    }

    wrapperProperties = new Properties();
    wrapperProperties.setProperty("wrapper.working.dir", eXistHome.orElse(Paths.get(".")).toString());
    wrapperProperties.setProperty("wrapper.config", wrapperConfig.toString());

    System.setProperty("wrapper.config", wrapperConfig.toString());

    installedAsService();

    boolean initSystemTray = true;
    if (isSystemTraySupported()) {
        initSystemTray = initSystemTray();
    }

    configDialog = new ConfigurationDialog(this::shutdown);

    splash = new SplashScreen(this);
    splash.addWindowListener(new WindowAdapter() {
        @Override
        public void windowOpened(WindowEvent windowEvent) {
            setServiceState();
            if (runningAsService.isPresent()) {
                splash.setStatus("eXist-db is already installed as service! Attaching to it ...");
                final Timer timer = new Timer(3000, (event) -> splash.setVisible(false));
                timer.setRepeats(false);
                timer.start();
            } else {
                if (ConfigurationUtility.isFirstStart()) {
                    splash.setVisible(false);
                    configDialog.open(true);
                    configDialog.requestFocus();
                } else {
                    startJetty();
                }
            }
        }
    });

    final boolean systemTrayReady = tray != null && initSystemTray && tray.getTrayIcons().length > 0;

    SwingUtilities.invokeLater(() -> utilityPanel = new UtilityPanel(Launcher.this, systemTrayReady));
}

From source file:org.haiku.haikudepotserver.api1.UserRatingApiImpl.java

@Override
public CreateUserRatingResult createUserRating(CreateUserRatingRequest request) throws ObjectNotFoundException {
    Preconditions.checkNotNull(request);
    Preconditions.checkState(!Strings.isNullOrEmpty(request.naturalLanguageCode));
    Preconditions.checkState(!Strings.isNullOrEmpty(request.pkgName));
    Preconditions.checkState(!Strings.isNullOrEmpty(request.pkgVersionArchitectureCode));
    Preconditions.checkArgument(!Strings.isNullOrEmpty(request.repositoryCode),
            "the repository code should be supplied");
    Preconditions.checkArgument(null == request.rating || request.rating >= UserRating.MIN_USER_RATING,
            "the user rating " + request.rating + " is less than the minimum allowed of "
                    + UserRating.MIN_USER_RATING);
    Preconditions.checkArgument(null == request.rating || request.rating <= UserRating.MAX_USER_RATING,
            "the user rating " + request.rating + " is greater than the maximum allowed of "
                    + UserRating.MIN_USER_RATING);

    if (null != request.comment) {
        request.comment = Strings.emptyToNull(request.comment.trim());
    }//from  ww w .  j  a v a2  s.c  o m

    // check to see that the user has not tried to create a user rating with essentially nothing
    // in it.

    if (Strings.isNullOrEmpty(request.comment) && null == request.userRatingStabilityCode
            && null == request.rating) {
        throw new IllegalStateException(
                "it is not possible to create a user rating with no meaningful rating data");
    }

    final ObjectContext context = serverRuntime.newContext();

    Optional<Pkg> pkgOptional = Pkg.tryGetByName(context, request.pkgName);

    if (!pkgOptional.isPresent()) {
        throw new ObjectNotFoundException(Pkg.class.getSimpleName(), request.pkgName);
    }

    Architecture architecture = getArchitecture(context, request.pkgVersionArchitectureCode);
    NaturalLanguage naturalLanguage = getNaturalLanguage(context, request.naturalLanguageCode);
    Repository repository = getRepository(context, request.repositoryCode);
    User user = User.tryGetByNickname(context, request.userNickname)
            .orElseThrow(() -> new ObjectNotFoundException(User.class.getSimpleName(), request.userNickname));

    Optional<UserRatingStability> userRatingStabilityOptional = Optional.empty();

    if (null != request.userRatingStabilityCode) {
        userRatingStabilityOptional = UserRatingStability.getByCode(context, request.userRatingStabilityCode);

        if (!userRatingStabilityOptional.isPresent()) {
            throw new ObjectNotFoundException(UserRatingStability.class.getSimpleName(),
                    request.userRatingStabilityCode);
        }
    }

    // check authorization

    Optional<User> authenticatedUserOptional = tryObtainAuthenticatedUser(context);

    if (!authenticatedUserOptional.isPresent()) {
        LOGGER.warn("only authenticated users are able to add user ratings");
        throw new AuthorizationFailureException();
    }

    if (!authenticatedUserOptional.get().getNickname().equals(user.getNickname())) {
        LOGGER.warn("it is not allowed to add a user rating for another user");
        throw new AuthorizationFailureException();
    }

    if (!authorizationService.check(context, authenticatedUserOptional.orElse(null), pkgOptional.get(),
            Permission.PKG_CREATEUSERRATING)) {
        throw new AuthorizationFailureException();
    }

    // check the package version

    Optional<PkgVersion> pkgVersionOptional;

    switch (request.pkgVersionType) {
    case LATEST:
        pkgVersionOptional = pkgService.getLatestPkgVersionForPkg(context, pkgOptional.get(), repository,
                Collections.singletonList(architecture));
        break;

    case SPECIFIC:
        pkgVersionOptional = PkgVersion.getForPkg(context, pkgOptional.get(), repository, architecture,
                new VersionCoordinates(request.pkgVersionMajor, request.pkgVersionMinor,
                        request.pkgVersionMicro, request.pkgVersionPreRelease, request.pkgVersionRevision));
        break;

    default:
        throw new IllegalStateException("unsupported pkg version type; " + request.pkgVersionType.name());
    }

    if (!pkgVersionOptional.isPresent()) {
        throw new ObjectNotFoundException(PkgVersion.class.getSimpleName(),
                pkgOptional.get().getName() + "_" + request.pkgVersionType.name());
    }

    if (!pkgVersionOptional.get().getIsLatest()) {
        throw new IllegalStateException(
                "it is not possible to add a user rating to a version other than the latest version.");
    }

    List<UserRating> legacyUserRatings = UserRating.findByUserAndPkg(context, user, pkgOptional.get());

    for (UserRating legacyUserRating : legacyUserRatings) {
        if (legacyUserRating.getPkgVersion().equals(pkgVersionOptional.get())) {
            throw new IllegalStateException("an existing user rating '" + legacyUserRating.getCode()
                    + "' already exists for this package version; it is not possible to add another one");
        }
    }

    // now create the new user rating.

    UserRating userRating = context.newObject(UserRating.class);
    userRating.setCode(UUID.randomUUID().toString());
    userRating.setUserRatingStability(userRatingStabilityOptional.orElse(null));
    userRating.setUser(user);
    userRating.setComment(Strings.emptyToNull(Strings.nullToEmpty(request.comment).trim()));
    userRating.setPkgVersion(pkgVersionOptional.get());
    userRating.setNaturalLanguage(naturalLanguage);
    userRating.setRating(request.rating);

    context.commitChanges();

    LOGGER.info("did create user rating for user {} on package {}", user.toString(),
            pkgOptional.get().toString());

    return new CreateUserRatingResult(userRating.getCode());

}

From source file:org.xwiki.contrib.repository.pypi.internal.searching.PypiPackageListIndexUpdateTask.java

@Override
public void run() {
    logger.info("Start of update lucene index task");
    boolean newIndexCreated = false;
    boolean isFirstUpdate = false;
    File currentIndex = pypiPackageListIndexDirectory.get();
    File indexDir = environment.getTemporaryDirectory();
    if (currentIndex == null) {
        isFirstUpdate = true;//from   www  . j ava2s  . co  m
    }
    IndexWriter indexWriter = null;
    Optional<InputStream> htmlPageInputStream = null;
    try {
        indexWriter = new IndexWriter(FSDirectory.open(indexDir.toPath()),
                new IndexWriterConfig(new StandardAnalyzer()));
        htmlPageInputStream = getSimpleApiHtmlPageInputStream();
        if (htmlPageInputStream.isPresent()) {
            List<String> packageNames = parseHtmlPageToPackagenames(htmlPageInputStream.get());
            packageNames = removePackagesIncludedInJython(packageNames);
            addAllValidPackagesToIndex(indexWriter, packageNames);
        }
        newIndexCreated = true;
    } catch (IOException e) {
        logger.error("IO problem whilst updating python package index", e);
    } catch (SAXException | ParserConfigurationException e) {
        logger.error("Problem occured whilst parsing list of packages from PyPi", e);
    } finally {
        IOUtils.closeQuietly(indexWriter);
        IOUtils.closeQuietly(htmlPageInputStream.orElse(null));
    }
    if (newIndexCreated) {
        File previousIndexDir = pypiPackageListIndexDirectory.get();
        pypiPackageListIndexDirectory.set(indexDir);
        try {
            if (previousIndexDir != null) {
                FileUtils.forceDelete(previousIndexDir);
            }
        } catch (Exception e) {

        }
        logger.info("End of update lucene index task. Pypi packages list index updated");
    } else {
        logger.info("End of update lucene index task. Pypi packages list update called but index not updated");
    }
}

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

/** Handles the prefix and suffix of the full hive schema
 *  https://www.elastic.co/guide/en/elasticsearch/hadoop/current/hive.html
 * @param table_name - if empty then "main_table"
 * @param bucket/*w  w  w. j  a v a 2 s . c o  m*/
 * @param schema
 * @param partial_hive_schema
 * @return
 */
public static Validation<String, String> generateFullHiveSchema(final Optional<String> table_name,
        final DataBucketBean bucket, final DataSchemaBean.DataWarehouseSchemaBean schema,
        Optional<Client> maybe_client, ElasticsearchIndexServiceConfigBean config) {
    // (ignore views for the moment)

    final String prefix = ErrorUtils.get("CREATE EXTERNAL TABLE {0} ", getTableName(bucket, schema));

    final DataSchemaBean.DataWarehouseSchemaBean.Table table = table_name.flatMap(t -> Optionals
            .ofNullable(schema.views()).stream().filter(v -> t.equals(v.database_name())).findFirst())
            .orElse(schema.main_table());

    final JsonNode user_schema = _mapper.convertValue(table.table_format(), JsonNode.class);

    final Validation<String, String> partial_table = generatePartialHiveSchema(prefix, user_schema, true);

    // (for the main table, just going to be the full alias - for views will need to be cleverer)
    final String index = Optionals
            .of(() -> bucket.data_schema().search_index_schema().technology_override_schema()
                    .get(SearchIndexSchemaDefaultBean.index_name_override_).toString())
            .orElseGet(() -> "r__" + BucketUtils.getUniqueSignature(bucket.full_name(), Optional.empty()));

    final Optional<ElasticsearchHiveOverrideBean> maybe_override = Optionals
            .of(() -> schema.technology_override_schema())
            .map(m -> BeanTemplateUtils.from(m, ElasticsearchHiveOverrideBean.class).get());

    // OK all this horrible code is intended to sort out the list of types to apply in the hive query
    final Optional<ElasticsearchHiveOverrideBean.TableOverride> table_override = maybe_override
            .map(cfg -> cfg.table_overrides().get(table_name.orElse(MAIN_TABLE_NAME)));
    final Optional<Set<String>> user_type_overrides = table_override.map(t -> t.types())
            .filter(l -> !l.isEmpty()).map(l -> new TreeSet<String>(l));
    final Set<String> mutable_type_set = user_type_overrides.orElseGet(() -> {
        return new TreeSet<String>(
                maybe_client.map(client -> ElasticsearchIndexUtils.getTypesForIndex(client, index).values())
                        .orElse(Collections.emptySet()));
    });

    final ElasticsearchIndexServiceConfigBean schema_config = ElasticsearchIndexConfigUtils
            .buildConfigBeanFromSchema(bucket, config, _mapper);
    final CollidePolicy collide_policy = Optionals
            .of(() -> schema_config.search_technology_override().collide_policy())
            .orElse(CollidePolicy.new_type);

    Optionals.of(() -> schema_config.search_technology_override().type_name_or_prefix()).map(Optional::of)
            .orElseGet(() -> Optional.of((collide_policy == CollidePolicy.new_type)
                    ? ElasticsearchContext.TypeContext.ReadWriteTypeContext.AutoRwTypeContext.DEFAULT_PREFIX
                    : ElasticsearchIndexServiceConfigBean.DEFAULT_FIXED_TYPE_NAME))
            .ifPresent(type_or_prefix -> {
                if (!user_type_overrides.isPresent()) { // leave alone if manually specified
                    if (collide_policy == CollidePolicy.new_type) { // add a few types
                        //TODO (ALEPH-17): need to make this get auto populated as new types are added, see the ALEPH-17 comment in ElasticsearchIndexService
                        if (mutable_type_set.size() < 10) {
                            IntStream.rangeClosed(1, 10).boxed().map(i -> type_or_prefix + i.toString())
                                    .forEach(type -> mutable_type_set.add(type));
                        }
                    } else { // OK in this case just make sure the default type is represented
                        mutable_type_set.add(type_or_prefix);
                    }
                }
            });

    final String suffix = Optional.of(" STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler' ")
            .map(s -> s + ErrorUtils.get(
                    "TBLPROPERTIES(''es.index.auto.create'' = ''false'', ''es.resource'' = ''{0}/{1}''", index,
                    mutable_type_set.stream().collect(Collectors.joining(","))))
            .map(s -> table_override.map(t -> t.name_mappings()).filter(m -> !m.isEmpty())
                    .map(m -> s + ", 'es.mapping.names' = '"
                            + m.entrySet().stream().map(kv -> kv.getKey() + ":" + kv.getValue())
                                    .collect(Collectors.joining(","))
                            + "'")
                    .orElse(s))
            .map(s -> table_override
                    .flatMap(t -> Optional.ofNullable(t.url_query()).map(ss -> "?" + ss).map(Optional::of)
                            .orElseGet(() -> Optional.ofNullable(t.json_query())
                                    .map(jq -> _mapper.convertValue(jq, JsonNode.class).toString())))
                    .map(ss -> s + ", 'es.query' = '" + ss + "'").orElse(s))
            .map(s -> s + ") ").get();

    return partial_table.map(s -> s + suffix);
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

private V removeAndNotify(K key, V value) {
    String encodedKey = encodeKey(key);
    byte[] encodedValue = encodeValue(value);
    Timestamp timestamp = timestampProvider.get(Maps.immutableEntry(key, value));
    Optional<MapValue> tombstone = tombstonesDisabled || timestamp == null ? Optional.empty()
            : Optional.of(MapValue.tombstone(timestamp));
    MapValue previousValue = removeInternal(encodedKey, Optional.ofNullable(encodedValue), tombstone);
    V decodedPreviousValue = null;//from ww w  .j  av  a2s.c o m
    if (previousValue != null) {
        decodedPreviousValue = previousValue.get(this::decodeValue);
        notifyPeers(new UpdateEntry(encodedKey, tombstone.orElse(null)),
                peerUpdateFunction.select(Maps.immutableEntry(key, decodedPreviousValue), membershipService));
        if (previousValue.isAlive()) {
            notifyListeners(new MapDelegateEvent<>(REMOVE, key, decodedPreviousValue));
        }
    }
    return decodedPreviousValue;
}