org.apache.commons.io.IOUtils Java Examples
The following examples show how to use
org.apache.commons.io.IOUtils.
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 File: OAuthTokenRetriever.java From cukes with 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 #2
Source File: JsonFilterReaderTest.java From knox with 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 #3
Source File: FormattersSmokeTest.java From yarg with 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 #4
Source File: ReadOnlyOccurrence.java From ontopia with 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 #5
Source File: ExportOperationIT.java From spliceengine with 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 #6
Source File: OptionsTest.java From asciidoctorj with 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 #7
Source File: TestConvertT2flowScufl2.java From incubator-taverna-language with 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 #8
Source File: FhirMetadataRetrievalTest.java From syndesis with 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 #9
Source File: CliHelpers.java From jobson with 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 #10
Source File: PackageManagerImpl.java From jackrabbit-filevault with 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 #11
Source File: InstallHistoryActivity.java From fdroidclient with 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 #12
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java From olingo-odata4 with 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 File: JsonExpandConverter.java From celos with 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 #14
Source File: VersionDetector.java From webdrivermanager with 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 #15
Source File: TestConfigurationParserTest.java From celos with 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 #16
Source File: APIManagerAdapter.java From apimanager-swagger-promote with 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 #17
Source File: ShiroConfig.java From supplierShop with 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 File: XeDateTest.java From takes with 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 #19
Source File: MCRTileCombineServlet.java From mycore with 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 #20
Source File: ZipUtils.java From youtubedl-android with 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 #21
Source File: PropertyHolder.java From framework with 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 #22
Source File: HttpOpenClient.java From lemon with 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 #23
Source File: InitializerServiceImplTest.java From openmrs-module-initializer with 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 #24
Source File: StrSubstitutorVisitor.java From studio with 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 #25
Source File: AbstractSpatialPrefixTreeFieldType.java From lucene-solr with 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 #26
Source File: MultipleUploadItems.java From elfinder-2.x-servlet with BSD 2-Clause "Simplified" License | 5 votes |
public void addItemProxy(final FileItemStream item) throws IOException { InputStream stream = item.openStream(); //ByteArrayOutputStream os = new ByteArrayOutputStream(); //create a temp source final File source = File.createTempFile("elfinder_upload_", "", _tempDir); FileOutputStream os = new FileOutputStream(source); IOUtils.copy(stream, os); os.close(); //final byte[] bs = os.toByteArray(); stream.close(); _logger.debug(String.format("saving item: %s", source.getCanonicalPath())); addItem((FileItemStream) Proxy.newProxyInstance(this.getClass() .getClassLoader(), new Class[]{FileItemStream.class, Finalizable.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("openStream".equals(method.getName())) { //return new ByteArrayInputStream(bs); return new FileInputStream(source); } if ("finalize".equals(method.getName())) { source.delete(); _logger.debug(String.format("removing item: %s", source.getCanonicalPath())); return null; } return method.invoke(item, args); } })); }
Example #27
Source File: RpsConsultaTest.java From nfse with MIT License | 5 votes |
@Test public void xmlDeveSerGeradoCorretamente() throws IOException{ String xmlTest = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("consultaRPS.xml")); RpsConsulta consultaRPS = new RpsConsulta(new RpsIdentificacao("1"), FabricaDeObjetosFake.getRpsPrestador()); String xml = consultaRPS.converterParaXml(); Assert.assertEquals(xml, xmlTest); }
Example #28
Source File: TextExporter.java From netbeans-mmd-plugin with Apache License 2.0 | 5 votes |
@Override public void doExport(@Nonnull final PluginContext context, @Nullable final JComponent options, @Nullable final OutputStream out) throws IOException { final String text = makeContent(context); File fileToSaveMap = null; OutputStream theOut = out; if (theOut == null) { fileToSaveMap = MindMapUtils.selectFileToSaveForFileFilter( context.getPanel(), this.getClass().getName(), Texts.getString("TextExporter.saveDialogTitle"), null, ".txt", Texts.getString("TextExporter.filterDescription"), Texts.getString("TextExporter.approveButtonText")); fileToSaveMap = MindMapUtils.checkFileAndExtension(context.getPanel(), fileToSaveMap, ".txt");//NOI18N theOut = fileToSaveMap == null ? null : new BufferedOutputStream(new FileOutputStream(fileToSaveMap, false)); } if (theOut != null) { try { IOUtils.write(text, theOut, "UTF-8"); } finally { if (fileToSaveMap != null) { IOUtils.closeQuietly(theOut); } } } }
Example #29
Source File: KafkaConsumer.java From attic-apex-malhar with Apache License 2.0 | 5 votes |
/** * The method is called in the deactivate method of the operator */ public void stop() { isAlive = false; statsSnapShot.stop(); holdingBuffer.clear(); IOUtils.closeQuietly(this); }
Example #30
Source File: ClassloaderChangeTestCase.java From velocity-engine with 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); }