List of usage examples for java.util Map forEach
default void forEach(BiConsumer<? super K, ? super V> action)
From source file:licorice.gui.MainPanel.java
private void processBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processBtnActionPerformed SwingUtilities.invokeLater(() -> { try {//w w w .j a v a 2 s . c o m minQual = Integer.parseInt(minQualField.getText()); processBtn.setEnabled(false); //progressBar = new JProgressBar(); progressBar.setMinimum(0); progressBar.setMaximum(100); Path genomePath = Paths.get(prop.getProperty("genome.path")); prop.setProperty("input.default_dir", fc.getCurrentDirectory().getAbsolutePath()); prop.setProperty("minimum.quality", minQual.toString()); prop.setProperty("maximum.nocall.rate", maxNC.toString()); prop.store(new FileOutputStream("licorice.properties"), null); Path inputPath = Paths.get(fileNameField.getText()); if (!inputPath.toFile().exists()) { JOptionPane.showMessageDialog(null, "Input file does not exist"); appendLog("Input file '" + inputPath + "' does not exist"); return; } Path outputPath = inputPath .resolveSibling(FilenameUtils.getBaseName(inputPath.getFileName().toString()) + ".txt"); appendLog("Output in: '" + outputPath.getParent() + "'\n"); appendLog("Analysis Started...\n"); processBtn.setText("Processing..."); SimpleGenomeRef genome = new SimpleGenomeRef(genomePath); GenomeRef.ValidationResult validation = genome.validate(); if (!validation.isValid()) { appendLog("Reference Error: '" + validation.getErrors() + "'\n"); return; } Path effectivePath = ZipUtil.directoryfy(inputPath); Map<String, String> samples = VCFUtils.makeSamplesDictionary(VCFUtils.listVCFFiles(effectivePath)); appendLog("==================================\n"); appendLog("Samples List\n"); appendLog("==================================\n"); appendLog("Sample\tFile"); samples.forEach((k, v) -> appendLog(String.format("%s\t%s\n", k, v))); appendLog("==================================\n"); Path samplesPath = inputPath.resolveSibling( FilenameUtils.getBaseName(inputPath.getFileName().toString()) + ".samples.txt"); appendLog("Samples List in: '" + samplesPath.getParent() + "'\n"); try (PrintStream out = new PrintStream(new FileOutputStream(samplesPath.toFile()))) { out.println("Sample\tFile"); samples.forEach((k, v) -> out.println(String.format("%s\t%s", k, v))); } analysis = new Analysis(genome, minQual, maxNC, false, outputPath, VCFUtils.listVCFFiles(effectivePath)); analysis.progressListener(progress -> progressBar.setValue(progress)); analysis.onFinish(() -> { log.info("Callback called"); appendLog("Analysis Finished.\n"); fileNameField.setText(""); processBtn.setText("Process"); processBtn.setEnabled(true); processBtn.repaint(); this.repaint(); return null; }); analysis.onException((Thread t, Throwable ex) -> { appendLog(ex.getMessage()); appendLog("Analysis Failed!!!"); JOptionPane.showMessageDialog(null, "Analysis Failed!!!"); processBtn.setText("Process"); processBtn.setEnabled(true); processBtn.repaint(); }); } catch (IOException ex) { appendLog(ex.getMessage() + "\n"); log.error(ex.getMessage()); JOptionPane.showMessageDialog(null, "Analysis Failed!!!"); ex.printStackTrace(); } analysis.start(); //progressBar. }); }
From source file:net.sf.jabref.model.entry.BibEntry.java
/** * Sets a number of fields simultaneously. The given HashMap contains field * names as keys, each mapped to the value to set. */// w w w . ja v a2 s. c o m public void setField(Map<String, String> fields) { Objects.requireNonNull(fields, "fields must not be null"); fields.forEach(this::setField); }
From source file:ch.silviowangler.i18n.ResourceBundler.java
public void generateResourceBundle() throws IOException { CSVParser records = CSVFormat.RFC4180.withDelimiter(separator.charAt(0)).withFirstRecordAsHeader() .withQuoteMode(QuoteMode.ALL) .parse(new InputStreamReader(new FileInputStream(this.csvFile), this.inputEncoding)); final Map<String, Integer> headers = records.getHeaderMap(); processHeader(headers.keySet());//from ww w .jav a 2s . c o m for (CSVRecord record : records) { processData(record); } final int propertiesFilesAmount = this.propertiesStore.size(); LOGGER.info("Will generate {} properties files with {} records each", propertiesFilesAmount, records.getRecordNumber()); // Properties Dateien schreiben for (int i = 0; i < propertiesFilesAmount; i++) { Map<String, String> properties = this.propertiesStore.get(i); File outputFile = new File(this.outputDir, this.bundleBaseName + "_" + this.languages.get(i) + ".properties"); LOGGER.info("Writing {} to {}", outputFile.getName(), outputFile.getParentFile().getAbsolutePath()); FileOutputStream outputStream = new FileOutputStream(outputFile); try (OutputStreamWriter writer = new OutputStreamWriter(outputStream, this.native2ascii ? Consts.ASCII : this.outputEncoding)) { properties.forEach((key, value) -> { try { writer.append(key).append("=").append(value).append("\n"); } catch (IOException e) { e.printStackTrace(); } }); writer.flush(); } } }
From source file:com.qwazr.utils.server.InFileSessionPersistenceManager.java
private void writeSession(File deploymentDir, String sessionId, PersistentSession persistentSession) { final Date expDate = persistentSession.getExpiration(); if (expDate == null) return; // No expiry date? no serialization final Map<String, Object> sessionData = persistentSession.getSessionData(); if (sessionData == null || sessionData.isEmpty()) return; // No attribute? no serialization File sessionFile = new File(deploymentDir, sessionId); try {// w w w.j av a 2s.com final FileOutputStream fileOutputStream = new FileOutputStream(sessionFile); try { final ObjectOutputStream out = new ObjectOutputStream(fileOutputStream); try { out.writeLong(expDate.getTime()); // The date is stored as long sessionData.forEach((attribute, object) -> writeSessionAttribute(out, attribute, object)); } finally { IOUtils.close(out); } } finally { IOUtils.close(fileOutputStream); } } catch (IOException e) { if (logger.isWarnEnabled()) logger.warn("Cannot save sessions in " + sessionFile + " " + e.getMessage(), e); } }
From source file:org.wso2.carbon.apimgt.core.impl.WSDL11ProcessorImpl.java
/** * Returns parameters, given http binding operation, verb and content type * * @param bindingOperation {@link BindingOperation} object * @param verb HTTP verb/*from w w w . jav a 2 s. c om*/ * @param contentType Content type * @return parameters, given http binding operation, verb and content type */ private List<WSDLOperationParam> getParameters(BindingOperation bindingOperation, String verb, String contentType) { List<WSDLOperationParam> params = new ArrayList<>(); Operation operation = bindingOperation.getOperation(); //Returns a single parameter called payload with body type if request can contain a body (PUT/POST) and // content type is not application/x-www-form-urlencoded OR multipart/form-data, // or content type is not provided if (APIMWSDLUtils.canContainBody(verb) && !APIMWSDLUtils.hasFormDataParams(contentType)) { WSDLOperationParam param = new WSDLOperationParam(); param.setName("Payload"); param.setParamType(WSDLOperationParam.ParamTypeEnum.BODY); params.add(param); if (log.isDebugEnabled()) { log.debug("Adding default Param for operation:" + operation.getName() + ", contentType: " + contentType); } return params; } if (operation != null) { Input input = operation.getInput(); if (input != null) { Message message = input.getMessage(); if (message != null) { Map map = message.getParts(); map.forEach((name, partObj) -> { WSDLOperationParam param = new WSDLOperationParam(); param.setName(name.toString()); if (log.isDebugEnabled()) { log.debug("Identified param for operation: " + operation.getName() + " param: " + name); } if (APIMWSDLUtils.canContainBody(verb)) { if (log.isDebugEnabled()) { log.debug("Operation " + operation.getName() + " can contain a body."); } //In POST, PUT operations, parameters always in body according to HTTP Binding spec if (APIMWSDLUtils.hasFormDataParams(contentType)) { param.setParamType(WSDLOperationParam.ParamTypeEnum.FORM_DATA); if (log.isDebugEnabled()) { log.debug("Param " + name + " type was set to formData."); } } //no else block since if content type is not form-data related, there can be only one // parameter which is payload body. This is handled in the first if block which is // if (canContainBody(verb) && !hasFormDataParams(contentType)) { .. } } else { //In GET operations, parameters always query or path as per HTTP Binding spec if (isUrlReplacement(bindingOperation)) { param.setParamType(WSDLOperationParam.ParamTypeEnum.PATH); if (log.isDebugEnabled()) { log.debug("Param " + name + " type was set to Path."); } } else { param.setParamType(WSDLOperationParam.ParamTypeEnum.QUERY); if (log.isDebugEnabled()) { log.debug("Param " + name + " type was set to Query."); } } } Part part = (Part) partObj; param.setDataType(part.getTypeName().getLocalPart()); if (log.isDebugEnabled()) { log.debug("Param " + name + " data type was set to " + param.getDataType()); } params.add(param); }); } } } return params; }
From source file:com.hurence.logisland.service.elasticsearch.Elasticsearch_5_4_0_ClientService.java
@Override public List<MultiGetResponseRecord> multiGet(List<MultiGetQueryRecord> multiGetQueryRecords) { List<MultiGetResponseRecord> multiGetResponseRecords = new ArrayList<>(); MultiGetRequestBuilder multiGetRequestBuilder = esClient.prepareMultiGet(); for (MultiGetQueryRecord multiGetQueryRecord : multiGetQueryRecords) { String index = multiGetQueryRecord.getIndexName(); String type = multiGetQueryRecord.getTypeName(); List<String> documentIds = multiGetQueryRecord.getDocumentIds(); String[] fieldsToInclude = multiGetQueryRecord.getFieldsToInclude(); String[] fieldsToExclude = multiGetQueryRecord.getFieldsToExclude(); if ((fieldsToInclude != null && fieldsToInclude.length > 0) || (fieldsToExclude != null && fieldsToExclude.length > 0)) { for (String documentId : documentIds) { MultiGetRequest.Item item = new MultiGetRequest.Item(index, type, documentId); item.fetchSourceContext(new FetchSourceContext(true, fieldsToInclude, fieldsToExclude)); multiGetRequestBuilder.add(item); }/*from w w w . ja va 2 s .c om*/ } else { multiGetRequestBuilder.add(index, type, documentIds); } } MultiGetResponse multiGetItemResponses = null; try { multiGetItemResponses = multiGetRequestBuilder.get(); } catch (ActionRequestValidationException e) { getLogger().error("MultiGet query failed : {}", new Object[] { e.getMessage() }); } if (multiGetItemResponses != null) { for (MultiGetItemResponse itemResponse : multiGetItemResponses) { GetResponse response = itemResponse.getResponse(); if (response != null && response.isExists()) { Map<String, Object> responseMap = response.getSourceAsMap(); Map<String, String> retrievedFields = new HashMap<>(); responseMap.forEach((k, v) -> { if (v != null) retrievedFields.put(k, v.toString()); }); multiGetResponseRecords.add(new MultiGetResponseRecord(response.getIndex(), response.getType(), response.getId(), retrievedFields)); } } } return multiGetResponseRecords; }
From source file:com.qwazr.server.InFileSessionPersistenceManager.java
private void writeSession(final Path deploymentDir, final String sessionId, final PersistentSession persistentSession) { final Date expDate = persistentSession.getExpiration(); if (expDate == null) return; // No expiry date? no serialization final Map<String, Object> sessionData = persistentSession.getSessionData(); if (sessionData == null) return; // No sessionData? no serialization final File sessionFile = deploymentDir.resolve(sessionId).toFile(); try (final ObjectOutputStream draftOutputStream = new ObjectOutputStream(new NullOutputStream())) { try (final ObjectOutputStream sessionOutputStream = new ObjectOutputStream( new FileOutputStream(sessionFile))) { sessionOutputStream.writeLong(expDate.getTime()); // The date is stored as long sessionData.forEach((attribute, object) -> writeSessionAttribute(draftOutputStream, sessionOutputStream, attribute, object)); }//from w ww . j a v a 2 s .c o m } catch (IOException | CancellationException e) { LOGGER.log(Level.SEVERE, e, () -> "Cannot save sessions in " + sessionFile); } }
From source file:org.ballerinalang.net.http.HttpUtil.java
public static void injectHeaders(HttpCarbonMessage msg, Map<String, String> headers) { if (headers != null) { headers.forEach((key, value) -> msg.setHeader(key, String.valueOf(value))); }/*from w w w.ja v a2 s . com*/ }
From source file:org.apache.metron.parsers.regex.RegularExpressionsParser.java
private void convertCamelCaseToUnderScore(Map<String, Object> json) { Map<String, String> oldKeyNewKeyMap = new HashMap<>(); for (Map.Entry<String, Object> entry : json.entrySet()) { if (capitalLettersPattern.matcher(entry.getKey()).matches()) { oldKeyNewKeyMap.put(entry.getKey(), CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, entry.getKey())); }/* ww w.j av a2 s . co m*/ } oldKeyNewKeyMap.forEach((oldKey, newKey) -> json.put(newKey, json.remove(oldKey))); }
From source file:ijfx.core.image.DefaultDatasetUtilsService.java
public <C extends Command> Module executeCommand(Class<C> type, Map<String, Object> parameters) { Module module = moduleService.createModule(commandService.getCommand(type)); try {/*from ww w. j av a2 s . c o m*/ module.initialize(); } catch (MethodCallException ex) { logger.log(Level.SEVERE, null, ex); } parameters.forEach((k, v) -> { module.setInput(k, v); module.setResolved(k, true); }); Future run = moduleService.run(module, false, parameters); try { run.get(); } catch (InterruptedException | ExecutionException ex) { logger.log(Level.SEVERE, null, ex); } return module; }