List of usage examples for com.google.common.collect ImmutableList size
int size();
From source file:com.freiheit.fuava.sftp.SftpOldFilesMovingLatestMultiFileFetcher.java
/** * Filters out the files that need to be downloaded. * * @param fileNamesList all files on the sftp server with a desired pattern in the file name. * @param fileType the file type that needs to be processed. * @return a list of files that need to be downloaded. *///ww w . j av a 2 s . c o m protected Iterable<Result<FetchedItem<SftpFilename>, SftpFilename>> moveOldFilesToSkippedAndReturnLatestFilename( final List<String> fileNamesList, final FileType fileType) throws SftpException, JSchException, ParseException, FileNotFoundException { final ImmutableList.Builder<Result<FetchedItem<SftpFilename>, SftpFilename>> files = new ImmutableList.Builder<>(); /* * We only extract the filename from the .ok-files in Order to find only * files that are ready. */ final String latestDateExtracted = FilenameUtil.extractLatestDateFromFilenames(fileNamesList, fileType, RemoteFileStatus.OK); if (latestDateExtracted == null) { LOG.info("No .ok file matching the schema found on the server. Nothing to download."); return files.build(); // return an empty list } // get list of all .ok files fulfilling the pattern defined by file type // make sure newer files are processed first final List<String> okFiles = Ordering.natural().reverse().immutableSortedCopy( FilenameUtil.getAllMatchingFilenames("", fileType, fileNamesList, RemoteFileStatus.OK)); // extract the latest timestamp of all ok.-files. final long latestTimestamp = FilenameUtil.timestampToLong(latestDateExtracted); // move all skipped files to skipped folder, add all files for download to the result list for (final String okFile : okFiles) { if (okFile != null) { final long timestamp = FilenameUtil.getDateFromFilename(okFile); if (isLatestFile(timestamp, latestTimestamp)) { files.add(moveToProcessing(fileType, latestTimestamp, okFile)); } else { // this file is older then the latest one, move it to the skipped folder silentlyMoveToSkipped(fileType, okFile); } } } final ImmutableList<Result<FetchedItem<SftpFilename>, SftpFilename>> result = files.build(); // warn if too many or too few items returned if (result.size() != 1) { LOG.warn("Unexpected number of Items in result: " + result); } return result; }
From source file:com.epam.dlab.configuration.BillingToolConfiguration.java
/** * Check and return module.// w w w .j a va 2 s. co m * * @param modules the list of modules. * @param name the name of module. * @param isOptional optional module or not. * @return module * @throws InitializationException */ private <T extends ModuleBase> T getModule(ImmutableList<T> modules, String name, boolean isOptional) throws InitializationException { T module = (modules != null && modules.size() == 1 ? modules.get(0) : null); if (!isOptional && module == null) { throw new InitializationException("Invalid configuration for property " + name); } return module; }
From source file:com.microsoft.thrifty.schema.Loader.java
/** * Loads and parses a Thrift file and all files included (both directly and * transitively) by it.// ww w . j a v a2 s . c o m * * @param path A relative or absolute path to a Thrift file. * @param loadedFiles A mapping of absolute paths to parsed Thrift files. */ private void loadFileRecursively(Path path, Map<Path, ThriftFileElement> loadedFiles) throws IOException { ThriftFileElement element = null; Path dir = null; Path file = findFirstExisting(path, null); if (file != null) { // Resolve symlinks, redundant '.' and '..' segments. file = file.normalize(); if (loadedFiles.containsKey(file.toAbsolutePath())) { return; } dir = file.getParent(); element = loadSingleFile(dir, file.getFileName()); } if (element == null) { throw new FileNotFoundException("Failed to locate " + path + " in " + includePaths); } loadedFiles.put(file.normalize().toAbsolutePath(), element); ImmutableList<IncludeElement> includes = element.includes(); if (includes.size() > 0) { includePaths.addFirst(dir); for (IncludeElement include : includes) { if (!include.isCpp()) { loadFileRecursively(Paths.get(include.path()), loadedFiles); } } includePaths.removeFirst(); } }
From source file:com.wandoulabs.jodis.RoundRobinJedisPool.java
private void resetPools() { ImmutableList<PooledObject> pools = this.pools; Map<String, PooledObject> addr2Pool = Maps.newHashMapWithExpectedSize(pools.size()); for (PooledObject pool : pools) { addr2Pool.put(pool.addr, pool);/*ww w . j a va2 s .com*/ } ImmutableList.Builder<PooledObject> builder = ImmutableList.builder(); for (ChildData childData : watcher.getCurrentData()) { try { JsonNode proxyInfo = MAPPER.readTree(childData.getData()); if (!CODIS_PROXY_STATE_ONLINE.equals(proxyInfo.get(JSON_NAME_CODIS_PROXY_STATE).asText())) { continue; } String addr = proxyInfo.get(JSON_NAME_CODIS_PROXY_ADDR).asText(); PooledObject pool = addr2Pool.remove(addr); if (pool == null) { LOG.info("Add new proxy: " + addr); String[] hostAndPort = addr.split(":"); String host = hostAndPort[0]; int port = Integer.parseInt(hostAndPort[1]); if (timeout == JEDIS_POOL_TIMEOUT_UNSET) { pool = new PooledObject(addr, new JedisPool(poolConfig, host, port)); } else { pool = new PooledObject(addr, new JedisPool(poolConfig, host, port, timeout)); } } builder.add(pool); } catch (Exception e) { LOG.warn("parse " + childData.getPath() + " failed", e); } } this.pools = builder.build(); for (PooledObject pool : addr2Pool.values()) { LOG.info("Remove proxy: " + pool.addr); pool.pool.close(); } }
From source file:org.apache.cloudstack.utils.CloudStackVersion.java
/** * {@inheritDoc}// w w w .ja v a 2 s. c om * * A couple of notes about the comparison rules for this method: * <ul> * <li>Three position versions are normalized to four position versions with the security release being * defaulted to zero (0). For example, for the purposes of comparision, <code>4.8.1</code> would be * normalized to <code>4.8.1.0</code> for all comparison operations.</li> * <li>A three position version with a null security release is considered equal to a four position * version number where the major release, minor release, and patch release are the same and the security * release for the four position version is zero (0). Therefore, the results of this method are <b>not</b> * symmetric with <code>equals</code></li> * <li>When comparing to <code>null</code>, this version is always considered greater than (i.e. returning * a value greater than zero (0).</li> * </ul> * * @param thatVersion The version to which to compare this instance * * @return A value less than zero (0) indicates this version is less than <code>thatVersion</code>. A value * equal to zero (0) indicates this value equals <code>thatValue</code>. A value greater than zero (0) * indicates this version is greater than <code>thatVersion</code>. * * @since 4.8.2.0 * */ @Override public int compareTo(final CloudStackVersion thatVersion) { if (thatVersion == null) { return 1; } // Normalize the versions to be 4 positions for the purposes of comparison ... final ImmutableList<Integer> values = normalizeVersionValues(asList()); final ImmutableList<Integer> thoseValues = normalizeVersionValues(thatVersion.asList()); for (int i = 0; i < values.size(); i++) { final int result = values.get(i).compareTo(thoseValues.get(i)); if (result != 0) { return result; } } return 0; }
From source file:com.qubole.presto.udfs.sqlFunction.hiveUdfs.Hash.java
@Override public ScalarFunctionImplementation specialize(Map<String, Type> types, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) { Type type = types.get("E"); // the argument need not be orderable, so no orderable check ImmutableList.Builder<Class<?>> builder = ImmutableList.builder(); for (int i = 0; i < arity; i++) { builder.add(type.getJavaType()); }/*www.jav a 2 s . c o m*/ ImmutableList<Class<?>> stackTypes = builder.build(); Class<?> clazz = generateHash(stackTypes, type); MethodHandle methodHandle = methodHandle(clazz, "hash", stackTypes.toArray(new Class<?>[stackTypes.size()])); List<Boolean> nullableParameters = ImmutableList.copyOf(Collections.nCopies(stackTypes.size(), false)); return new ScalarFunctionImplementation(false, nullableParameters, methodHandle, isDeterministic()); }
From source file:com.google.errorprone.bugpatterns.DoubleBraceInitialization.java
@Override public Description matchNewClass(NewClassTree tree, VisitorState state) { ClassTree body = tree.getClassBody(); if (body == null) { return NO_MATCH; }//w ww. ja v a2s . co m ImmutableList<? extends Tree> members = body.getMembers().stream() .filter(m -> !(m instanceof MethodTree && ASTHelpers.isGeneratedConstructor((MethodTree) m))) .collect(toImmutableList()); if (members.size() != 1) { return NO_MATCH; } Tree member = Iterables.getOnlyElement(members); if (!(member instanceof BlockTree)) { return NO_MATCH; } BlockTree block = (BlockTree) member; Optional<CollectionTypes> collectionType = Arrays.stream(CollectionTypes.values()) .filter(type -> type.constructorMatcher.matches(tree, state)).findFirst(); if (!collectionType.isPresent()) { return NO_MATCH; } Description.Builder description = buildDescription(tree); collectionType.get().maybeFix(tree, state, block).ifPresent(description::addFix); return description.build(); }
From source file:com.facebook.buck.versions.VersionedTargetGraph.java
@Nullable @Override//from w ww . j av a2s. c o m protected TargetNode<?, ?> getInternal(BuildTarget target) { // If this node is in the graph under the given name, return it. TargetNode<?, ?> node = targetsToNodes.get(target); if (node != null) { return node; } ImmutableList<ImmutableSet<Flavor>> flavorList = flavorMap.get(target.getUnflavoredBuildTarget()); if (flavorList == null) { return null; } // Otherwise, see if this node exists in the graph with a "less" flavored name. We initially // select all targets which contain a subset of the original flavors, which should be sorted by // from largest flavor set to smallest. We then use the first match, and verify the subsequent // matches are subsets. ImmutableList<ImmutableSet<Flavor>> matches = RichStream.from(flavorList) .filter(target.getFlavors()::containsAll).toImmutableList(); if (!matches.isEmpty()) { ImmutableSet<Flavor> firstMatch = matches.get(0); for (ImmutableSet<Flavor> subsequentMatch : matches.subList(1, matches.size())) { Preconditions.checkState(firstMatch.size() > subsequentMatch.size()); Preconditions.checkState(firstMatch.containsAll(subsequentMatch), "Found multiple disjoint flavor matches for %s: %s and %s", target.getUnflavoredBuildTarget(), firstMatch, subsequentMatch); } return Preconditions.checkNotNull(targetsToNodes.get(target.withFlavors(firstMatch))) .withFlavors(target.getFlavors()); } // Otherwise, return `null` to indicate this node isn't in the target graph. return null; }
From source file:com.google.errorprone.bugpatterns.CatchFail.java
Optional<Fix> deleteFix(TryTree tree, ImmutableList<CatchTree> catchBlocks, VisitorState state) { SuggestedFix.Builder fix = SuggestedFix.builder(); if (tree.getFinallyBlock() != null || catchBlocks.size() < tree.getCatches().size()) { // If the try statement has a finally region, or other catch blocks, delete only the // unnecessary blocks. catchBlocks.forEach(fix::delete); } else {/*from w w w. ja v a2 s . c o m*/ // The try statement has no finally region and all catch blocks are unnecessary. Replace it // with the try statements, deleting all catches. List<? extends StatementTree> tryStatements = tree.getBlock().getStatements(); // If the try block is empty, all of the catches are dead, so just delete the whole try and // don't modify the signature of the method if (tryStatements.isEmpty()) { return Optional.of(fix.delete(tree).build()); } else { String source = state.getSourceCode().toString(); // Replace the full region to work around a GJF partial formatting bug that prevents it from // re-indenting unchanged lines. This means that fixes may overlap, but that's (hopefully) // unlikely. // TODO(b/24140798): emit more precise replacements if GJF is fixed fix.replace(tree, source.substring(((JCTree) tryStatements.get(0)).getStartPosition(), state.getEndPosition(Iterables.getLast(tryStatements)))); } } MethodTree enclosing = findEnclosing(state.getPath()); if (enclosing == null) { // There isn't an enclosing method, possibly because we're in a lambda or initializer block. return Optional.empty(); } if (isExpectedExceptionTest(ASTHelpers.getSymbol(enclosing), state)) { // Replacing the original exception with fail() may break badly-structured expected-exception // tests, so don't use that fix for methods annotated with @Test(expected=...). return Optional.empty(); } // Fix up the enclosing method's throws declaration to include the new thrown exception types. Collection<Type> thrownTypes = ASTHelpers.getSymbol(enclosing).getThrownTypes(); Types types = state.getTypes(); // Find all types in the deleted catch blocks that are not already in the throws declaration. ImmutableList<Type> toThrow = catchBlocks.stream().map(c -> ASTHelpers.getType(c.getParameter())) // convert multi-catch to a list of component types .flatMap(t -> t instanceof UnionClassType ? ImmutableList.copyOf(((UnionClassType) t).getAlternativeTypes()).stream() : Stream.of(t)) .filter(t -> thrownTypes.stream().noneMatch(x -> types.isAssignable(t, x))) .collect(toImmutableList()); if (!toThrow.isEmpty()) { if (!JUnitMatchers.TEST_CASE.matches(enclosing, state)) { // Don't add throws declarations to methods that don't look like test cases, since it may // not be a safe local refactoring. return Optional.empty(); } String throwsString = toThrow.stream().map(t -> SuggestedFixes.qualifyType(state, fix, t)).distinct() .collect(joining(", ")); if (enclosing.getThrows().isEmpty()) { // Add a new throws declaration. fix.prefixWith(enclosing.getBody(), "throws " + throwsString); } else { // Append to an existing throws declaration. fix.postfixWith(Iterables.getLast(enclosing.getThrows()), ", " + throwsString); } } return Optional.of(fix.build()); }
From source file:com.facebook.buck.apple.xcode.ProjectGenerator.java
/** * Take a List of configuration layers and try to fit it into the xcode configuration layers * layout./* w w w.jav a 2s.c o m*/ * * @throws com.facebook.buck.util.HumanReadableException if the configuration layers are not in * the right layout to be coerced into standard xcode layout. */ private static ConfigInXcodeLayout extractXcodeConfigurationLayers(BuildTarget buildTarget, XcodeRuleConfiguration configuration) { ConfigInXcodeLayout extractedLayers = null; ImmutableList<XcodeRuleConfiguration.Layer> layers = configuration.getLayers(); switch (layers.size()) { case 2: if (layers.get(0).getLayerType() == XcodeRuleConfiguration.LayerType.FILE && layers.get(1).getLayerType() == XcodeRuleConfiguration.LayerType.FILE) { extractedLayers = new ConfigInXcodeLayout(buildTarget, layers.get(0).getPath(), ImmutableMap.<String, String>of(), layers.get(1).getPath(), ImmutableMap.<String, String>of()); } break; case 4: if (layers.get(0).getLayerType() == XcodeRuleConfiguration.LayerType.FILE && layers.get(1).getLayerType() == XcodeRuleConfiguration.LayerType.INLINE_SETTINGS && layers.get(2).getLayerType() == XcodeRuleConfiguration.LayerType.FILE && layers.get(3).getLayerType() == XcodeRuleConfiguration.LayerType.INLINE_SETTINGS) { extractedLayers = new ConfigInXcodeLayout(buildTarget, layers.get(0).getPath(), layers.get(1).getInlineSettings().or(ImmutableMap.<String, String>of()), layers.get(2).getPath(), layers.get(3).getInlineSettings().or(ImmutableMap.<String, String>of())); } break; default: // handled later on by the fact that extractLayers is null break; } if (extractedLayers == null) { throw new HumanReadableException("Configuration layers cannot be expressed in xcode for target: " + buildTarget + "\n" + " expected: [File, Inline settings, File, Inline settings]"); } return extractedLayers; }