List of usage examples for com.google.common.collect ImmutableMap.Builder putAll
public final void putAll(Map<? extends K, ? extends V> map)
From source file:dagger.internal.codegen.BasicProcessor.java
private void reportMissingElements(Map<String, ? extends Optional<? extends Element>> missingElements, Collection<ElementName> missingElementNames) { if (!missingElementNames.isEmpty()) { ImmutableMap.Builder<String, Optional<? extends Element>> allMissingElements = ImmutableMap.builder(); allMissingElements.putAll(missingElements); for (ElementName missingElement : missingElementNames) { if (!missingElements.containsKey(missingElement.name())) { allMissingElements.put(missingElement.name(), missingElement.getElement(elements)); }// w ww. j av a2 s . c o m } missingElements = allMissingElements.build(); } for (Entry<String, ? extends Optional<? extends Element>> missingElementEntry : missingElements .entrySet()) { Optional<? extends Element> missingElement = missingElementEntry.getValue(); if (missingElement.isPresent()) { processingEnv.getMessager().printMessage(ERROR, processingErrorMessage("this " + Ascii.toLowerCase(missingElement.get().getKind().name())), missingElement.get()); } else { processingEnv.getMessager().printMessage(ERROR, processingErrorMessage(missingElementEntry.getKey())); } } }
From source file:google.registry.tools.CreateOrUpdatePremiumListCommand.java
@Override public String execute() throws Exception { ImmutableMap.Builder<String, Object> params = new ImmutableMap.Builder<>(); params.put(NAME_PARAM, name);/*from w w w . j a v a 2s .c o m*/ String inputFileContents = new String(Files.readAllBytes(inputFile), UTF_8); String requestBody = Joiner.on('&').withKeyValueSeparator("=") .join(ImmutableMap.of(INPUT_PARAM, URLEncoder.encode(inputFileContents, UTF_8.toString()))); ImmutableMap<String, ?> extraParams = getParameterMap(); if (extraParams != null) { params.putAll(extraParams); } // Call the server and get the response data String response = connection.send(getCommandPath(), params.build(), MediaType.FORM_DATA, requestBody.getBytes()); return extractServerResponse(response); }
From source file:io.prestosql.orc.checkpoint.Checkpoints.java
public static Map<StreamId, StreamCheckpoint> getStreamCheckpoints(Set<Integer> columns, List<OrcType> columnTypes, boolean compressed, int rowGroupId, List<ColumnEncoding> columnEncodings, Map<StreamId, Stream> streams, Map<StreamId, List<RowGroupIndex>> columnIndexes) throws InvalidCheckpointException { // map from (column, sequence) to available StreamKind ImmutableSetMultimap.Builder<ColumnAndSequence, StreamKind> streamKindsBuilder = ImmutableSetMultimap .builder();//from w w w. j a va 2s. c o m for (Stream stream : streams.values()) { streamKindsBuilder.put(new ColumnAndSequence(stream.getColumn(), stream.getSequence()), stream.getStreamKind()); } SetMultimap<ColumnAndSequence, StreamKind> streamKinds = streamKindsBuilder.build(); ImmutableMap.Builder<StreamId, StreamCheckpoint> checkpoints = ImmutableMap.builder(); for (Map.Entry<StreamId, List<RowGroupIndex>> entry : columnIndexes.entrySet()) { int column = entry.getKey().getColumn(); if (!columns.contains(column)) { continue; } int sequence = entry.getKey().getSequence(); List<Integer> positionsList = entry.getValue().get(rowGroupId).getPositions(); ColumnEncodingKind columnEncoding = columnEncodings.get(column).getColumnEncoding(sequence) .getColumnEncodingKind(); OrcTypeKind columnType = columnTypes.get(column).getOrcTypeKind(); Set<StreamKind> availableStreams = streamKinds.get(new ColumnAndSequence(column, sequence)); ColumnPositionsList columnPositionsList = new ColumnPositionsList(column, sequence, columnType, positionsList); switch (columnType) { case BOOLEAN: checkpoints.putAll(getBooleanColumnCheckpoints(column, sequence, compressed, availableStreams, columnPositionsList)); break; case BYTE: checkpoints.putAll(getByteColumnCheckpoints(column, sequence, compressed, availableStreams, columnPositionsList)); break; case SHORT: case INT: case LONG: case DATE: checkpoints.putAll(getLongColumnCheckpoints(column, sequence, columnEncoding, compressed, availableStreams, columnPositionsList)); break; case FLOAT: checkpoints.putAll(getFloatColumnCheckpoints(column, sequence, compressed, availableStreams, columnPositionsList)); break; case DOUBLE: checkpoints.putAll(getDoubleColumnCheckpoints(column, sequence, compressed, availableStreams, columnPositionsList)); break; case TIMESTAMP: checkpoints.putAll(getTimestampColumnCheckpoints(column, sequence, columnEncoding, compressed, availableStreams, columnPositionsList)); break; case BINARY: case STRING: case VARCHAR: case CHAR: checkpoints.putAll(getSliceColumnCheckpoints(column, sequence, columnEncoding, compressed, availableStreams, columnPositionsList)); break; case LIST: case MAP: checkpoints.putAll(getListOrMapColumnCheckpoints(column, sequence, columnEncoding, compressed, availableStreams, columnPositionsList)); break; case STRUCT: checkpoints.putAll(getStructColumnCheckpoints(column, sequence, compressed, availableStreams, columnPositionsList)); break; case DECIMAL: checkpoints.putAll(getDecimalColumnCheckpoints(column, sequence, columnEncoding, compressed, availableStreams, columnPositionsList)); break; default: throw new IllegalArgumentException("Unsupported column type " + columnType); } // The DWRF code is not meticulous in the handling of checkpoints. It appears that for the first row group // it will write checkpoints for all streams, but in other cases it will write only the streams that exist. // We detect this case by checking that all offsets in the initial position list are zero, and if so, we // clear the extra offsets if (columnPositionsList.hasNextPosition() && !Iterables.all(positionsList, equalTo(0))) { throw new InvalidCheckpointException(format( "Column %s, of type %s, contains %s offset positions, but only %s positions were consumed", column, columnType, positionsList.size(), columnPositionsList.getIndex())); } } return checkpoints.build(); }
From source file:google.registry.tools.ListObjectsCommand.java
@Override public void run() throws Exception { ImmutableMap.Builder<String, Object> params = new ImmutableMap.Builder<>(); if (fields != null) { params.put(FIELDS_PARAM, fields); }/*from w w w. ja va 2s . c o m*/ if (printHeaderRow != null) { params.put(PRINT_HEADER_ROW_PARAM, printHeaderRow); } if (fullFieldNames) { params.put(FULL_FIELD_NAMES_PARAM, Boolean.TRUE); } ImmutableMap<String, Object> extraParams = getParameterMap(); if (extraParams != null) { params.putAll(extraParams); } // Call the server and get the response data. String response = connection.send(getCommandPath(), params.build(), MediaType.PLAIN_TEXT_UTF_8, new byte[0]); // Parse the returned JSON and make sure it's a map. Object obj = JSONValue.parse(response.substring(JSON_SAFETY_PREFIX.length())); if (!(obj instanceof Map<?, ?>)) { throw new VerifyException("Server returned unexpected JSON: " + response); } @SuppressWarnings("unchecked") Map<String, Object> responseMap = (Map<String, Object>) obj; // Get the status. obj = responseMap.get("status"); if (obj == null) { throw new VerifyException("Server returned no status"); } if (!(obj instanceof String)) { throw new VerifyException("Server returned non-string status"); } String status = (String) obj; // Handle errors. if (status.equals("error")) { obj = responseMap.get("error"); if (obj == null) { throw new VerifyException("Server returned no error message"); } System.out.println(obj); // Handle success. } else if (status.equals("success")) { obj = responseMap.get("lines"); if (obj == null) { throw new VerifyException("Server returned no response data"); } if (!(obj instanceof List<?>)) { throw new VerifyException("Server returned unexpected response data"); } for (Object lineObj : (List<?>) obj) { System.out.println(lineObj); } // Handle unexpected status values. } else { throw new VerifyException("Server returned unexpected status"); } }
From source file:edu.cmu.lti.oaqa.baseqa.answer.score.scorers.TypeCoercionAnswerScorer.java
@Override public Map<String, Double> score(JCas jcas, Answer answer) { Set<CandidateAnswerOccurrence> caos = TypeUtil.getCandidateAnswerVariants(answer).stream() .map(TypeUtil::getCandidateAnswerOccurrences).flatMap(Collection::stream).collect(toSet()); List<Set<String>> typesList = caos.stream().map(cao -> offset2ctypes.get(TypeUtil.annotationOffset(cao))) .collect(toList());/*from www . j av a 2 s . c o m*/ ImmutableMap.Builder<String, Double> feat2value = ImmutableMap.builder(); atLimits.stream().filter(limit -> limit <= ats.size()).forEach(limit -> { Set<String> limitedLats = ImmutableSet.copyOf(ats.subList(0, limit)); double[] typecorRatios = typesList.stream().mapToDouble(types -> { int overlap = Sets.intersection(limitedLats, types).size(); int maxOverlap = Math.min(limitedLats.size(), types.size()); return Scorer.safeDividedBy(overlap, maxOverlap); }).toArray(); feat2value.putAll(Scorer.generateSummaryFeatures(typecorRatios, "type-coercion-" + limit, "avg", "max", "min", "pos-ratio", "one-ratio", "any-one")); }); return feat2value.build(); }
From source file:org.apache.aurora.scheduler.updater.OneWayJobUpdater.java
/** * Performs an evaluation of the job. An evaluation would normally be triggered to initiate the * update, as a result of a state change relevant to the update, or due to a * {@link InstanceAction#WATCH_TASK requested} instance re-evaluation. * * @param instancesNeedingUpdate Instances triggering the event, if any. * @param stateProvider Provider to fetch state of instances, and pass to * {@link StateEvaluator#evaluate(Object)}. * @return The outcome of the evaluation, including the state of the job update and actions the * caller should perform on individual instances. * @throws IllegalStateException if the job updater is not currently * {@link OneWayStatus#WORKING working} state, as indicated by a previous evaluation. *///from w w w .j a v a2 s .co m synchronized EvaluationResult<K> evaluate(Map<K, T> instancesNeedingUpdate, InstanceStateProvider<K, T> stateProvider) { if (stateMachine.getState() == OneWayStatus.IDLE) { stateMachine.transition(OneWayStatus.WORKING); } Preconditions.checkState(stateMachine.getState() == OneWayStatus.WORKING, "Attempted to evaluate an inactive job updater."); // Call order is important here: update on-demand instances, evaluate new instances, compute // job update state. ImmutableMap.Builder<K, SideEffect> actions = ImmutableMap.<K, SideEffect>builder() // Re-evaluate instances that are in need of update. .putAll(evaluateInstances(instancesNeedingUpdate)); if (computeJobUpdateStatus() == OneWayStatus.WORKING) { // If ready to begin updating more instances, evaluate those as well. actions.putAll(startNextInstanceGroup(stateProvider)); } return new EvaluationResult<>(computeJobUpdateStatus(), actions.build()); }
From source file:org.apache.brooklyn.location.jclouds.JcloudsSshMachineLocation.java
@Override public Map<String, String> toMetadataRecord() { Optional<NodeMetadata> node = getOptionalNode(); Optional<Hardware> hardware = getOptionalHardware(); List<? extends Processor> processors = hardware.isPresent() ? hardware.get().getProcessors() : null; ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); builder.putAll(super.toMetadataRecord()); putIfNotNull(builder, "provider", getParent().getProvider()); putIfNotNull(builder, "account", getParent().getIdentity()); putIfNotNull(builder, "region", getParent().getRegion()); putIfNotNull(builder, "serverId", getJcloudsId()); putIfNotNull(builder, "imageId", getImageId()); putIfNotNull(builder, "instanceTypeName", (hardware.isPresent() ? hardware.get().getName() : null)); putIfNotNull(builder, "instanceTypeId", (hardware.isPresent() ? hardware.get().getProviderId() : null)); putIfNotNull(builder, "ram", "" + (hardware.isPresent() ? hardware.get().getRam() : null)); putIfNotNull(builder, "cpus", "" + (processors != null ? processors.size() : null)); try {/* w w w . ja v a2 s. c om*/ OsDetails osDetails = getOsDetails(); putIfNotNull(builder, "osName", osDetails.getName()); putIfNotNull(builder, "osArch", osDetails.getArch()); putIfNotNull(builder, "is64bit", osDetails.is64bit() ? "true" : "false"); } catch (Exception e) { Exceptions.propagateIfFatal(e); LOG.warn("Unable to get OS Details for " + node + "; continuing", e); } return builder.build(); }
From source file:dagger.internal.codegen.ComponentImplementation.java
/** * Returns the names of modifiable module methods for this implementation and all inherited * implementations, keyed by the corresponding module's {@link ComponentRequirement}. *//*from www. ja v a 2s. co m*/ ImmutableMap<ComponentRequirement, String> getAllModifiableModuleMethods() { ImmutableMap.Builder<ComponentRequirement, String> methods = ImmutableMap.builder(); methods.putAll(modifiableModuleMethods); superclassImplementation .ifPresent(superclass -> methods.putAll(superclass.getAllModifiableModuleMethods())); return methods.build(); }
From source file:com.facebook.buck.android.exopackage.ExopackageInstaller.java
public void finishExoFileInstallation(ImmutableSortedSet<Path> presentFiles, ExopackageInfo exoInfo) throws Exception { ImmutableSet.Builder<Path> wantedPaths = ImmutableSet.builder(); ImmutableMap.Builder<Path, String> metadata = ImmutableMap.builder(); if (exoInfo.getDexInfo().isPresent()) { DexExoHelper dexExoHelper = new DexExoHelper(pathResolver, projectFilesystem, exoInfo.getDexInfo().get()); wantedPaths.addAll(dexExoHelper.getFilesToInstall().keySet()); metadata.putAll(dexExoHelper.getMetadataToInstall()); }/* w w w . j a va 2 s . c om*/ if (exoInfo.getNativeLibsInfo().isPresent()) { NativeExoHelper nativeExoHelper = new NativeExoHelper(() -> { try { return device.getDeviceAbis(); } catch (Exception e) { throw new HumanReadableException("Unable to communicate with device", e); } }, pathResolver, projectFilesystem, exoInfo.getNativeLibsInfo().get()); wantedPaths.addAll(nativeExoHelper.getFilesToInstall().keySet()); metadata.putAll(nativeExoHelper.getMetadataToInstall()); } if (exoInfo.getResourcesInfo().isPresent()) { ResourcesExoHelper resourcesExoHelper = new ResourcesExoHelper(pathResolver, projectFilesystem, exoInfo.getResourcesInfo().get()); wantedPaths.addAll(resourcesExoHelper.getFilesToInstall().keySet()); metadata.putAll(resourcesExoHelper.getMetadataToInstall()); } if (exoInfo.getModuleInfo().isPresent()) { ModuleExoHelper moduleExoHelper = new ModuleExoHelper(pathResolver, projectFilesystem, exoInfo.getModuleInfo().get()); wantedPaths.addAll(moduleExoHelper.getFilesToInstall().keySet()); metadata.putAll(moduleExoHelper.getMetadataToInstall()); } deleteUnwantedFiles(presentFiles, wantedPaths.build()); installMetadata(metadata.build()); }
From source file:com.google.devtools.build.lib.rules.apple.AppleConfiguration.java
/** * Returns a map of environment variables (derived from configuration) that should be propagated * for actions pertaining to the given apple platform. Keys are variable names and values are * their corresponding values./*from w w w. j a va 2 s . c om*/ */ @SkylarkCallable(name = "target_apple_env") public Map<String, String> getTargetAppleEnvironment(Platform platform) { ImmutableMap.Builder<String, String> mapBuilder = ImmutableMap.builder(); mapBuilder.putAll(appleTargetPlatformEnv(platform)); return mapBuilder.build(); }