List of usage examples for com.google.common.collect ImmutableList size
int size();
From source file:org.cyclop.service.importer.intern.ParallelQueryImporter.java
private ImmutableList<CqlQuery> parse(Scanner scanner) { StopWatch timer = null;/* w ww.ja va 2 s. co m*/ if (LOG.isDebugEnabled()) { timer = new StopWatch(); timer.start(); } ImmutableList.Builder<CqlQuery> build = ImmutableList.builder(); while (scanner.hasNext()) { String nextStr = StringUtils.trimToNull(scanner.next()); if (nextStr == null) { continue; } CqlQuery query = new CqlQuery(CqlQueryType.UNKNOWN, nextStr); build.add(query); } ImmutableList<CqlQuery> res = build.build(); if (LOG.isDebugEnabled()) { timer.stop(); LOG.debug("Parsed {} queries in {}", res.size(), timer.toString()); } return res; }
From source file:com.opengamma.strata.pricer.bond.DiscountingBondFutureProductPricer.java
/** * Calculates the price of the bond future product. * <p>/* ww w. ja v a2s . c o m*/ * The price of the product is the price on the valuation date. * <p> * Strata uses <i>decimal prices</i> for bond futures. This is coherent with the pricing of {@link FixedCouponBond}. * For example, a price of 99.32% is represented in Strata by 0.9932. * * @param future the future * @param discountingProvider the discounting provider * @return the price of the product, in decimal form */ public double price(ResolvedBondFuture future, LegalEntityDiscountingProvider discountingProvider) { ImmutableList<ResolvedFixedCouponBond> basket = future.getDeliveryBasket(); int size = basket.size(); double[] priceBonds = new double[size]; for (int i = 0; i < size; ++i) { ResolvedFixedCouponBond bond = basket.get(i); double dirtyPrice = bondPricer.dirtyPriceFromCurves(bond, discountingProvider, future.getLastDeliveryDate()); priceBonds[i] = bondPricer.cleanPriceFromDirtyPrice(bond, future.getLastDeliveryDate(), dirtyPrice) / future.getConversionFactors().get(i); } return Doubles.min(priceBonds); }
From source file:de.metanome.backend.input.database.ResultSetWithoutRelationNameFixture.java
public ResultSet getTestData() throws SQLException { ResultSet resultSet = mock(ResultSet.class); ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); // Expected values // Expected column count when(resultSetMetaData.getColumnCount()).thenReturn(numberOfColumns()); // Simulate SQLException when starting count at 0. when(resultSetMetaData.getTableName(0)).thenThrow(new SQLException()); // Simulate that JDBC driver is not properly reporting relation names (e.g., Redshift). when(resultSetMetaData.getTableName(1)).thenReturn(null); ImmutableList<String> expectedColumnNames = getExpectedColumnNames(); // Simulate SQLException when starting count at 0. when(resultSetMetaData.getColumnName(0)).thenThrow(new SQLException()); for (int i = 0; i < expectedColumnNames.size(); i++) { when(resultSetMetaData.getColumnLabel(i + 1)).thenReturn(expectedColumnNames.get(i)); }/* w w w . j ava2s . c o m*/ // Expected values when calling getMetaData when(resultSet.getMetaData()).thenReturn(resultSetMetaData); // Expected values when calling next when(resultSet.next()).thenReturn(false); return resultSet; }
From source file:com.opengamma.strata.pricer.bond.DiscountingBondFutureProductPricer.java
/** * Calculates the price of the bond future product with z-spread. * <p>/*from w w w . j a v a 2 s . c o m*/ * The price of the product is the price on the valuation date. * <p> * The z-spread is a parallel shift applied to continuously compounded rates or periodic compounded rates * of the issuer discounting curve. * <p> * Strata uses <i>decimal prices</i> for bond futures. This is coherent with the pricing of {@link FixedCouponBond}. * For example, a price of 99.32% is represented in Strata by 0.9932. * * @param future the future * @param discountingProvider the discounting provider * @param zSpread the z-spread * @param compoundedRateType the compounded rate type * @param periodPerYear the number of periods per year * @return the price of the product, in decimal form */ public double priceWithZSpread(ResolvedBondFuture future, LegalEntityDiscountingProvider discountingProvider, double zSpread, CompoundedRateType compoundedRateType, int periodPerYear) { ImmutableList<ResolvedFixedCouponBond> basket = future.getDeliveryBasket(); int size = basket.size(); double[] priceBonds = new double[size]; for (int i = 0; i < size; ++i) { ResolvedFixedCouponBond bond = basket.get(i); double dirtyPrice = bondPricer.dirtyPriceFromCurvesWithZSpread(bond, discountingProvider, zSpread, compoundedRateType, periodPerYear, future.getLastDeliveryDate()); priceBonds[i] = bondPricer.cleanPriceFromDirtyPrice(bond, future.getLastDeliveryDate(), dirtyPrice) / future.getConversionFactors().get(i); } return Doubles.min(priceBonds); }
From source file:org.ambraproject.service.migration.BootstrapMigratorServiceImpl.java
/** * Apply all migrations.//w w w .ja va2 s . c o m * * @throws Exception on an error */ public void migrate() throws Exception { ImmutableList<Migration> migrations = Migrations.getAllMigrations(); int binaryVersion = migrations.get(migrations.size() - 1).getVersion(); int dbVersion = fetchDatabaseVersion(); //Throws an exception if the database version is further into //the future then this version of the ambra war if (binaryVersion < dbVersion) { log.error("Binary version: " + binaryVersion + ", DB version: " + dbVersion); throw new Exception("The ambra war is out of date with the database, " + "update this war file to the latest version."); } waitForOtherMigrations(); for (Migration migration : migrations) { if (dbVersion < migration.getVersion()) { migration.migrate(hibernateTemplate); } } }
From source file:com.opengamma.strata.collect.io.PropertySet.java
/** * Gets a single value from this property set. * <p>/* w w w . j a v a 2 s. c om*/ * This returns the value associated with the specified key. * If more than one value, or no value, is associated with the key an exception is thrown. * * @param key the key name * @return the value * @throws IllegalArgumentException if the key does not exist, or if more than one value is associated */ public String value(String key) { ArgChecker.notNull(key, "key"); ImmutableList<String> values = keyValueMap.get(key); if (values.size() == 0) { throw new IllegalArgumentException("Unknown key: " + key); } if (values.size() > 1) { throw new IllegalArgumentException("Multiple values for key: " + key); } return values.get(0); }
From source file:com.google.testing.i18n.sanitycheck.checkers.OrderingChecker.java
@VisibleForTesting void makeCheck(ImmutableList<Collator> collators, ImmutableList<String> tokenizedInput, ULocale locale, String message) {/* w w w. j a va2 s . c o m*/ int position = 0; boolean failed = false; if (tokenizedInput != null) { main: for (int i = 1; i < tokenizedInput.size(); i++) { position = i; for (Collator testCollator : collators) { if (testCollator.compare(tokenizedInput.get(i - 1), tokenizedInput.get(i)) <= 0) { continue main; } } failed = true; break; } } String errorMessage = message != null ? message : String.format("List is not sorted for %s. Should have \"%s\" <= \"%s\" at position %s.", locale, tokenizedInput.get(position), tokenizedInput.get(position - 1), position); Assert.assertFalse(errorMessage, failed); }
From source file:org.lanternpowered.server.text.gson.JsonTextTranslatableSerializer.java
@SuppressWarnings("deprecation") @Override//from ww w . ja va 2 s .co m public JsonElement serialize(TranslatableText src, Type typeOfSrc, JsonSerializationContext context) { final Translation translation = src.getTranslation(); if (this.networkingFormat && !(translation instanceof MinecraftTranslation)) { final ImmutableList<Object> arguments = src.getArguments(); final Object[] rawArguments = arguments.toArray(new Object[arguments.size()]); final Locale locale = currentLocale.get(); for (int i = 0; i < rawArguments.length; i++) { Object object = rawArguments[i]; if (object instanceof TextRepresentable) { if (!(object instanceof Text)) { object = ((TextRepresentable) object).toText(); } rawArguments[i] = ((LanternTextSerializer) TextSerializers.LEGACY_FORMATTING_CODE) .serialize((Text) object, locale); } else { rawArguments[i] = object.toString(); } } final String content = src.getTranslation().get(locale, rawArguments); return JsonTextLiteralSerializer.serializeLiteralText(src, content, context, this.removeComplexity); } final JsonObject obj = new JsonObject(); obj.addProperty(TRANSLATABLE, src.getTranslation().getId()); final ImmutableList<Object> arguments = src.getArguments(); if (!arguments.isEmpty()) { final JsonArray argumentsArray = new JsonArray(); for (Object object : arguments) { // Only primitive strings and text json is allowed, // so we need to convert the objects if possible if (object instanceof TextRepresentable) { if (!(object instanceof Text)) { object = ((TextRepresentable) object).toText(); } argumentsArray.add(context.serialize(object, Text.class)); } else { argumentsArray.add(new JsonPrimitive(object.toString())); } } obj.add(TRANSLATABLE_ARGS, argumentsArray); } serialize(obj, src, context); return obj; }
From source file:com.facebook.buck.macho.CompDirReplacer.java
private void processThinBinary(final MachoMagicInfo magicInfo, final String oldCompDir, final String updatedCompDir) { buffer.position(0);// ww w . j a v a 2 s . c o m ImmutableList<SegmentCommand> segmentCommands = LoadCommandUtils.findLoadCommandsWithClass(buffer, nulTerminatedCharsetDecoder, SegmentCommand.class); Preconditions.checkArgument(segmentCommands.size() == 1, "Found %d SegmentCommands, expected 1", segmentCommands.size()); processSectionsInSegmentCommand(segmentCommands.get(0), magicInfo, oldCompDir, updatedCompDir); }
From source file:com.google.devtools.build.lib.integration.blackbox.framework.ProcessRunner.java
public ProcessResult runSynchronously() throws Exception { ImmutableList<String> args = parameters.arguments(); final List<String> commandParts = new ArrayList<>(args.size() + 1); commandParts.add(parameters.name()); commandParts.addAll(args);//from ww w . j a v a 2s. c o m logger.info("Running: " + commandParts.stream().collect(Collectors.joining(" "))); ProcessBuilder processBuilder = new ProcessBuilder(commandParts); processBuilder.directory(parameters.workingDirectory()); parameters.environment().ifPresent(map -> processBuilder.environment().putAll(map)); parameters.redirectOutput().ifPresent(path -> processBuilder.redirectOutput(path.toFile())); parameters.redirectError().ifPresent(path -> processBuilder.redirectError(path.toFile())); Process process = processBuilder.start(); try (ProcessStreamReader outReader = parameters.redirectOutput().isPresent() ? null : createReader(process.getInputStream(), ">> "); ProcessStreamReader errReader = parameters.redirectError().isPresent() ? null : createReader(process.getErrorStream(), "ERROR: ")) { long timeoutMillis = parameters.timeoutMillis(); if (!process.waitFor(timeoutMillis, TimeUnit.MILLISECONDS)) { throw new TimeoutException(String.format("%s timed out after %d seconds (%d millis)", parameters.name(), timeoutMillis / 1000, timeoutMillis)); } List<String> err = errReader != null ? errReader.get() : Files.readAllLines(parameters.redirectError().get()); List<String> out = outReader != null ? outReader.get() : Files.readAllLines(parameters.redirectOutput().get()); if (parameters.expectedExitCode() != process.exitValue()) { throw new ProcessRunnerException( String.format("Expected exit code %d, but found %d.\nError: %s\nOutput: %s", parameters.expectedExitCode(), process.exitValue(), StringUtilities.joinLines(err), StringUtilities.joinLines(out))); } if (parameters.expectedEmptyError()) { if (!err.isEmpty()) { throw new ProcessRunnerException( "Expected empty error stream, but found: " + StringUtilities.joinLines(err)); } } return ProcessResult.create(parameters.expectedExitCode(), out, err); } finally { process.destroy(); } }