Java Code Examples for org.apache.commons.io.IOUtils
The following examples show how to use
org.apache.commons.io.IOUtils.
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 check out the related API usage on the sidebar.
Example #1
Source Project: celos Author: collectivemedia File: TestConfigurationParserTest.java License: Apache License 2.0 | 6 votes |
@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()); }
Example #2
Source Project: mycore Author: MyCoRe-Org File: MCRTileCombineServlet.java License: GNU General Public License v3.0 | 6 votes |
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); } } }
Example #3
Source Project: youtubedl-android Author: yausername File: ZipUtils.java License: GNU General Public License v3.0 | 6 votes |
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); } } } } }
Example #4
Source Project: framework Author: ww20081120 File: PropertyHolder.java License: Apache License 2.0 | 6 votes |
/** * 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); } }
Example #5
Source Project: lucene-solr Author: apache File: AbstractSpatialPrefixTreeFieldType.java License: Apache License 2.0 | 6 votes |
/** * 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); } }; }
Example #6
Source Project: jobson Author: adamkewley File: CliHelpers.java License: Apache License 2.0 | 6 votes |
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); }
Example #7
Source Project: syndesis Author: syndesisio File: FhirMetadataRetrievalTest.java License: Apache License 2.0 | 6 votes |
@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"); }
Example #8
Source Project: incubator-taverna-language Author: apache File: TestConvertT2flowScufl2.java License: Apache License 2.0 | 6 votes |
@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); }
Example #9
Source Project: knox Author: apache File: JsonFilterReaderTest.java License: Apache License 2.0 | 6 votes |
@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>" ) ); }
Example #10
Source Project: webdrivermanager Author: bonigarcia File: VersionDetector.java License: Apache License 2.0 | 6 votes |
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; }
Example #11
Source Project: celos Author: collectivemedia File: JsonExpandConverter.java License: Apache License 2.0 | 6 votes |
@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"))); }
Example #12
Source Project: olingo-odata4 Author: apache File: AcceptHeaderAcceptCharsetHeaderITCase.java License: Apache License 2.0 | 6 votes |
@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.")); }
Example #13
Source Project: cukes Author: ctco File: OAuthTokenRetriever.java License: Apache License 2.0 | 6 votes |
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); }
Example #14
Source Project: yarg Author: cuba-platform File: FormattersSmokeTest.java License: Apache License 2.0 | 6 votes |
@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); }
Example #15
Source Project: ontopia Author: ontopia File: ReadOnlyOccurrence.java License: Apache License 2.0 | 6 votes |
@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 } }
Example #16
Source Project: takes Author: yegor256 File: XeDateTest.java License: MIT License | 6 votes |
/** * 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]" ) ); }
Example #17
Source Project: supplierShop Author: guchengwuyue File: ShiroConfig.java License: MIT License | 6 votes |
/** * 返回配置文件流 避免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); } }
Example #18
Source Project: jackrabbit-filevault Author: apache File: PackageManagerImpl.java License: Apache License 2.0 | 6 votes |
/** * {@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); } } }
Example #19
Source Project: openmrs-module-initializer Author: mekomsolutions File: InitializerServiceImplTest.java License: MIT License | 6 votes |
@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")); }
Example #20
Source Project: asciidoctorj Author: asciidoctor File: OptionsTest.java License: Apache License 2.0 | 6 votes |
@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[] }
Example #21
Source Project: studio Author: craftercms File: StrSubstitutorVisitor.java License: GNU General Public License v3.0 | 6 votes |
@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; } }
Example #22
Source Project: spliceengine Author: splicemachine File: ExportOperationIT.java License: GNU Affero General Public License v3.0 | 6 votes |
@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])))); }
Example #23
Source Project: fdroidclient Author: f-droid File: InstallHistoryActivity.java License: GNU General Public License v3.0 | 6 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_install_history); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitle(getString(R.string.install_history)); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); String text = ""; try { ContentResolver resolver = getContentResolver(); Cursor cursor = resolver.query(InstallHistoryService.LOG_URI, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); cursor.close(); } ParcelFileDescriptor pfd = resolver.openFileDescriptor(InstallHistoryService.LOG_URI, "r"); FileDescriptor fd = pfd.getFileDescriptor(); FileInputStream fileInputStream = new FileInputStream(fd); text = IOUtils.toString(fileInputStream, Charset.defaultCharset()); } catch (IOException | SecurityException | IllegalStateException e) { e.printStackTrace(); } TextView textView = findViewById(R.id.text); textView.setText(text); }
Example #24
Source Project: lemon Author: xuhuisheng File: HttpOpenClient.java License: Apache License 2.0 | 6 votes |
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; } }
Example #25
Source Project: apimanager-swagger-promote Author: Axway-API-Management-Plus File: APIManagerAdapter.java License: Apache License 2.0 | 6 votes |
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) {} } }
Example #26
Source Project: velocity-engine Author: apache File: ClassloaderChangeTestCase.java License: Apache License 2.0 | 5 votes |
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); }
Example #27
Source Project: jackrabbit-filevault Author: apache File: DefaultMetaInf.java License: Apache License 2.0 | 5 votes |
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); } } }
Example #28
Source Project: fess Author: codelibs File: ProcessHelper.java License: Apache License 2.0 | 5 votes |
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."); } }
Example #29
Source Project: javamoney-examples Author: JavaMoney File: MonetaryAmountCollectionReaderProvider.java License: Apache License 2.0 | 5 votes |
@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()); }
Example #30
Source Project: nifi-protobuf-processor Author: whiver File: SchemaParserTest.java License: MIT License | 5 votes |
@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())); } }