下面列出了怎么用org.apache.commons.io.IOUtils的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testHiveInput() throws Exception {
String tableCreationScript = "table creation script";
String js = "ci.hiveInput(\"dbname\", \"tablename\", ci.fixFile(\"" + tableCreationScript + "\"))";
TestConfigurationParser parser = new TestConfigurationParser();
NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string");
HiveTableDeployer hiveTableDeployer = (HiveTableDeployer) creatorObj.unwrap();
FixFile tableCreationFile = hiveTableDeployer.getTableCreationScriptFile().create(null);
Assert.assertEquals(hiveTableDeployer.getDatabaseName(), new DatabaseName("dbname"));
Assert.assertEquals(hiveTableDeployer.getTableName(), "tablename");
Assert.assertEquals(IOUtils.toString(tableCreationFile.getContent()), tableCreationScript);
Assert.assertNull(hiveTableDeployer.getDataFileCreator());
}
private void sendThumbnail(final File iviewFile, final HttpServletResponse response) throws IOException {
try (ZipFile zipFile = new ZipFile(iviewFile)) {
final ZipEntry ze = zipFile.getEntry("0/0/0.jpg");
if (ze != null) {
response.setHeader("Cache-Control", "max-age=" + MCRTileServlet.MAX_AGE);
response.setContentType("image/jpeg");
response.setContentLength((int) ze.getSize());
try (ServletOutputStream out = response.getOutputStream();
InputStream zin = zipFile.getInputStream(ze)) {
IOUtils.copy(zin, out);
}
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
}
public static void unzip(InputStream inputStream, File targetDirectory) throws IOException, IllegalAccessException {
try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new BufferedInputStream(inputStream))) {
ZipArchiveEntry entry = null;
while ((entry = zis.getNextZipEntry()) != null) {
File entryDestination = new File(targetDirectory, entry.getName());
// prevent zipSlip
if (!entryDestination.getCanonicalPath().startsWith(targetDirectory.getCanonicalPath() + File.separator)) {
throw new IllegalAccessException("Entry is outside of the target dir: " + entry.getName());
}
if (entry.isDirectory()) {
entryDestination.mkdirs();
} else {
entryDestination.getParentFile().mkdirs();
try (OutputStream out = new FileOutputStream(entryDestination)) {
IOUtils.copy(zis, out);
}
}
}
}
}
/**
* Description: <br>
*
* @author 王伟<br>
* @taskId <br>
* @param inputStream
* @param map
* @throws IOException <br>
*/
@SuppressWarnings("unchecked")
private static void loadYml(final InputStream inputStream, final Map<String, String> map) throws IOException {
try {
Yaml yaml = new Yaml();
HashMap<String, Object> value = yaml.loadAs(inputStream, HashMap.class);
if (MapUtils.isNotEmpty(value)) {
for (Entry<String, Object> entry : value.entrySet()) {
transfer(entry.getKey(), entry.getValue(), map);
}
}
}
finally {
IOUtils.closeQuietly(inputStream);
}
}
/**
* This analyzer is not actually used for indexing. It is implemented here
* so that the analysis UI will show reasonable tokens.
*/
@Override
public Analyzer getIndexAnalyzer() {
return new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
PrefixTreeStrategy s = newSpatialStrategy(fieldName == null ? getTypeName() : fieldName);
PrefixTreeStrategy.ShapeTokenStream ts = s.tokenStream();
return new TokenStreamComponents(r -> {
try {
ts.setShape(parseShape(IOUtils.toString(r)));
} catch (IOException e) {
throw new RuntimeException(e);
}
}, ts);
}
};
}
public static CliOutputs runAndGetOutputs(File pwd, String... args) throws IOException, InterruptedException {
final Process process = new ProcessBuilder(getAllArgs(Arrays.asList(args)))
.directory(pwd)
.start();
final byte stdout[] = IOUtils.toByteArray(process.getInputStream());
final byte stderr[] = IOUtils.toByteArray(process.getErrorStream());
final int exitCode = process.waitFor();
System.out.println(String.format("Process exited with exit code of %s", exitCode));
System.out.println("Stdout:");
System.out.print(new String(stdout));
System.out.println("Stderr:");
System.out.print(new String(stderr));
return new CliOutputs(stdout, stderr, exitCode);
}
@Test
public void includeResourcesInBundle() throws Exception {
Path bundle = FileSystems.getDefault().getPath("target/classes/META-INF/syndesis/schemas/dstu3/bundle.json");
String inspection;
try (InputStream fileIn = Files.newInputStream(bundle)) {
inspection = IOUtils.toString(fileIn, StandardCharsets.UTF_8);
}
String inspectionWithResources = FhirMetadataRetrieval.includeResources(inspection, "patient", "account");
ObjectMapper mapper = io.atlasmap.v2.Json.mapper();
XmlDocument xmlDocument = mapper.readValue(inspectionWithResources, XmlDocument.class);
XmlComplexType resource = (XmlComplexType) xmlDocument.getFields().getField().get(0);
Assertions.assertThat(resource.getName()).isEqualTo("tns:Bundle");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:resource", "tns:Patient");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:resource", "tns:Patient", "tns:contained", "tns:Account");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:response", "tns:outcome", "tns:Patient");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:response", "tns:outcome", "tns:Patient", "tns:contained", "tns:Account");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:resource", "tns:Account");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:resource", "tns:Account", "tns:contained", "tns:Patient");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:response", "tns:outcome", "tns:Account");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:response", "tns:outcome", "tns:Account", "tns:contained", "tns:Patient");
}
@Test
public void convertToScufl2() throws Exception {
File tmp = File.createTempFile("helloworld", ".t2flow");
tmp.deleteOnExit();
InputStream ebi = getClass().getResourceAsStream("/workflows/t2flow/helloworld.t2flow");
FileOutputStream output = new FileOutputStream(tmp);
IOUtils.copy(ebi, output);
output.close();
ConvertT2flowToWorkflowBundle.main(new String[]{tmp.getAbsolutePath()});
File scufl2File = new File(tmp.getAbsolutePath().replace(".t2flow", ".wfbundle"));
assertTrue(scufl2File.isFile());
try (ZipFile zip = new ZipFile(scufl2File)) {
assertNotNull(zip.getEntry("workflowBundle.rdf"));
}
scufl2File.deleteOnExit();
// System.out.println(scufl2File);
}
@Test
public void testUnscopedStreaming() throws IOException {
InputStream stream = TestUtils.getResourceStream( this.getClass(), "simple-values.json" );
String input = IOUtils.toString( stream, StandardCharsets.UTF_8 );
UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter=1" );
UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "$['test-str']", "test-rule" );
assertNotNull(applyConfig);
JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
String output = IOUtils.toString( filter );
JsonAssert.with( output ).assertThat( "name<test-str>", is( "value:null<text>" ) );
}
public Optional<String> getDriverVersionFromRepository(
Optional<String> driverVersion, URL driverUrl,
Charset versionCharset, String driverName, String versionLabel,
String latestLabel) {
String url = driverVersion.isPresent()
? driverUrl + latestLabel + "_" + driverVersion.get()
: driverUrl + versionLabel;
Optional<String> result = Optional.empty();
try (InputStream response = httpClient
.execute(httpClient.createHttpGet(new URL(url))).getEntity()
.getContent()) {
result = Optional.of(IOUtils.toString(response, versionCharset)
.replaceAll("\r\n", ""));
} catch (Exception e) {
log.warn("Exception reading {} to get latest version of {} ({})",
url, driverName, e.getMessage());
}
if (result.isPresent()) {
log.debug("Latest version of {} according to {} is {}", driverName,
url, result.get());
}
return result;
}
@Override
public FixFile convert(TestRun tr, FixFile ff) throws Exception {
List<String> stringList = Lists.newArrayList();
BufferedReader reader = new BufferedReader(new InputStreamReader(ff.getContent()));
String line;
while ((line = reader.readLine()) != null) {
JsonElement jsonElement = jsonParser.parse(line);
for (String field : expandFields) {
try {
String strField = jsonElement.getAsJsonObject().get(field).getAsString();
JsonElement fieldElem = jsonParser.parse(strField);
jsonElement.getAsJsonObject().add(field, fieldElem);
} catch(Exception e) {
throw new Exception("Error caused in line: " + line + " trying to expand field: " + field, e);
}
}
stringList.add(gson.toJson(jsonElement));
}
return new FixFile(IOUtils.toInputStream(StringUtils.join(stringList,"\n")));
}
@Test
public void multipleValuesInAcceptHeaderWithIncorrectParam() throws Exception {
URL url = new URL(SERVICE_URI + "ESAllPrim");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.GET.name());
connection.setRequestProperty(HttpHeader.ACCEPT, "application/json,"
+ "application/json;q=0.1,application/json;q=<1");
connection.connect();
assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode());
final String content = IOUtils.toString(connection.getErrorStream());
assertTrue(content.contains("The content-type range 'application/json;q=<1' is not "
+ "supported as value of the Accept header."));
}
public Map<String, String> getOAuthResponse() throws IOException {
String authServer = world.getOrThrow(OAuthCukesConstants.AUTH_SERVER);
String clientId = world.getOrThrow(OAuthCukesConstants.CLIENT_ID);
String clientSecret = world.getOrThrow(OAuthCukesConstants.CLIENT_SECRET);
String grantType = world.getOrThrow(OAuthCukesConstants.GRANT_TYPE);
URL url = new URL(authServer);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Authorization", "Basic " + Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes()));
connection.addRequestProperty("content-type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("a=b" + getRequestParameter(grantType));
writer.flush();
int responseCode = connection.getResponseCode();
if (responseCode >= 400) {
throw new IllegalStateException("Cannot retrieve OAuth token: " + IOUtils.toString(connection.getErrorStream()));
}
String response = IOUtils.toString(connection.getInputStream());
Type type = new TypeToken<Map<String, String>>() {
}.getType();
return new Gson().fromJson(response, type);
}
@Test
public void testDocx() throws Exception {
BandData root = createRootBand();
root.addReportFieldFormats(Collections.singletonList(new ReportFieldFormatImpl("Band1.col2", "${html}")));
BandData footer = root.getChildByName("Footer");
BandData footerChild = new BandData("FooterChild", footer);
footerChild.addData("nestedData", "NESTED_DATA");
footerChild.addData("nestedData.withPoint", "NESTED_DATA_WITH_POINT");
footer.addChild(footerChild);
FileOutputStream outputStream = new FileOutputStream("./result/smoke/result.docx");
ReportFormatter formatter = new DefaultFormatterFactory().createFormatter(new FormatterFactoryInput("docx", root,
new ReportTemplateImpl("", "./modules/core/test/smoketest/test.docx", "./modules/core/test/smoketest/test.docx", ReportOutputType.docx), outputStream));
formatter.renderDocument();
IOUtils.closeQuietly(outputStream);
}
@Override
public String getValue() {
Object value = loadField(Occurrence.LF_value);
if (value instanceof String) {
return (String) value;
} else if (value instanceof OnDemandValue) {
OnDemandValue odv = (OnDemandValue)value;
try {
Reader r = (Reader)odv.getValue(_p_getTransaction());
try {
return IOUtils.toString(r);
} finally {
r.close();
}
} catch (IOException e) {
throw new OntopiaRuntimeException(e);
}
} else if (value != null) {
throw new OntopiaRuntimeException("Occurrence value cannot be non-null at this point: " + value);
} else {
return null; // FIXME: or possibly something else
}
}
/**
* XeDate can build XML response.
* @throws IOException If some problem inside
*/
@Test
public void buildsXmlResponse() throws IOException {
MatcherAssert.assertThat(
IOUtils.toString(
new RsXembly(
new XeAppend(
"root",
new XeDate()
)
).body(),
StandardCharsets.UTF_8
),
XhtmlMatchers.hasXPaths(
"/root[@date]"
)
);
}
/**
* 返回配置文件流 避免ehcache配置文件一直被占用,无法完全销毁项目重新部署
*/
protected InputStream getCacheManagerConfigFileInputStream()
{
String configFile = "classpath:ehcache/ehcache-shiro.xml";
InputStream inputStream = null;
try
{
inputStream = ResourceUtils.getInputStreamForPath(configFile);
byte[] b = IOUtils.toByteArray(inputStream);
InputStream in = new ByteArrayInputStream(b);
return in;
}
catch (IOException e)
{
throw new ConfigurationException(
"Unable to obtain input stream for cacheManagerConfigFile [" + configFile + "]", e);
}
finally
{
IOUtils.closeQuietly(inputStream);
}
}
/**
* {@inheritDoc}
*/
@Override
public VaultPackage rewrap(ExportOptions opts, VaultPackage src, File file)
throws IOException, RepositoryException {
OutputStream out = null;
boolean isTmp = false;
boolean success = false;
try {
if (file == null) {
file = File.createTempFile("filevault", ".zip");
isTmp = true;
}
out = FileUtils.openOutputStream(file);
rewrap(opts, src, out);
IOUtils.closeQuietly(out);
success = true;
VaultPackage pack = new ZipVaultPackage(file, isTmp);
dispatch(PackageEvent.Type.REWRAPP, pack.getId(), null);
return pack;
} finally {
IOUtils.closeQuietly(out);
if (isTmp && !success) {
FileUtils.deleteQuietly(file);
}
}
}
@Test
public void addKeyValues_shouldFillKeyValuesCache() throws Exception {
InitializerServiceImpl iniz = new InitializerServiceImpl();
InputStream is = getClass().getClassLoader()
.getResourceAsStream("org/openmrs/module/initializer/include/jsonKeyValues.json");
iniz.addKeyValues(is);
Assert.assertEquals("value1", iniz.getValueFromKey("key1"));
Assert.assertEquals("value2", iniz.getValueFromKey("key2"));
Assert.assertEquals("value3", iniz.getValueFromKey("key3"));
is = IOUtils.toInputStream("{\"key1\":\"value12\"}");
iniz.addKeyValues(is);
Assert.assertEquals("value12", iniz.getValueFromKey("key1"));
}
@Test
public void convert_to_dedicated_file() throws Exception {
//tag::optionToFile[]
File targetFile = //...
//end::optionToFile[]
temporaryFolder.newFile("toFileExample.html");
//tag::optionToFile[]
asciidoctor.convert(
"Hello World",
OptionsBuilder.options()
.toFile(targetFile) // <1>
.safe(SafeMode.UNSAFE) // <2>
.get());
assertTrue(targetFile.exists());
assertThat(
IOUtils.toString(new FileReader(targetFile)),
containsString("<p>Hello World"));
//end::optionToFile[]
}
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
logger.debug("Replacing parameters in file: {0}", file);
try (InputStream inputStream = Files.newInputStream(file)) {
String originalContent = IOUtils.toString(inputStream);
String updatedContent = strSubstitutor.replace(originalContent);
if (!StringUtils.equals(originalContent, updatedContent)) {
logger.debug("Updating file {}", file);
Files.write(file, updatedContent.getBytes(StandardCharsets.UTF_8));
}
return FileVisitResult.CONTINUE;
} catch (IOException e) {
logger.error("Error reading file {0}", e, file);
throw e;
}
}
@Test
public void export_compressed_gz() throws Exception {
new TableCreator(methodWatcher.getOrCreateConnection())
.withCreate("create table export_compressed_gz(a smallint,b double, c time,d varchar(20))")
.withInsert("insert into export_compressed_gz values(?,?,?,?)")
.withRows(getTestRows()).create();
String exportSQL = buildExportSQL("select * from export_compressed_gz order by a asc", "GZIP");
exportAndAssertExportResults(exportSQL, 6);
File[] files = temporaryFolder.listFiles(new PatternFilenameFilter(".*csv.gz"));
assertEquals(1, files.length);
assertEquals("" +
"25,3.14159,14:31:20,varchar1\n" +
"26,3.14159,14:31:20,varchar1\n" +
"27,3.14159,14:31:20,varchar1 space\n" +
"28,3.14159,14:31:20,\"varchar1 , comma\"\n" +
"29,3.14159,14:31:20,\"varchar1 \"\" quote\"\n" +
"30,3.14159,14:31:20,varchar1\n",
IOUtils.toString(new GZIPInputStream(new FileInputStream(files[0]))));
}
public SysDTO findSys(String code) {
try {
String url = baseUrl + "/open/rs/remote/findSys.do?code" + code;
HttpURLConnection conn = (HttpURLConnection) new URL(url)
.openConnection();
String text = IOUtils.toString(conn.getInputStream(), "UTF-8");
BaseDTO baseDto = jsonMapper.fromJson(text, BaseDTO.class);
Object result = baseDto.getData();
SysDTO sysDto = jsonMapper.fromJson(jsonMapper.toJson(result),
SysDTO.class);
return sysDto;
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
return null;
}
}
private static APIImage getAPIImageFromAPIM(String backendApiID) throws AppException {
APIImage image = new APIImage();
URI uri;
HttpResponse httpResponse = null;
try {
uri = new URIBuilder(CommandParameters.getInstance().getAPIManagerURL()).setPath(RestAPICall.API_VERSION + "/proxies/"+backendApiID+"/image").build();
RestAPICall getRequest = new GETRequest(uri, null);
httpResponse = getRequest.execute();
if(httpResponse == null || httpResponse.getEntity() == null) return null; // no Image found in API-Manager
InputStream is = httpResponse.getEntity().getContent();
image.setImageContent(IOUtils.toByteArray(is));
image.setBaseFilename("api-image");
if(httpResponse.containsHeader("Content-Type")) {
String contentType = httpResponse.getHeaders("Content-Type")[0].getValue();
image.setContentType(contentType);
}
return image;
} catch (Exception e) {
throw new AppException("Can't read Image from API-Manager.", ErrorCode.API_MANAGER_COMMUNICATION, e);
} finally {
try {
if(httpResponse!=null)
((CloseableHttpResponse)httpResponse).close();
} catch (Exception ignore) {}
}
}
public TestClassloader()
throws Exception
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
InputStream fis = getClass().getResourceAsStream("/" + testclass);
IOUtils.copy(fis, os);
fis.close();
os.close();
byte[] barr = os.toByteArray();
fooClass = defineClass("classloader.Foo", barr, 0, barr.length);
}
protected void saveFilter(@NotNull File metaDir)
throws IOException {
if (filter != null) {
File file = new File(metaDir, Constants.FILTER_XML);
try (OutputStream output = FileUtils.openOutputStream(file)) {
IOUtils.copy(filter.getSource(), output);
}
}
}
public void sendCommand(final String sessionId, final String command) {
final JobProcess jobProcess = runningProcessMap.get(sessionId);
if (jobProcess != null) {
try {
final OutputStream out = jobProcess.getProcess().getOutputStream();
IOUtils.write(command + "\n", out, Constants.CHARSET_UTF_8);
out.flush();
} catch (final IOException e) {
throw new JobProcessingException(e);
}
} else {
throw new JobNotFoundException("Job for " + sessionId + " is not found.");
}
}
@Override
public Collection<MonetaryAmount> readFrom(Class<Collection<MonetaryAmount>> type,
Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
String json = IOUtils.toString(entityStream);
String[] texts = gson.fromJson(json, String[].class);
return Stream.of(texts).map(Money::parse).collect(Collectors.toList());
}
@Test
public void compileProto() throws Exception {
InputStream referenceSchema = SchemaParserTest.class.getResourceAsStream("/schemas/Person.desc");
try (CompiledSchema resultSchema = SchemaParser.compileProto(SchemaParserTest.class.getResource("/schemas/Person.proto").getPath())) {
Assert.assertTrue("Compiled Person.proto should be equal to Person.desc", IOUtils.contentEquals(referenceSchema, resultSchema.read()));
}
}
@Test
public void testXmlToClickEvent() throws IOException {
String xml = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("message/event/click.xml"));
XmlMessageHeader xmlRequest = QyXmlMessages.fromXml(xml);
Assert.assertNotNull(xmlRequest);
Assert.assertTrue(xmlRequest instanceof QyClickEvent);
Assert.assertEquals("EVENTKEY", ((QyClickEvent) xmlRequest).getEventKey());
}