Example usage for java.util Map forEach

List of usage examples for java.util Map forEach

Introduction

In this page you can find the example usage for java.util Map forEach.

Prototype

default void forEach(BiConsumer<? super K, ? super V> action) 

Source Link

Document

Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

Usage

From source file:com.streamsets.pipeline.lib.dirspooler.SpoolDirRunnable.java

private void setHeaders(Record record, Map<String, Object> recordHeaderAttr) throws IOException {
    recordHeaderAttr.forEach((k, v) -> record.getHeader().setAttribute(k, v.toString()));
}

From source file:io.klerch.alexa.state.handler.AWSS3StateHandler.java

/**
 * {@inheritDoc}//from w  w w . j a v a2  s  . co m
 */
@Override
public Map<String, AlexaStateObject> readValues(final Map<String, AlexaScope> idsInScope)
        throws AlexaStateException {
    final Map<String, AlexaStateObject> stateObjectMap = new HashMap<>();
    // first read all the session-scoped items and put to result map
    stateObjectMap.putAll(super.readValues(idsInScope));

    idsInScope.forEach((id, scope) -> {
        if (scope.isIn(AlexaScope.USER, AlexaScope.APPLICATION)) {
            final String filePath = AlexaScope.USER.includes(scope) ? getUserScopedFilePath(id)
                    : getAppScopedFilePath(id);
            try {
                // get S3 file
                getS3FileContentsAsString(filePath)
                        // wrap its contents in state object
                        .map(fileContents -> new AlexaStateObject(id, fileContents, scope))
                        // add to result map
                        .ifPresent(stateObject -> stateObjectMap.putIfAbsent(id, stateObject));
            } catch (final AlexaStateException | AmazonS3Exception e) {
                // we are fine with an exception likely caused by file (state) not exists
                log.warn("Could not read from '" + filePath + "'.", e);
            }
        }
    });
    return stateObjectMap;
}

From source file:org.apache.hadoop.hive.kafka.KafkaStorageHandler.java

@Override
public void configureJobConf(TableDesc tableDesc, JobConf jobConf) {
    Map<String, String> properties = new HashMap<>();
    configureInputJobProperties(tableDesc, properties);
    configureOutputJobProperties(tableDesc, properties);
    properties.forEach(jobConf::set);
    try {//from w  ww  .ja  v a 2  s .c  om
        KafkaUtils.copyDependencyJars(jobConf, KafkaStorageHandler.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.redhat.red.offliner.ftest.SinglePlaintextDownloadOfTarballFTest.java

private File makeTarball(final Map<String, byte[]> entries) throws IOException {
    File tgz = temporaryFolder.newFile();
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(
            new GzipCompressorOutputStream(new FileOutputStream(tgz)))) {
        entries.forEach((name, content) -> {
            try {
                File entryFile = temporaryFolder.newFile();
                FileUtils.writeByteArrayToFile(entryFile, content);

                TarArchiveEntry entry = new TarArchiveEntry(entryFile, name);
                //                entry.setSize( content.length );
                //                entry.setMode( 0644 );
                //                entry.setGroupId( 1000 );
                //                entry.setUserId( 1000 );

                tarOut.putArchiveEntry(entry);

                System.out.printf("Entry: %s mode: '0%s'\n", entry.getName(),
                        Integer.toString(entry.getMode(), 8));

                tarOut.write(content);//  w  w  w . j a v  a2s .  c  o m
                tarOut.closeArchiveEntry();
            } catch (IOException e) {
                e.printStackTrace();
                fail("Failed to write tarball");
            }
        });

        tarOut.flush();
    }

    try (TarArchiveInputStream tarIn = new TarArchiveInputStream(
            new GzipCompressorInputStream(new FileInputStream(tgz)))) {
        TarArchiveEntry entry = null;
        while ((entry = tarIn.getNextTarEntry()) != null) {
            byte[] entryData = new byte[(int) entry.getSize()];
            int read = tarIn.read(entryData, 0, entryData.length);
            assertThat("Not enough bytes read for: " + entry.getName(), read, equalTo((int) entry.getSize()));
            assertThat(entry.getName() + ": data doesn't match input",
                    Arrays.equals(entries.get(entry.getName()), entryData), equalTo(true));
        }
    }

    return tgz;
}

From source file:eu.esdihumboldt.hale.io.geoserver.rest.AbstractResourceManager.java

private URI buildRequestUri(String url, Map<String, String> parameters) throws URISyntaxException {

    URIBuilder uriBuilder = new URIBuilder(url);
    if (parameters != null) {
        parameters.forEach((param, value) -> uriBuilder.addParameter(param, value));
    }//from  w w w  .j  av  a 2 s  . c  o m

    return uriBuilder.build();
}

From source file:alfio.repository.TicketFieldRepository.java

default void updateOrInsert(Map<String, List<String>> values, int ticketId, int eventId) {
    Map<String, TicketFieldValue> toUpdate = findAllByTicketIdGroupedByName(ticketId);
    values = Optional.ofNullable(values).orElseGet(Collections::emptyMap);
    Map<String, Integer> fieldNameToId = findAdditionalFieldsForEvent(eventId).stream()
            .collect(Collectors.toMap(TicketFieldConfiguration::getName, TicketFieldConfiguration::getId));

    values.forEach((fieldName, fieldValues) -> {
        String fieldValue;//from  w  w w. j  a  va2s .  co m
        if (fieldValues.size() == 1) {
            fieldValue = fieldValues.get(0);
        } else if (fieldValues.stream().anyMatch(StringUtils::isNotBlank)) {
            fieldValue = Json.toJson(fieldValues);
        } else {
            fieldValue = "";
        }

        boolean isNotBlank = StringUtils.isNotBlank(fieldValue);
        if (toUpdate.containsKey(fieldName)) {
            TicketFieldValue field = toUpdate.get(fieldName);
            if (isNotBlank) {
                updateValue(field.getTicketId(), field.getTicketFieldConfigurationId(), fieldValue);
            } else {
                deleteValue(field.getTicketId(), field.getTicketFieldConfigurationId());
            }
        } else if (fieldNameToId.containsKey(fieldName) && isNotBlank) {
            insertValue(ticketId, fieldNameToId.get(fieldName), fieldValue);
        }
    });
}

From source file:com.qwazr.crawler.web.manager.WebCrawlThread.java

private void crawlUrlMap(Set<URI> crawledURIs, Map<String, Integer> urlMap) {

    urlMap.forEach(new BiConsumer<String, Integer>() {
        @Override/*ww w  . j  a v a 2  s.co  m*/
        public void accept(String uri, Integer depth) {
            try {
                crawlOne(crawledURIs, new URI(uri), null, depth);
            } catch (Exception e) {
                logger.warn("Malformed URI: " + uri);
            }
        }
    });
}

From source file:org.codice.ddf.cxf.paos.PaosInInterceptor.java

@VisibleForTesting
HttpUnsuccessfulResponseHandler getHttpUnsuccessfulResponseHandler(Message message) {
    return (request, response, supportsRetry) -> {
        String redirectLocation = response.getHeaders().getLocation();
        if (isRedirect(request, response, redirectLocation)) {
            String method = (String) message.get(Message.HTTP_REQUEST_METHOD);
            HttpContent content = null;/*w w w .jav a 2 s . com*/
            if (!isRedirectable(method)) {
                try (TemporaryFileBackedOutputStream tfbos = new TemporaryFileBackedOutputStream()) {
                    message.setContent(OutputStream.class, tfbos);
                    BodyWriter bodyWriter = new BodyWriter();
                    bodyWriter.handleMessage(message);
                    ByteSource byteSource = tfbos.asByteSource();
                    content = new InputStreamContent((String) message.get(Message.CONTENT_TYPE),
                            byteSource.openStream()).setLength(byteSource.size());
                }
            }

            // resolve the redirect location relative to the current location
            request.setUrl(new GenericUrl(request.getUrl().toURL(redirectLocation)));
            request.setRequestMethod(method);
            request.setContent(content);
            // remove Authorization and If-* headers
            request.getHeaders().setAuthorization((String) null);
            request.getHeaders().setIfMatch(null);
            request.getHeaders().setIfNoneMatch(null);
            request.getHeaders().setIfModifiedSince(null);
            request.getHeaders().setIfUnmodifiedSince(null);
            request.getHeaders().setIfRange(null);
            request.getHeaders().setCookie((String) ((List) response.getHeaders().get("set-cookie")).get(0));

            Map<String, List<String>> headers = (Map<String, List<String>>) message
                    .get(Message.PROTOCOL_HEADERS);
            headers.forEach((key, value) -> request.getHeaders().set(key, value));
            return true;
        }
        return false;
    };
}

From source file:ch.uzh.phys.ecn.oboma.map.model.Node.java

@Override
public void infect() {
    Map<Agent, InfectionState> agentMods = new HashMap<>();
    final Consumer<Agent> doInfect = a -> {
        InfectionState next = mInfectionFunction.apply(a, this);
        if (next != a.getState()) {
            agentMods.put(a, next);/*from  w  w  w  . ja  v  a2s .  c o  m*/
        }
    };
    mAgents.stream().map(AgentPlacement::getAgent).forEach(doInfect);
    mLeavingAgents.forEach(doInfect);
    agentMods.forEach((a, i) -> a.setState(i));
}

From source file:org.apache.hadoop.hbase.client.AsyncBatchRpcRetryingCaller.java

private void onComplete(Map<byte[], RegionRequest> actionsByRegion, int tries, ServerName serverName,
        MultiResponse resp) {/*w ww .  j a v a 2  s .  c  o m*/
    List<Action> failedActions = new ArrayList<>();
    actionsByRegion.forEach((rn, regionReq) -> {
        RegionResult regionResult = resp.getResults().get(rn);
        if (regionResult != null) {
            regionReq.actions.forEach(
                    action -> onComplete(action, regionReq, tries, serverName, regionResult, failedActions));
        } else {
            Throwable t = resp.getException(rn);
            Throwable error;
            if (t == null) {
                LOG.error("Server sent us neither results nor exceptions for " + Bytes.toStringBinary(rn));
                error = new RuntimeException("Invalid response");
            } else {
                error = translateException(t);
                logException(tries, () -> Stream.of(regionReq), error, serverName);
                conn.getLocator().updateCachedLocation(regionReq.loc, error);
                if (error instanceof DoNotRetryIOException || tries >= maxAttempts) {
                    failAll(regionReq.actions.stream(), tries, error, serverName);
                    return;
                }
                addError(regionReq.actions, error, serverName);
                failedActions.addAll(regionReq.actions);
            }
        }
    });
    if (!failedActions.isEmpty()) {
        tryResubmit(failedActions.stream(), tries);
    }
}