com.google.common.io.Resources类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(12.9k)|赞(0)|评价(0)|浏览(224)

本文整理了Java中com.google.common.io.Resources类的一些代码示例,展示了Resources类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Resources类的具体详情如下:
包路径:com.google.common.io.Resources
类名称:Resources

Resources介绍

[英]Provides utility methods for working with resources in the classpath. Note that even though these methods use URL parameters, they are usually not appropriate for HTTP or other non-classpath resources.

All method parameters must be non-null unless documented otherwise.
[中]

代码示例

代码示例来源:origin: springside/springside4

/**
 * 读取规则见本类注释.
 */
public static InputStream asStream(String resourceName) throws IOException {
  return Resources.getResource(resourceName).openStream();
}

代码示例来源:origin: Graylog2/graylog2-server

@GET
@Produces(MediaType.TEXT_HTML)
@Path("index.html")
public String index(@Context HttpHeaders httpHeaders) throws IOException {
  final URL templateUrl = this.getClass().getResource("/swagger/index.html.template");
  final String template = Resources.toString(templateUrl, StandardCharsets.UTF_8);
  final Map<String, Object> model = ImmutableMap.of(
      "baseUri", RestTools.buildExternalUri(httpHeaders.getRequestHeaders(), httpConfiguration.getHttpExternalUri()).resolve(HttpConfiguration.PATH_API).toString());
  return templateEngine.transform(template, model);
}

代码示例来源:origin: prestodb/presto

public ExampleRecordSet(ExampleSplit split, List<ExampleColumnHandle> columnHandles)
{
  requireNonNull(split, "split is null");
  this.columnHandles = requireNonNull(columnHandles, "column handles is null");
  ImmutableList.Builder<Type> types = ImmutableList.builder();
  for (ExampleColumnHandle column : columnHandles) {
    types.add(column.getColumnType());
  }
  this.columnTypes = types.build();
  try {
    byteSource = Resources.asByteSource(split.getUri().toURL());
  }
  catch (MalformedURLException e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: prestodb/presto

protected PrestoCliLauncher()
    throws IOException
{
  nationTableInteractiveLines = readLines(getResource("com/facebook/presto/tests/cli/interactive_query.results"), UTF_8);
  nationTableBatchLines = readLines(getResource("com/facebook/presto/tests/cli/batch_query.results"), UTF_8);
}

代码示例来源:origin: springside/springside4

/**
 * 读取文件的每一行,读取规则见本类注释.
 */
public static String toString(String resourceName) throws IOException {
  return Resources.toString(Resources.getResource(resourceName), Charsets.UTF_8);
}

代码示例来源:origin: prestodb/presto

@BeforeTestWithContext
public void setup()
    throws Exception
{
  hdfsClient.createDirectory("/user/hive/warehouse/TestAvroSchemaUrl/schemas");
  try (InputStream inputStream = Resources.asByteSource(Resources.getResource("avro/original_schema.avsc")).openStream()) {
    hdfsClient.saveFile("/user/hive/warehouse/TestAvroSchemaUrl/schemas/original_schema.avsc", inputStream);
  }
}

代码示例来源:origin: ninjaframework/ninja

url = Resources.getResource(logbackConfigurationFile);
} catch (IllegalArgumentException ex) {
      url = new File(logbackConfigurationFile).toURI().toURL();
  try {
    url = new URL(logbackConfigurationFile);
  } catch (MalformedURLException ex) {

代码示例来源:origin: apache/nifi

URI uri;
try {
  uri = new URI(uriOrLiteral);
} catch (URISyntaxException e) {
if(uri.getScheme() == null) {
  throw new SchemaNotFoundException("If the schema is not a JSON string, a scheme must be specified in the URI "
      + "(ex: dataset:, view:, resource:, file:, hdfs:, etc).");
  if ("dataset".equals(uri.getScheme()) || "view".equals(uri.getScheme())) {
    return Datasets.load(uri).getDataset().getDescriptor().getSchema();
  } else if ("resource".equals(uri.getScheme())) {
    try (InputStream in = Resources.getResource(uri.getSchemeSpecificPart()).openStream()) {
      return parseSchema(uri, in);

代码示例来源:origin: killbill/killbill

@Test(groups = "fast")
public void testCatalogLoad() {
  try {
    XMLLoader.getObjectFromString(Resources.getResource("SpyCarBasic.xml").toExternalForm(), StandaloneCatalog.class);
    XMLLoader.getObjectFromString(Resources.getResource("SpyCarAdvanced.xml").toExternalForm(), StandaloneCatalog.class);
    XMLLoader.getObjectFromString(Resources.getResource("WeaponsHire.xml").toExternalForm(), StandaloneCatalog.class);
    XMLLoader.getObjectFromString(Resources.getResource("WeaponsHireSmall.xml").toExternalForm(), StandaloneCatalog.class);
    XMLLoader.getObjectFromString(Resources.getResource("catalogTest.xml").toExternalForm(), StandaloneCatalog.class);
    XMLLoader.getObjectFromString(Resources.getResource("UsageExperimental.xml").toExternalForm(), StandaloneCatalog.class);
  } catch (Exception e) {
    Assert.fail(e.toString());
  }
}

代码示例来源:origin: killbill/killbill

@Test(groups = "fast")
  public void test() throws Exception {
    final URI uri = new URI(Resources.getResource("WeaponsHireSmall.xml").toExternalForm());
    final StandaloneCatalog catalog = XMLLoader.getObjectFromUri(uri, StandaloneCatalog.class);
    Assert.assertNotNull(catalog);
    final DefaultPlanRules rules = catalog.getPlanRules();

    final PlanSpecifier specifier = new PlanSpecifier("Laser-Scope", BillingPeriod.MONTHLY,
                             "DEFAULT");

    final PlanAlignmentCreate alignment = rules.getPlanCreateAlignment(specifier, catalog);
    Assert.assertEquals(alignment, PlanAlignmentCreate.START_OF_SUBSCRIPTION);

    final PlanSpecifier specifier2 = new PlanSpecifier("Extra-Ammo", BillingPeriod.MONTHLY,
                              "DEFAULT");

    final PlanAlignmentCreate alignment2 = rules.getPlanCreateAlignment(specifier2, catalog);
    Assert.assertEquals(alignment2, PlanAlignmentCreate.START_OF_BUNDLE);
  }
}

代码示例来源:origin: killbill/killbill

@Test(groups = "fast")
  public void testLoadCatalogFromExternalFile() throws CatalogApiException, IOException, URISyntaxException {
    final File originFile = new File(Resources.getResource("SpyCarBasic.xml").toURI());
    final File destinationFile = new File(Files.createTempDir().toString() + "/SpyCarBasicRelocated.xml");
    destinationFile.deleteOnExit();
    Files.copy(originFile, destinationFile);
    final VersionedCatalog c = loader.loadDefaultCatalog(destinationFile.toURI().toString());
    Assert.assertEquals(c.getCatalogName(), "SpyCarBasic");
  }
}

代码示例来源:origin: killbill/killbill

@Test(groups = "fast")
public void testExistingTenantOverdue() throws OverdueApiException, URISyntaxException, IOException {
  final InternalCallContext differentMultiTenantContext = Mockito.mock(InternalCallContext.class);
  final Long otherMultiTenantRecordId = otherMultiTenantContext.getTenantRecordId();
  final InputStream tenantInputOverdueConfig = UriAccessor.accessUri(new URI(Resources.getResource("OverdueConfig2.xml").toExternalForm()));
  final String tenantOverdueConfigXML = CharStreams.toString(new InputStreamReader(tenantInputOverdueConfig, "UTF-8"));
  final InputStream otherTenantInputOverdueConfig = UriAccessor.accessUri(new URI(Resources.getResource("OverdueConfig.xml").toExternalForm()));
  final String otherTenantOverdueConfigXML = CharStreams.toString(new InputStreamReader(otherTenantInputOverdueConfig, "UTF-8"));
  Mockito.when(tenantInternalApi.getTenantOverdueConfig(Mockito.any(InternalTenantContext.class))).thenAnswer(new Answer<String>() {
  Assert.assertNotNull(differentResult);
  Assert.assertEquals(differentResult.getOverdueStatesAccount().getStates().length, 1);
  Assert.assertTrue(differentResult.getOverdueStatesAccount().getStates()[0].isClearState());
  overdueConfigCache.loadDefaultOverdueConfig(Resources.getResource("OverdueConfig.xml").toExternalForm());

代码示例来源:origin: PegaSysEng/pantheon

private static String jsonConfig(final String resourceName) {
 try {
  URI uri = Resources.getResource(resourceName).toURI();
  return Resources.toString(uri.toURL(), UTF_8);
 } catch (final URISyntaxException | IOException e) {
  throw new IllegalStateException(e);
 }
}

代码示例来源:origin: io.airlift.airship/airship-coordinator

@Test
  public void testJsonDecode()
      throws Exception
  {
    String json = Resources.toString(Resources.getResource("assignment.json"), Charsets.UTF_8);
    AssignmentRepresentation actual = codec.fromJson(json);

    assertEquals(actual, expected);
  }
}

代码示例来源:origin: prestodb/presto

private static void installElasticsearchPlugin(QueryRunner queryRunner, TestingElasticsearchConnectorFactory factory)
    throws Exception
{
  ElasticsearchPlugin plugin = new ElasticsearchPlugin();
  plugin.setConnectorFactory(factory);
  queryRunner.installPlugin(plugin);
  URL metadataUrl = getResource(ElasticsearchQueryRunner.class, "/queryrunner");
  assertNotNull(metadataUrl, "metadataUrl is null");
  URI metadataUri = metadataUrl.toURI();
  Map<String, String> config = new HashMap<>();
  config.put("elasticsearch.default-schema-name", TPCH_SCHEMA);
  config.put("elasticsearch.table-description-directory", metadataUri.toString());
  config.put("elasticsearch.scroll-size", "1000");
  config.put("elasticsearch.scroll-timeout", "1m");
  config.put("elasticsearch.max-hits", "1000000");
  config.put("elasticsearch.request-timeout", "2m");
  config.put("elasticsearch.max-request-retries", "3");
  config.put("elasticsearch.max-request-retry-time", "5s");
  queryRunner.createCatalog("elasticsearch", "elasticsearch", config);
}

代码示例来源:origin: killbill/killbill

@Test(groups = "fast")
public void testLoad() throws CatalogApiException {
  final DefaultVersionedCatalog c = loader.loadDefaultCatalog(Resources.getResource("versionedCatalog").toString());
  Assert.assertEquals(c.getVersions().size(), 4);
  DateTime dt = new DateTime("2011-01-01T00:00:00+00:00");
  Assert.assertEquals(c.getVersions().get(0).getEffectiveDate(), dt.toDate());
  dt = new DateTime("2011-02-02T00:00:00+00:00");
  Assert.assertEquals(c.getVersions().get(1).getEffectiveDate(), dt.toDate());
  dt = new DateTime("2011-02-03T00:00:00+00:00");
  Assert.assertEquals(c.getVersions().get(2).getEffectiveDate(), dt.toDate());
  dt = new DateTime("2011-03-03T00:00:00+00:00");
  Assert.assertEquals(c.getVersions().get(3).getEffectiveDate(), dt.toDate());
}

代码示例来源:origin: prestodb/presto

@Test
  public void testMetadata()
      throws Exception
  {
    URL metadataUrl = Resources.getResource(TestExampleClient.class, "/example-data/example-metadata.json");
    assertNotNull(metadataUrl, "metadataUrl is null");
    URI metadata = metadataUrl.toURI();
    ExampleClient client = new ExampleClient(new ExampleConfig().setMetadata(metadata), CATALOG_CODEC);
    assertEquals(client.getSchemaNames(), ImmutableSet.of("example", "tpch"));
    assertEquals(client.getTableNames("example"), ImmutableSet.of("numbers"));
    assertEquals(client.getTableNames("tpch"), ImmutableSet.of("orders", "lineitem"));

    ExampleTable table = client.getTable("example", "numbers");
    assertNotNull(table, "table is null");
    assertEquals(table.getName(), "numbers");
    assertEquals(table.getColumns(), ImmutableList.of(new ExampleColumn("text", createUnboundedVarcharType()), new ExampleColumn("value", BIGINT)));
    assertEquals(table.getSources(), ImmutableList.of(metadata.resolve("numbers-1.csv"), metadata.resolve("numbers-2.csv")));
  }
}

代码示例来源:origin: com.nesscomputing.migratory/migratory-core

@Override
public Collection<URI> loadFolder(final URI folderUri, final String pattern)
{
  try {
    final URI uriLocation = Resources.getResource(this.getClass(), folderUri.getPath()).toURI();
    return loaderManager.loadFolder(uriLocation, pattern);
  }
  catch (URISyntaxException e) {
    throw new MigratoryException(Reason.INTERNAL, e);
  }
}

代码示例来源:origin: prestodb/presto

private static Map<String, Map<String, ExampleTable>> lookupSchemas(URI metadataUri, JsonCodec<Map<String, List<ExampleTable>>> catalogCodec)
    throws IOException
{
  URL result = metadataUri.toURL();
  String json = Resources.toString(result, UTF_8);
  Map<String, List<ExampleTable>> catalog = catalogCodec.fromJson(json);
  return ImmutableMap.copyOf(transformValues(catalog, resolveAndIndexTables(metadataUri)));
}

代码示例来源:origin: google/guava

public void testGetResource_contextClassLoader() throws IOException {
 // Check that we can find a resource if it is visible to the context class
 // loader, even if it is not visible to the loader of the Resources class.
 File tempFile = createTempFile();
 PrintWriter writer = new PrintWriter(tempFile, "UTF-8");
 writer.println("rud a chur ar an méar fhada");
 writer.close();
 // First check that we can't find it without setting the context loader.
 // This is a sanity check that the test doesn't spuriously pass because
 // the resource is visible to the system class loader.
 try {
  Resources.getResource(tempFile.getName());
  fail("Should get IllegalArgumentException");
 } catch (IllegalArgumentException expected) {
 }
 // Now set the context loader to one that should find the resource.
 URL baseUrl = tempFile.getParentFile().toURI().toURL();
 URLClassLoader loader = new URLClassLoader(new URL[] {baseUrl});
 ClassLoader oldContextLoader = Thread.currentThread().getContextClassLoader();
 try {
  Thread.currentThread().setContextClassLoader(loader);
  URL url = Resources.getResource(tempFile.getName());
  String text = Resources.toString(url, Charsets.UTF_8);
  assertEquals("rud a chur ar an méar fhada\n", text);
 } finally {
  Thread.currentThread().setContextClassLoader(oldContextLoader);
 }
}

相关文章