Example usage for java.util.function Function identity

List of usage examples for java.util.function Function identity

Introduction

In this page you can find the example usage for java.util.function Function identity.

Prototype

static <T> Function<T, T> identity() 

Source Link

Document

Returns a function that always returns its input argument.

Usage

From source file:com.haulmont.cuba.gui.components.listeditor.ListEditorPopupWindow.java

protected LookupField createComponentForEnum() {
    if (enumClass == null) {
        throw new IllegalStateException("EnumClass parameter is not defined");
    }/*from www  .  j a va2 s . c om*/
    LookupField lookupField = createLookupField();
    Enum[] enumConstants = enumClass.getEnumConstants();
    Map<String, Enum> enumValuesMap = Stream.of(enumConstants)
            .collect(Collectors.toMap(o -> messages.getMessage(o), Function.identity()));
    lookupField.setOptionsMap(enumValuesMap);
    return lookupField;
}

From source file:it.greenvulcano.gvesb.api.controller.GvConfigurationControllerRest.java

@GET
@Path("/configuration/{configId}")
@Produces(MediaType.APPLICATION_JSON)//  www . j  av  a 2s. c om
@RolesAllowed({ Authority.ADMINISTRATOR, Authority.MANAGER })
public Response getArchivedConfigServices(@PathParam("configId") String id) {

    try {
        byte[] gvcore = gvConfigurationManager.extract(id, "GVCore.xml");

        if (gvcore != null && gvcore.length > 0) {

            Document gvcoreDocument = documentBuilder.parse(new ByteArrayInputStream(gvcore));

            NodeList serviceNodes = XMLConfig.getNodeList(gvcoreDocument, "//Service");

            Map<String, ServiceDTO> services = IntStream.range(0, serviceNodes.getLength())
                    .mapToObj(serviceNodes::item).map(ServiceDTO::buildServiceFromConfig)
                    .filter(Optional::isPresent).map(Optional::get)
                    .collect(Collectors.toMap(ServiceDTO::getIdService, Function.identity()));

            LOG.debug("Services found " + serviceNodes.getLength());
            return Response.ok(toJson(services)).build();

        }

        return Response.status(Response.Status.NOT_FOUND).build();

    } catch (XMLConfigException | JsonProcessingException xmlConfigException) {
        LOG.error("Error reading services configuration", xmlConfigException);
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(toJson(xmlConfigException)).build());
    } catch (Exception e) {
        LOG.error("Error reading services configuration", e);
        return Response.status(Response.Status.NOT_FOUND).build();

    }

}

From source file:com.github.steveash.guavate.Guavate.java

/**
 * Collector used at the end of a stream to build an immutable map.
 * <p>/*from  www  .j  a  va  2  s.co  m*/
 * A collector is used to gather data at the end of a stream operation.
 * This method returns a collector allowing streams to be gathered into
 * an {@link ImmutableMap}.
 * <p>
 * This returns a map by extracting a key from each element.
 * The input stream must resolve to unique keys.
 * The value associated with each key is the stream element.
 * See {@link Collectors#toMap(Function, Function)} for more details.
 * @param <T> the type of the stream elements
 * @param <K> the type of the keys in the result map
 * @param keyExtractor function to produce keys from stream elements
 * @return the immutable map collector
 * @throws IllegalArgumentException if the same key is generated twice
 */
public static <T, K> Collector<T, ?, ImmutableMap<K, T>> toImmutableMap(
        Function<? super T, ? extends K> keyExtractor) {

    return toImmutableMap(keyExtractor, Function.identity());
}

From source file:ddf.catalog.history.Historian.java

/**
 * Versions deleted {@link Metacard}s.//from  ww w  .  j ava  2s.c o  m
 *
 * @param deleteResponse Versions this responses deleted metacards
 */
public DeleteResponse version(DeleteResponse deleteResponse)
        throws SourceUnavailableException, IngestException {
    if (doSkip(deleteResponse)) {
        return deleteResponse;
    }
    setSkipFlag(deleteResponse);

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Versioning Deleted Metacards {}", deleteResponse);
    }

    List<Metacard> originalMetacards = deleteResponse.getDeletedMetacards().stream()
            .filter(isNotVersionNorDeleted).collect(Collectors.toList());

    if (originalMetacards.isEmpty()) {
        LOGGER.trace("No deleted metacards applicable to versioning");
        SecurityLogger.audit("Skipping versioning deleted metacards with ids: {}",
                deleteResponse.getDeletedMetacards().stream().map(Metacard::getId).collect(TO_A_STRING));
        return deleteResponse;
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Versioning following deleted metacards: {}",
                originalMetacards.stream().map(Metacard::getId).collect(TO_A_STRING));
    }

    // [OriginalMetacardId: Original Metacard]
    Map<String, Metacard> originalMetacardsMap = originalMetacards.stream()
            .collect(Collectors.toMap(Metacard::getId, Function.identity(), Historian::firstInWinsMerge));

    // [ContentItem.getId: content items]
    Map<String, List<ContentItem>> contentItems = getContent(getReadStorageRequests(originalMetacards));

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Got content under the following ID's: {}",
                contentItems.keySet().stream().collect(TO_A_STRING));
    }

    Function<String, Action> getAction = id -> contentItems.containsKey(id) ? Action.DELETED_CONTENT
            : Action.DELETED;
    // VERSION_OF_ID is equivalent to the Original Metacard ID
    // [MetacardVersion.VERSION_OF_ID: versioned metacard]
    Map<String, Metacard> versionedMap = getVersionMetacards(originalMetacards, getAction,
            (Subject) deleteResponse.getRequest().getProperties().get(SecurityConstants.SECURITY_SUBJECT));

    if (LOGGER.isDebugEnabled() && !versionedMap.keySet().equals(originalMetacardsMap.keySet())) {
        LOGGER.debug("There is not a one to one mapping between original metacards and their versions!"
                + " (Some metacards may not have been versioned or too many versions may have been created). "
                + "More information regarding the IDs is available by setting log level to trace "
                + "(log:set trace ddf.catalog.history)");
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Original Metacards: {}",
                    originalMetacards.stream().map(Metacard::getId).collect(TO_A_STRING));
            LOGGER.trace("Version Metacards: {}", versionedMap.keySet().stream().collect(TO_A_STRING));
        }
    }

    CreateStorageResponse createStorageResponse = versionContentItems(contentItems, versionedMap);
    if (createStorageResponse != null) {
        setResourceUriForContent(/*Mutable*/ versionedMap, createStorageResponse);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Successfully stored content under ids: {}",
                    createStorageResponse.getCreatedContentItems());
        }
    }

    executeAsSystem(
            () -> catalogProvider().create(new CreateRequestImpl(new ArrayList<>(versionedMap.values()))));
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Successfully created versioned metacards under ids: {}",
                versionedMap.values().stream().map(Metacard::getId).collect(TO_A_STRING));
    }

    String userid = subjectIdentity.getUniqueIdentifier(
            (Subject) deleteResponse.getProperties().get(SecurityConstants.SECURITY_SUBJECT));
    List<Metacard> deletionMetacards = versionedMap
            .entrySet().stream().map(s -> new DeletedMetacardImpl(uuidGenerator.generateUuid(), s.getKey(),
                    userid, s.getValue().getId(), originalMetacardsMap.get(s.getKey())))
            .collect(Collectors.toList());

    CreateResponse deletionMetacardsCreateResponse = executeAsSystem(
            () -> catalogProvider().create(new CreateRequestImpl(deletionMetacards, new HashMap<>())));

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Successfully created deletion metacards under ids: {}", deletionMetacardsCreateResponse
                .getCreatedMetacards().stream().map(Metacard::getId).collect(TO_A_STRING));
    }

    return deleteResponse;
}

From source file:org.codice.ddf.itests.common.ServiceManagerImpl.java

@Override
public void restartBundles(String... bundleSymbolicNames) throws BundleException {
    LOGGER.debug("Restarting bundles {}", bundleSymbolicNames);

    Map<String, Bundle> bundleLookup = Arrays.stream(getBundleContext().getBundles())
            .collect(Collectors.toMap(Bundle::getSymbolicName, Function.identity(), (a, b) -> a));

    List<Bundle> bundles = Arrays.stream(bundleSymbolicNames).map(bundleLookup::get)
            .collect(Collectors.toList());

    for (Bundle bundle : bundles) {
        bundle.stop();/* w w w . j  a v  a  2s  .  c  o  m*/
    }

    for (Bundle bundle : Lists.reverse(bundles)) {
        bundle.start();
    }
}

From source file:org.codice.ddf.catalog.ui.util.EndpointUtil.java

public Map<String, Result> getMetacardsWithTagByAttributes(String attributeName,
        Collection<String> attributeValues, Filter tagFilter) {
    if (attributeValues.isEmpty()) {
        return new HashMap<>();
    }/* w w  w. j  a  v  a  2s.c o m*/

    Filter attributeFilter = buildAttributeFilter(attributeName, attributeValues, true);
    Filter queryFilter = filterBuilder.allOf(attributeFilter, tagFilter);

    ResultIterable resultIterable = resultIterable(catalogFramework,
            new QueryRequestImpl(
                    new QueryImpl(queryFilter, 1, pageSize, new SortByImpl(Core.MODIFIED, SortOrder.DESCENDING),
                            false, TimeUnit.SECONDS.toMillis(10)),
                    false, null, additionalSort(new HashMap<>(), Core.ID, SortOrder.ASCENDING)));

    return resultIterable.stream().collect(Collectors.toMap(result -> result.getMetacard().getId(),
            Function.identity(), EndpointUtil::firstInWinsMerge));
}

From source file:jp.co.opentone.bsol.linkbinder.service.correspon.impl.CorresponFullTextSearchServiceImpl.java

private void setSummaryData(SearchFullTextSearchCorresponCondition condition,
        ElasticsearchSearchResultRecord rec, FullTextSearchCorresponsResult r) {
    Stream<String> highlights = null;
    switch (condition.getFullTextSearchMode()) {
    case ALL://  www . j  a  v a  2 s .com
        highlights = Stream
                .of(rec.getHighlightedFragments("body"), rec.getHighlightedFragments("attachments.name"),
                        rec.getHighlightedFragments("attachments.content.content"))
                .flatMap(Function.identity());
        break;
    case SUBJECT:
        highlights = rec.getHighlightedFragments("title");
        break;
    case SUBJECT_AND_BODY:
        highlights = rec.getHighlightedFragments("body");
        break;
    case ATTACHED_FILE:
        highlights = Stream
                .of(rec.getHighlightedFragments("attachments.name"),
                        rec.getHighlightedFragments("attachments.content.content"))
                .flatMap(Function.identity());
        break;
    default:
    }

    List<FullTextSearchSummaryData> summaryDataList = highlights.collect(
            () -> new ArrayList<FullTextSearchSummaryData>(),
            (t, v) -> t.add(new FullTextSearchSummaryData(v, false)), (t, u) -> t.addAll(u));

    if (condition.isIncludeImage()) {
        summaryDataList.addAll(rec.getHighlightedFragments("attachments.extractedText").collect(
                () -> new ArrayList<FullTextSearchSummaryData>(),
                (t, v) -> t.add(new FullTextSearchSummaryData(v, false)), (t, u) -> t.addAll(u)));
    }
    r.setSummaryList(summaryDataList);
}

From source file:org.kitodo.production.model.Subfolder.java

/**
 * Search for files with the file management interface.
 *
 * @param query/*from  w w  w. j  a v  a2s  .  co  m*/
 *            search request consisting of an indication of the folder to be
 *            searched and a pattern to which the file names must correspond
 * @return a map from the canonical file name part to the URI
 */
private Map<String, URI> listDirectory(Pair<URI, Pattern> query) {
    FilenameFilter filter = (dir, name) -> query.getRight().matcher(name).matches();
    Stream<URI> relativeURIs = fileService.getSubUris(filter, query.getLeft()).parallelStream();
    Stream<URI> absoluteURIs = relativeURIs.map(
            uri -> new File(FilenameUtils.concat(ConfigCore.getKitodoDataDirectory(), uri.getPath())).toURI());
    Function<URI, String> keyMapper = createKeyMapperForPattern(query.getRight());
    return absoluteURIs.collect(Collectors.toMap(keyMapper, Function.identity(), (previous, latest) -> latest,
            () -> new TreeMap<>(new MetadataImageComparator())));
}

From source file:com.streamsets.pipeline.stage.bigquery.destination.BigQueryTarget.java

/**
 * Convert the sdc Field to an object for row content
 *///ww w  . ja  v  a2s. c o  m
private Object getValueFromField(String fieldPath, Field field) {
    LOG.trace("Visiting Field Path '{}' of type '{}'", fieldPath, field.getType());
    switch (field.getType()) {
    case LIST:
        //REPEATED
        List<Field> listField = field.getValueAsList();
        //Convert the list to map with indices as key and Field as value (Map<Integer, Field>)
        Map<Integer, Field> fields = IntStream.range(0, listField.size()).boxed()
                .collect(Collectors.toMap(Function.identity(), listField::get));
        //filter map to remove fields with null value
        fields = fields.entrySet().stream().filter(e -> e.getValue().getValue() != null)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        //now use the map index to generate field path and generate object for big query write
        return fields.entrySet().stream()
                .map(e -> getValueFromField(fieldPath + "[" + e.getKey() + "]", e.getValue()))
                .collect(Collectors.toList());
    case MAP:
    case LIST_MAP:
        //RECORD
        return field.getValueAsMap().entrySet().stream().filter(me -> me.getValue().getValue() != null)
                .collect(Collectors.toMap(Map.Entry::getKey,
                        e -> getValueFromField(fieldPath + "/" + e.getKey(), e.getValue())));
    case DATE:
        return dateFormat.format(field.getValueAsDate());
    case TIME:
        return timeFormat.format(field.getValueAsTime());
    case DATETIME:
        return dateTimeFormat.format(field.getValueAsDatetime());
    case BYTE_ARRAY:
        return Base64.getEncoder().encodeToString(field.getValueAsByteArray());
    case DECIMAL:
    case BYTE:
    case CHAR:
    case FILE_REF:
        throw new IllegalArgumentException(
                Utils.format(Errors.BIGQUERY_12.getMessage(), fieldPath, field.getType()));
    default:
        //Boolean -> Map to Boolean in big query
        //Float, Double -> Map to Float in big query
        //String -> maps to String in big query
        //Short, Integer, Long -> Map to integer in big query
        return field.getValue();
    }
}

From source file:util.ItUtils.java

@CheckForNull
public static Map<String, Measure> getMeasuresWithVariationsByMetricKey(Orchestrator orchestrator,
        String componentKey, String... metricKeys) {
    return newWsClient(orchestrator).measures()
            .component(new ComponentWsRequest().setComponentKey(componentKey).setMetricKeys(asList(metricKeys))
                    .setAdditionalFields(singletonList("periods")))
            .getComponent().getMeasuresList().stream()
            .collect(Collectors.toMap(Measure::getMetric, Function.identity()));
}