javax.management.openmbean.OpenDataException#com.google.common.io.Resources源码实例Demo

下面列出了javax.management.openmbean.OpenDataException#com.google.common.io.Resources 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: blueocean-plugin   文件: ParallelNavigationTest.java
/**
 * 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");
}
 
源代码2 项目: tint   文件: DigiMorph.java
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);

}
 
源代码3 项目: tint   文件: InverseDigiMorph.java
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);

}
 
源代码4 项目: mojito   文件: AndroidStringsXmlReaderTest.java
@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());
}
 
源代码5 项目: dremio-oss   文件: TestParquetScan.java
@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();
}
 
源代码6 项目: besu   文件: AbstractEthGraphQLHttpServiceTest.java
@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);
}
 
源代码7 项目: swagger-codegen-tooling   文件: YamlToJson.java
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();
}
 
源代码8 项目: zeppelin   文件: SubmarineUI.java
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);
  }
}
 
源代码9 项目: datacollector   文件: TestProtobufDataGenerator.java
@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());
}
 
源代码10 项目: gcp-ingestion   文件: SinkMainTest.java
@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()));
}
 
源代码11 项目: calcite   文件: MongoAdapterTest.java
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;
    }
  });
}
 
源代码12 项目: gcp-ingestion   文件: RepublisherMainTest.java
@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));
}
 
源代码13 项目: glowroot   文件: ClassAnalyzer.java
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;
}
 
源代码14 项目: curiostack   文件: ECDSA256VerifierTest.java
@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);
}
 
源代码15 项目: jinjava   文件: IfTagTest.java
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);
  }
}
 
源代码16 项目: gecco   文件: GeccoEngine.java
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;
}
 
源代码17 项目: incubator-gobblin   文件: DownloadUtils.java
/**
 * 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;
}
 
源代码18 项目: hbase-indexer   文件: HBaseIndexingOptionsTest.java
@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());

}
 
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();
}
 
源代码20 项目: keywhiz   文件: JsonCookieTest.java
@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);
}
 
源代码21 项目: blueocean-plugin   文件: PipelineNodeTest.java
@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));
}
 
源代码22 项目: web-data-extractor   文件: JerryExtractorTest.java
@Before
public void before() {
    try {
        html = Resources.toString(Resources.getResource("list.html"), Charsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
源代码23 项目: athenz   文件: DynamoDBClientFetcherImplTest.java
@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);
}
 
源代码24 项目: onedev   文件: GitUtilsTest.java
@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);
	}
}
 
源代码25 项目: json-flattener   文件: JsonFlattenerTest.java
@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());
}
 
源代码26 项目: jinjava   文件: CallTagTest.java
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);
  }
}
 
源代码27 项目: vertx-s3-client   文件: AbstractS3ClientTest.java
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
    );
}
 
@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"));
}
 
源代码29 项目: DataflowTemplates   文件: ResourceUtils.java
/**
 * 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;
}
 
源代码30 项目: styx   文件: StyxSchedulerTest.java
@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);
}