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

The following examples show how to use com.google.common.io.Resources#getResource() . 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: UIConfigurationManagementClient.java    From skywalking with Apache License 2.0 6 votes vote down vote up
public List<DashboardConfiguration> getAllTemplates(Boolean includingDisabled) throws IOException {
    final URL queryFileUrl = Resources.getResource("ui-getTemplates.gql");
    final String queryString =
        Resources.readLines(queryFileUrl, StandardCharsets.UTF_8)
                 .stream()
                 .filter(it -> !it.startsWith("#"))
                 .collect(Collectors.joining())
                 .replace("{includingDisabled}", String.valueOf(includingDisabled));

    final ResponseEntity<GQLResponse<DashboardConfigurationListWrapper>> responseEntity = restTemplate.exchange(
        new RequestEntity<>(queryString, HttpMethod.POST, URI.create(endpointUrl)),
        new ParameterizedTypeReference<GQLResponse<DashboardConfigurationListWrapper>>() {
        }
    );

    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        throw new RuntimeException("Response status != 200, actual: " + responseEntity.getStatusCode());
    }

    return Objects.requireNonNull(responseEntity.getBody()).getData().getConfigurations();
}
 
Example 2
Source File: RepackZipEntriesStepTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Before
public void buildSampleZipFile() throws IOException {
  parent = tmp.newFolder("foo");
  filesystem = TestProjectFilesystems.createProjectFilesystem(parent);
  zipFile = parent.resolve("example.zip");

  // Turns out that the zip filesystem generates slightly different output from the output stream.
  // Since we've modeled our outputstreams after the zip output stream, be compatible with that.
  try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zipFile))) {
    ZipEntry entry = new ZipEntry("file");
    stream.putNextEntry(entry);
    String packageName = getClass().getPackage().getName().replace('.', '/');
    URL sample = Resources.getResource(packageName + "/sample-bytes.dat");
    stream.write(Resources.toByteArray(sample));
  }
}
 
Example 3
Source File: VersionIterator.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public VersionInfo(){
  try {
    version = DremioVersionInfo.getVersion(); // get dremio version (x.y.z)
    URL u = Resources.getResource("git.properties");
    if(u != null){
      Properties p = new Properties();
      p.load(Resources.asByteSource(u).openStream());
      commit_id = p.getProperty("git.commit.id");
      build_email = p.getProperty("git.build.user.email");
      commit_time = p.getProperty("git.commit.time");
      build_time = p.getProperty("git.build.time");
      commit_message = p.getProperty("git.commit.message.short");

    }
  } catch (IOException | IllegalArgumentException e) {
    logger.warn("Failure while trying to load \"git.properties\" file.", e);
  }
}
 
Example 4
Source File: HiveTestDataGenerator.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private void createNestedListWithNullsHiveTables(final Driver hiveDriver) throws Exception {
  final File nestedListWithNullsParquetDir = new File(BaseTestQuery.getTempDir("nestedlistwithnullsparquet"));
  nestedListWithNullsParquetDir.mkdirs();
  final URL nestedListWithNullsParquetUrl = Resources.getResource("list_list_null_test.parquet");
  if (nestedListWithNullsParquetUrl == null) {
    throw new IOException(String.format("Unable to find path %s.", "list_list_null_test.parquet"));
  }

  // parquet file has following columns with one valid row
  // col1 array<array<array<string> with value [[['a', null], null], null]
  final File nestedListWithNullsParquetFile = new File(nestedListWithNullsParquetDir, "list_list_null_test.parquet");
  nestedListWithNullsParquetFile.deleteOnExit();
  nestedListWithNullsParquetDir.deleteOnExit();
  Files.write(Paths.get(nestedListWithNullsParquetFile.toURI()), Resources.toByteArray(nestedListWithNullsParquetUrl));

  final String nestedListTest = "create external table array_nested_with_nulls_test_ext1(" +
    "col1 array<array<array<string>>>)" +
    "stored as parquet location '" + nestedListWithNullsParquetFile.getParent() + "'";
  executeQuery(hiveDriver, nestedListTest);
}
 
Example 5
Source File: IntegrationDedicatedTaskDriverClusterSuite.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
protected Collection<Config> getTaskDriverConfigs() {
  // task driver config initialization
  URL url = Resources.getResource("BasicTaskDriver.conf");
  Config taskDriverConfig = ConfigFactory.parseURL(url);
  taskDriverConfig = taskDriverConfig.withFallback(getClusterConfig());
  Config taskDriver1 = addInstanceName(taskDriverConfig, "TaskDriver1");
  return ImmutableList.of(taskDriver1);
}
 
Example 6
Source File: ApiService_ExportAsJsonTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private void shouldConvertAsJsonWithoutPages(ApiSerializer.Version version, String filename) throws IOException {
    String jsonForExport = apiService.exportAsJson(API_ID, version.getVersion(), SystemRole.PRIMARY_OWNER.name(), "pages");

    URL url =  Resources.getResource("io/gravitee/rest/api/management/service/export-convertAsJsonForExportWithoutPages" + (filename != null ? "-"+ filename : "") +".json");
    String expectedJson = Resources.toString(url, Charsets.UTF_8);

    assertThat(jsonForExport).isNotNull();
    assertThat(objectMapper.readTree(expectedJson)).isEqualTo(objectMapper.readTree(jsonForExport));
}
 
Example 7
Source File: StreamServiceTest.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetStreams_2_0_17()
    throws OpenDataException, IOException, ReaperException, ClassNotFoundException, InterruptedException {

  // fake the response a 2.0.17 would return when asked for streams
  CompositeData streamSession = makeCompositeData_2_0_17();

  // compare the test payload with an actual payload grabbed from a 2.0.17 ccm node
  URL url = Resources.getResource("repair-samples/stream-report-2-0-17.txt");
  String ref = Resources.toString(url, Charsets.UTF_8);
  assertEquals(ref.replaceAll("\\s", ""), streamSession.toString().replaceAll("\\s", ""));

  // init the stream manager
  JmxProxy proxy = (JmxProxy) mock(Class.forName("io.cassandrareaper.jmx.JmxProxyImpl"));
  StreamManagerMBean streamingManagerMBean = Mockito.mock(StreamManagerMBean.class);
  JmxProxyTest.mockGetStreamManagerMBean(proxy, streamingManagerMBean);
  when(streamingManagerMBean.getCurrentStreams()).thenReturn(ImmutableSet.of(streamSession));

  AppContext cxt = new AppContext();
  cxt.config = TestRepairConfiguration.defaultConfig();
  cxt.jmxConnectionFactory = mock(JmxConnectionFactory.class);
  when(cxt.jmxConnectionFactory.connectAny(Mockito.anyList())).thenReturn(proxy);
  ClusterFacade clusterFacadeSpy = Mockito.spy(ClusterFacade.create(cxt));
  Mockito.doReturn("dc1").when(clusterFacadeSpy).getDatacenter(any());

  // do the actual pullStreams() call, which should succeed
  List<StreamSession> result = StreamService
      .create(() -> clusterFacadeSpy)
      .listStreams(Node.builder().withHostname("127.0.0.1").build());

  verify(streamingManagerMBean, times(1)).getCurrentStreams();
  assertEquals(1, result.size());
}
 
Example 8
Source File: TestSolrAuthzBinding.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
/**
 * Test that a user that doesn't exist throws an exception
 * when trying to authorize
 */
@Test
public void testNoUser() throws Exception {
   SolrAuthzConf solrAuthzConf =
     new SolrAuthzConf(Resources.getResource("sentry-site.xml"));
   setUsableAuthzConf(solrAuthzConf);
   SolrAuthzBinding binding = new SolrAuthzBinding(solrAuthzConf);
  try {
    binding.authorizeCollection(new Subject("bogus"), infoCollection, querySet);
    Assert.fail("Expected SentryGroupNotFoundException");
  } catch (SentryGroupNotFoundException e) {
  }
}
 
Example 9
Source File: TestSolrAuthzBinding.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomGroupMapping() throws Exception {
  SolrAuthzConf solrAuthzConf =
    new SolrAuthzConf(Resources.getResource("sentry-site.xml"));
  setUsableAuthzConf(solrAuthzConf);
  solrAuthzConf.set(AuthzConfVars.AUTHZ_PROVIDER.getVar(), "org.apache.sentry.provider.common.HadoopGroupResourceAuthorizationProvider");
  solrAuthzConf.set("hadoop.security.group.mapping",
    FoobarGroupMappingServiceProvider.class.getName());
  SolrAuthzBinding binding = new SolrAuthzBinding(solrAuthzConf);
  final String user = "userTestSolrAuthzBinding";
  assertEquals(1, binding.getGroups(user).size());
  assertTrue(binding.getGroups(user).contains("foobar"));
}
 
Example 10
Source File: JsonUnflattenerTest.java    From json-flattener with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithKeepArrays() throws IOException {
  URL url = Resources.getResource("test4.json");
  String json = Resources.toString(url, Charsets.UTF_8);

  assertEquals(json, JsonUnflattener.unflatten(new JsonFlattener(json)
      .withFlattenMode(FlattenMode.KEEP_ARRAYS).flatten()));
}
 
Example 11
Source File: IntegrationBasicSuite.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public Config getManagerConfig() {
  // manager config initialization
  URL url = Resources.getResource("BasicManager.conf");
  Config managerConfig = ConfigFactory.parseURL(url);
  managerConfig = managerConfig.withFallback(getClusterConfig());
  return managerConfig.resolve();
}
 
Example 12
Source File: HiveTestDataGenerator.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private void createComplexVarcharHiveTables(final Driver hiveDriver) throws Exception {
  final File complexVarcharParquetDir = new File(BaseTestQuery.getTempDir("complexvarcharparquet"));
  complexVarcharParquetDir.mkdirs();
  final URL complexVarcharParquetUrl = Resources.getResource("varchar_complex.parquet");
  if (complexVarcharParquetUrl == null) {
    throw new IOException(String.format("Unable to find path %s.", "varchar_complex.parquet"));
  }

  // parquet file has following columns with one valid row, all varchars have 'abcdefghijklmno' as value
  // col1 varchar(15)
  // col2 struct<f1:varchar(15)>
  // col3 struct<f1:struct<subf1:varchar(15)>>
  // col4 struct<f1:array<varchar(15)>>
  // col5 array<struct<f1:varchar(15)>>
  // col6 array<varchar(15)>
  // col7 array<array<array<array<varchar(15)>>>>
  final File complexVarcharParquetFile = new File(complexVarcharParquetDir, "varchar_complex.parquet");
  complexVarcharParquetFile.deleteOnExit();
  complexVarcharParquetDir.deleteOnExit();
  Files.write(Paths.get(complexVarcharParquetFile.toURI()), Resources.toByteArray(complexVarcharParquetUrl));

  // create a table with matching names and types with different varchar lengths
  final String varcharTruncationTest =
    "create external table varchar_truncation_test_ext1("
      + "col1 varchar(2), "
      + "col2 struct<f1:varchar(4)>, "
      + "col3 struct<f1:struct<subf1:varchar(6)>>, "
      + "col4 struct<f1:array<varchar(8)>>, "
      + "col5 array<struct<f1:varchar(10)>>, "
      + "col6 array<varchar(12)>, "
      + "col7 array<array<array<array<varchar(14)>>>> ) "
      + "stored as parquet location '"
      + complexVarcharParquetFile.getParent()
      + "'";
  executeQuery(hiveDriver, varcharTruncationTest);
}
 
Example 13
Source File: RestoreMetadataTaskTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  integrityCheckStrategies = spy(new HashMap<>());
  integrityCheckStrategies.put(Maven2Format.NAME, testIntegrityCheckStrategy);
  integrityCheckStrategies.put(DEFAULT_NAME, defaultIntegrityCheckStrategy);

  underTest =
      new RestoreMetadataTask(blobStoreManager, repositoryManager, ImmutableMap.of("maven2", restoreBlobStrategy),
          blobstoreUsageChecker, dryRunPrefix, integrityCheckStrategies, bucketStore, maintenanceService);

  reset(integrityCheckStrategies); // reset this mock so we more easily verify calls

  configuration = new TaskConfiguration();
  configuration.setString(BLOB_STORE_NAME_FIELD_ID, BLOBSTORE_NAME);
  configuration.setId(BLOBSTORE_NAME);
  configuration.setTypeId(TYPE_ID);

  when(repositoryManager.get("maven-central")).thenReturn(repository);
  when(repository.getFormat()).thenReturn(mavenFormat);
  when(mavenFormat.getValue()).thenReturn("maven2");

  URL resource = Resources
      .getResource("test-restore/content/vol-1/chp-1/86e20baa-0bca-4915-a7dc-9a4f34e72321.properties");
  blobAttributes = new FileBlobAttributes(Paths.get(resource.toURI()));
  blobAttributes.load();
  blobId = new BlobId("86e20baa-0bca-4915-a7dc-9a4f34e72321");
  when(fileBlobStore.getBlobIdStream()).thenReturn(Stream.of(blobId));
  when(blobStoreManager.get(BLOBSTORE_NAME)).thenReturn(fileBlobStore);

  when(fileBlobStore.get(blobId, true)).thenReturn(blob);
  when(fileBlobStore.getBlobAttributes(blobId)).thenReturn(blobAttributes);

  when(dryRunPrefix.get()).thenReturn("");
}
 
Example 14
Source File: YangToSourcesPluginTestIT.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static Optional<String> getEffectiveSettingsXML() throws URISyntaxException, VerificationException,
        IOException {
    final URL path = Resources.getResource(YangToSourcesPluginTestIT.class, "/test-parent/pom.xml");
    final File buildDir = new File(path.toURI()).getParentFile().getParentFile().getParentFile();
    final File effectiveSettingsXML = new File(buildDir, "effective-settings.xml");
    if (effectiveSettingsXML.exists()) {
        return Optional.of(effectiveSettingsXML.getAbsolutePath());
    }

    fail(effectiveSettingsXML.getAbsolutePath());
    return Optional.empty();
}
 
Example 15
Source File: IntegrationBasicSuite.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
protected Config getClusterConfig() {
  URL url = Resources.getResource("BasicCluster.conf");
  Config config = ConfigFactory.parseURL(url);

  Map<String, String> configMap = new HashMap<>();
  String zkConnectionString = this.testingZKServer.getConnectString();
  configMap.put(GobblinClusterConfigurationKeys.ZK_CONNECTION_STRING_KEY, zkConnectionString);
  configMap.put(GobblinTaskRunner.CLUSTER_APP_WORK_DIR, this.workPath.toString());
  Config overrideConfig = ConfigFactory.parseMap(configMap);

  return overrideConfig.withFallback(config);
}
 
Example 16
Source File: YarnClientTest.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseAppAttemptsContainers() throws IOException {
  String jsonFile = "ws-v1-cluster-apps-application_id-appattempts-appattempt_id-containers.json";
  URL urlJson = Resources.getResource(jsonFile);
  String jsonContent = Resources.toString(urlJson, Charsets.UTF_8);

  List<Map<String, Object>> list = yarnClient.parseAppAttemptsContainers(jsonContent);

  list.get(0).get(YarnClient.HOST_IP);
  list.get(0).get(YarnClient.HOST_PORT);
  list.get(0).get(YarnClient.CONTAINER_PORT);

  LOGGER.info("");
}
 
Example 17
Source File: SwaggerService_ParseTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private PageEntity getPage(String resource, String contentType) throws IOException {
    URL url = Resources.getResource(resource);
    String descriptor = Resources.toString(url, Charsets.UTF_8);
    PageEntity pageEntity = new PageEntity();
    pageEntity.setContent(descriptor);
    pageEntity.setContentType(contentType);
    return pageEntity;
}
 
Example 18
Source File: TraceHandlerDelegate.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public URL getTemplateGroup() {
  return Resources.getResource(TraceHandlerDelegate.class, "templates.stg");
}
 
Example 19
Source File: HiveTestDataGenerator.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private void createSimpleListWithNullsHiveTables(final Driver hiveDriver) throws Exception {
  final File simpleListWithNullsParquetDir = new File(BaseTestQuery.getTempDir("simplelistwithnullsparquet"));
  simpleListWithNullsParquetDir.mkdirs();
  final URL simpleListWithNullsParquetUrl = Resources.getResource("simple_list_with_nulls_test.parquet");
  if (simpleListWithNullsParquetUrl == null) {
    throw new IOException(String.format("Unable to find path %s.", "simple_list_with_nulls_test.parquet"));
  }

  // parquet file has following columns with one valid row
  // length of array value of each column is 4, and 3rd element is null
  // tinyintcol array<tinyint>
  // smallintcol array<smallint>
  // intcol array<int>
  // bigintcol array<bigint>
  // floatcol array<float>
  // doublcol array<double>
  // decimalcol array<decimal(10,3)>
  // charcol array<char(16)>
  // varcharcol array<varchar(16)>
  // stringcol array<string>
  // datecol array<date>
  // timestampcol array<timestamp>
  final File simpleListWithNullsParquetFile = new File(simpleListWithNullsParquetDir, "simple_list_with_nulls_test.parquet");
  simpleListWithNullsParquetFile.deleteOnExit();
  simpleListWithNullsParquetDir.deleteOnExit();
  Files.write(Paths.get(simpleListWithNullsParquetFile.toURI()), Resources.toByteArray(simpleListWithNullsParquetUrl));

  // create good table with matching names, types and positions
  final String basicAllMatchingTest = "create external table array_simple_with_nulls_test_ext1(" +
    "tinyintcol array<tinyint>, "+
    "smallintcol array<smallint>, "+
    "intcol array<int>, "+
    "bigintcol array<bigint>, "+
    "floatcol array<float>, "+
    "doublecol array<double>, "+
    "decimalcol array<decimal(10,3)>, "+
    "charcol array<char(16)>, "+
    "varcharcol array<varchar(16)>, "+
    "stringcol array<string>, " +
    "datecol array<date>, " +
    "timestampcol array<timestamp> ) " +
    "stored as parquet location '" + simpleListWithNullsParquetFile.getParent() + "'";
  executeQuery(hiveDriver, basicAllMatchingTest);

  // create good table with matching names, types and positions
  final String upPromoteWithNulls = "create external table array_simple_with_nulls_test_ext2(" +
    "tinyintcol array<bigint>, "+
    "smallintcol array<bigint>, "+
    "intcol array<bigint>, "+
    "bigintcol array<bigint>, "+
    "floatcol array<double>, "+
    "doublecol array<double>, "+
    "decimalcol array<decimal(3,1)>, "+
    "charcol array<char(16)>, "+
    "varcharcol array<varchar(16)>, "+
    "stringcol array<string>, " +
    "datecol array<date>, " +
    "timestampcol array<timestamp> ) " +
    "stored as parquet location '" + simpleListWithNullsParquetFile.getParent() + "'";
  executeQuery(hiveDriver, upPromoteWithNulls);
}
 
Example 20
Source File: ResourceUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 读取规则见本类注释.
 */
public static URL asUrl(String resourceName) {
	return Resources.getResource(resourceName);
}