List of usage examples for com.google.common.collect ImmutableMap size
int size();
From source file:com.google.devtools.build.android.XmlResourceValues.java
static XmlResourceValue parsePublic(XMLEventReader eventReader, StartElement start, Namespaces.Collector namespacesCollector) throws XMLStreamException { namespacesCollector.collectFrom(start); // The tag should be unary. if (!isEndTag(eventReader.peek(), start.getName())) { throw new XMLStreamException(String.format("<public> tag should be unary %s", start), start.getLocation());//from w w w . ja v a2 s . co m } // The tag should have a valid type attribute, and optionally an id attribute. ImmutableMap<String, String> attributes = ImmutableMap.copyOf(parseTagAttributes(start)); String typeAttr = attributes.get(SdkConstants.ATTR_TYPE); ResourceType type; if (typeAttr != null) { type = ResourceType.getEnum(typeAttr); if (type == null || type == ResourceType.PUBLIC) { throw new XMLStreamException(String.format("<public> tag has invalid type attribute %s", start), start.getLocation()); } } else { throw new XMLStreamException(String.format("<public> tag missing type attribute %s", start), start.getLocation()); } String idValueAttr = attributes.get(SdkConstants.ATTR_ID); Optional<Integer> id = Optional.absent(); if (idValueAttr != null) { try { id = Optional.of(Integer.decode(idValueAttr)); } catch (NumberFormatException e) { throw new XMLStreamException(String.format("<public> has invalid id number %s", start), start.getLocation()); } } if (attributes.size() > 2) { throw new XMLStreamException(String.format("<public> has unexpected attributes %s", start), start.getLocation()); } return PublicXmlResourceValue.create(type, id); }
From source file:com.github.steveash.typedconfig.resolver.ProxyValueResolver.java
private boolean proxyEquals(Class<?> thisIface, ImmutableMap<Method, ValueResolver> thisResolvers, Object that) {//from w w w. j ava2s . co m if (!(that instanceof ProxiedConfiguration)) return false; ProxiedConfiguration thatConfig = ((ProxiedConfiguration) that); Class<?> thatIface = thatConfig.getInterfaceClass(); if (!thisIface.equals(thatIface)) return false; ImmutableMap<Method, ValueResolver> thatResolvers = thatConfig.getResolvers(); if (thisResolvers.size() != thatResolvers.size()) throw new IllegalStateException("not sure how the same iface can have different resolver map"); for (Entry<Method, ValueResolver> thisEntry : thisResolvers.entrySet()) { Object thisValue = thisEntry.getValue().resolve(); Object thatValue = thatResolvers.get(thisEntry.getKey()).resolve(); if (!thisValue.equals(thatValue)) return false; } return true; }
From source file:org.grycap.gpf4med.DownloadService.java
/** * Uses a group of URIs to retrieve objects and writes them to the same number of files. This method will do * its best effort to optimally handle the downloads, opening a pool of connections to the servers and reusing * them as much as possible. Also, it will create several concurrent threads in the JVM in order to perform * simultaneous downloads.//from ww w . jav a 2 s .c om * @param requests a key-value map with the list of requests to handle. The source of the object is the key of * the map, while the value is the destination file. * @param validator checks the file for correctness. * @param config download settings. * @param encryptionProvider an optional encryption provider that, when available, is used to encrypt the * files after download. * @param task an optional task that will be executed passing each individual file as parameter, when the download * of the file ends. * @return the requests that could not be served after exhausting the individual retries. * @throws IOException if an error occurs in the execution of the operation. */ public ImmutableMap<URI, File> download(final ImmutableMap<URI, File> requests, final @Nullable FileValidator validator, final DownloadConfiguration config, final @Nullable FileEncryptionProvider encryptionProvider, final @Nullable PostProcessTask<File> task) throws IOException { checkArgument(requests != null, "Uninitialized request"); checkArgument(config != null, "Uninitialized configuration"); ImmutableMap<URI, File> pending = ImmutableMap.copyOf(requests); final List<URI> cancelled = new ArrayList<URI>(); try { for (int attempt = 0; attempt < config.getRetries() && !pending.isEmpty() && pending.size() > cancelled.size(); attempt++) { LOGGER.info("Attempt " + (attempt + 1) + " to download " + requests.size() + " files"); // create connection manager final PoolingNHttpClientConnectionManager connectionManager = createConnectionManager(); // create HTTP asynchronous client int eSoTimeoutMs = config.soToMs + (int) (config.soToMs * attempt * (config.toIncPercent >= 0.0d && config.toIncPercent <= 1.0d ? config.toIncPercent : 0.0d)); int eConnTimeoutMs = config.connToMs + (int) (config.connToMs * attempt * (config.toIncPercent >= 0.0d && config.toIncPercent <= 1.0d ? config.toIncPercent : 0.0d)); final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(eConnTimeoutMs) .setConnectionRequestTimeout(eConnTimeoutMs).setSocketTimeout(eSoTimeoutMs).build(); final CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom() .setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build(); httpclient.start(); // attempt to perform download try { final CountDownLatch latch = new CountDownLatch(pending.size()); for (final Map.Entry<URI, File> entry : pending.entrySet()) { final URI uri = entry.getKey(); if (cancelled.contains(uri)) { continue; } final File file = entry.getValue(); FileUtils.forceMkdir(file.getParentFile()); final HttpGet request = new HttpGet(uri); final HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer( new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), request); final ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(file) { @Override protected File process(final HttpResponse response, final File file, final ContentType contentType) throws Exception { releaseResources(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { FileUtils.deleteQuietly(file); throw new ClientProtocolException( "Download failed: " + response.getStatusLine()); } if (validator != null && !validator.isValid(file)) { FileUtils.deleteQuietly(file); cancelled.add(uri); throw new IOException( file.getCanonicalPath() + " not recognised as a supported file format"); } if (encryptionProvider != null) { try { final File cipherFile = File .createTempFile(RandomStringUtils.random(8, true, true), ".tmp"); encryptionProvider.encrypt(new FileInputStream(file), new FileOutputStream(cipherFile)); FileUtils.deleteQuietly(file); FileUtils.moveFile(cipherFile, file); LOGGER.info("File encrypted: " + file.getCanonicalPath()); } catch (Exception e) { FileUtils.deleteQuietly(file); cancelled.add(uri); LOGGER.warn("Failed to encrypt: " + file.getCanonicalPath(), e); throw new IOException("File encryption failed"); } } LOGGER.info("Download succeed to file: " + file.getCanonicalPath()); return file; } }; httpclient.execute(producer, consumer, new FutureCallback<File>() { @Override public void completed(final File result) { request.releaseConnection(); latch.countDown(); if (task != null) { task.apply(result); } LOGGER.info("Request succeed: " + request.getRequestLine() + " => Response file length: " + result.length()); } @Override public void failed(final Exception ex) { request.releaseConnection(); FileUtils.deleteQuietly(file); latch.countDown(); LOGGER.error("Request failed: " + request.getRequestLine() + "=>" + ex); } @Override public void cancelled() { request.releaseConnection(); FileUtils.deleteQuietly(file); latch.countDown(); LOGGER.error("Request cancelled: " + request.getRequestLine()); } }); } latch.await(); } finally { try { httpclient.close(); } catch (Exception ignore) { } try { shutdown(connectionManager, 0l); } catch (Exception ignore) { } } // populate the pending list with the files that does not exist final ImmutableMap.Builder<URI, File> builder = new ImmutableMap.Builder<URI, File>(); for (final Map.Entry<URI, File> entry : requests.entrySet()) { if (!entry.getValue().exists()) { builder.put(entry.getKey(), entry.getValue()); } } pending = builder.build(); if ((attempt + 1) < config.retries && !pending.isEmpty() && pending.size() > cancelled.size()) { final long waitingTime = (long) (config.soToMs * 0.1d); LOGGER.info("Waiting " + waitingTime + " ms before attempt " + (attempt + 2) + " to download " + requests.size() + " pending files"); Thread.sleep(waitingTime); } } } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new IOException("Download has failed", e); } return pending; }
From source file:net.navatwo.jfxproperties.RealPropertyObjectBuilder.java
/** * Provides a breadth-first component to build up the tree of all of the {@link PropertyObject} found * in the {@link #base} type's hierarchy. * * @param cache Known {@link PropertyObject} instances to save lookup times * @return Mapping of classes to their associated {@link PropertyObject} value *///from www . j a v a 2s .c o m ImmutableMap<Class<?>, PropertyObject<?>> build(ImmutableMap<Class<?>, PropertyObject<?>> cache) { logger.traceEntry("Builder.RealBuilder#build(cache: {} entries)", cache.size()); // Utilize the cache by adding all the known entites to the #allCollectors field cache.forEach( (type, propertyObject) -> allCollectors.put(type, new TypePropertiesCollector(propertyObject))); // Do a breadth-first search from the bottom of the class hierarchy // and add fields/methods as they're found. If a type has interfaces, we // check those, too! // "visit" action is done by creating a new TypePropertiesCollector to visit the class found. Deque<Class<?>> q = new ArrayDeque<>(); q.addLast(base.getRawType()); visited.add(Object.class); // do this so it never tries to keep going higher // Mark all of the known classes as visited visited.addAll(allCollectors.keySet()); // Do a DFS via the TypePropertiesCollector#collect method while (!q.isEmpty()) { final Class<?> currentClazz = q.pop(); final TypeToken<?> current = base.resolveType(currentClazz); if (isTypeBadPredicate.test(currentClazz) || visited.contains(currentClazz)) { continue; } TypePropertiesCollector c = new TypePropertiesCollector(current); c.collect(q); allCollectors.put(currentClazz, c); } logger.trace("Finished breadth-first search to find all fields/methods"); throwIfPropertyErrors(); // Do a DFS to build up all of the Collectors Deque<TypePropertiesCollector> dfsPath = new ArrayDeque<>(); buildHierarchyRec(dfsPath, new HashSet<>(), allCollectors.get(base.getRawType())); Map<Class<?>, PropertyObject<?>> builtObjects = new HashMap<>(); while (!dfsPath.isEmpty()) { TypePropertiesCollector current = dfsPath.pop(); TypeToken<?> type = current.getBase(); // Get the super TypePropertiesCollectors List<? extends PropertyObject<?>> supers = Stream .concat(Stream.of(type.getRawType().getSuperclass()), Arrays.stream(type.getRawType().getInterfaces())) .filter(Objects::nonNull).filter(isTypeBadPredicate.negate()).map(t -> { PropertyObject<?> po = builtObjects.get(t); checkState(po != null, "PropertyObject not loaded before super requested, " + "super: %s, base: %s", t, type); return po; }).collect(Collectors.toList()); @SuppressWarnings("unchecked") // I hate this, but its required :( PropertyObject<?> po = (PropertyObject<?>) new PropertyObject(type, supers, current.ignoredProperties, current.propertyTypes, current.fieldsMap, current.methodsMap); builtObjects.put(type.getRawType(), po); } // Now the maps have all been filled, we pass the values to the PropertyObject constructor to // let it decide how to format them. return logger.traceExit(ImmutableMap.copyOf(builtObjects)); }
From source file:org.grycap.gpf4med.DocumentFetcher.java
public void fecth(final ImmutableList<URL> urls) { checkArgument(urls != null, "Uninitialized URLs"); final ImmutableMap.Builder<URI, File> pendingBuilder = new ImmutableMap.Builder<URI, File>(); try {//from w ww.j a va 2 s.co m final File cacheDir = new File(ConfigurationManager.INSTANCE.getLocalCacheDir(), "reports"); final ImmutableMap.Builder<URI, File> requestBuilder = new ImmutableMap.Builder<URI, File>(); for (final URL url : urls) { try { if (URLUtils.isRemoteProtocol(url)) { final URI source = url.toURI().normalize(); final File destination = new File(cacheDir, NamingUtils.genSafeFilename(new String[] { source.toString() }, null, ".xml")); requestBuilder.put(source, destination); } else if (URLUtils.isFileProtocol(url)) { FileQueue.INSTANCE.add(FileUtils.toFile(url)); } else { FileQueue.INSTANCE.failed(1); LOGGER.warn("Ignoring unsupported URL: " + url.toString()); } } catch (Exception e2) { FileQueue.INSTANCE.failed(); } } final DownloadConfiguration downloadConfig = new DownloadConfiguration(CONNECTION_TIMEOUT_MILLIS, READ_TIMEOUT_MILLIS, RETRIES, TIMEOUT_INCREMENT_PERCENTAGE); final ImmutableMap<URI, File> pending = new DownloadService().download(requestBuilder.build(), null, downloadConfig, ConfigurationManager.INSTANCE.getFileEncryptionProvider(), new PostProcessTask<File>() { @Override public void apply(final File object) { FileQueue.INSTANCE.add(object); } }); if (pending != null) { pendingBuilder.putAll(pending); } } catch (Exception e) { final ImmutableMap<URI, File> pending = pendingBuilder.build(); if (pending != null && pending.size() > 0) { FileQueue.INSTANCE.failed(pending.size()); } } }
From source file:com.facebook.buck.skylark.parser.SkylarkProjectBuildFileParser.java
private ImplicitlyLoadedExtension loadImplicitExtension(String basePath, Label containingLabel) throws IOException, InterruptedException { Optional<ImplicitInclude> implicitInclude = packageImplicitIncludeFinder .findIncludeForBuildFile(Paths.get(basePath)); if (!implicitInclude.isPresent()) { return ImplicitlyLoadedExtension.empty(); }/*from w w w .j av a 2s . c om*/ // Only export requested symbols, and ensure that all requsted symbols are present. ExtensionData data = loadExtension(LoadImport.of(containingLabel, implicitInclude.get().getLoadPath())); ImmutableMap<String, Object> symbols = data.getExtension().getBindings(); ImmutableMap<String, String> expectedSymbols = implicitInclude.get().getSymbols(); Builder<String, Object> loaded = ImmutableMap.builderWithExpectedSize(expectedSymbols.size()); for (Entry<String, String> kvp : expectedSymbols.entrySet()) { Object symbol = symbols.get(kvp.getValue()); if (symbol == null) { throw BuildFileParseException.createForUnknownParseError( String.format("Could not find symbol '%s' in implicitly loaded extension '%s'", kvp.getValue(), implicitInclude.get().getLoadPath().getImportString())); } loaded.put(kvp.getKey(), symbol); } return ImplicitlyLoadedExtension.of(data, loaded.build()); }
From source file:com.facebook.buck.versions.ParallelVersionedTargetGraphBuilder.java
@Override protected VersionInfo getVersionInfo(TargetNode<?> node) { VersionInfo info = this.versionInfo.get(node.getBuildTarget()); if (info != null) { return info; }//from w w w . j a v a 2 s . co m Map<BuildTarget, ImmutableSet<Version>> versionDomain = new HashMap<>(); Optional<TargetNode<VersionedAliasDescriptionArg>> versionedNode = TargetGraphVersionTransformations .getVersionedNode(node); if (versionedNode.isPresent()) { ImmutableMap<Version, BuildTarget> versions = versionedNode.get().getConstructorArg().getVersions(); // Merge in the versioned deps and the version domain. versionDomain.put(node.getBuildTarget(), versions.keySet()); // If this version has only one possible choice, there's no need to wrap the constraints from // it's transitive deps in an implication constraint. if (versions.size() == 1) { Map.Entry<Version, BuildTarget> ent = versions.entrySet().iterator().next(); VersionInfo depInfo = getVersionInfo(getNode(ent.getValue())); versionDomain.putAll(depInfo.getVersionDomain()); } else { // For each version choice, inherit the transitive constraints by wrapping them in an // implication dependent on the specific version that pulls them in. for (Map.Entry<Version, BuildTarget> ent : versions.entrySet()) { VersionInfo depInfo = getVersionInfo(getNode(ent.getValue())); versionDomain.putAll(depInfo.getVersionDomain()); } } } else { // Merge in the constraints and version domain/deps from transitive deps. for (BuildTarget depTarget : TargetGraphVersionTransformations.getDeps(typeCoercerFactory, node)) { TargetNode<?> dep = getNode(depTarget); if (TargetGraphVersionTransformations.isVersionPropagator(dep) || TargetGraphVersionTransformations.getVersionedNode(dep).isPresent()) { VersionInfo depInfo = getVersionInfo(dep); versionDomain.putAll(depInfo.getVersionDomain()); } } } info = VersionInfo.of(versionDomain); this.versionInfo.put(node.getBuildTarget(), info); return info; }
From source file:com.isotrol.impe3.pms.core.obj.PortalObject.java
List<SetFilterDTO> getSetFilterDTOs() { ImmutableMap<String, SetFilterValue> filters = setFilters.get(); final List<SetFilterDTO> list = Lists.newArrayListWithCapacity(filters.size()); if (filters.isEmpty()) { return list; }//from www . j av a2 s.co m for (String set : Ordering.natural().sortedCopy(filters.keySet())) { SetFilterValue v = filters.get(set); SetFilterDTO dto = new SetFilterDTO(); dto.setName(set); dto.setType(v.getType()); dto.setDescription(v.getDescription()); list.add(dto); } return list; }
From source file:com.pinterest.pinlater.backends.mysql.PinLaterMySQLBackend.java
private ImmutableMap.Entry<String, MySQLDataSources> getRandomShard() { ImmutableMap<String, MySQLDataSources> shardMap = shardMapRef.get(); if (shardMap == null || shardMap.isEmpty()) { return null; }// ww w . j a va 2 s.c o m int rand = RANDOM.nextInt(shardMap.size()); return shardMap.entrySet().asList().get(rand); }
From source file:com.pinterest.pinlater.backends.mysql.PinLaterMySQLBackend.java
private ImmutableMap.Entry<String, MySQLDataSources> getRandomEnqueueableShard() { ImmutableMap<String, MySQLDataSources> enqueueableShardMap = getEnqueueableShards(); if (enqueueableShardMap.isEmpty()) { return null; }/*w ww .j a v a2 s . com*/ int rand = RANDOM.nextInt(enqueueableShardMap.size()); return enqueueableShardMap.entrySet().asList().get(rand); }