Java Code Examples for com.google.common.io.Resources

The following examples show how to use com.google.common.io.Resources. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: blueocean-plugin   Source File: ParallelNavigationTest.java    License: 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 2
Source Project: tint   Source File: DigiMorph.java    License: 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 3
Source Project: tint   Source File: InverseDigiMorph.java    License: 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 4
Source Project: mojito   Source File: AndroidStringsXmlReaderTest.java    License: 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 5
Source Project: dremio-oss   Source File: TestParquetScan.java    License: 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 6
Source Project: besu   Source File: AbstractEthGraphQLHttpServiceTest.java    License: 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 7
Source Project: swagger-codegen-tooling   Source File: YamlToJson.java    License: 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 8
Source Project: zeppelin   Source File: SubmarineUI.java    License: 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 9
Source Project: datacollector   Source File: TestProtobufDataGenerator.java    License: 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 10
Source Project: gcp-ingestion   Source File: SinkMainTest.java    License: 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 11
Source Project: calcite   Source File: MongoAdapterTest.java    License: 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 Project: gcp-ingestion   Source File: RepublisherMainTest.java    License: 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 Project: glowroot   Source File: ClassAnalyzer.java    License: 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 14
Source Project: curiostack   Source File: ECDSA256VerifierTest.java    License: 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 15
Source Project: jinjava   Source File: IfTagTest.java    License: 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 16
Source Project: gecco   Source File: GeccoEngine.java    License: 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 17
Source Project: incubator-gobblin   Source File: DownloadUtils.java    License: 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 18
Source Project: hbase-indexer   Source File: HBaseIndexingOptionsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEvaluateIndexingSpecification_CombinationOfCmdlineAndZk() throws Exception {

    // Create an indexer -- verify INDEXER_ADDED event
    IndexerDefinition indexerDef = new IndexerDefinitionBuilder()
            .name("userindexer")
            .configuration(Resources.toByteArray(Resources.getResource(getClass(), "user_indexer.xml")))
            .connectionParams(ImmutableMap.of(
                    "solr.zk", "myZkHost/solr",
                    "solr.collection", "mycollection"))
            .build();
    addAndWaitForIndexer(indexerDef);

    opts.hbaseIndexerZkHost = "localhost:" + ZK_CLIENT_PORT;
    opts.hbaseIndexerName = "userindexer";
    opts.hbaseTableName = "mytable";
    opts.zkHost = "myOtherZkHost/solr";

    opts.evaluateIndexingSpecification();

    INDEXER_MODEL.deleteIndexerInternal("userindexer");

    IndexingSpecification expectedSpec = new IndexingSpecification(
            "mytable", "userindexer", null,
            Resources.toByteArray(Resources.getResource(getClass(), "user_indexer.xml")), ImmutableMap.of(
                    "solr.zk", "myOtherZkHost/solr",
                    "solr.collection", "mycollection"));

    assertEquals(expectedSpec, opts.getIndexingSpecification());

}
 
Example 19
private static void prepareDBDataForTest() throws Exception {
  // copy data file to test dir
  File dataDir = context.getDataDir();
  File dataFile = new File(dataDir, MULTI_TYPE_DATA_FILE_NAME);
  FileOutputStream to = new FileOutputStream(dataFile);
  Resources.copy(Resources.getResource(MULTI_TYPE_DATA_FILE_NAME), to);
  to.close();

  // setup db objects needed by the test
  Connection connection = context.createConnection(ADMIN1);
  Statement statement = context.createStatement(connection);

  statement.execute("DROP DATABASE IF EXISTS DB_1 CASCADE");
  statement.execute("CREATE DATABASE DB_1");
  statement.execute("USE DB_1");
  statement.execute("CREATE TABLE TAB_1(A STRING, B STRING)");
  statement.execute("LOAD DATA LOCAL INPATH '" + dataFile.getPath() + "' INTO TABLE TAB_1");
  statement.execute("CREATE VIEW VIEW_1(A,B) AS SELECT A,B FROM TAB_1");
  statement.execute("CREATE TABLE TAB_2(A STRING, B STRING)");
  statement.execute("LOAD DATA LOCAL INPATH '" + dataFile.getPath() + "' INTO TABLE TAB_2");
  statement.execute("CREATE VIEW VIEW_2(A,B) AS SELECT A,B FROM TAB_2");
  //create table with partitions
  statement.execute("CREATE TABLE TAB_3 (A STRING, B STRING) partitioned by (C STRING)");
  statement.execute("ALTER TABLE TAB_3 ADD PARTITION (C=1)");
  statement.execute("ALTER TABLE TAB_3 ADD PARTITION (C=2)");
  statement.execute("LOAD DATA LOCAL INPATH '" + dataFile.getPath() + "' INTO TABLE TAB_3 PARTITION (C=1)");
  statement.execute("LOAD DATA LOCAL INPATH '" + dataFile.getPath() + "' INTO TABLE TAB_3 PARTITION (C=2)");
  statement.close();
  connection.close();
}
 
Example 20
Source Project: keywhiz   Source File: JsonCookieTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void handlesSerializedVersionField() throws Exception {
  JsonCookie expected = JsonCookie.create("session", "session-contents", "localhost", "/admin", true, true);

  String json = Resources.toString(Resources.getResource("fixtures/cookie_with_version.json"), UTF_8);
  JsonCookie actual = Jackson.newObjectMapper().readValue(json, JsonCookie.class);

  assertThat(actual).isEqualTo(expected);
}
 
Example 21
Source Project: blueocean-plugin   Source File: PipelineNodeTest.java    License: MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-38339")
public void downstreamBuildLinks() throws Exception {
    FreeStyleProject downstream1 = j.createFreeStyleProject("downstream1");
    FreeStyleProject downstream2 = j.createFreeStyleProject("downstream2");

    WorkflowJob upstream = j.createProject(WorkflowJob.class, "upstream");

    URL resource = Resources.getResource(getClass(), "downstreamBuildLinks.jenkinsfile");
    String jenkinsFile = Resources.toString(resource, Charsets.UTF_8);
    upstream.setDefinition(new CpsFlowDefinition(jenkinsFile, true));

    j.assertBuildStatus(Result.SUCCESS, upstream.scheduleBuild2(0));

    WorkflowRun r = upstream.getLastBuild();

    List<Map> resp = get("/organizations/jenkins/pipelines/upstream/runs/" + r.getId() + "/nodes/", List.class);

    assertEquals("number of nodes", 5, resp.size());

    Matcher actionMatcher1 = new NodeDownstreamBuildActionMatcher("downstream1");
    Matcher actionMatcher2 = new NodeDownstreamBuildActionMatcher("downstream2");

    List<Map> actions = (List<Map>) resp.get(2).get("actions");
    assertThat("node #2 contains a link to downstream1", actions, hasItem(actionMatcher1));

    actions = (List<Map>) resp.get(3).get("actions");
    assertThat("node #3 contains a link to downstream2", actions, hasItem(actionMatcher2));

    actions = (List<Map>) resp.get(4).get("actions");
    assertThat("node #4 contains a link to downstream1", actions, hasItem(actionMatcher1));
    assertThat("node #4 contains a link to downstream1", actions, hasItem(actionMatcher2));
}
 
Example 22
Source Project: web-data-extractor   Source File: JerryExtractorTest.java    License: 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);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 23
Source Project: athenz   Source File: DynamoDBClientFetcherImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAuthenticatedClient() {
    String certPath = Resources.getResource("gdpr.aws.core.cert.pem").getPath();//public
    String keyPath = Resources.getResource("unit_test_gdpr.aws.core.key.pem").getPath();//private

    System.setProperty(ZTS_PROP_DYNAMODB_KEY_PATH, keyPath);
    System.setProperty(ZTS_PROP_DYNAMODB_CERT_PATH, certPath);
    System.setProperty(ZTS_PROP_DYNAMODB_DOMAIN, "test.domain");
    System.setProperty(ZTS_PROP_DYNAMODB_REGION, "test.region");
    System.setProperty(ZTS_PROP_DYNAMODB_ROLE, "test.role");
    System.setProperty(ZTS_PROP_DYNAMODB_TRUSTSTORE, "test.truststore");
    System.setProperty(ZTS_PROP_DYNAMODB_TRUSTSTORE_PASSWORD, "test.truststore.password");
    System.setProperty(ZTS_PROP_DYNAMODB_ZTS_URL, "https://dev.zts.athenzcompany.com:4443/zts/v1");

    DynamoDBClientFetcherImpl dynamoDBClientFetcher = new DynamoDBClientFetcherImpl();
    PrivateKeyStore keyStore = Mockito.mock(PrivateKeyStore.class);
    ZTSClientNotificationSender ztsClientNotificationSender = Mockito.mock(ZTSClientNotificationSender.class);
    AmazonDynamoDB dynamoDBClient = dynamoDBClientFetcher.getDynamoDBClient(ztsClientNotificationSender, keyStore).getAmazonDynamoDB();
    assertNotNull(dynamoDBClient);

    System.clearProperty(ZTS_PROP_DYNAMODB_KEY_PATH);
    System.clearProperty(ZTS_PROP_DYNAMODB_CERT_PATH);
    System.clearProperty(ZTS_PROP_DYNAMODB_DOMAIN);
    System.clearProperty(ZTS_PROP_DYNAMODB_REGION);
    System.clearProperty(ZTS_PROP_DYNAMODB_ROLE);
    System.clearProperty(ZTS_PROP_DYNAMODB_TRUSTSTORE);
    System.clearProperty(ZTS_PROP_DYNAMODB_TRUSTSTORE_PASSWORD);
    System.clearProperty(ZTS_PROP_DYNAMODB_ZTS_URL);
}
 
Example 24
Source Project: onedev   Source File: GitUtilsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testMergeWithLinkAndLinkConflict() throws Exception {
	File tempDir;
	
	tempDir = FileUtils.createTempDir();
	try (InputStream is = Resources.getResource(GitUtilsTest.class, "git-conflict-link-link.zip").openStream()) {
		ZipUtils.unzip(is, tempDir);
		try (Git git = Git.open(tempDir)) {
			ObjectId mergeCommitId;

			mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"), 
					git.getRepository().resolve("dev"), false, user, user, "merge commit", false);
			
			assertNull(mergeCommitId);

			mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"), 
					git.getRepository().resolve("dev"), false, user, user, "merge commit", true);
			
			assertNotNull(mergeCommitId);
			
			try (	RevWalk revWalk = new RevWalk(git.getRepository())) {
				RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);
				TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "lib", mergeCommit.getTree());
				assertTrue(treeWalk != null && treeWalk.getFileMode(0) == FileMode.GITLINK);
				treeWalk = TreeWalk.forPath(git.getRepository(), ".gitmodules", mergeCommit.getTree());
				BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), ".gitmodules", FileMode.GITLINK.getBits());
				Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());
				assertTrue(blob.getText().getContent().trim().endsWith("/home/robin/temp/lib"));
			}
		}
	} finally {
		deleteDir(tempDir, 3);
	}
}
 
Example 25
Source Project: json-flattener   Source File: JsonFlattenerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFlattenAsMap() throws IOException {
  URL url = Resources.getResource("test2.json");
  String json = Resources.toString(url, Charsets.UTF_8);

  assertEquals(
      "{\"a.b\":1,\"a.c\":null,\"a.d[0]\":false,\"a.d[1]\":true,\"e\":\"f\",\"g\":2.3}",
      JsonFlattener.flattenAsMap(json).toString());
}
 
Example 26
Source Project: jinjava   Source File: CallTagTest.java    License: Apache License 2.0 5 votes vote down vote up
private String fixture(String name) {
  try {
    return Resources.toString(
      Resources.getResource(String.format("tags/calltag/%s.jinja", name)),
      StandardCharsets.UTF_8
    );
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 27
Source Project: vertx-s3-client   Source File: AbstractS3ClientTest.java    License: Apache License 2.0 5 votes vote down vote up
void mockInitMultipartUploadErrorResponse(Header... expectedHeaders) throws IOException {
    mock(
            ImmutableMap.of("uploads", ImmutableList.of("")),
            "POST",
            "/bucket/key",
            403,
            Resources.toByteArray(Resources.getResource(AbstractS3ClientTest.class, "/response/errorResponse.xml")),
            expectedHeaders
    );
}
 
Example 28
Source Project: docker-java   Source File: DefaultDockerClientConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAuthConfigurationsFromConfigJson() throws URISyntaxException {
    File cfgFile = new File(Resources.getResource("com.github.dockerjava.core/registry.v2").toURI());
    DefaultDockerClientConfig clientConfig = new DefaultDockerClientConfig(URI.create(
        "unix://foo"), cfgFile.getAbsolutePath(), "apiVersion", "registryUrl", "registryUsername", "registryPassword",
        "registryEmail", null);

    AuthConfigurations authConfigurations = clientConfig.getAuthConfigurations();
    assertThat(authConfigurations, notNullValue());
    assertThat(authConfigurations.getConfigs().get("https://test.docker.io/v2/"), notNullValue());

    AuthConfig authConfig = authConfigurations.getConfigs().get("https://test.docker.io/v2/");
    assertThat(authConfig.getUsername(), equalTo("user"));
    assertThat(authConfig.getPassword(), equalTo("password"));
}
 
Example 29
Source Project: DataflowTemplates   Source File: ResourceUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the file contents of the dead-letter schema file within the project's resources into
 * a {@link String} object.
 *
 * @return The schema JSON string.
 */
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 30
Source Project: styx   Source File: StyxSchedulerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetKubernetesClientNullClusterCaCertificate() throws Exception {
  var clientCertificate = Resources.toString(Resources.getResource("client.crt"), UTF_8);
  var clientKey = Resources.toString(Resources.getResource("client.key"), UTF_8);

  exception.expect(NullPointerException.class);
  getKubernetesClient("", null, clientCertificate, clientKey);
}