Java 类com.google.common.io.Resources 实例源码

项目:ARCLib    文件:ArclibXmlGeneratorTest.java   
/**
 * Tests that also the child elements have been created at the destination xpath when the source element is nested
 */
@Test
public void generateArclibXmlNestedElementMapping() throws SAXException, ParserConfigurationException, XPathExpressionException,
        IOException,
        TransformerException {
    SipProfile profile = new SipProfile();
    String sipProfileXml = Resources.toString(this.getClass().getResource(
            "/arclibxmlgeneration/sipProfiles/sipProfileNestedElementMapping.xml"), StandardCharsets
            .UTF_8);
    profile.setXml(sipProfileXml);

    store.save(profile);

    String arclibXml = generator.generateArclibXml(SIP_PATH, profile.getId());
    assertThat(arclibXml, is(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<METS:mets xmlns:METS=\"http://www.loc.gov/METS/\"><METS:metsHdr CREATEDATE=\"2013-01-22T10:55:20Z\" ID=\"kpw01169310\" LASTMODDATE=\"2013-01-22T10:55:20Z\" RECORDSTATUS=\"COMPLETE\">\r\n\t\t<METS:agent ROLE=\"CREATOR\" TYPE=\"ORGANIZATION\"> \r\n\t\t\t<METS:name>Exon s.r.o.</METS:name>\r\n\t\t</METS:agent>\r\n\t\t<METS:agent ROLE=\"ARCHIVIST\" TYPE=\"ORGANIZATION\"> \r\n\t\t\t<METS:name>ZLG001</METS:name>\r\n\t\t</METS:agent>\r\n\t</METS:metsHdr>\r\n</METS:mets>"));
}
项目:Equella    文件:UserConfigurableServlet.java   
@Override
public String call() throws Exception
{
    try
    {
        final URL resource = Resources.getResource("configurable.txt");
        final File f = new File(resource.toURI());
        if( !f.exists() )
        {
            return NO_CONTENT;
        }
        if( lastMod == 0 || lastMod < f.lastModified() )
        {
            final CharSource charSource = Resources.asCharSource(resource, Charset.forName("utf-8"));
            final StringWriter sw = new StringWriter();
            charSource.copyTo(sw);
            lastContent = sw.toString();
            lastMod = f.lastModified();
        }
        return lastContent;
    }
    catch( Exception e )
    {
        return NO_CONTENT;
    }
}
项目:ARCLib    文件:ArclibXmlGeneratorTest.java   
/**
 * Tests that only single element has been created at the destination xPath when specifying the position of the source element
 */
@Test
public void generateArclibXmlElementAtPositionMapping() throws SAXException, ParserConfigurationException, XPathExpressionException,
        IOException,
        TransformerException {
    SipProfile profile = new SipProfile();
    String sipProfileXml = Resources.toString(this.getClass().getResource(
            "/arclibxmlgeneration/sipProfiles/sipProfileElementAtPositionMapping.xml"), StandardCharsets
            .UTF_8);
    profile.setXml(sipProfileXml);

    store.save(profile);

    String arclibXml = generator.generateArclibXml(SIP_PATH, profile.getId());
    assertThat(arclibXml, is("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<METS:mets xmlns:METS=\"http://www.loc.gov/METS/\"><METS:metsHdr xmlns:METS=\"http://arclib.lib.cas.cz/ARCLIB_XML\"><METS:agent ROLE=\"CREATOR\" TYPE=\"ORGANIZATION\"> \r\n\t\t\t<METS:name>Exon s.r.o.</METS:name>\r\n\t\t</METS:agent>\r\n</METS:metsHdr></METS:mets>"));
}
项目:appinventor-extensions    文件:Compiler.java   
private void prepareCompTypes(Set<String> neededTypes) {
  try {
    JSONArray buildInfo = new JSONArray(Resources.toString(
        Compiler.class.getResource(COMP_BUILD_INFO), Charsets.UTF_8));

    Set<String> allSimpleTypes = Sets.newHashSet();
    for (int i = 0; i < buildInfo.length(); ++i) {
      JSONObject comp = buildInfo.getJSONObject(i);
      allSimpleTypes.add(comp.getString("type"));
    }

    simpleCompTypes = Sets.newHashSet(neededTypes);
    simpleCompTypes.retainAll(allSimpleTypes);

    extCompTypes = Sets.newHashSet(neededTypes);
    extCompTypes.removeAll(allSimpleTypes);

  } catch (Exception e) {
    e.printStackTrace();
  }
}
项目:dremio-oss    文件:FunctionInitializer.java   
private CompilationUnit get(Class<?> c) throws IOException {
    URL u = getSourceURL(c);
    try (Reader reader = Resources.asCharSource(u, UTF_8).openStream()) {
      String body = CharStreams.toString(reader);

      // TODO: Hack to remove annotations so Janino doesn't choke. Need to reconsider this problem...
      body = body.replaceAll("@\\w+(?:\\([^\\\\]*?\\))?", "");
      for(Replacement r : REPLACERS){
        body = r.apply(body);
      }
//       System.out.println("original");
      // System.out.println(body);;
      // System.out.println("decompiled");
      // System.out.println(decompile(c));

      try {
        return new Parser(new Scanner(null, new StringReader(body))).parseCompilationUnit();
      } catch (CompileException e) {
        logger.warn("Failure while parsing function class:\n{}", body, e);
        return null;
      }

    }

  }
项目:rdf4j-schema-generator    文件:SchemaGeneratorSpecialTest.java   
@Test
public final void testReservedWordsHandling() throws Exception {
    Path outputPath = testDir.resolve("output");
    Files.createDirectories(outputPath);

    RDF4JSchemaGeneratorCore testBuilder = new RDF4JSchemaGeneratorCore(Resources.getResource("oa.ttl").getPath(), "text/turtle");

    Path javaFilePath = outputPath.resolve("OA.java");
    testBuilder.generate(javaFilePath);

    assertTrue("Java file was not found", Files.exists(javaFilePath));
    assertTrue("Java file was empty", Files.size(javaFilePath) > 0);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Files.copy(javaFilePath, out);
    String result = new String(out.toByteArray(), StandardCharsets.UTF_8);
    assertTrue(result.contains("public static final IRI hasTarget"));
    assertTrue(result.contains("public static final IRI _default"));
}
项目:QDrill    文件:TestConvertFunctions.java   
@Ignore // TODO(DRILL-2326) remove this when we get rid of the scalar replacement option test cases below
@Test
public void testBigIntVarCharReturnTripConvertLogical() throws Exception {
  final String logicalPlan = Resources.toString(
      Resources.getResource(CONVERSION_TEST_LOGICAL_PLAN), Charsets.UTF_8);
  final List<QueryDataBatch> results =  testLogicalWithResults(logicalPlan);
  int count = 0;
  final RecordBatchLoader loader = new RecordBatchLoader(getAllocator());
  for (QueryDataBatch result : results) {
    count += result.getHeader().getRowCount();
    loader.load(result.getHeader().getDef(), result.getData());
    if (loader.getRecordCount() > 0) {
      VectorUtil.showVectorAccessibleContent(loader);
    }
    loader.clear();
    result.release();
  }
  assertTrue(count == 10);
}
项目:minikube-build-tools-for-java    文件:TarStreamBuilderTest.java   
@Before
public void setUp() throws IOException, URISyntaxException {
  // Gets the test resource files.
  Path fileA = Paths.get(Resources.getResource("fileA").toURI());
  Path fileB = Paths.get(Resources.getResource("fileB").toURI());
  Path directoryA = Paths.get(Resources.getResource("directoryA").toURI());

  expectedFileAString = new String(Files.readAllBytes(fileA), StandardCharsets.UTF_8);
  expectedFileBString = new String(Files.readAllBytes(fileB), StandardCharsets.UTF_8);

  // Prepares a test TarStreamBuilder.
  testTarStreamBuilder.addEntry(
      new TarArchiveEntry(fileA.toFile(), "some/path/to/resourceFileA"));
  testTarStreamBuilder.addEntry(new TarArchiveEntry(fileB.toFile(), "crepecake"));
  testTarStreamBuilder.addEntry(new TarArchiveEntry(directoryA.toFile(), "some/path/to"));
}
项目:state-channels    文件:CassandraUtil.java   
public static void executeSchemaCql(Session session, boolean deleteData) {
    try {

        URL schema = Resources.getResource("schema.cql");
        String schemaCql = Resources.toString(schema, Charset.forName("UTF-8"));
        schemaCql = schemaCql.replaceAll("(?m)//.*$", "");
        String[] statements = schemaCql.split(";");

        if (deleteData) {
            dropSchema(session);
        }

        for (String statement : statements) {
            statement = statement.trim();
            if (statement.isEmpty()) continue;
            executeWithLog(session, statement);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
项目:QDrill    文件:ReplaceMethodInvoke.java   
public static void main(String[] args) throws Exception {
  final String k2 = "org/apache/drill/Pickle.class";
  final URL url = Resources.getResource(k2);
  final byte[] clazz = Resources.toByteArray(url);
  final ClassReader cr = new ClassReader(clazz);

  final ClassWriter cw = writer();
  final TraceClassVisitor visitor = new TraceClassVisitor(cw, new Textifier(), new PrintWriter(System.out));
  final ValueHolderReplacementVisitor v2 = new ValueHolderReplacementVisitor(visitor, true);
  cr.accept(v2, ClassReader.EXPAND_FRAMES );//| ClassReader.SKIP_DEBUG);

  final byte[] output = cw.toByteArray();
  Files.write(output, new File("/src/scratch/bytes/S.class"));
  check(output);

  final DrillConfig c = DrillConfig.forClient();
  final SystemOptionManager m = new SystemOptionManager(c, new LocalPStoreProvider(c));
  m.init();
  try (QueryClassLoader ql = new QueryClassLoader(DrillConfig.create(), m)) {
    ql.injectByteCode("org.apache.drill.Pickle$OutgoingBatch", output);
    Class<?> clz = ql.loadClass("org.apache.drill.Pickle$OutgoingBatch");
    clz.getMethod("x").invoke(null);
  }
}
项目:oryx2    文件:SecureAPIConfigIT.java   
@Test
public void testUserPassword() throws Exception {
  startServer(buildUserPasswordConfig());

  Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication("oryx", "pass".toCharArray());
    }
  });

  try {
    String response = Resources.toString(
        new URL("http://localhost:" + getHTTPPort() + "/helloWorld"),
        StandardCharsets.UTF_8);
    assertEquals("Hello, World", response);
  } finally {
    Authenticator.setDefault(null);
  }
}
项目:rest-modeling-framework    文件:CollectionGenerator.java   
@VisibleForTesting
String generateContent(final URL staticFile, final Api api) throws IOException {
    final ST st = getStGroup(staticFile);

    final String fileName = new File(staticFile.getPath()).getName();
    st.add("api", new ApiGenModel(api));
    if (fileName.equals("collection.json.stg")) {
        st.add("id", "f367b534-c9ea-e7c5-1f46-7a27dc6a30ba");
        final String readme = getStGroup(Resources.getResource("templates/postman/README.md.stg")).render();
        st.add("readme", readme);
    }
    if (fileName.equals("template.json.stg"))  {
        st.add("id", "5bb74f05-5e78-4aee-b59e-492c947bc160");
    }
    return st.render();
}
项目:de.flapdoodle.solid    文件:WordpressRssConverterTest.java   
@Test
public void sampleWordpressDump() throws IOException, DocumentException {
    try (Reader reader = new InputStreamReader(Resources.asByteSource(Resources.getResource(getClass(), "wordpress-sample-rss.xml")).openBufferedStream())) {
        WordpressRss wordpressRss = WordpressRssConverter.build(XmlParser.of(reader));
        System.out.println("------------------------");
        System.out.println(wordpressRss);
        System.out.println("------------------------");
        ImmutableList<Document> documents = WordpressRss2Solid.convert(wordpressRss);
        documents.forEach(doc -> {
            String docAsString = doc.toString();
            int idx = docAsString.indexOf("---");
            if (idx!=-1) {
                int idxE = docAsString.indexOf("---", idx+3);
                if (idxE!=-1) {
                    docAsString=docAsString.substring(0, idxE+3);
                }
            }
            System.out.println(docAsString);
        });
        System.out.println("------------------------");
    }
}
项目:hashsdn-controller    文件:ModuleFactoryBundleTracker.java   
@Override
public Boolean addingBundle(final Bundle bundle, final BundleEvent event) {
    URL resource = bundle.getEntry("META-INF/services/" + ModuleFactory.class.getName());
    LOG.trace("Got addingBundle event of bundle {}, resource {}, event {}", bundle, resource, event);
    if (resource != null) {
        try {
            for (String factoryClassName : Resources.readLines(resource, StandardCharsets.UTF_8)) {
                registerFactory(factoryClassName, bundle);
            }

            return Boolean.TRUE;
        } catch (final IOException e) {
            LOG.error("Error while reading {}", resource, e);
            throw new RuntimeException(e);
        }
    }

    return Boolean.FALSE;
}
项目:DBus    文件:PropertiesUtils.java   
/**
 * create a Properties object use the config file
 * @param configFile a file path
 * @return Properties object
 * @throws Exception
 */
public static Properties getProps(String configFile) throws IOException {
    //InputStream is = getClass().getClassLoader().getResourceAsStream(configFile);
    InputStream is = null;
    try {
        is = Resources.getResource(configFile).openStream();

        Properties props = new Properties();
        props.load(is);
        return props;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
项目:dremio-oss    文件:IndexServlet.java   
private VersionInfo getVersionInfo() {
  String version = DremioVersionInfo.getVersion(); // get dremio version (x.y.z)
  long buildTime = 0;
  CommitInfo commitInfo = null;

  try {
    URL u = Resources.getResource("git.properties");

    if (u != null) {
      Properties p = new Properties();
      p.load(Resources.asByteSource(u).openStream());
      buildTime = DateTime.parse(p.getProperty("git.build.time"), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ")).getMillis();
      commitInfo = new CommitInfo(
        p.getProperty("git.commit.id"),
        p.getProperty("git.build.user.email"),
        DateTime.parse(p.getProperty("git.commit.time"), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ")).getMillis(),
        p.getProperty("git.commit.message.short"));
    }
  } catch (Exception e) {
    logger.warn("Failure when trying to access and parse git.properties.", e);
  }
  return new VersionInfo(version, buildTime, commitInfo);
}
项目:QDrill    文件: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();
}
项目:gradle-circle-style    文件:TestCommon.java   
public static String readTestFile(String filename) {
    try {
        return Resources.toString(WhoCalled.$.getCallingClass().getResource(filename), Charsets.UTF_8);
    } catch (IOException e) {
        throw new AssertionError(e);
    }
}
项目:QDrill    文件:PlanningBase.java   
protected static String getFile(String resource) throws IOException {
  final URL url = Resources.getResource(resource);
  if (url == null) {
    throw new IOException(String.format("Unable to find path %s.", resource));
  }
  return Resources.toString(url, Charsets.UTF_8);
}
项目:integrations    文件:DemoData.java   
private static Dataset<Row> getPayloadFromCsv(final SparkSession sparkSession ) {

        String csvPath = Resources.getResource( "DemoJustice9-28.csv" ).getPath();

        Dataset<Row> payload = sparkSession
                .read()
                .format( "com.databricks.spark.csv" )
                .option( "header", "true" )
                .load( csvPath );

        return payload;
    }
项目:biosses    文件:FeatureExtractor.java   
public void readCombineOntologyMethodFeature() throws IOException {

        BufferedReader buffer = new BufferedReader(new FileReader(Resources.getResource("correlationResult/ourResults/combined/avgCombinedSw.txt").getFile()));
        String line;
        int currentPairIndex = 0;
        while((line=buffer.readLine())!= null){
            Pair currentPair = pairs.get(currentPairIndex);
            currentPair.setCombinedOntologyMethod(Double.valueOf(line));
            currentPairIndex++;

        }

    }
项目:ARCLib    文件:ArclibXmlGeneratorTest.java   
/**
 * Tests the aggregation mapping for generation of the <i>ARCLIB:eventAgent</i> element.
 */
@Test
public void generateArclibEventAgent() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException,
        TransformerException {
    SipProfile profile = new SipProfile();
    String sipProfileXml = Resources.toString(this.getClass().getResource(
            "/arclibxmlgeneration/sipProfiles/sipProfileEventCount.xml"), StandardCharsets.UTF_8);
    profile.setXml(sipProfileXml);

    store.save(profile);

    String arclibXml = generator.generateArclibXml(SIP_PATH, profile.getId());
    assertThat(arclibXml, is("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<METS:mets xmlns:METS=\"http://www.loc.gov/METS/\"><METS:amdSec xmlns:METS=\"http://arclib.lib.cas.cz/ARCLIB_XML\"><METS:digiprovMD><METS:mdWrap><METS:xmlData><ARCLIB:eventAgents xmlns:ARCLIB=\"http://arclib.lib.cas.cz/ARCLIB_XML\"><ARCLIB:eventAgent><premis:eventType>capture</premis:eventType>\r\n</ARCLIB:eventAgent></ARCLIB:eventAgents></METS:xmlData></METS:mdWrap></METS:digiprovMD></METS:amdSec><METS:amdSec xmlns:METS=\"http://arclib.lib.cas.cz/ARCLIB_XML\"><METS:digiprovMD><METS:mdWrap><METS:xmlData><ARCLIB:eventAgents xmlns:ARCLIB=\"http://arclib.lib.cas.cz/ARCLIB_XML\"><ARCLIB:eventAgent><premis:eventType>migration</premis:eventType>\r\n</ARCLIB:eventAgent></ARCLIB:eventAgents></METS:xmlData></METS:mdWrap></METS:digiprovMD></METS:amdSec></METS:mets>"));
}
项目:vt-support    文件:StorageImpl.java   
private synchronized Flowable<VectorTileConfig> queryConfigFlowable() {
  final URL url = Resources.getResource("metadata_raw.sql");
  String query;
  try {
    query = Resources.toString(url, Charsets.UTF_8);
  } catch (final IOException ex) {
    return Flowable.error(ex);
  }
  return dataSource.select(query)
      .get(rs -> new VectorTileConfig(rs.getInt("min_zoom"), rs.getInt("max_zoom"),
          rs.getInt("max_zoom_minx"), rs.getInt("max_zoom_miny"), rs.getInt("max_zoom_maxx"),
          rs.getInt("max_zoom_maxy")));
}
项目:dremio-oss    文件:ByteCodeLoader.java   
@Override
public byte[] load(String path) throws ClassTransformationException, IOException {
  URL u = this.getClass().getResource(path);
  if (u == null) {
    throw new ClassTransformationException(String.format("Unable to find TemplateClass at path %s", path));
  }
  return Resources.toByteArray(u);
}
项目:dremio-oss    文件:StoragePlugins.java   
public static void main(String[] args) throws Exception{
  SabotConfig config = SabotConfig.create();
  ScanResult scanResult = ClassPathScanner.fromPrescan(config);
  LogicalPlanPersistence lpp = new LogicalPlanPersistence(config, scanResult);
  String data = Resources.toString(Resources.getResource("storage-engines.json"), Charsets.UTF_8);
  StoragePlugins se = lpp.getMapper().readValue(data,  StoragePlugins.class);
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  lpp.getMapper().writeValue(System.out, se);
  lpp.getMapper().writeValue(os, se);
  se = lpp.getMapper().readValue(new ByteArrayInputStream(os.toByteArray()), StoragePlugins.class);
  System.out.println(se);
}
项目:Lagerta    文件:DBResource.java   
public void executeResource(String resourceName) throws SQLException {
    URL resource = DBResource.class.getResource(resourceName);
    try (Connection connection = dataSource.getConnection();
         Statement statement = connection.createStatement()) {
        String query = Resources.toString(resource, Charsets.UTF_8);
        statement.executeUpdate(query);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
项目:vrap    文件:WebJarHandler.java   
/**
 * If vrap is running from a shadow/flat jar, the webjars will be directly available on the classpath.
 * In this case the jar file system will be empty and the returned uri optional uri will be empty.
 *
 * @param moduleName the module name
 * @param version the version
 *
 * @return the optional jar uri
 */
private Optional<URI> jarUri(final String moduleName, final String version) {
    final String webJarPath = Joiner.on("/").join(WEBJAR_ROOT, moduleName, version);
    final String resourceUrl = Resources.getResource(webJarPath).toString();
    final String codeLocationUrl = "jar:" + getClass().getProtectionDomain().getCodeSource().getLocation().toString();

    return resourceUrl.startsWith(codeLocationUrl) ?
            Optional.empty() :
            Optional.of(URI.create(resourceUrl.split("!")[0]));
}
项目:syndesis    文件:DataMapperClassInspectorTest.java   
@Test
public void shouldHandleNesting() throws IOException {
    DataMapperClassInspector dataMapperClassInspector = new DataMapperClassInspector(cache, new RestTemplate(), config);

    mockServer.expect().get().withPath("/v2/atlas/java/class?className=twitter4j.StatusJSONImpl").andReturn(200, Resources.toString(getClass().getResource("/twitter4j.StatusJSONImpl.json"), Charset.defaultCharset())).always();
    mockServer.expect().get().withPath("/v2/atlas/java/class?className=twitter4j.Logger").andReturn(200, Resources.toString(getClass().getResource("/twitter4j.Logger.json"), Charset.defaultCharset())).always();
    mockServer.expect().get().withPath("/v2/atlas/java/class?className=twitter4j.LoggerFactory").andReturn(200, Resources.toString(getClass().getResource("/twitter4j.LoggerFactory.json"), Charset.defaultCharset())).always();
    List<String> paths = dataMapperClassInspector.getPaths("java", "twitter4j.StatusJSONImpl", null, null);

    Assert.assertNotNull(paths);
    Assert.assertTrue(paths.contains("id"));
    Assert.assertTrue(paths.contains("logger.infoEnabled"));
}
项目:CustomWorldGen    文件:LootTableManager.java   
@Nullable
private LootTable loadBuiltinLootTable(ResourceLocation resource)
{
    URL url = LootTableManager.class.getResource("/assets/" + resource.getResourceDomain() + "/loot_tables/" + resource.getResourcePath() + ".json");

    if (url != null)
    {
        String s;

        try
        {
            s = Resources.toString(url, Charsets.UTF_8);
        }
        catch (IOException ioexception)
        {
            LootTableManager.LOGGER.warn("Couldn\'t load loot table {} from {}", new Object[] {resource, url, ioexception});
            return LootTable.EMPTY_LOOT_TABLE;
        }

        try
        {
            return net.minecraftforge.common.ForgeHooks.loadLootTable(LootTableManager.GSON_INSTANCE, resource, s, false);
        }
        catch (JsonParseException jsonparseexception)
        {
            LootTableManager.LOGGER.error("Couldn\'t load loot table {} from {}", new Object[] {resource, url, jsonparseexception});
            return LootTable.EMPTY_LOOT_TABLE;
        }
    }
    else
    {
        return null;
    }
}
项目:activiti-analytics-spring-boot    文件:AnalyticsConfig.java   
@SuppressWarnings("unchecked")
@Bean
public MappingConfiguration mappingConfiguration() {
    logger.debug("creating mappingConfiguration bean");
    MappingConfiguration mappingConf = new MappingConfiguration();
    try {
        URL endStateConfigUrl = Resources.getResource("mappingconfig/end-state-mapping.json");
        String endStateConfigJSON = Resources.toString(endStateConfigUrl, Charsets.UTF_8);
        mappingConf.setEndStateConfigMap((List<Map<String, Object>>) new ObjectMapper()
                .readValue(endStateConfigJSON, new TypeReference<List<Object>>() {
                }));

        URL allProcessConfigUrl = Resources.getResource("mappingconfig/all-processes-mapping-config.json");
        String allProcessConfigJSON = Resources.toString(allProcessConfigUrl, Charsets.UTF_8);
        mappingConf.setAllProcessConfigMap((Map<String, Object>) new ObjectMapper().readValue(allProcessConfigJSON,
                new TypeReference<Map<String, Object>>() {
                }));

        URL allTasksConfigUrl = Resources.getResource("mappingconfig/all-tasks-mapping-config.json");
        String allTasksConfigJSON = Resources.toString(allTasksConfigUrl, Charsets.UTF_8);
        mappingConf.setAllTasksConfigMap((Map<String, Object>) new ObjectMapper().readValue(allTasksConfigJSON,
                new TypeReference<Map<String, Object>>() {
                }));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return mappingConf;
}
项目:rest-modeling-framework    文件:CollectionGenerator.java   
public List<File> generate(final File outputPath, Api api) throws IOException {
    final URL resourcePath = Resources.getResource("templates/postman/");
    final List<URL> files = Helper.getTemplatesFromDirectory("templates/postman/");
    final ObjectMapper mapper = new ObjectMapper();

    final List<File> f = Lists.newArrayList();
    for (URL staticFile : files) {
        final String content = generateContent(staticFile, api);
        final String outputFileName = staticFile.toString()
                .replace(".stg", "")
                .replace(resourcePath.toString(), "");
        final File outputFile = new File(
                outputPath,
                outputFileName
        );
        f.add(generateFile(content, outputFile));
        if (outputFileName.endsWith("json")) {
            try {
                mapper.readTree(content);
            } catch (JsonParseException e) {
                System.out.println("Error generating " + outputFileName + ": Invalid JSON");
                System.out.println(e);
            }
        }
    }
    f.add(copyFile(Resources.getResource("templates/postman/connection_settings.png").openStream(), new File(outputPath, "connection_settings.png")));

    return f;
}
项目:de.flapdoodle.solid    文件:XmlParserTest.java   
@Test
@Ignore
public void sampleWordpress() throws DocumentException, IOException {
    try (Reader reader = new InputStreamReader(Resources.asByteSource(Resources.getResource(getClass(), "wordpress-sample-rss.xml")).openBufferedStream())) {
        XmlParser.of(reader)
            .collect((parent,element) -> {
                System.out.println(parent);
                System.out.println(" - "+element);
                return ImmutableList.of();
            });
    }
}
项目:rest-modeling-framework    文件:RequestGenerator.java   
String generateRequest(final RequestGenModel request) {
    final STGroupFile stGroup = createSTGroup(Resources.getResource(resourcesPath + TYPE_RESOURCE + ".stg"));
    final ST st = stGroup.getInstanceOf("request");
    st.add("vendorName", vendorName);
    st.add("request", request);
    return st.render();
}
项目:QDrill    文件:TestOptiqPlans.java   
@Test
public void testJoinPlan() throws Exception {
  final RemoteServiceSet serviceSet = RemoteServiceSet.getLocalServiceSet();

  try (final Drillbit bit1 = new Drillbit(config, serviceSet);
      final DrillClient client = new DrillClient(config, serviceSet.getCoordinator());) {
    bit1.run();
    client.connect();
    final List<QueryDataBatch> results = client.runQuery(org.apache.drill.exec.proto.UserBitShared.QueryType.PHYSICAL,
        Resources.toString(Resources.getResource("physical_join.json"), Charsets.UTF_8));
    final RecordBatchLoader loader = new RecordBatchLoader(bit1.getContext().getAllocator());
    for (final QueryDataBatch b : results) {
      System.out.println(String.format("Got %d results", b.getHeader().getRowCount()));
      loader.load(b.getHeader().getDef(), b.getData());
      for (final VectorWrapper<?> vw : loader) {
        System.out.println(vw.getValueVector().getField().toExpr());
        final ValueVector vv = vw.getValueVector();
        for (int i = 0; i < vv.getAccessor().getValueCount(); i++) {
          final Object o = vv.getAccessor().getObject(i);
          System.out.println(vv.getAccessor().getObject(i));
        }
      }
      loader.clear();
      b.release();
    }
    client.close();
  }
}
项目:biosses    文件:FeatureExtractor.java   
public void readGroundTruth() throws IOException {
    BufferedReader buffer = new BufferedReader(new FileReader(Resources.getResource("correlationResult/groundTruth/test.txt").getFile()));
    String line;
    while((line=buffer.readLine())!= null){
        groundTruthList.add(Double.valueOf(line));
    }
}
项目:morf    文件:ConnectionResourcesBean.java   
private static Properties propertiesFromUrl(URL propertiesUrl) {
  try (InputStream stream = new ByteArrayInputStream(Resources.toByteArray(propertiesUrl))) {
    return propertiesFromStream(stream);
  } catch (Exception e) {
    throw new RuntimeException("Failed to load properties from URL [" + propertiesUrl + "]", e);
  }
}
项目:de.flapdoodle.solid    文件:Toml2PropertyTreeTest.java   
@Test
public void mapToml() throws IOException {
    String tomlContent = Resources.asCharSource(Resources.getResource(getClass(), "sample.toml"), Charsets.UTF_8).read();
    Toml toml = Toml.parse(tomlContent);
    PropertyTree propertyMap = new Toml2PropertyTree().asPropertyTree(toml);
    assertEquals("FixedPropertyTree{map={date=[Either{optLeft=2012-04-06}], created=[Either{optLeft=Tue Oct 24 23:04:33 CEST 2006}], description=[Either{optLeft=spf13-vim is a cross platform distribution of vim plugins and resources for Vim.}], categories=[Either{optLeft=Development}, Either{optLeft=VIM}], title=[Either{optLeft=spf13-vim 3.0 release and new website}], slug=[Either{optLeft=spf13-vim-3-0-release-and-new-website}], tags=[Either{optLeft=.vimrc}, Either{optLeft=plugins}, Either{optLeft=spf13-vim}, Either{optLeft=vim}]}}", propertyMap.toString());
}
项目:cryptotrader    文件:CoincheckContextTest.java   
@Test(enabled = false) // TODO
public void testListTrades() throws Exception {

    Key key = Key.builder().instrument(BTC_JPY.name()).timestamp(Instant.parse("2017-08-02T00:00:00.000Z")).build();
    String data = Resources.toString(getResource("json/coincheck_trade.json"), UTF_8);
    doReturn(data).when(target).request(GET, "https://coincheck.com/api/trades?pair=btc_jpy&limit=500", null, null);

    // Found
    List<Trade> values = target.listTrades(key, null);
    assertEquals(values.size(), 3, values.toString());
    assertEquals(values.get(0).getTimestamp(), Instant.parse("2017-08-01T07:50:15.000Z"));
    assertEquals(values.get(0).getPrice(), new BigDecimal("320932"));
    assertEquals(values.get(0).getSize(), new BigDecimal("0.0065"));
    assertEquals(values.get(1).getTimestamp(), Instant.parse("2017-08-01T07:50:15.001Z"));
    assertEquals(values.get(1).getPrice(), new BigDecimal("320931"));
    assertEquals(values.get(1).getSize(), new BigDecimal("0.165828"));
    assertEquals(values.get(2).getTimestamp(), Instant.parse("2017-08-01T07:50:15.002Z"));
    assertEquals(values.get(2).getPrice(), new BigDecimal("320995"));
    assertEquals(values.get(2).getSize(), new BigDecimal("0.44"));

    // Not found
    List<Trade> unknown = target.listTrades(Key.builder().instrument("FOO").build(), null);
    assertEquals(unknown.size(), 0);

    // Cached
    doReturn(null).when(target).request(any(), any(), any(), any());
    List<Trade> cached = target.listTrades(key, null);
    assertEquals(cached, values);

    // Filtered
    List<Trade> filtered = target.listTrades(key, Instant.parse("2017-08-01T07:50:15.001Z"));
    assertEquals(filtered.size(), 2, filtered.toString());
    assertEquals(filtered.get(0), values.get(1));
    assertEquals(filtered.get(1), values.get(2));

}
项目:syndesis    文件:DataMapperClassInspectorTest.java   
@Test
public void shouldHandleInterfaces() throws IOException {
    DataMapperClassInspector dataMapperClassInspector = new DataMapperClassInspector(cache, new RestTemplate(), config);
    mockServer.expect().get().withPath("/v2/atlas/java/class?className=twitter4j.Status").andReturn(200, Resources.toString(getClass().getResource("/twitter4j.Status.json"), Charset.defaultCharset())).always();

    List<String> paths = dataMapperClassInspector.getPaths("java", "twitter4j.Status", null, null);

    Assert.assertNotNull(paths);
    Assert.assertTrue(paths.contains("id"));
}
项目:de.flapdoodle.solid    文件:TomlTest.java   
@Test
public void arraysOfTableSample() throws IOException {
    String source=Resources.toString(Resources.getResource(getClass(), "arraysOfTable.toml"), Charsets.UTF_8);
    Toml toml = Toml.parse(source);
    Map<String, Object> asMap = toml.asMap();
    System.out.println("map -> "+asMap);

    GroupedPropertyMap groupedMap = new Toml2GroupedPropertyMap().asGroupedPropertyMap(toml);
    System.out.println("map -> "+groupedMap.prettyPrinted());
}