List of usage examples for org.apache.commons.io IOUtils write
public static void write(StringBuffer data, OutputStream output, String encoding) throws IOException
StringBuffer
to bytes on an OutputStream
using the specified character encoding. From source file:de.tudarmstadt.ukp.clarin.webanno.tsv.WebannoTsv3Writer.java
@Override public void process(JCas aJCas) throws AnalysisEngineProcessException { OutputStream docOS = null;//w w w . j a v a2 s . c o m try { docOS = getOutputStream(aJCas, filenameSuffix); setSlotLinkTypes(); setLinkMaps(aJCas); setTokenSentenceAddress(aJCas); setAmbiguity(aJCas); setSpanAnnotation(aJCas); setChainAnnotation(aJCas); setRelationAnnotation(aJCas); writeHeader(docOS); for (AnnotationUnit unit : units) { if (sentenceUnits.containsKey(unit)) { String[] sentWithNl = sentenceUnits.get(unit).split("\n"); IOUtils.write(LF + "#Text=" + sentWithNl[0] + LF, docOS, encoding); // if sentence contains new line character // GITHUB ISSUE 318: New line in sentence should be exported as is if (sentWithNl.length > 1) { for (int i = 0; i < sentWithNl.length - 1; i++) { IOUtils.write("#Text=" + sentWithNl[i + 1] + LF, docOS, encoding); } } } if (unit.isSubtoken) { IOUtils.write( unitsLineNumber.get(unit) + TAB + unit.begin + "-" + unit.end + TAB + unit.token + TAB, docOS, encoding); } else { IOUtils.write( unitsLineNumber.get(unit) + TAB + unit.begin + "-" + unit.end + TAB + unit.token + TAB, docOS, encoding); } for (String type : featurePerLayer.keySet()) { List<List<String>> annos = annotationsPerPostion.getOrDefault(type, new HashMap<>()) .getOrDefault(unit, new ArrayList<>()); List<String> merged = null; for (List<String> annofs : annos) { if (merged == null) { merged = annofs; } else { for (int i = 0; i < annofs.size(); i++) { merged.set(i, merged.get(i) + "|" + annofs.get(i)); } } } if (merged != null) { for (String anno : merged) { IOUtils.write(anno + TAB, docOS, encoding); } } // No annotation of this type in this layer else { // if type do not have a feature, if (featurePerLayer.get(type).size() == 0) { IOUtils.write("_" + TAB, docOS, encoding); } else { for (String feature : featurePerLayer.get(type)) { IOUtils.write("_" + TAB, docOS, encoding); } } } } IOUtils.write(LF, docOS, encoding); } } catch (Exception e) { throw new AnalysisEngineProcessException(e); } finally { closeQuietly(docOS); } }
From source file:io.selendroid.builder.SelendroidServerBuilder.java
File createAndAddCustomizedAndroidManifestToSelendroidServer() throws IOException, ShellCommandException, AndroidSdkException { String targetPackageName = applicationUnderTest.getBasePackage(); File tempdir = new File(FileUtils.getTempDirectoryPath() + File.separatorChar + targetPackageName + System.currentTimeMillis()); if (!tempdir.exists()) { tempdir.mkdirs();// w w w .j a v a 2 s . c o m } File customizedManifest = new File(tempdir, "AndroidManifest.xml"); log.info("Adding target package '" + targetPackageName + "' to " + customizedManifest.getAbsolutePath()); // add target package InputStream inputStream = getResourceAsStream(selendroidApplicationXmlTemplate); if (inputStream == null) { throw new SelendroidException("AndroidApplication.xml template file was not found."); } String content = IOUtils.toString(inputStream, Charset.defaultCharset().displayName()); // find the first occurance of "package" and appending the targetpackagename to begining int i = content.toLowerCase().indexOf("package"); int cnt = 0; for (; i < content.length(); i++) { if (content.charAt(i) == '\"') { cnt++; } if (cnt == 2) { break; } } content = content.substring(0, i) + "." + targetPackageName + content.substring(i); log.info("Final Manifest File:\n" + content); content = content.replaceAll(SELENDROID_TEST_APP_PACKAGE, targetPackageName); // Seems like this needs to be done if (content.contains(ICON)) { content = content.replaceAll(ICON, ""); } OutputStream outputStream = new FileOutputStream(customizedManifest); IOUtils.write(content, outputStream, Charset.defaultCharset().displayName()); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); // adding the xml to an empty apk CommandLine createManifestApk = new CommandLine(AndroidSdk.aapt()); createManifestApk.addArgument("package", false); createManifestApk.addArgument("-M", false); createManifestApk.addArgument(customizedManifest.getAbsolutePath(), false); createManifestApk.addArgument("-I", false); createManifestApk.addArgument(AndroidSdk.androidJar(), false); createManifestApk.addArgument("-F", false); createManifestApk.addArgument(tempdir.getAbsolutePath() + File.separatorChar + "manifest.apk", false); createManifestApk.addArgument("-f", false); log.info(ShellCommand.exec(createManifestApk, 20000L)); ZipFile manifestApk = new ZipFile( new File(tempdir.getAbsolutePath() + File.separatorChar + "manifest.apk")); ZipArchiveEntry binaryManifestXml = manifestApk.getEntry("AndroidManifest.xml"); File finalSelendroidServerFile = new File(tempdir.getAbsolutePath() + "selendroid-server.apk"); ZipArchiveOutputStream finalSelendroidServer = new ZipArchiveOutputStream(finalSelendroidServerFile); finalSelendroidServer.putArchiveEntry(binaryManifestXml); IOUtils.copy(manifestApk.getInputStream(binaryManifestXml), finalSelendroidServer); ZipFile selendroidPrebuildApk = new ZipFile(selendroidServer.getAbsolutePath()); Enumeration<ZipArchiveEntry> entries = selendroidPrebuildApk.getEntries(); for (; entries.hasMoreElements();) { ZipArchiveEntry dd = entries.nextElement(); finalSelendroidServer.putArchiveEntry(dd); IOUtils.copy(selendroidPrebuildApk.getInputStream(dd), finalSelendroidServer); } finalSelendroidServer.closeArchiveEntry(); finalSelendroidServer.close(); manifestApk.close(); log.info("file: " + finalSelendroidServerFile.getAbsolutePath()); return finalSelendroidServerFile; }
From source file:com.rest4j.generator.Generator.java
public void generate() throws Exception { ApiFactory fac = new ApiFactory(apiXml, null, null); for (String className : preprocessors) { Preprocessor p = (Preprocessor) Class.forName(className).newInstance(); fac.addPreprocessor(p);//from w w w.j ava 2 s .co m } Document xml = fac.getDocument(); preprocess(xml); URL url = getStylesheet(); String filename = "index.html"; for (TemplateParam param : params) { if (param.getName().equals("filename")) { filename = param.getValue(); } } Document doc = transform(xml, url); cleanupBeforePostprocess(doc.getDocumentElement()); if (postprocessingXSLT != null) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document composed = documentBuilder.newDocument(); org.w3c.dom.Element top = composed.createElementNS("http://rest4j.com/api-description", "top"); composed.appendChild(top); top.appendChild(composed.adoptNode(xml.getDocumentElement())); top.appendChild(composed.adoptNode(doc.getDocumentElement())); xml = null; doc = null; // free some mem doc = transform(composed, postprocessingXSLT); } if ("files".equals(doc.getDocumentElement().getLocalName())) { // break the result into files for (Node child : Util.it(doc.getDocumentElement().getChildNodes())) { if ("file".equals(child.getLocalName())) { if (child.getAttributes().getNamedItem("name") == null) { throw new IllegalArgumentException("Attribute name not found in <file>"); } String name = child.getAttributes().getNamedItem("name").getTextContent(); File file = new File(outputDir, name); file.getParentFile().mkdirs(); System.out.println("Write " + file.getAbsolutePath()); Attr copyFromAttr = (Attr) child.getAttributes().getNamedItem("copy-from"); if (copyFromAttr == null) { cleanupFinal((Element) child); if (child.getAttributes().getNamedItem("text") != null) { // plain-text output FileOutputStream fos = new FileOutputStream(file); try { IOUtils.write(child.getTextContent(), fos, "UTF-8"); } finally { IOUtils.closeQuietly(fos); } } else { output(child, file); } } else { String copyFrom = copyFromAttr.getValue(); URL asset = getClass().getClassLoader().getResource(copyFrom); if (asset == null) { asset = getClass().getResource(copyFrom); } if (asset == null) { File assetFile = new File(copyFrom); if (!assetFile.canRead()) { if (postprocessingXSLT != null) { asset = new URL(postprocessingXSLT, copyFrom); try { asset.openStream().close(); } catch (FileNotFoundException fnfe) { asset = null; } } if (asset == null) { asset = new URL(getStylesheet(), copyFrom); try { asset.openStream().close(); } catch (FileNotFoundException fnfe) { asset = null; } } if (asset == null) throw new IllegalArgumentException("File '" + copyFrom + "' specified by @copy-from not found in the classpath or filesystem"); } else { asset = assetFile.toURI().toURL(); } } InputStream is = asset.openStream(); OutputStream fos = new FileOutputStream(file); try { IOUtils.copy(is, fos); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } else if (child.getNodeType() == Node.ELEMENT_NODE) { throw new IllegalArgumentException("Something but <file> found inside <files>"); } } } else { File file = new File(outputDir, filename); System.out.println("Write " + file.getAbsolutePath()); cleanupFinal(doc.getDocumentElement()); DOMSource source = new DOMSource(doc); FileOutputStream fos = new FileOutputStream(file); try { StreamResult result = new StreamResult(fos); Transformer trans = tFactory.newTransformer(); trans.transform(source, result); } finally { IOUtils.closeQuietly(fos); } } }
From source file:com.haulmont.cuba.core.app.filestorage.FileStorage.java
protected synchronized void writeLog(File file, boolean remove) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); StringBuilder sb = new StringBuilder(); sb.append(df.format(timeSource.currentTimestamp())).append(" "); sb.append("[").append(userSessionSource.getUserSession().getUser()).append("] "); sb.append(remove ? "REMOVE" : "CREATE").append(" "); sb.append("\"").append(file.getAbsolutePath()).append("\"\n"); File rootDir;/*from w ww.j a v a 2 s . c o m*/ try { rootDir = file.getParentFile().getParentFile().getParentFile().getParentFile(); } catch (NullPointerException e) { log.error("Unable to write log: invalid file storage structure", e); return; } File logFile = new File(rootDir, "storage.log"); try { try (FileOutputStream fos = new FileOutputStream(logFile, true)) { IOUtils.write(sb.toString(), fos, StandardCharsets.UTF_8.name()); } } catch (IOException e) { log.error("Unable to write log", e); } }
From source file:com.igormaznitsa.mindmap.exporters.TextExporter.java
@Override public void doExport(final MindMapPanel panel, final JComponent options, final OutputStream out) throws IOException { final State state = new State(); state.append("# Generated by NB Mind Map Plugin (https://github.com/raydac/netbeans-mmd-plugin)") .nextLine();//NOI18N state.append("# ").append(new Timestamp(new java.util.Date().getTime()).toString()).nextLine().nextLine();//NOI18N int shift = 0; final Topic root = panel.getModel().getRoot(); if (root != null) { writeTopic(root, '=', shift, state);//NOI18N shift += SHIFT_STEP;/*from w ww . j a v a 2 s . co m*/ final Topic[] children = Utils.getLeftToRightOrderedChildrens(root); for (final Topic t : children) { writeInterTopicLine(state); writeTopic(t, '-', shift, state); shift += SHIFT_STEP; for (final Topic tt : t.getChildren()) { writeOtherTopicRecursively(tt, shift, state); } shift -= SHIFT_STEP; } } final String text = state.toString(); File fileToSaveMap = null; OutputStream theOut = out; if (theOut == null) { fileToSaveMap = selectFileForFileFilter(panel, BUNDLE.getString("TextExporter.saveDialogTitle"), ".txt", BUNDLE.getString("TextExporter.filterDescription"), BUNDLE.getString("TextExporter.approveButtonText")); fileToSaveMap = checkFileAndExtension(panel, 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); } } } }
From source file:ch.cyberduck.core.s3.S3SingleUploadServiceTest.java
@Test public void testUploadWithSHA256Checksum() throws Exception { final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(), new Credentials(System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")))) { };//from ww w.j a v a2s. com session.open(new DisabledHostKeyCallback()); session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback()); final S3SingleUploadService service = new S3SingleUploadService(session, new S3WriteFeature(session, new S3DisabledMultipartService())); final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final String name = UUID.randomUUID().toString() + ".txt"; final Path test = new Path(container, name, EnumSet.of(Path.Type.file)); final Local local = new Local(System.getProperty("java.io.tmpdir"), name); final String random = new RandomStringGenerator.Builder().build().generate(1000); final OutputStream out = local.getOutputStream(false); IOUtils.write(random, out, Charset.defaultCharset()); out.close(); final TransferStatus status = new TransferStatus(); status.setLength(random.getBytes().length); status.setMime("text/plain"); service.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), status, new DisabledLoginCallback()); assertTrue(new S3FindFeature(session).find(test)); final PathAttributes attributes = new S3AttributesFinderFeature(session).find(test); assertEquals(random.getBytes().length, attributes.getSize()); final Map<String, String> metadata = new S3MetadataFeature(session, new S3AccessControlListFeature(session)) .getMetadata(test); assertFalse(metadata.isEmpty()); assertEquals("text/plain", metadata.get("Content-Type")); new S3DefaultDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); local.delete(); session.close(); }