List of usage examples for java.util Map getOrDefault
default V getOrDefault(Object key, V defaultValue)
From source file:fr.cph.stock.entities.Portfolio.java
protected Map<String, List<Equity>> getSectorByCompanies() { final Map<String, List<Equity>> map = new TreeMap<>(); List<Equity> companies; for (final Equity equity : getEquities()) { if (equity.getCompany().getFund()) { companies = map.getOrDefault(Constants.FUND, new ArrayList<>()); companies.add(equity);/*from www .j a v a2 s . com*/ map.putIfAbsent(Constants.FUND, companies); } else { final String sector = equity.getCurrentSector(); if (StringUtils.isEmpty(sector)) { companies = map.getOrDefault(Constants.UNKNOWN, new ArrayList<>()); companies.add(equity); map.putIfAbsent(Constants.UNKNOWN, companies); } else { companies = map.getOrDefault(sector, new ArrayList<>()); companies.add(equity); map.putIfAbsent(sector, companies); } } } return map; }
From source file:nlmt.topicmodels.HierarchicalLDAModel.java
/** * Using the stick breaking convention and the count of number of words in the document * at the various levels, return an array containing the probabilities of each level. * In other words calculate p(level)./*from w ww .j a va 2s . c o m*/ * * @param documentTopicCounts the counts of the number of words in each level * @return an array of probabilities for each level */ protected double[] getLevelProbabilities(Map<Integer, Integer> documentTopicCounts) { double[] probabilities = new double[maxDepth]; int totalWordCount = documentTopicCounts.values().stream().mapToInt(v -> v).sum(); double remainingStickLength = 1.0; for (int i = 0; i < maxDepth - 1; i++) { int wordCountAtLevel = documentTopicCounts.getOrDefault(i, 0); double stickPiece = (((1 - m) * pi) + wordCountAtLevel) / (pi + totalWordCount); totalWordCount -= wordCountAtLevel; probabilities[i] = stickPiece * remainingStickLength; remainingStickLength *= 1.0 - stickPiece; } probabilities[maxDepth - 1] = 1.0 - Arrays.stream(probabilities).sum(); return probabilities; }
From source file:org.wso2.carbon.transport.file.connector.sender.VFSClientConnector.java
@Override public boolean send(CarbonMessage carbonMessage, CarbonCallback carbonCallback, Map<String, String> map) throws ClientConnectorException { FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true); String fileURI = map.get(Constants.FILE_URI); String action = map.get(Constants.ACTION); FileType fileType;/*from ww w.j a va 2s . c om*/ ByteBuffer byteBuffer; InputStream inputStream = null; OutputStream outputStream = null; try { FileSystemManager fsManager = VFS.getManager(); FileObject path = fsManager.resolveFile(fileURI, opts); fileType = path.getType(); switch (action) { case Constants.CREATE: boolean isFolder = Boolean.parseBoolean(map.getOrDefault("create-folder", "false")); if (path.exists()) { throw new ClientConnectorException("File already exists: " + path.getName().getURI()); } if (isFolder) { path.createFolder(); } else { path.createFile(); } break; case Constants.WRITE: if (!path.exists()) { path.createFile(); path.refresh(); fileType = path.getType(); } if (fileType == FileType.FILE) { if (carbonMessage instanceof BinaryCarbonMessage) { BinaryCarbonMessage binaryCarbonMessage = (BinaryCarbonMessage) carbonMessage; byteBuffer = binaryCarbonMessage.readBytes(); } else { throw new ClientConnectorException("Carbon message received is not a BinaryCarbonMessage"); } byte[] bytes = byteBuffer.array(); if (map.get(Constants.APPEND) != null) { outputStream = path.getContent() .getOutputStream(Boolean.parseBoolean(map.get(Constants.APPEND))); } else { outputStream = path.getContent().getOutputStream(); } outputStream.write(bytes); outputStream.flush(); } break; case Constants.DELETE: if (path.exists()) { int filesDeleted = path.delete(Selectors.SELECT_ALL); if (logger.isDebugEnabled()) { logger.debug(filesDeleted + " files successfully deleted"); } } else { throw new ClientConnectorException( "Failed to delete file: " + path.getName().getURI() + " not found"); } break; case Constants.COPY: if (path.exists()) { String destination = map.get("destination"); FileObject dest = fsManager.resolveFile(destination, opts); dest.copyFrom(path, Selectors.SELECT_ALL); } else { throw new ClientConnectorException( "Failed to copy file: " + path.getName().getURI() + " not found"); } break; case Constants.MOVE: if (path.exists()) { //TODO: Improve this to fix issue #331 String destination = map.get("destination"); FileObject newPath = fsManager.resolveFile(destination, opts); FileObject parent = newPath.getParent(); if (parent != null && !parent.exists()) { parent.createFolder(); } if (!newPath.exists()) { path.moveTo(newPath); } else { throw new ClientConnectorException("The file at " + newPath.getURL().toString() + " already exists or it is a directory"); } } else { throw new ClientConnectorException( "Failed to move file: " + path.getName().getURI() + " not found"); } break; case Constants.READ: if (path.exists()) { //TODO: Do not assume 'path' always refers to a file inputStream = path.getContent().getInputStream(); byte[] bytes = toByteArray(inputStream); BinaryCarbonMessage message = new BinaryCarbonMessage(ByteBuffer.wrap(bytes), true); message.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION, org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE); carbonMessageProcessor.receive(message, carbonCallback); } else { throw new ClientConnectorException( "Failed to read file: " + path.getName().getURI() + " not found"); } break; case Constants.EXISTS: TextCarbonMessage message = new TextCarbonMessage(Boolean.toString(path.exists())); message.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION, org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE); carbonMessageProcessor.receive(message, carbonCallback); break; default: return false; } } catch (RuntimeException e) { throw new ClientConnectorException("Runtime Exception occurred : " + e.getMessage(), e); } catch (Exception e) { throw new ClientConnectorException("Exception occurred while processing file: " + e.getMessage(), e); } finally { closeQuietly(inputStream); closeQuietly(outputStream); } return true; }
From source file:org.apache.metron.maas.discovery.ServiceDiscoverer.java
private void updateState() { Map<Model, List<ModelEndpoint>> state = new HashMap<>(); Map<String, String> modelToVersion = new HashMap<>(); Map<String, ServiceInstance<ModelEndpoint>> containerToEndpoint = new HashMap<>(); try {/*from w ww . j a v a 2 s . c om*/ for (String name : serviceDiscovery.queryForNames()) { for (ServiceInstance<ModelEndpoint> endpoint : serviceDiscovery.queryForInstances(name)) { ModelEndpoint ep = endpoint.getPayload(); if (LOG.isDebugEnabled()) { LOG.debug("Found model endpoint " + ep); } //initialize to the existing current version, defaulting to this version String currentVersion = modelToVersion.getOrDefault(ep.getName(), ep.getVersion()); //if the version for this endpont is greater than the current version, then use this one //otherwise use the version we know about. //essentially it's equivalent to currentVersion = max(ep.getVersion(), currentVersion) currentVersion = currentVersion.compareTo(ep.getVersion()) < 0 ? ep.getVersion() : currentVersion; modelToVersion.put(ep.getName(), currentVersion); containerToEndpoint.put(ep.getContainerId(), endpoint); Model model = new Model(ep.getName(), ep.getVersion()); List<ModelEndpoint> endpoints = state.get(model); if (endpoints == null) { endpoints = new ArrayList<>(); state.put(model, endpoints); } endpoints.add(ep); } } rwLock.writeLock().lock(); try { this.modelToCurrentVersion = modelToVersion; this.state = state; this.containerToEndpoint = containerToEndpoint; if (LOG.isDebugEnabled()) { LOG.debug("Containers found: " + containerToEndpoint); } } finally { rwLock.writeLock().unlock(); } } catch (Exception e) { LOG.error(e.getMessage(), e); } finally { } }
From source file:alfio.controller.api.admin.EventApiController.java
@RequestMapping("/events/{eventName}/additional-field") public List<TicketFieldConfigurationAndAllDescriptions> getAllAdditionalField( @PathVariable("eventName") String eventName) { final Map<Integer, List<TicketFieldDescription>> descById = ticketFieldRepository .findDescriptions(eventName).stream() .collect(Collectors.groupingBy(TicketFieldDescription::getTicketFieldConfigurationId)); return ticketFieldRepository.findAdditionalFieldsForEvent(eventName).stream() .map(field -> new TicketFieldConfigurationAndAllDescriptions(field, descById.getOrDefault(field.getId(), Collections.emptyList()))) .collect(toList());/* w w w .ja va2 s . c o m*/ }
From source file:com.streamsets.pipeline.lib.dirspooler.DirectorySpooler.java
private void addFileToQueue(WrappedFile file, boolean checkCurrent) { Preconditions.checkNotNull(file, "file cannot be null"); if (checkCurrent) { final boolean currentFileExists = currentFile != null && StringUtils.isNotEmpty(currentFile.toString()); /* param "file" is invalid to add to queue if it is "less" than current file, in this case, useLastModified */ final boolean invalid = currentFileExists && (fs.compare(file, currentFile, useLastModified) < 0); if (invalid) { String invalidReason; if (useLastModified) { final Map<String, Object> currentFileMetadata = currentFile != null ? currentFile.getCustomMetadata() : Collections.emptyMap(); final Map<String, Object> newFileMetadata = file.getCustomMetadata(); final long currentMtime = (long) currentFileMetadata .getOrDefault(HeaderAttributeConstants.LAST_MODIFIED_TIME, -1l); final long currentCtime = (long) currentFileMetadata .getOrDefault(HeaderAttributeConstants.LAST_CHANGE_TIME, -1l); final long newMtime = (long) newFileMetadata .getOrDefault(HeaderAttributeConstants.LAST_MODIFIED_TIME, -1l); final long newCtime = (long) newFileMetadata .getOrDefault(HeaderAttributeConstants.LAST_CHANGE_TIME, -1l); invalidReason = String.format( "it is older than the current file (which is '%s' with %s %d, %s %d): %s %d, %s %d", currentFile.getAbsolutePath(), HeaderAttributeConstants.LAST_MODIFIED_TIME, currentMtime, HeaderAttributeConstants.LAST_CHANGE_TIME, currentCtime, HeaderAttributeConstants.LAST_MODIFIED_TIME, newMtime, HeaderAttributeConstants.LAST_CHANGE_TIME, newCtime); } else { invalidReason = String.format("it is earlier lexicographically than the current file (%s)", currentFile.getAbsolutePath()); }/*from w w w. ja v a 2s.c o m*/ LOG.warn("File '{}' cannot be added to the queue; reason: {}", file.getAbsolutePath(), invalidReason); // allow control to flow through anyway (so file gets added to queue), since that has been the behavior forever } } if (!filesSet.contains(file)) { filesQueue.add(file); this.lastQueuedFile = fs.compare(file, this.lastQueuedFile, this.useLastModified) > 0 ? file : this.lastQueuedFile; filesSet.add(file); spoolQueueMeter.mark(filesQueue.size()); } else { LOG.debug("File '{}' already in queue, ignoring", file); } }
From source file:org.apache.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor.java
/** * A generalized implementation of the "eval" operation. It handles script evaluation and iteration of results * so as to write {@link ResponseMessage} objects down the Netty pipeline. It also handles script timeouts, * iteration timeouts, metrics and building bindings. Note that result iteration is delegated to the * {@link #handleIterator} method, so those extending this class could override that method for better control * over result iteration.// w w w . j a va2 s. co m * * @param context The current Gremlin Server {@link Context} * @param gremlinExecutorSupplier A function that returns the {@link GremlinExecutor} to use in executing the * script evaluation. * @param bindingsSupplier A function that returns the {@link Bindings} to provide to the * {@link GremlinExecutor#eval} method. */ protected void evalOpInternal(final Context context, final Supplier<GremlinExecutor> gremlinExecutorSupplier, final BindingSupplier bindingsSupplier) throws OpProcessorException { final Timer.Context timerContext = evalOpTimer.time(); final ChannelHandlerContext ctx = context.getChannelHandlerContext(); final RequestMessage msg = context.getRequestMessage(); final GremlinExecutor gremlinExecutor = gremlinExecutorSupplier.get(); final Settings settings = context.getSettings(); final Map<String, Object> args = msg.getArgs(); final String script = (String) args.get(Tokens.ARGS_GREMLIN); final String language = args.containsKey(Tokens.ARGS_LANGUAGE) ? (String) args.get(Tokens.ARGS_LANGUAGE) : null; final Bindings bindings = new SimpleBindings(); // sessionless requests are always transaction managed, but in-session requests are configurable. final boolean managedTransactionsForRequest = manageTransactions ? true : (Boolean) args.getOrDefault(Tokens.ARGS_MANAGE_TRANSACTION, false); final GremlinExecutor.LifeCycle lifeCycle = GremlinExecutor.LifeCycle.build().beforeEval(b -> { try { b.putAll(bindingsSupplier.get()); } catch (OpProcessorException ope) { // this should bubble up in the GremlinExecutor properly as the RuntimeException will be // unwrapped and the root cause thrown throw new RuntimeException(ope); } }).withResult(o -> { final Iterator itty = IteratorUtils.asIterator(o); logger.debug("Preparing to iterate results from - {} - in thread [{}]", msg, Thread.currentThread().getName()); try { handleIterator(context, itty); } catch (TimeoutException ex) { final String errorMessage = String.format( "Response iteration exceeded the configured threshold for request [%s] - %s", msg, ex.getMessage()); logger.warn(errorMessage); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT) .statusMessage(errorMessage).create()); if (managedTransactionsForRequest) attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement); } catch (Exception ex) { logger.warn(String.format("Exception processing a script on request [%s].", msg), ex); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR) .statusMessage(ex.getMessage()).create()); if (managedTransactionsForRequest) attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement); } }).create(); final CompletableFuture<Object> evalFuture = gremlinExecutor.eval(script, language, bindings, lifeCycle); evalFuture.handle((v, t) -> { timerContext.stop(); if (t != null) { if (t instanceof OpProcessorException) { ctx.writeAndFlush(((OpProcessorException) t).getResponseMessage()); } else if (t instanceof TimedInterruptTimeoutException) { // occurs when the TimedInterruptCustomizerProvider is in play final String errorMessage = String.format( "A timeout occurred within the script during evaluation of [%s] - consider increasing the limit given to TimedInterruptCustomizerProvider", msg); logger.warn(errorMessage); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT) .statusMessage( "Timeout during script evaluation triggered by TimedInterruptCustomizerProvider") .create()); } else if (t instanceof TimeoutException) { final String errorMessage = String.format( "Response evaluation exceeded the configured threshold for request [%s] - %s", msg, t.getMessage()); logger.warn(errorMessage, t); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT) .statusMessage(t.getMessage()).create()); } else { logger.warn(String.format("Exception processing a script on request [%s].", msg), t); ctx.writeAndFlush( ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_SCRIPT_EVALUATION) .statusMessage(t.getMessage()).create()); } } return null; }); }
From source file:com.ccserver.digital.service.LOSService.java
private String getConfiguration(String key, String out) { Map<String, String> map = configLos; if (map == null || map.isEmpty()) { return out; } else// w ww .j a v a 2s . co m return map.getOrDefault(key, out); }
From source file:alfio.controller.api.admin.EventApiController.java
@RequestMapping("/events/{eventName}/export.csv") public void downloadAllTicketsCSV(@PathVariable("eventName") String eventName, HttpServletRequest request, HttpServletResponse response, Principal principal) throws IOException { List<String> fields = Arrays .asList(Optional.ofNullable(request.getParameterValues("fields")).orElse(new String[] {})); Event event = loadEvent(eventName, principal); Map<Integer, TicketCategory> categoriesMap = eventManager.loadTicketCategories(event).stream() .collect(Collectors.toMap(TicketCategory::getId, Function.identity())); ZoneId eventZoneId = event.getZoneId(); Predicate<String> contains = FIXED_FIELDS::contains; response.setContentType("text/csv;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-export.csv"); try (ServletOutputStream out = response.getOutputStream(); CSVWriter writer = new CSVWriter(new OutputStreamWriter(out))) { for (int marker : BOM_MARKERS) {//UGLY-MODE_ON: specify that the file is written in UTF-8 with BOM, thanks to alexr http://stackoverflow.com/a/4192897 out.write(marker);/*from w ww . ja va 2s .c om*/ } writer.writeNext(fields.stream().map(f -> { if (f.startsWith(CUSTOM_FIELDS_PREFIX)) { return f.substring(CUSTOM_FIELDS_PREFIX.length()); } return f; }).toArray(String[]::new)); eventManager.findAllConfirmedTicketsForCSV(eventName, principal.getName()).stream().map(t -> { List<String> line = new ArrayList<>(); if (fields.contains("ID")) { line.add(t.getUuid()); } if (fields.contains("Creation")) { line.add(t.getCreation().withZoneSameInstant(eventZoneId).toString()); } if (fields.contains("Category")) { line.add(categoriesMap.get(t.getCategoryId()).getName()); } if (fields.contains("Event")) { line.add(eventName); } if (fields.contains("Status")) { line.add(t.getStatus().toString()); } if (fields.contains("OriginalPrice")) { line.add(MonetaryUtil.centsToUnit(t.getSrcPriceCts()).toString()); } if (fields.contains("PaidPrice")) { line.add(MonetaryUtil.centsToUnit(t.getFinalPriceCts()).toString()); } if (fields.contains("Discount")) { line.add(MonetaryUtil.centsToUnit(t.getDiscountCts()).toString()); } if (fields.contains("VAT")) { line.add(MonetaryUtil.centsToUnit(t.getVatCts()).toString()); } if (fields.contains("ReservationID")) { line.add(t.getTicketsReservationId()); } if (fields.contains("Full Name")) { line.add(t.getFullName()); } if (fields.contains("First Name")) { line.add(t.getFirstName()); } if (fields.contains("Last Name")) { line.add(t.getLastName()); } if (fields.contains("E-Mail")) { line.add(t.getEmail()); } if (fields.contains("Locked")) { line.add(String.valueOf(t.getLockedAssignment())); } if (fields.contains("Language")) { line.add(String.valueOf(t.getUserLanguage())); } if (fields.contains("Confirmation")) { line.add(t.getTicketReservation().getConfirmationTimestamp().withZoneSameInstant(eventZoneId) .toString()); } if (fields.contains("Billing Address")) { line.add(t.getTicketReservation().getBillingAddress()); } //obviously not optimized Map<String, String> additionalValues = ticketFieldRepository.findAllValuesForTicketId(t.getId()); fields.stream().filter(contains.negate()).filter(f -> f.startsWith(CUSTOM_FIELDS_PREFIX)) .forEachOrdered(field -> { String customFieldName = field.substring(CUSTOM_FIELDS_PREFIX.length()); line.add(additionalValues.getOrDefault(customFieldName, "").replaceAll("\"", "")); }); return line.toArray(new String[line.size()]); }).forEachOrdered(writer::writeNext); writer.flush(); out.flush(); } }
From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.kubernetes.v1.KubernetesV1DistributedService.java
default List<ConfigSource> stageProfiles(AccountDeploymentDetails<KubernetesAccount> details, GenerateService.ResolvedConfiguration resolvedConfiguration) { SpinnakerService thisService = getService(); ServiceSettings thisServiceSettings = resolvedConfiguration.getServiceSettings(thisService); SpinnakerRuntimeSettings runtimeSettings = resolvedConfiguration.getRuntimeSettings(); Integer version = getRunningServiceDetails(details, runtimeSettings).getLatestEnabledVersion(); if (version == null) { version = 0;//from w ww .jav a 2 s . c om } else { version++; } String namespace = getNamespace(thisServiceSettings); KubernetesV1ProviderUtils.createNamespace(details, namespace); String name = getServiceName(); Map<String, String> env = new HashMap<>(); List<ConfigSource> configSources = new ArrayList<>(); Map<String, Profile> serviceProfiles = resolvedConfiguration.getProfilesForService(thisService.getType()); Set<String> requiredFiles = new HashSet<>(); for (SidecarService sidecarService : getSidecars(runtimeSettings)) { for (Profile profile : sidecarService.getSidecarProfiles(resolvedConfiguration, thisService)) { if (profile == null) { throw new HalException(Problem.Severity.FATAL, "Service " + sidecarService.getService().getCanonicalName() + " is required but was not supplied for deployment."); } serviceProfiles.put(profile.getName(), profile); requiredFiles.addAll(profile.getRequiredFiles()); } } Map<String, Set<Profile>> collapseByDirectory = new HashMap<>(); for (Map.Entry<String, Profile> entry : serviceProfiles.entrySet()) { Profile profile = entry.getValue(); String mountPoint = Paths.get(profile.getOutputFile()).getParent().toString(); Set<Profile> profiles = collapseByDirectory.getOrDefault(mountPoint, new HashSet<>()); profiles.add(profile); requiredFiles.addAll(profile.getRequiredFiles()); collapseByDirectory.put(mountPoint, profiles); } String stagingPath = getSpinnakerStagingPath(details.getDeploymentName()); if (!requiredFiles.isEmpty()) { String secretName = KubernetesV1ProviderUtils.componentDependencies(name, version); String mountPoint = null; for (String file : requiredFiles) { String nextMountPoint = Paths.get(file).getParent().toString(); if (mountPoint == null) { mountPoint = nextMountPoint; } assert (mountPoint.equals(nextMountPoint)); } Set<Pair<File, String>> pairs = requiredFiles.stream().map(f -> { return new ImmutablePair<>(new File(f), new File(f).getName()); }).collect(Collectors.toSet()); KubernetesV1ProviderUtils.upsertSecret(details, pairs, secretName, namespace); configSources.add(new ConfigSource().setId(secretName).setMountPath(mountPoint)); } int ind = 0; for (Map.Entry<String, Set<Profile>> entry : collapseByDirectory.entrySet()) { env.clear(); String mountPoint = entry.getKey(); Set<Profile> profiles = entry.getValue(); env.putAll(profiles.stream().reduce(new HashMap<>(), (acc, profile) -> { acc.putAll(profile.getEnv()); return acc; }, (a, b) -> { a.putAll(b); return a; })); String secretName = KubernetesV1ProviderUtils.componentSecret(name + ind, version); ind += 1; Set<Pair<File, String>> pairs = profiles.stream().map(p -> { return new ImmutablePair<>(new File(stagingPath, p.getName()), new File(p.getOutputFile()).getName()); }).collect(Collectors.toSet()); KubernetesV1ProviderUtils.upsertSecret(details, pairs, secretName, namespace); configSources.add(new ConfigSource().setId(secretName).setMountPath(mountPoint).setEnv(env)); } return configSources; }