Java Code Examples for com.google.common.io.Resources#toString()

The following examples show how to use com.google.common.io.Resources#toString() . 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: TestThriftIdlGenerator.java    From drift with Apache License 2.0 6 votes vote down vote up
private static void assertGenerated(Class<?> clazz, String name, Consumer<ThriftIdlGeneratorConfig.Builder> configConsumer)
        throws IOException
{
    String expected = Resources.toString(getResource(format("expected/%s.txt", name)), UTF_8);

    ThriftIdlGeneratorConfig.Builder config = ThriftIdlGeneratorConfig.builder()
            .includes(ImmutableMap.of())
            .namespaces(ImmutableMap.of())
            .recursive(true);
    configConsumer.accept(config);

    ThriftIdlGenerator generator = new ThriftIdlGenerator(config.build());
    String idl = generator.generate(ImmutableList.of(clazz.getName()));

    assertEquals(idl, expected);
}
 
Example 2
Source File: EthGraphQLHttpBySpecTest.java    From besu with Apache License 2.0 6 votes vote down vote up
private void graphQLCall(final String name) throws IOException {
  final String testSpecFile = name + ".json";
  final String json =
      Resources.toString(
          EthGraphQLHttpBySpecTest.class.getResource(testSpecFile), Charsets.UTF_8);
  final JsonObject spec = new JsonObject(json);
  final String rawRequestBody = spec.getString("request");
  final RequestBody requestBody = RequestBody.create(GRAPHQL, rawRequestBody);
  final Request request = new Request.Builder().post(requestBody).url(baseUrl).build();

  importBlocks(1, BLOCKS.size());
  try (final Response resp = client.newCall(request).execute()) {
    final JsonObject expectedRespBody = spec.getJsonObject("response");
    final String resultStr = resp.body().string();

    final JsonObject result = new JsonObject(resultStr);
    Assertions.assertThat(result).isEqualTo(expectedRespBody);

    final int expectedStatusCode = spec.getInteger("statusCode");
    Assertions.assertThat(resp.code()).isEqualTo(expectedStatusCode);
  }
}
 
Example 3
Source File: CommuterTest.java    From log-synth with Apache License 2.0 6 votes vote down vote up
@Test
public void testSampleTrips() throws IOException {
    SchemaSampler s = new SchemaSampler(Resources.toString(Resources.getResource("schema027.json"), Charsets.UTF_8));
    for (int i = 0; i < 20; i++) {
        JsonNode r = s.sample();
        verifyFields(r, ImmutableList.of("vehicle", "trip"));
        verifyFields(r.get("trip"), ImmutableList.of("home", "work", "trips"));
        verifyFields(r.get("trip").get("home"), ImmutableList.of("zip", "longitude", "latitude"));
        verifyFields(r.get("trip").get("work"), ImmutableList.of("longitude", "latitude"));
        verifyFields(r.get("trip").get("trips").get(0),
                ImmutableList.of("data", "t", "start", "timestamp", "type", "distance_km", "duration"));
        verifyFields(r.get("trip").get("trips").get(0).get("data").get(0),
                ImmutableList.of("longitude", "latitude", "t", "timestamp", "mph", "rpm", "throttle"));

        int total = 0;
        JsonNode trips = r.get("trip").get("trips");
        for (JsonNode trip : trips) {
            total += trip.get("data").size();
        }
        int n = r.get("trip").get("trips").size();
        System.out.printf("%d,%d\n", total, n);
        assertTrue(String.format("Expected lots of detail but only saw %d records", total), total > 500 && total < 100000);
        assertTrue(String.format("But only a few trips (saw %d)", n), n > 2 && n < 40);
    }
}
 
Example 4
Source File: ParserUtils.java    From QVisual with Apache License 2.0 5 votes vote down vote up
public static String readFile(String path) {
    try {
        return Resources.toString(Resources.getResource(path), Charset.forName("UTF-8"));
    } catch (IOException e) {
        logger.error("[reading file] by path: " + path, e);
    }

    return null;
}
 
Example 5
Source File: ParentProjectDescriptor.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private CharSequence loadResource(final String resourcePath) {
  try {
    return Resources.toString(this.getClass().getClassLoader().getResource(resourcePath), Charsets.ISO_8859_1);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 6
Source File: GlobalStateCliUtilsTest.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testGlobalStateCliUtil() throws IOException {
    final GlobalBuilder builder = buildGlobal(true);
    GlobalStateCliUtils.displayRibOperationalState(RIB_ID, builder.build(), this.stream);

    final String expected = Resources.toString(getClass().getClassLoader().getResource("global.txt"),
        StandardCharsets.UTF_8);
    assertEquals(expected, this.output.toString());
}
 
Example 7
Source File: PafServerStub.java    From vics with MIT License 5 votes vote down vote up
public void willCreateANewContactRecord(String ern) throws IOException {
    String fileName = String.format("postContact,%s", ern);
    String file = requireNonNull(files.get(fileName),
            String.format("No json file for POST contact request ern=%s", ern));
    String jsonResponse = Resources.toString(getResource(file), UTF_8);

    String urlPath = String.format("/v1/voters/%s", ern);
    wireMock.register(post(urlPathMatching(urlPath))
            .willReturn(aResponse()
                    .withBody(jsonResponse)
                    .withStatus(200)
                    .withHeader(CONTENT_TYPE, "application/json")));
}
 
Example 8
Source File: ScriptingOriginTestUtil.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public static String getScript(String scriptName, Class searchClass) {
  try {
    URL url = Resources.getResource(searchClass, scriptName);
    return Resources.toString(url, Charsets.UTF_8);
  } catch (IOException e) {
    System.out.println(e);
    return null;
  }
}
 
Example 9
Source File: AutoEscapeTagTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Test
public void itEscapesVarsInScope() throws IOException {
  Map<String, Object> context = new HashMap<>();
  context.put("myvar", "foo < bar");

  String template = Resources.toString(
    Resources.getResource("tags/autoescapetag/autoescape.jinja"),
    StandardCharsets.UTF_8
  );
  String result = jinjava.render(template, context);

  assertThat(result).contains("1. foo < bar", "2. foo &lt; bar", "3. foo < bar");
}
 
Example 10
Source File: AlertManager.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public void alert(List<String> emailIds, Throwable throwable) {
  StringWriter stringWriter = new StringWriter();
  PrintWriter printWriter = new PrintWriter(stringWriter);
  throwable.printStackTrace(printWriter);
  String description = stringWriter.toString();
  String subject = "ERROR: " + throwable;
  long timestamp = System.currentTimeMillis();
  String errorCode = "UNKNOWN";
  if (throwable instanceof PipelineException) {
    PipelineException pipelineException = (PipelineException)throwable;
    timestamp = pipelineException.getErrorMessage().getTimestamp();
    subject =  "ERROR: " + pipelineException.getLocalizedMessage();
    errorCode = pipelineException.getErrorCode().getCode();
  }
  try {
    URL url = Resources.getResource(EmailConstants.ALERT_ERROR_EMAIL_TEMPLATE);
    String emailBody = Resources.toString(url, Charsets.UTF_8);
    java.text.DateFormat dateTimeFormat = new SimpleDateFormat(EmailConstants.DATE_MASK, Locale.ENGLISH);
    emailBody = emailBody.replace(EmailConstants.ERROR_CODE, errorCode)
      .replace(EmailConstants.TIME_KEY, dateTimeFormat.format(new Date(timestamp)))
      .replace(EmailConstants.PIPELINE_NAME_KEY, Strings.nullToEmpty(pipelineTitle))
      .replace(EmailConstants.DESCRIPTION_KEY, Strings.nullToEmpty(description))
      .replace(EmailConstants.URL_KEY, runtimeInfo.getBaseHttpUrl() + EmailConstants.PIPELINE_URL + pipelineId);
    subject = EmailConstants.STREAMSETS_DATA_COLLECTOR_ALERT + subject;
    if (LOG.isDebugEnabled()) {
      LOG.debug("Email Alert: subject = " + subject + ", body = " + emailBody);
    }
    if(emailSender == null) {
      LOG.error("Email Sender is not configured. Alert with message '{}' will not be sent via email:",
        emailBody, throwable);
    } else {
      emailSender.send(emailIds, subject, emailBody);
    }
  } catch (EmailException | IOException e) {
    LOG.error("Error sending alert email, reason: {}", e.toString(), e);
    //Log error and move on. This should not stop the pipeline.
  }
}
 
Example 11
Source File: SchemaHelperTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
public void schemaHelper_ExtractsName_schemaName_badId() throws Exception {
	URL url = Resources.getResource(path + "B-badid.json");
	String text = Resources.toString(url, Charsets.UTF_8);
	String nameFromSchema = SchemaHelper.extractNameFromSchema(text, "Not", "Even");

	assertEquals("Not", nameFromSchema);

}
 
Example 12
Source File: YAMLUtils.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Map loadAsMap(String path) throws IOException {
    try {
        String content = Resources.toString(Resources.getResource(path), Charset.forName("UTF-8"));
        LOG.debug("Loaded resource file '{}'\n{}", path, content);
        return loadStringAsMap(content);
    } catch (IllegalArgumentException e) {
        return new HashMap();
    }
}
 
Example 13
Source File: KaramelEvaluation.java    From karamel with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, KaramelException, InterruptedException {
  String fileName = "flink_gce_eval";
  String clusterName = "flink";
  String outputName = "timestat.txt";
  int numRound = 5;
  int increase = 20;

  ClusterStatistics.setFileName(outputName);
  String ymlString = Resources.toString(
      Resources.getResource("se/kth/karamel/backend/evaluation/" + fileName + ".yml"), Charsets.UTF_8);
  SshKeyPair sshKeys = api.loadSshKeysIfExist("");
  if (sshKeys == null) {
    sshKeys = api.generateSshKeysAndUpdateConf(clusterName);
  }
  api.registerSshKeys(sshKeys);
  api.updateGceCredentialsIfValid(Settings.KARAMEL_ROOT_PATH + "/gce-key.json");

  KaramelEvaluation evaluation = new KaramelEvaluation();

  for (int i = 9; i < 100; i = i + increase) {
    ymlString = ymlString.replace(NUM_VM_PARAM, String.valueOf(i));
    ClusterStatistics.setExperimentName(String.format("%s%d", fileName, i));
    for (int j = 0; j < numRound; j++) {
      evaluation.evaluatePhases(ymlString, clusterName);
    }
  }
}
 
Example 14
Source File: PafServerStub.java    From vics with MIT License 5 votes vote down vote up
public void willUndoVoterVoted(String ern) throws IOException {
    String file = requireNonNull("json/paf-undo-voted.json");
    String jsonData = Resources.toString(getResource(file), UTF_8);

    String urlPath = "/v1/voters/" + ern + "/voted";
    wireMock.register(delete(urlPathMatching(urlPath))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withBody(jsonData)));
}
 
Example 15
Source File: GuavaIOUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenReadUsingResources_thenRead() throws IOException {
    final String expectedValue = "Hello world";

    final URL url = Resources.getResource("test1.in");
    final String result = Resources.toString(url, Charsets.UTF_8);

    assertEquals(expectedValue, result);
}
 
Example 16
Source File: JsonFlattenerTest.java    From json-flattener with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testPrintMode() throws IOException {
  URL url = Resources.getResource("test.json");
  String src = Resources.toString(url, Charsets.UTF_8);

  String json =
      new JsonFlattener(src).withPrintMode(PrintMode.MINIMAL).flatten();
  assertEquals(mapper.readTree(json).toString(), json);

  json = new JsonFlattener(src).withPrintMode(PrintMode.REGULAR).flatten();
  assertEquals(mapper.readTree(json).toString(), json);

  json = new JsonFlattener(src).withPrintMode(PrintMode.PRETTY).flatten();
  assertEquals(mapper.readTree(json).toPrettyString(), json);

  src = "[[123]]";
  json = new JsonFlattener(src).withFlattenMode(FlattenMode.KEEP_ARRAYS)
      .withPrintMode(PrintMode.MINIMAL).flatten();
  assertEquals(mapper.readTree(json).toString(), json);

  json = new JsonFlattener(src).withFlattenMode(FlattenMode.KEEP_ARRAYS)
      .withPrintMode(PrintMode.REGULAR).flatten();
  assertEquals(mapper.readTree(json).toString(), json);

  json = new JsonFlattener(src).withFlattenMode(FlattenMode.KEEP_ARRAYS)
      .withPrintMode(PrintMode.PRETTY).flatten();
  assertEquals(mapper.readTree(json).toPrettyString(), json);
}
 
Example 17
Source File: ResourceResolver.java    From blueocean-plugin with MIT License 4 votes vote down vote up
public String loadResource(String path) throws IOException {
    return Resources.toString(getResourceURL(path), Charsets.UTF_8);
}
 
Example 18
Source File: SoyTemplateSkylarkSignatureRendererTest.java    From buck with Apache License 2.0 4 votes vote down vote up
private static String getExpectedContent(String resourceName) throws IOException {
  return Resources.toString(
      Resources.getResource(SoyTemplateSkylarkSignatureRendererTest.class, resourceName),
      StandardCharsets.UTF_8);
}
 
Example 19
Source File: RdfReaderFactoryTest.java    From RDFUnit with Apache License 2.0 3 votes vote down vote up
@Test
public void testCreateReaderFromText() throws IOException, RdfReaderException {

    URL url = Resources.getResource(this.getClass(),"/org/aksw/rdfunit/io/onetriple.ttl");
    String content = Resources.toString(url, Charsets.UTF_8);

    RdfReader reader = RdfReaderFactory.createReaderFromText(content, "TTL");

    Model model = reader.read();
    assertThat(model.isIsomorphicWith(ReaderTestUtils.createOneTripleModel())).isTrue();

    }
 
Example 20
Source File: AnomalyDetectionIndices.java    From anomaly-detection with Apache License 2.0 2 votes vote down vote up
/**
 * Get anomaly detector index mapping json content.
 *
 * @return anomaly detector index mapping
 * @throws IOException IOException if mapping file can't be read correctly
 */
private String getAnomalyDetectorMappings() throws IOException {
    URL url = AnomalyDetectionIndices.class.getClassLoader().getResource(ANOMALY_DETECTORS_INDEX_MAPPING_FILE);
    return Resources.toString(url, Charsets.UTF_8);
}