com.google.common.io.CharSource Java Examples

The following examples show how to use com.google.common.io.CharSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SensitivityCsvLoaderTest.java    From Strata with Apache License 2.0 6 votes vote down vote up
@Test
public void test_parse_grid() {
  CharSource source =
      ResourceLocator.ofClasspath("com/opengamma/strata/loader/csv/sensitivity-grid.csv").getCharSource();

  assertThat(LOADER.isKnownFormat(source)).isTrue();
  ValueWithFailures<ListMultimap<String, CurveSensitivities>> test = LOADER.parse(ImmutableList.of(source));
  assertThat(test.getFailures().size()).as(test.getFailures().toString()).isEqualTo(0);
  assertThat(test.getValue().size()).isEqualTo(1);
  List<CurveSensitivities> list = test.getValue().get("");
  assertThat(list).hasSize(1);

  CurveSensitivities csens0 = list.get(0);
  assertThat(csens0.getTypedSensitivities()).hasSize(1);
  String tenors = "1D, 1W, 2W, 1M, 3M, 6M, 12M, 2Y, 5Y, 10Y";
  assertSens(csens0, ZERO_RATE_DELTA, "GBP", GBP, tenors, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
  assertSens(csens0, ZERO_RATE_DELTA, "USD-LIBOR-3M", USD, tenors, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
}
 
Example #2
Source File: SensitivityCsvLoaderTest.java    From Strata with Apache License 2.0 6 votes vote down vote up
@Test
public void test_parse_multipleSources() {
  CharSource source1 = CharSource.wrap(
      "Reference,Sensitivity Tenor,Zero Rate Delta\n" +
          "GBP-LIBOR,P1M,1.1\n" +
          "GBP-LIBOR,P2M,1.2\n");
  CharSource source2 = CharSource.wrap(
      "Reference,Sensitivity Tenor,Zero Rate Delta\n" +
          "GBP-LIBOR,P3M,1.3\n" +
          "GBP-LIBOR,P6M,1.4\n");
  ValueWithFailures<ListMultimap<String, CurveSensitivities>> test = LOADER.parse(ImmutableList.of(source1, source2));
  assertThat(test.getFailures().size()).as(test.getFailures().toString()).isEqualTo(0);
  assertThat(test.getValue().keySet()).hasSize(1);
  List<CurveSensitivities> list = test.getValue().get("");
  assertThat(list).hasSize(2);

  CurveSensitivities csens0 = list.get(0);
  assertThat(csens0.getTypedSensitivities()).hasSize(1);
  assertSens(csens0, ZERO_RATE_DELTA, "GBP-LIBOR", GBP, "1M, 2M", 1.1, 1.2);

  CurveSensitivities csens1 = list.get(1);
  assertThat(csens1.getTypedSensitivities()).hasSize(1);
  assertSens(csens1, ZERO_RATE_DELTA, "GBP-LIBOR", GBP, "3M, 6M", 1.3, 1.4);
}
 
Example #3
Source File: RatesCalibrationCsvLoader.java    From Strata with Apache License 2.0 6 votes vote down vote up
private static ImmutableMap<CurveGroupName, RatesCurveGroupDefinition> parse0(
    CharSource groupsCharSource,
    CharSource settingsCharSource,
    Map<CurveName, SeasonalityDefinition> seasonality,
    Collection<CharSource> curveNodeCharSources) {

  // load curve groups and settings
  List<RatesCurveGroupDefinition> curveGroups = RatesCurveGroupDefinitionCsvLoader.parseCurveGroupDefinitions(groupsCharSource);
  Map<CurveName, LoadedCurveSettings> settingsMap = RatesCurvesCsvLoader.parseCurveSettings(settingsCharSource);

  // load curve definitions
  List<CurveDefinition> curveDefinitions = curveNodeCharSources.stream()
      .flatMap(res -> parseSingle(res, settingsMap).stream())
      .collect(toImmutableList());

  // Add the curve definitions to the curve group definitions
  return curveGroups.stream()
      .map(groupDefinition -> groupDefinition.withCurveDefinitions(curveDefinitions).withSeasonalityDefinitions(seasonality))
      .collect(toImmutableMap(groupDefinition -> groupDefinition.getName()));
}
 
Example #4
Source File: TestCodeProvider.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/***/
public static String getContentsFromFileEntry(final ZipEntry entry, String rootName) throws IOException,
		URISyntaxException {
	URL rootURL = Thread.currentThread().getContextClassLoader().getResource(rootName);
	try (final ZipFile root = new ZipFile(new File(rootURL.toURI()));) {
		ByteSource byteSource = new ByteSource() {
			@Override
			public InputStream openStream() throws IOException {
				return root.getInputStream(entry);
			}
		};

		CharSource charSrc = byteSource.asCharSource(Charsets.UTF_8);
		return charSrc.read();
	}
}
 
Example #5
Source File: CorpusEventFrameLoader2016.java    From tac-kbp-eal with MIT License 6 votes vote down vote up
@Override
public CorpusEventLinking loadCorpusEventFrames(final CharSource source)
    throws IOException {
  int lineNo = 1;
  try (final BufferedReader in = source.openBufferedStream()) {
    final ImmutableSet.Builder<CorpusEventFrame> ret = ImmutableSet.builder();
    String line;
    while ((line = in.readLine()) != null) {
      if (!line.isEmpty() && !line.startsWith("#")) {
        // check for blank or comment lines
        ret.add(parseLine(line));
      }
    }
    return CorpusEventLinking.of(ret.build());
  } catch (Exception e) {
    throw new IOException("Error on line " + lineNo + " of " + source, e);
  }
}
 
Example #6
Source File: SensitivityCsvLoader.java    From Strata with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether the source is a CSV format sensitivities file.
 * <p>
 * This parses the headers as CSV and checks that mandatory headers are present.
 * 
 * @param charSource  the CSV character source to check
 * @return true if the source is a CSV file with known headers, false otherwise
 */
public boolean isKnownFormat(CharSource charSource) {
  try (CsvIterator csv = CsvIterator.of(charSource, true)) {
    if (!csv.containsHeader(TENOR_HEADER) && !csv.containsHeader(DATE_HEADER)) {
      return false;
    }
    if (csv.containsHeader(REFERENCE_HEADER) && csv.containsHeader(TYPE_HEADER) && csv.containsHeader(VALUE_HEADER)) {
      return true;  // standard format
    } else if (csv.containsHeader(REFERENCE_HEADER) || csv.containsHeader(TYPE_HEADER)) {
      return true;  // list or grid format
    } else {
      return csv.headers().stream().anyMatch(SensitivityCsvLoader::knownReference);  // implied grid format
    }
  } catch (RuntimeException ex) {
    return false;
  }
}
 
Example #7
Source File: RatesCurvesCsvLoader.java    From Strata with Apache License 2.0 6 votes vote down vote up
private static Multimap<LocalDate, Curve> parseSingle(
    Predicate<LocalDate> datePredicate,
    CharSource curvesResource,
    Map<CurveName, LoadedCurveSettings> settingsMap) {

  CsvFile csv = CsvFile.of(curvesResource, true);
  Map<LoadedCurveKey, List<LoadedCurveNode>> allNodes = new HashMap<>();
  for (CsvRow row : csv.rows()) {
    String dateStr = row.getField(CURVE_DATE);
    String curveNameStr = row.getField(CURVE_NAME);
    String pointDateStr = row.getField(CURVE_POINT_DATE);
    String pointValueStr = row.getField(CURVE_POINT_VALUE);
    String pointLabel = row.getField(CURVE_POINT_LABEL);

    LocalDate date = LoaderUtils.parseDate(dateStr);
    if (datePredicate.test(date)) {
      LocalDate pointDate = LoaderUtils.parseDate(pointDateStr);
      double pointValue = Double.valueOf(pointValueStr);

      LoadedCurveKey key = LoadedCurveKey.of(date, CurveName.of(curveNameStr));
      List<LoadedCurveNode> curveNodes = allNodes.computeIfAbsent(key, k -> new ArrayList<>());
      curveNodes.add(LoadedCurveNode.of(pointDate, pointValue, pointLabel));
    }
  }
  return buildCurves(settingsMap, allNodes);
}
 
Example #8
Source File: LegalEntityRatesCurvesCsvLoader.java    From Strata with Apache License 2.0 6 votes vote down vote up
private static Map<LocalDate, Map<CurveName, Curve>> parseCurves(
    Predicate<LocalDate> datePredicate,
    CharSource settingsResource,
    Collection<CharSource> curvesResources) {

  // load curve settings
  Map<CurveName, LoadedCurveSettings> settingsMap = parseCurveSettings(settingsResource);

  // load curves, ensuring curves only be seen once within a date
  Map<LocalDate, Map<CurveName, Curve>> resultMap = new TreeMap<>();
  for (CharSource curvesResource : curvesResources) {
    Multimap<LocalDate, Curve> fileCurvesByDate = parseSingle(datePredicate, curvesResource, settingsMap);
    // Ensure curve names are unique, with a good error message
    for (LocalDate date : fileCurvesByDate.keySet()) {
      Collection<Curve> fileCurves = fileCurvesByDate.get(date);
      Map<CurveName, Curve> resultCurves = resultMap.computeIfAbsent(date, d -> new HashMap<>());
      for (Curve fileCurve : fileCurves) {
        if (resultCurves.put(fileCurve.getName(), fileCurve) != null) {
          throw new IllegalArgumentException(
              "Rates curve loader found multiple curves with the same name: " + fileCurve.getName());
        }
      }
    }
  }
  return resultMap;
}
 
Example #9
Source File: NewSessionPayload.java    From selenium with Apache License 2.0 6 votes vote down vote up
private Collection<Map<String, Object>> getFirstMatches() throws IOException {
  CharSource charSource = backingStore.asByteSource().asCharSource(UTF_8);
  try (Reader reader = charSource.openBufferedStream();
       JsonInput input = json.newInput(reader)) {
    input.beginObject();
    while (input.hasNext()) {
      String name = input.nextName();
      if ("capabilities".equals(name)) {
        input.beginObject();
        while (input.hasNext()) {
          name = input.nextName();
          if ("firstMatch".equals(name)) {
            return input.read(LIST_OF_MAPS_TYPE);
          } else {
            input.skipValue();
          }
        }
        input.endObject();
      } else {
        input.skipValue();
      }
    }
  }
  return null;
}
 
Example #10
Source File: CsvFileTest.java    From Strata with Apache License 2.0 6 votes vote down vote up
@Test
public void test_equalsHashCodeToString() {
  CsvFile a1 = CsvFile.of(CharSource.wrap(CSV1), true);
  CsvFile a2 = CsvFile.of(CharSource.wrap(CSV1), true);
  CsvFile b = CsvFile.of(CharSource.wrap(CSV2), true);
  CsvFile c = CsvFile.of(CharSource.wrap(CSV3), false);
  // file
  assertThat(a1.equals(a1)).isTrue();
  assertThat(a1.equals(a2)).isTrue();
  assertThat(a1.equals(b)).isFalse();
  assertThat(a1.equals(c)).isFalse();
  assertThat(a1.equals(null)).isFalse();
  assertThat(a1.equals(ANOTHER_TYPE)).isFalse();
  assertThat(a1.hashCode()).isEqualTo(a2.hashCode());
  assertThat(a1.toString()).isNotNull();
  // row
  assertThat(a1.row(0).equals(a1.row(0))).isTrue();
  assertThat(a1.row(0).equals(a2.row(0))).isTrue();
  assertThat(a1.row(0).equals(b.row(0))).isFalse();
  assertThat(c.row(0).equals(c.row(1))).isFalse();
  assertThat(a1.row(0).equals(ANOTHER_TYPE)).isFalse();
  assertThat(a1.row(0).equals(null)).isFalse();
  assertThat(a1.row(0).hashCode()).isEqualTo(a2.row(0).hashCode());
  assertThat(a1.row(0)).isNotNull();
}
 
Example #11
Source File: SensitivityCsvWriterTest.java    From Strata with Apache License 2.0 6 votes vote down vote up
@Test
public void test_write_standard_roundTrip() {
  CharSource source =
      ResourceLocator.ofClasspath("com/opengamma/strata/loader/csv/sensitivity-standard.csv").getCharSource();
  ValueWithFailures<ListMultimap<String, CurveSensitivities>> parsed1 = LOADER.parse(ImmutableList.of(source));
  assertThat(parsed1.getFailures().size()).as(parsed1.getFailures().toString()).isEqualTo(0);
  assertThat(parsed1.getValue().size()).isEqualTo(1);
  List<CurveSensitivities> csensList1 = parsed1.getValue().get("");
  assertThat(csensList1).hasSize(1);
  CurveSensitivities csens1 = csensList1.get(0);

  StringBuffer buf = new StringBuffer();
  WRITER.write(csens1, buf);
  String content = buf.toString();

  ValueWithFailures<ListMultimap<String, CurveSensitivities>> parsed2 =
      LOADER.parse(ImmutableList.of(CharSource.wrap(content)));
  assertThat(parsed2.getFailures().size()).as(parsed2.getFailures().toString()).isEqualTo(0);
  assertThat(parsed2.getValue().size()).isEqualTo(1);
  List<CurveSensitivities> csensList2 = parsed2.getValue().get("");
  assertThat(csensList2).hasSize(1);
  CurveSensitivities csens2 = csensList2.get(0);

  assertThat(csens2).isEqualTo(csens1);
}
 
Example #12
Source File: SensitivityCsvLoaderTest.java    From Strata with Apache License 2.0 6 votes vote down vote up
@Test
public void test_parse_grid_tenorAndDateColumns() {
  CharSource source = CharSource.wrap(
      "Sensitivity Type,Sensitivity Tenor,Sensitivity Date,GBP\n" +
          "ZeroRateGamma,1M,2018-06-30,1\n");
  assertThat(LOADER.isKnownFormat(source)).isTrue();
  ValueWithFailures<ListMultimap<String, CurveSensitivities>> test = LOADER.parse(ImmutableList.of(source));
  assertThat(test.getFailures().size()).as(test.getFailures().toString()).isEqualTo(0);
  assertThat(test.getValue().size()).isEqualTo(1);
  List<CurveSensitivities> list = test.getValue().get("");
  assertThat(list).hasSize(1);

  CurveSensitivities csens0 = list.get(0);
  assertThat(csens0.getTypedSensitivities()).hasSize(1);
  CurrencyParameterSensitivities cpss = csens0.getTypedSensitivity(ZERO_RATE_GAMMA);
  assertThat(cpss.getSensitivities()).hasSize(1);
  CurrencyParameterSensitivity cps = cpss.getSensitivities().get(0);
  assertThat(cps.getParameterMetadata()).hasSize(1);
  assertThat(cps.getParameterMetadata().get(0)).isEqualTo(TenorDateParameterMetadata.of(date(2018, 6, 30), TENOR_1M));
}
 
Example #13
Source File: SensitivityCsvLoaderTest.java    From Strata with Apache License 2.0 6 votes vote down vote up
@Test
public void test_parse_grid_duplicateTenor() {
  CharSource source = CharSource.wrap(
      "Sensitivity Type,Sensitivity Tenor,GBP\n" +
          "ZeroRateGamma,P6M,1\n" +
          "ZeroRateGamma,12M,2\n" +
          "ZeroRateGamma,12M,3\n");
  assertThat(LOADER_DATE.isKnownFormat(source)).isTrue();
  ValueWithFailures<ListMultimap<String, CurveSensitivities>> test = LOADER_DATE.parse(ImmutableList.of(source));
  assertThat(test.getFailures().size()).as(test.getFailures().toString()).isEqualTo(0);
  assertThat(test.getValue().size()).isEqualTo(1);
  List<CurveSensitivities> list = test.getValue().get("");
  assertThat(list).hasSize(1);

  CurveSensitivities csens0 = list.get(0);
  assertThat(csens0.getTypedSensitivities()).hasSize(1);
  assertSens(csens0, ZERO_RATE_GAMMA, "GBP", GBP, "6M, 1Y", 1, 5);  // 12M -> 1Y
}
 
Example #14
Source File: ConfigurationBuilder.java    From sputnik with Apache License 2.0 5 votes vote down vote up
public static Configuration initFromResource(String configurationResource) {
    notBlank(configurationResource, "You need to provide url with configuration properties");
    log.info("Initializing configuration properties from url {}", configurationResource);

    CharSource charSource = Resources.asCharSource(getResource(configurationResource), Charsets.UTF_8);
    try (Reader resourceStream = charSource.openStream()) {
        Properties properties = new Properties();
        properties.load(resourceStream);
        return initFromProperties(properties);
    } catch (IOException e) {
        log.error("Configuration initialization failed", e);
        throw new RuntimeException(e);
    }
}
 
Example #15
Source File: QuoteFilter.java    From tac-kbp-eal with MIT License 5 votes vote down vote up
public static QuoteFilter createFromOriginalText(Map<Symbol, ? extends CharSource> originalTexts)
    throws IOException {
  checkNotNull(originalTexts);

  final ImmutableMap.Builder<Symbol, ImmutableRangeSet<Integer>> ret = ImmutableMap.builder();
  for (final Map.Entry<Symbol, ? extends CharSource> originalTextPair : originalTexts
      .entrySet()) {
    final Symbol docID = originalTextPair.getKey();
    final CharSource originalTextSource = originalTextPair.getValue();

    ret.put(docID, computeQuotedRegions(originalTextSource.read()));
  }
  return createFromBannedRegions(ret.build());
}
 
Example #16
Source File: CfgGuiTest.java    From aion with MIT License 5 votes vote down vote up
@Test
public void fromXML() throws IOException, XMLStreamException {
    String testXml = "<gui><launcher><stuff-here-does-not-matter /></launcher></gui>";
    XMLStreamReader xmlStream =
            XMLInputFactory.newInstance()
                    .createXMLStreamReader(CharSource.wrap(testXml).openStream());

    CfgGui unit = new CfgGui();
    CfgGuiLauncher cfgGuiLauncher = mock(CfgGuiLauncher.class);

    unit.setCfgGuiLauncher(cfgGuiLauncher);

    unit.fromXML(xmlStream);
    verify(cfgGuiLauncher).fromXML(xmlStream);
}
 
Example #17
Source File: CsvIteratorTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_of_blank_row() {
  try (CsvIterator csvFile = CsvIterator.of(CharSource.wrap(CSV3), false)) {
    assertThat(csvFile.hasNext()).isTrue();
    CsvRow row0 = csvFile.next();
    assertThat(row0.fieldCount()).isEqualTo(2);
    assertThat(row0.field(0)).isEqualTo("r11");
    assertThat(row0.field(1)).isEqualTo("r12");
    CsvRow row1 = csvFile.next();
    assertThat(row1.fieldCount()).isEqualTo(2);
    assertThat(row1.field(0)).isEqualTo("r21");
    assertThat(row1.field(1)).isEqualTo("r22");
    assertThat(csvFile.hasNext()).isFalse();
  }
}
 
Example #18
Source File: Formatter.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Format the given input (a Java compilation unit) into the output stream.
 *
 * @throws FormatterException if the input cannot be parsed
 */
public void formatSource(CharSource input, CharSink output)
        throws FormatterException, IOException {
    // TODO(cushon): proper support for streaming input/output. Input may
    // not be feasible (parsing) but output should be easier.
    output.write(formatSource(input.read()));
}
 
Example #19
Source File: SensitivityCsvLoaderTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_parse_standard_dateInTenorColumn() {
  CharSource source = CharSource.wrap(
      "Reference,Sensitivity Type,Sensitivity Tenor,Value\n" +
          "GBP,ZeroRateGamma,2018-06-30,1\n");
  assertThat(LOADER_DATE.isKnownFormat(source)).isTrue();
  ValueWithFailures<ListMultimap<String, CurveSensitivities>> test = LOADER_DATE.parse(ImmutableList.of(source));
  assertThat(test.getFailures()).hasSize(1);
  assertThat(test.getValue().size()).isEqualTo(0);
  FailureItem failure0 = test.getFailures().get(0);
  assertThat(failure0.getReason()).isEqualTo(FailureReason.PARSING);
  assertThat(failure0.getMessage())
      .isEqualTo("CSV file could not be parsed at line 2: Invalid tenor '2018-06-30', must be expressed as nD, nW, nM or nY");
}
 
Example #20
Source File: DistributionLoader.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static <R extends Readable & Closeable> Map<String, Distribution> loadDistribution(CharSource input)
        throws IOException
{
    Iterator<String> iterator = filter(input.readLines().iterator(), new Predicate<String>()
    {
        @Override
        public boolean apply(String line)
        {
            line = line.trim();
            return !line.isEmpty() && !line.startsWith("#");
        }
    });

    return loadDistributions(iterator);
}
 
Example #21
Source File: FormattingJavaFileObject.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Writer openWriter() throws IOException {
  final StringBuilder stringBuilder = new StringBuilder(DEFAULT_FILE_SIZE);
  return new Writer() {
    @Override
    public void write(char[] chars, int start, int end) throws IOException {
      stringBuilder.append(chars, start, end - start);
    }

    @Override
    public void flush() throws IOException {}

    @Override
    public void close() throws IOException {
      try {
        formatter.formatSource(
            CharSource.wrap(stringBuilder),
            new CharSink() {
              @Override
              public Writer openStream() throws IOException {
                return fileObject.openWriter();
              }
            });
      } catch (FormatterException e) {
        // An exception will happen when the code being formatted has an error. It's better to
        // log the exception and emit unformatted code so the developer can view the code which
        // caused a problem.
        try (Writer writer = fileObject.openWriter()) {
          writer.append(stringBuilder.toString());
        }
        if (messager != null) {
          messager.printMessage(Diagnostic.Kind.NOTE, "Error formatting " + getName());
        }
      }
    }
  };
}
 
Example #22
Source File: GuavaIOUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenReadUsingCharSource_thenRead() throws IOException {
    final String expectedValue = "Hello world";
    final File file = new File("src/test/resources/test1.in");

    final CharSource source = Files.asCharSource(file, Charsets.UTF_8);

    final String result = source.read();
    assertEquals(expectedValue, result);
}
 
Example #23
Source File: FpmlDocumentParserTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void notFpml() {
  String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
      "<root fpm=\"\" fp=\"\" f=\"\">\r\n" +
      "</root>";
  ByteSource resource = CharSource.wrap(xml).asByteSource(StandardCharsets.UTF_8);
  FpmlDocumentParser parser = FpmlDocumentParser.of(FpmlPartySelector.any());
  assertThat(parser.isKnownFormat(resource)).isFalse();
  assertThatExceptionOfType(FpmlParseException.class)
      .isThrownBy(() -> parser.parseTrades(resource))
      .withMessageStartingWith("Unable to find FpML root element");
}
 
Example #24
Source File: CharSourcesTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void testOfContentByteArrayWithCharset() throws Exception {
  byte[] inputText = "H\u0000e\u0000l\u0000l\u0000o\u0000".getBytes(Charsets.UTF_8);
  CharSource charSource = CharSources.ofContent(inputText, Charsets.UTF_16LE);
  assertThat(charSource.readFirstLine()).isEqualTo("Hello");
  assertThat(charSource.length()).isEqualTo(5);
}
 
Example #25
Source File: CsvFileTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_of_quotingWithEquals() {
  CsvFile csvFile = CsvFile.of(CharSource.wrap(CSV4B), false);
  assertThat(csvFile.rowCount()).isEqualTo(2);
  assertThat(csvFile.row(0).fieldCount()).isEqualTo(2);
  assertThat(csvFile.row(0).field(0)).isEqualTo("alpha");
  assertThat(csvFile.row(0).field(1)).isEqualTo("be, \"at\", one");
  assertThat(csvFile.row(1).fieldCount()).isEqualTo(2);
  assertThat(csvFile.row(1).field(0)).isEqualTo("r21");
  assertThat(csvFile.row(1).field(1)).isEqualTo(" r22 ");
}
 
Example #26
Source File: JavaXToReaderUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenUsingGuava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException {
    final InputStream initialStream = ByteSource.wrap("With Guava".getBytes()).openStream();
    final byte[] buffer = ByteStreams.toByteArray(initialStream);
    final Reader targetReader = CharSource.wrap(new String(buffer)).openStream();

    targetReader.close();
}
 
Example #27
Source File: CsvFileTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_of_headerComment() {
  CsvFile csvFile = CsvFile.of(CharSource.wrap(CSV7), true);
  assertThat(csvFile.rowCount()).isEqualTo(1);
  assertThat(csvFile.row(0).lineNumber()).isEqualTo(3);

  assertThat(csvFile.headers().size()).isEqualTo(2);
  assertThat(csvFile.headers().get(0)).isEqualTo("h1");
  assertThat(csvFile.headers().get(1)).isEqualTo("h2");
  assertThat(csvFile.row(0).fieldCount()).isEqualTo(2);
  assertThat(csvFile.row(0).field(0)).isEqualTo("r1");
  assertThat(csvFile.row(0).field(1)).isEqualTo("r2");
}
 
Example #28
Source File: TradeCsvLoaderTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_load_bulletPayment() {
  TradeCsvLoader test = TradeCsvLoader.standard();
  ResourceLocator locator = ResourceLocator.of("classpath:com/opengamma/strata/loader/csv/fxtrades.csv");
  ImmutableList<CharSource> charSources = ImmutableList.of(locator.getCharSource());
  ValueWithFailures<List<BulletPaymentTrade>> loadedData = test.parse(charSources, BulletPaymentTrade.class);
  assertThat(loadedData.getValue()).hasSize(2);

  BulletPaymentTrade expected0 = BulletPaymentTrade.builder()
      .info(TradeInfo.builder()
          .id(StandardId.of("OG", "tradeId21"))
          .tradeDate(date(2016, 12, 6))
          .build())
      .product(BulletPayment.builder()
          .payReceive(RECEIVE)
          .value(CurrencyAmount.of(USD, 25000))
          .date(AdjustableDate.of(date(2016, 12, 8), BusinessDayAdjustment.of(FOLLOWING, USNY)))
          .build())
      .build();
  assertBeanEquals(expected0, loadedData.getValue().get(0));

  BulletPaymentTrade expected1 = BulletPaymentTrade.builder()
      .info(TradeInfo.builder()
          .id(StandardId.of("OG", "tradeId22"))
          .tradeDate(date(2016, 12, 22))
          .build())
      .product(BulletPayment.builder()
          .payReceive(PAY)
          .value(CurrencyAmount.of(GBP, 35000))
          .date(AdjustableDate.of(date(2016, 12, 24), BusinessDayAdjustment.of(FOLLOWING, GBLO)))
          .build())
      .build();
  assertBeanEquals(expected1, loadedData.getValue().get(1));

  checkRoundtrip(BulletPaymentTrade.class, loadedData.getValue(), expected0, expected1);
}
 
Example #29
Source File: YangToolUtil.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Converts XML source into XML Document.
 *
 * @param xmlInput to convert
 * @return Document
 */
public static Document toDocument(CharSource xmlInput) {
    try {
        return DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
            .parse(new InputSource(xmlInput.openStream()));
    } catch (ParserConfigurationException | SAXException | IOException e) {
        log.error("Exception thrown", e);
        return null;
    }
}
 
Example #30
Source File: AbstractFMT.java    From fmt-maven-plugin with MIT License 5 votes vote down vote up
private boolean formatSourceFile(
    File file, Formatter formatter, JavaFormatterOptions.Style style) {
  if (file.isDirectory()) {
    getLog().info("File '" + file + "' is a directory. Skipping.");
    return true;
  }

  if (verbose) {
    getLog().debug("Formatting '" + file + "'.");
  }

  CharSource source = com.google.common.io.Files.asCharSource(file, Charsets.UTF_8);
  try {
    String input = source.read();
    String formatted = formatter.formatSource(input);
    formatted = RemoveUnusedImports.removeUnusedImports(formatted);
    if (!skipSortingImports) {
      formatted = ImportOrderer.reorderImports(formatted, style);
    }
    if (!input.equals(formatted)) {
      onNonComplyingFile(file, formatted);
      nonComplyingFiles += 1;
    }
    filesProcessed.add(file.getAbsolutePath());
    if (filesProcessed.size() % 100 == 0) {
      logNumberOfFilesProcessed();
    }
  } catch (FormatterException | IOException e) {
    getLog().error("Failed to format file '" + file + "'.", e);
    return false;
  }
  return true;
}