com.google.common.io.Resources Java Examples

The following examples show how to use com.google.common.io.Resources. 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: YamlToJson.java    From swagger-codegen-tooling with Apache License 2.0 6 votes vote down vote up
protected String getYamlFileContentAsJson() throws IOException {
    String data = "";
    if (yamlInputPath.startsWith("http") || yamlInputPath.startsWith("https")) {

        data = new String(Resources.toByteArray(new URL(yamlInputPath)));
    } else {
        data = new String(Files.readAllBytes(java.nio.file.Paths.get(new File(yamlInputPath).toURI())));
    }

    ObjectMapper yamlMapper = Yaml.mapper();
    JsonNode rootNode = yamlMapper.readTree(data);

    // must have swagger node set
    JsonNode swaggerNode = rootNode.get("swagger");

    return rootNode.toString();
}
 
Example #2
Source File: DownloadUtils.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Get ivy settings file from classpath
 */
public static File getIvySettingsFile() throws IOException {
  URL settingsUrl = Thread.currentThread().getContextClassLoader().getResource(IVY_SETTINGS_FILE_NAME);
  if (settingsUrl == null) {
    throw new IOException("Failed to find " + IVY_SETTINGS_FILE_NAME + " from class path");
  }

  // Check if settingsUrl is file on classpath
  File ivySettingsFile = new File(settingsUrl.getFile());
  if (ivySettingsFile.exists()) {
    // can access settingsUrl as a file
    return ivySettingsFile;
  }

  // Create temporary Ivy settings file.
  ivySettingsFile = File.createTempFile("ivy.settings", ".xml");
  ivySettingsFile.deleteOnExit();

  try (OutputStream os = new BufferedOutputStream(new FileOutputStream(ivySettingsFile))) {
    Resources.copy(settingsUrl, os);
  }

  return ivySettingsFile;
}
 
Example #3
Source File: GeccoEngine.java    From gecco with MIT License 6 votes vote down vote up
private GeccoEngine startsJson() {
	try {
		URL url = Resources.getResource("starts.json");
		File file = new File(url.getPath());
		if (file.exists()) {
			String json = Files.toString(file, Charset.forName("UTF-8"));
			List<StartRequestList> list = JSON.parseArray(json, StartRequestList.class);
			for (StartRequestList start : list) {
				start(start.toRequest());
			}
		}
	} catch (IllegalArgumentException ex) {
		log.info("starts.json not found");
	} catch (IOException ioex) {
		log.error(ioex);
	}
	return this;
}
 
Example #4
Source File: IfTagTest.java    From jinjava with Apache License 2.0 6 votes vote down vote up
private TagNode fixture(String name) {
  try {
    return (TagNode) new TreeParser(
      interpreter,
      Resources.toString(
        Resources.getResource(String.format("tags/iftag/%s.jinja", name)),
        StandardCharsets.UTF_8
      )
    )
      .buildTree()
      .getChildren()
      .getFirst();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #5
Source File: ParallelNavigationTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 * This checks that we can run a pipeline with 2 long running parallel branches.
 * You should be able to click between one and the other and see it progressing.
 */
@Test
@Retry(3)
public void parallelNavigationTest() throws IOException, GitAPIException, InterruptedException {
    // Create navTest
    logger.info("Creating pipeline " + navTest);
    URL navTestJenkinsfile = Resources.getResource(ParallelNavigationTest.class, "ParallelNavigationTest/Jenkinsfile");
    Files.copy(new File(navTestJenkinsfile.getFile()), new File(git.gitDirectory, "Jenkinsfile"));
    git.addAll();
    git.commit("Initial commit for " + navTest);
    logger.info("Committed Jenkinsfile for " + navTest);
    navTestPipeline = mbpFactory.pipeline(navTest).createPipeline(git);
    logger.info("Finished creating " + navTest);

    logger.info("Beginning parallelNavigationTest()");
    navTestPipeline.getRunDetailsPipelinePage().open(1);
    // At first we see branch one
    wait.until(By.xpath("//*[text()=\"firstBranch\"]"));
    logger.info("Found first branch");
    wait.until(By.xpath("//*[text()=\"first branch visible\"]"));
    // and clicking on the unselected node will yield us the second branch
    wait.click(By.xpath("//*[contains(@class, 'pipeline-node')][3]"));
    wait.until(By.xpath("//*[text()=\"secondBranch\"]"));
    wait.until(By.xpath("//*[text()=\"second branch visible\"]"));
    logger.info("Found second branch");
}
 
Example #6
Source File: DigiMorph.java    From tint with GNU General Public License v3.0 6 votes vote down vote up
public DigiMorph(String model_path) {
    if (model_path == null) {
        try {
            File file = File.createTempFile("mapdb", "mapdb");
            file.deleteOnExit();
            byte[] bytes = Resources.toByteArray(Resources.getResource("italian.db"));
            Files.write(file.toPath(), bytes);
            model_path = file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    this.model_path = model_path;
    volume = MappedFileVol.FACTORY.makeVolume(model_path, true);
    this.map = SortedTableMap.open(volume, Serializer.STRING, Serializer.STRING);

}
 
Example #7
Source File: InverseDigiMorph.java    From tint with GNU General Public License v3.0 6 votes vote down vote up
public InverseDigiMorph(String model_path) {
    if (model_path == null) {
        try {
            File file = File.createTempFile("mapdb", "mapdb");
            file.deleteOnExit();
            byte[] bytes = Resources.toByteArray(Resources.getResource("inverse-italian.db"));
            Files.write(file.toPath(), bytes);
            model_path = file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    this.model_path = model_path;
    volume = MappedFileVol.FACTORY.makeVolume(model_path, true);
    this.map = SortedTableMap.open(volume, Serializer.STRING, Serializer.STRING);

}
 
Example #8
Source File: ECDSA256VerifierTest.java    From curiostack with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  SignerConfig config =
      ImmutableSignerConfig.builder()
          .privateKeyBase64(
              Base64.getEncoder()
                  .encodeToString(
                      Resources.toByteArray(Resources.getResource("test-signer-private.pem"))))
          .publicKeyBase64(
              Base64.getEncoder()
                  .encodeToString(
                      Resources.toByteArray(Resources.getResource("test-signer-public.pem"))))
          .build();
  signer = new ECDSA256Signer(config);
  verifier = new ECDSA256Verifier(config);
}
 
Example #9
Source File: AndroidStringsXmlReaderTest.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Test
public void fromFilePluralSeparatorTest() throws IOException, SAXException, ParserConfigurationException {
    List<AndroidStringsTextUnit> androidStringsTextUnitList = AndroidStringsXmlReader.fromFile(Resources.getResource("com/box/l10n/mojito/android/strings/copytune_pinboard_plural_separator.xml").getPath(), "_");

    int index = 0;
    assertEquals("pinterest", androidStringsTextUnitList.get(index).getName());
    assertEquals("Pinterest", androidStringsTextUnitList.get(index).getContent());

    index++;
    assertEquals("pins_one", androidStringsTextUnitList.get(index).getName());
    assertEquals("1 Pin", androidStringsTextUnitList.get(index).getContent());
    assertEquals("one", androidStringsTextUnitList.get(index).getPluralForm());
    assertEquals("pins_other", androidStringsTextUnitList.get(index).getPluralFormOther());

    index++;
    assertEquals("pins_other", androidStringsTextUnitList.get(index).getName());
    assertEquals("{num_pins} Pins", androidStringsTextUnitList.get(index).getContent());
    assertEquals("other", androidStringsTextUnitList.get(index).getPluralForm());
    assertEquals("pins_other", androidStringsTextUnitList.get(index).getPluralFormOther());
}
 
Example #10
Source File: TestParquetScan.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessFile() throws Exception {
  Path p = new Path("/tmp/nation_test_parquet_scan");
  if (fs.exists(p)) {
    fs.delete(p, true);
  }

  fs.mkdirs(p);

  byte[] bytes = Resources.toByteArray(Resources.getResource("tpch/nation.parquet"));

  FSDataOutputStream os = fs.create(new Path(p, "nation.parquet"));
  os.write(bytes);
  os.close();
  fs.create(new Path(p, "_SUCCESS")).close();
  fs.create(new Path(p, "_logs")).close();

  testBuilder()
      .sqlQuery("select count(*) c from dfs.tmp.nation_test_parquet_scan where 1 = 1")
      .unOrdered()
      .baselineColumns("c")
      .baselineValues(25L)
      .build()
      .run();
}
 
Example #11
Source File: MongoAdapterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static void populate(MongoCollection<Document> collection, URL resource)
    throws IOException {
  Objects.requireNonNull(collection, "collection");

  if (collection.countDocuments() > 0) {
    // delete any existing documents (run from a clean set)
    collection.deleteMany(new BsonDocument());
  }

  MongoCollection<BsonDocument> bsonCollection = collection.withDocumentClass(BsonDocument.class);
  Resources.readLines(resource, StandardCharsets.UTF_8, new LineProcessor<Void>() {
    @Override public boolean processLine(String line) throws IOException {
      bsonCollection.insertOne(BsonDocument.parse(line));
      return true;
    }

    @Override public Void getResult() {
      return null;
    }
  });
}
 
Example #12
Source File: RepublisherMainTest.java    From gcp-ingestion with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testPerChannel() throws Exception {
  String outputPath = outputFolder.getRoot().getAbsolutePath();
  String inputPath = Resources.getResource("testdata/republisher-integration").getPath();
  String input = inputPath + "/per-channel-*.ndjson";
  String output = outputPath + "/out-${channel}";

  Republisher.main(new String[] { "--inputFileFormat=json", "--inputType=file",
      "--input=" + input, "--outputFileFormat=json", "--outputType=file",
      "--perChannelDestination=" + output, "--outputFileCompression=UNCOMPRESSED",
      "--perChannelSampleRatios={\"beta\":1.0,\"release\":0.5}", "--redisUri=" + redis.uri,
      "--errorOutputType=stderr" });

  List<String> inputLinesBeta = Lines.files(inputPath + "/per-channel-beta.ndjson");
  List<String> outputLinesBeta = Lines.files(outputPath + "/out-beta*.ndjson");
  assertThat(outputLinesBeta, matchesInAnyOrder(inputLinesBeta));

  List<String> outputLinesNightly = Lines.files(outputPath + "/out-nightly*.ndjson");
  assertThat(outputLinesNightly, Matchers.hasSize(0));

  List<String> outputLinesRelease = Lines.files(outputPath + "/out-release*.ndjson");
  assertThat("50% random sample of 20 elements should produce at least 2",
      outputLinesRelease.size(), Matchers.greaterThanOrEqualTo(2));
  assertThat("50% random sample of 20 elements should produce at most 18",
      outputLinesRelease.size(), Matchers.lessThanOrEqualTo(18));
}
 
Example #13
Source File: SinkMainTest.java    From gcp-ingestion with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testAttributePlaceholders() {
  String inputPath = Resources.getResource("testdata/attribute-placeholders").getPath();
  String input = inputPath + "/*.ndjson";
  String output = outputPath + "/${host:-no_host}/${geo_city:-no_city}/out";

  Sink.main(new String[] { "--inputFileFormat=json", "--inputType=file", "--input=" + input,
      "--outputFileFormat=json", "--outputType=file", "--output=" + output,
      "--outputFileCompression=UNCOMPRESSED", "--errorOutputType=stderr" });

  assertThat(Lines.files(outputPath + "/**/out*.ndjson"),
      matchesInAnyOrder(Lines.files(inputPath + "/*.ndjson")));

  assertThat(Lines.files(outputPath + "/hostA/cityA/out*.ndjson"),
      matchesInAnyOrder(Lines.files(inputPath + "/hostA-cityA.ndjson")));

  assertThat(Lines.files(outputPath + "/hostA/cityB/out*.ndjson"),
      matchesInAnyOrder(Lines.files(inputPath + "/hostA-cityB.ndjson")));

  assertThat(Lines.files(outputPath + "/no_host/cityA/out*.ndjson"),
      matchesInAnyOrder(Lines.files(inputPath + "/null-cityA.ndjson")));

  assertThat(Lines.files(outputPath + "/no_host/cityB/out*.ndjson"),
      matchesInAnyOrder(Collections.emptyList()));
}
 
Example #14
Source File: AbstractEthGraphQLHttpServiceTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setupConstants() throws Exception {
  PROTOCOL_SCHEDULE = MainnetProtocolSchedule.create();

  final URL blocksUrl = BlockTestUtil.getTestBlockchainUrl();

  final URL genesisJsonUrl = BlockTestUtil.getTestGenesisUrl();

  BLOCKS = new ArrayList<>();
  try (final RawBlockIterator iterator =
      new RawBlockIterator(
          Paths.get(blocksUrl.toURI()),
          rlp -> BlockHeader.readFrom(rlp, new MainnetBlockHeaderFunctions()))) {
    while (iterator.hasNext()) {
      BLOCKS.add(iterator.next());
    }
  }

  final String genesisJson = Resources.toString(genesisJsonUrl, Charsets.UTF_8);

  GENESIS_BLOCK = BLOCKS.get(0);
  GENESIS_CONFIG = GenesisState.fromJson(genesisJson, PROTOCOL_SCHEDULE);
}
 
Example #15
Source File: TestProtobufDataGenerator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void writeWithOneOfAndMap() throws Exception {
  ByteArrayOutputStream bOut = new ByteArrayOutputStream();
  byte[] expected = FileUtils.readFileToByteArray(new File(Resources.getResource("TestProtobuf3.ser").getPath()));
  DataGenerator dataGenerator = getDataGenerator(bOut, "TestRecordProtobuf3.desc", "TestRecord", true);

  Record record = getContext().createRecord("");
  Map<String, Field> rootField = new HashMap<>();
  rootField.put("first_name", Field.create("Adam"));
  rootField.put("full_name", Field.create(Field.Type.STRING, null));
  rootField.put("samples", Field.create(ImmutableList.of(Field.create(1), Field.create(2))));
  Map<String, Field> entries = ImmutableMap.of(
      "hello", Field.create("world"),
      "bye", Field.create("earth")
  );
  rootField.put("test_map", Field.create(entries));
  record.set(Field.create(rootField));

  dataGenerator.write(record);
  dataGenerator.flush();
  dataGenerator.close();

  assertArrayEquals(expected, bOut.toByteArray());
}
 
Example #16
Source File: SubmarineUI.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public void createLogHeadUI() {
  try {
    HashMap<String, Object> mapParams = new HashMap();
    URL urlTemplate = Resources.getResource(SUBMARINE_LOG_HEAD_JINJA);
    String template = Resources.toString(urlTemplate, Charsets.UTF_8);
    Jinjava jinjava = new Jinjava();
    String submarineUsage = jinjava.render(template, mapParams);

    InterpreterResultMessageOutput outputUI = intpContext.out.getOutputAt(1);
    outputUI.clear();
    outputUI.write(submarineUsage);
    outputUI.flush();
  } catch (IOException e) {
    LOGGER.error("Can't print usage", e);
  }
}
 
Example #17
Source File: ClassAnalyzer.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static List<AnalyzedMethodKey> getNonAbstractMethods(String className,
        @Nullable ClassLoader loader) throws ClassNotFoundException, IOException {
    String path = ClassNames.toInternalName(className) + ".class";
    URL url;
    if (loader == null) {
        // null loader means the bootstrap class loader
        url = ClassLoader.getSystemResource(path);
    } else {
        url = loader.getResource(path);
    }
    if (url == null) {
        // what follows is just a best attempt in the sort-of-rare case when a custom class
        // loader does not expose .class file contents via getResource(), e.g.
        // org.codehaus.groovy.runtime.callsite.CallSiteClassLoader
        return getNonAbstractMethodsPlanB(className, loader);
    }
    byte[] bytes = Resources.toByteArray(url);
    NonAbstractMethodClassVisitor accv = new NonAbstractMethodClassVisitor();
    new ClassReader(bytes).accept(accv, ClassReader.SKIP_FRAMES + ClassReader.SKIP_CODE);
    return accv.analyzedMethodKeys;
}
 
Example #18
Source File: PmdTestUtils.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
public static String getResourceContent(String path) {
  try {
    return Resources.toString(Resources.getResource(PmdTestUtils.class, path), Charsets.UTF_8);
  } catch (IOException e) {
    throw new IllegalArgumentException("Could not load resource " + path, e);
  }
}
 
Example #19
Source File: CoincheckContextTest.java    From cryptotrader with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testFetchOrders() throws Exception {

    String data = Resources.toString(getResource("json/coincheck_order.json"), UTF_8);
    doReturn(data).when(target).executePrivate(GET, "https://coincheck.com/api/exchange/orders/opens", null, null);

    // Found
    List<CoincheckOrder> orders = target.fetchOrders(Key.builder().build());
    assertEquals(orders.size(), 2, orders.toString());
    assertEquals(orders.get(0).getId(), "202835");
    assertEquals(orders.get(0).getProduct(), "btc_jpy");
    assertEquals(orders.get(0).getActive(), TRUE);
    assertEquals(orders.get(0).getOrderPrice(), new BigDecimal("26890"));
    assertEquals(orders.get(0).getOrderQuantity(), new BigDecimal("0.5527"));
    assertEquals(orders.get(0).getFilledQuantity(), null);
    assertEquals(orders.get(0).getRemainingQuantity(), new BigDecimal("0.5527"));
    assertEquals(orders.get(0).getSide(), "buy");
    assertEquals(orders.get(1).getId(), "202836");
    assertEquals(orders.get(1).getProduct(), "btc_jpy");
    assertEquals(orders.get(1).getActive(), TRUE);
    assertEquals(orders.get(1).getOrderPrice(), new BigDecimal("26990"));
    assertEquals(orders.get(1).getOrderQuantity(), new BigDecimal("-0.77"));
    assertEquals(orders.get(1).getFilledQuantity(), null);
    assertEquals(orders.get(1).getRemainingQuantity(), new BigDecimal("-0.77"));
    assertEquals(orders.get(1).getSide(), "sell");

    // Cached
    doReturn(null).when(target).executePrivate(any(), any(), any(), any());
    List<CoincheckOrder> cached = target.fetchOrders(Key.builder().build());
    assertEquals(cached, orders);

}
 
Example #20
Source File: UrlTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void readDirectoryContents() throws IOException {
  Files.createDirectory(path);
  Files.createFile(path.resolve("a.txt"));
  Files.createFile(path.resolve("b.txt"));
  Files.createDirectory(path.resolve("c"));

  URL url = path.toUri().toURL();
  assertThat(Resources.asCharSource(url, UTF_8).read()).isEqualTo("a.txt\nb.txt\nc\n");
}
 
Example #21
Source File: PythonTestDescription.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableList<? extends Step> getBuildSteps(
    BuildContext context, BuildableContext buildableContext) {
  buildableContext.recordArtifact(output);
  return ImmutableList.of(
      MkdirStep.of(
          BuildCellRelativePath.fromCellRelativePath(
              context.getBuildCellRootPath(), getProjectFilesystem(), output.getParent())),
      new WriteFileStep(
          getProjectFilesystem(),
          Resources.asByteSource(
              Resources.getResource(PythonTestDescription.class, DEFAULT_TEST_MAIN_NAME)),
          output,
          /* executable */ false));
}
 
Example #22
Source File: SnippetSet.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an input supplier which works on the given resource root path. All input names are
 * resolved as resource paths relative to this root, and read from the class path.
 */
public static InputSupplier resourceInputSupplier(final String root) {
  return new InputSupplier() {
    @Override public Iterable<String> readInput(String snippetSetName) throws IOException {
      try {
        return Resources.readLines(
            Resources.getResource(root.isEmpty() ? snippetSetName :  root + "/" + snippetSetName),
            UTF_8);
      } catch (Exception e) {
        throw new IOException(e);
      }
    }
  };
}
 
Example #23
Source File: WorkflowLegacyMigrationTest.java    From conductor with Apache License 2.0 5 votes vote down vote up
private Workflow loadWorkflowSnapshot(String resourcePath) throws Exception {

        String content = Resources.toString(WorkflowLegacyMigrationTest.class.getResource(resourcePath), StandardCharsets.UTF_8);
        String workflowId = IDGenerator.generate();
        content = content.replace(WORKFLOW_INSTANCE_ID_PLACEHOLDER, workflowId);

        Workflow workflow = objectMapper.readValue(content, Workflow.class);
        workflow.setWorkflowId(workflowId);

        return workflow;
    }
 
Example #24
Source File: ResourceUtil.java    From feast with Apache License 2.0 5 votes vote down vote up
public static String getDeadletterTableSchemaJson() {
  String schemaJson = null;
  try {
    schemaJson =
        Resources.toString(
            Resources.getResource(DEADLETTER_SCHEMA_FILE_PATH), StandardCharsets.UTF_8);
  } catch (Exception e) {
    log.error(
        "Unable to read {} file from the resources folder!", DEADLETTER_SCHEMA_FILE_PATH, e);
  }
  return schemaJson;
}
 
Example #25
Source File: ExtractorsTest.java    From web-data-extractor with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    try {
        baseHtml = Resources.toString(Resources.getResource("demo1.html"), Charsets.UTF_8);
        base4Html = Resources.toString(Resources.getResource("demo4.xml"), Charsets.UTF_8);
        listHtml = Resources.toString(Resources.getResource("list.html"), Charsets.UTF_8);
        listHtml2 = Resources.toString(Resources.getResource("list2.html"), Charsets.UTF_8);
        jsonString = Resources.toString(Resources.getResource("example.json"), Charsets.UTF_8);
        base5Xml = Resources.toString(Resources.getResource("demo5.xml"), Charsets.UTF_8);

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #26
Source File: TokenWhitespaceTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
private List<Token> scanTokens(String srcPath, JinjavaConfig config) {
  try {
    return Lists.newArrayList(
      new TokenScanner(
        Resources.toString(Resources.getResource(srcPath), StandardCharsets.UTF_8),
        config
      )
    );
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #27
Source File: SelectorExtractorTest.java    From web-data-extractor with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    try {
        html = Resources.toString(Resources.getResource("list.html"), Charsets.UTF_8);
        html2 = Resources.toString(Resources.getResource("list2.html"), Charsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #28
Source File: PafServerStub.java    From vics with MIT License 5 votes vote down vote up
public void willReturnStreetsByWard(String wardCode) throws IOException {
    String file = requireNonNull(files.get(wardCode), "No json file for ward=" + wardCode);
    String jsonResponse = Resources.toString(getResource(file), UTF_8);

    String urlPath = String.format("/v1/wards/%s/streets", wardCode);
    wireMock.register(get(urlPathMatching(urlPath))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader(CONTENT_TYPE, "application/json")
                    .withBody(jsonResponse)));
}
 
Example #29
Source File: HttpProcessorIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private static String getBody(String path) {
  try {
    return Resources.toString(Resources.getResource(path), Charsets.UTF_8);
  } catch (IOException e) {
    throw new RuntimeException("Failed to read test resource: " + path);
  }
}
 
Example #30
Source File: Agent.java    From james with Apache License 2.0 5 votes vote down vote up
private static void printBanner(AgentConfiguration agentConfiguration) {
    if (!agentConfiguration.isQuiet()) {
        URL bannerURL = Resources.getResource(Agent.class, "banner.txt");
        try {
            Resources.readLines(bannerURL, StandardCharsets.UTF_8).forEach(System.err::println);
        } catch (IOException e) {
            LOG.warn("Error reading banner resource, looks like something is wrong with the agent jar", e);
        }
    }
}