List of usage examples for java.io Writer flush
public abstract void flush() throws IOException;
From source file:annis.gui.exporter.CSVExporter.java
@Override public boolean convertText(String queryAnnisQL, int contextLeft, int contextRight, Set<String> corpora, List<String> keys, String argsAsString, WebResource annisResource, Writer out, EventBus eventBus) { //this is a full result export try {/*from w w w . j av a 2 s.c o m*/ WebResource res = annisResource.path("search").path("matrix").queryParam("csv", "true") .queryParam("corpora", StringUtils.join(corpora, ",")) .queryParam("q", Helper.encodeJersey(queryAnnisQL)); if (argsAsString.startsWith("metakeys=")) { res = res.queryParam("metakeys", argsAsString.substring("metakeys".length() + 1)); } try (InputStream result = res.get(InputStream.class)) { IOUtils.copy(result, out); } out.flush(); return true; } catch (UniformInterfaceException ex) { log.error(null, ex); Notification n = new Notification("Service exception", ex.getResponse().getEntity(String.class), Notification.Type.WARNING_MESSAGE, true); n.show(Page.getCurrent()); } catch (ClientHandlerException ex) { log.error(null, ex); } catch (IOException ex) { log.error(null, ex); } return false; }
From source file:com.android.emailcommon.internet.Rfc822Output.java
/** * Write the body text. If only one version of the body is specified (either plain text * or HTML), the text is written directly. Otherwise, the plain text and HTML bodies * are both written with the appropriate headers. * * Note this always uses base64, even when not required. Slightly less efficient for * US-ASCII text, but handles all formats even when non-ascii chars are involved. A small * optimization might be to prescan the string for safety and send raw if possible. * * @param writer the output writer/*from ww w.j a v a 2 s . co m*/ * @param out the output stream inside the writer (used for byte[] access) * @param bodyText Plain text and HTML versions of the original text of the message */ private static void writeTextWithHeaders(Writer writer, OutputStream out, String[] bodyText) throws IOException { String text = bodyText[INDEX_BODY_TEXT]; String html = bodyText[INDEX_BODY_HTML]; if (text == null) { writer.write("\r\n"); // a truly empty message } else { String multipartBoundary = null; boolean multipart = html != null; // Simplified case for no multipart - just emit text and be done. if (multipart) { // continue with multipart headers, then into multipart body multipartBoundary = getNextBoundary(); writeHeader(writer, "Content-Type", "multipart/alternative; boundary=\"" + multipartBoundary + "\""); // Finish headers and prepare for body section(s) writer.write("\r\n"); writeBoundary(writer, multipartBoundary, false); } // first multipart element is the body writeHeader(writer, "Content-Type", "text/plain; charset=utf-8"); writeHeader(writer, "Content-Transfer-Encoding", "base64"); writer.write("\r\n"); byte[] textBytes = text.getBytes("UTF-8"); writer.flush(); out.write(Base64.encode(textBytes, Base64.CRLF)); if (multipart) { // next multipart section writeBoundary(writer, multipartBoundary, false); writeHeader(writer, "Content-Type", "text/html; charset=utf-8"); writeHeader(writer, "Content-Transfer-Encoding", "base64"); writer.write("\r\n"); byte[] htmlBytes = html.getBytes("UTF-8"); writer.flush(); out.write(Base64.encode(htmlBytes, Base64.CRLF)); // end of multipart section writeBoundary(writer, multipartBoundary, true); } } }
From source file:com.joliciel.jochre.search.JochreIndexBuilderImpl.java
private void updateDocumentInternal(File documentDir) { try {/* w w w .ja v a 2s . c o m*/ LOG.info("Updating index for " + documentDir.getName()); File zipFile = new File(documentDir, documentDir.getName() + ".zip"); if (!zipFile.exists()) { LOG.info("Nothing to index in " + documentDir.getName()); return; } long zipDate = zipFile.lastModified(); this.deleteDocumentInternal(documentDir); File[] offsetFiles = documentDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".obj"); } }); for (File offsetFile : offsetFiles) { offsetFile.delete(); } int i = 0; Map<String, String> fields = new TreeMap<String, String>(); File metaDataFile = new File(documentDir, "metadata.txt"); Scanner scanner = new Scanner( new BufferedReader(new InputStreamReader(new FileInputStream(metaDataFile), "UTF-8"))); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String key = line.substring(0, line.indexOf('\t')); String value = line.substring(line.indexOf('\t')); fields.put(key, value); } scanner.close(); JochreXmlDocument xmlDoc = this.searchService.newDocument(); JochreXmlReader reader = this.searchService.getJochreXmlReader(xmlDoc); ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze = null; while ((ze = zis.getNextEntry()) != null) { LOG.debug("Adding zipEntry " + i + ": " + ze.getName()); String baseName = ze.getName().substring(0, ze.getName().lastIndexOf('.')); UnclosableInputStream uis = new UnclosableInputStream(zis); reader.parseFile(uis, baseName); i++; } zis.close(); i = 0; StringBuilder sb = new StringBuilder(); coordinateStorage = searchService.getCoordinateStorage(); offsetLetterMap = new HashMap<Integer, JochreXmlLetter>(); int startPage = -1; int endPage = -1; int docCount = 0; int wordCount = 0; int cumulWordCount = 0; for (JochreXmlImage image : xmlDoc.getImages()) { if (startPage < 0) startPage = image.getPageIndex(); endPage = image.getPageIndex(); int remainingWords = xmlDoc.wordCount() - (cumulWordCount + wordCount); LOG.debug("Word count: " + wordCount + ", cumul word count: " + cumulWordCount + ", total xml words: " + xmlDoc.wordCount() + ", remaining words: " + remainingWords); if (wordsPerDoc > 0 && wordCount >= wordsPerDoc && remainingWords >= wordsPerDoc) { LOG.debug("Creating new index doc: " + docCount); JochreIndexDocument indexDoc = searchService.newJochreIndexDocument(documentDir, docCount, sb, coordinateStorage, startPage, endPage, fields); indexDoc.save(indexWriter); docCount++; sb = new StringBuilder(); coordinateStorage = searchService.getCoordinateStorage(); startPage = image.getPageIndex(); offsetLetterMap = new HashMap<Integer, JochreXmlLetter>(); cumulWordCount += wordCount; wordCount = 0; } LOG.debug("Processing page: " + image.getFileNameBase()); File imageFile = null; for (String imageExtension : imageExtensions) { imageFile = new File(documentDir, image.getFileNameBase() + "." + imageExtension); if (imageFile.exists()) break; imageFile = null; } if (imageFile == null) throw new RuntimeException("No image found in directory " + documentDir.getAbsolutePath() + ", baseName " + image.getFileNameBase()); coordinateStorage.addImage(sb.length(), imageFile.getName(), image.getPageIndex()); for (JochreXmlParagraph par : image.getParagraphs()) { coordinateStorage.addParagraph(sb.length(), new Rectangle(par.getLeft(), par.getTop(), par.getRight(), par.getBottom())); for (JochreXmlRow row : par.getRows()) { coordinateStorage.addRow(sb.length(), new Rectangle(row.getLeft(), row.getTop(), row.getRight(), row.getBottom())); int k = 0; for (JochreXmlWord word : row.getWords()) { wordCount++; for (JochreXmlLetter letter : word.getLetters()) { offsetLetterMap.put(sb.length(), letter); if (letter.getText().length() > 1) { for (int j = 1; j < letter.getText().length(); j++) { offsetLetterMap.put(sb.length() + j, letter); } } sb.append(letter.getText()); } k++; boolean finalDash = false; if (k == row.getWords().size() && word.getText().endsWith("-") && word.getText().length() > 1) finalDash = true; if (!finalDash) sb.append(" "); } } sb.append("\n"); } i++; } JochreIndexDocument indexDoc = searchService.newJochreIndexDocument(documentDir, docCount, sb, coordinateStorage, startPage, endPage, fields); indexDoc.save(indexWriter); File lastIndexDateFile = new File(documentDir, "indexDate.txt"); Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(lastIndexDateFile, false), "UTF8")); writer.write("" + zipDate); writer.flush(); writer.close(); } catch (IOException ioe) { LogUtils.logError(LOG, ioe); throw new RuntimeException(ioe); } }
From source file:com.joliciel.csvLearner.utils.FScoreCalculator.java
public void writeScoresToCSVFile(File fscoreFile) { try {// w w w . ja v a 2s. c o m fscoreFile.delete(); fscoreFile.createNewFile(); Writer fscoreFileWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(fscoreFile, false), "UTF8")); try { this.writeScoresToCSV(fscoreFileWriter); } finally { fscoreFileWriter.flush(); fscoreFileWriter.close(); } } catch (IOException ioe) { throw new RuntimeException(ioe); } }
From source file:de.tudarmstadt.ukp.dkpro.core.io.web1t.util.Web1TFileSplitter.java
public void split() throws IOException { Map<String, String> letterToFileNameMap = mapStartingLettersToFilenames(); Map<String, File> fileMap = mapFileNamesToFileHandels(letterToFileNameMap); Map<File, BufferedWriter> fileHandleToBufferdWriterMap = mapFileHandelsToWriterHandels(fileMap); Map<String, BufferedWriter> writerMap = mapFileNamesToWriterHandels(fileMap, fileHandleToBufferdWriterMap); splittedFiles = generateListOfUniqueFiles(fileMap); BufferedReader reader = null; try {/*from w w w . j a v a 2 s. c o m*/ reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), fileEncoding)); String TAB = "\t"; String LF = "\n"; String readLine = null; while ((readLine = reader.readLine()) != null) { int indexOfTab = readLine.indexOf(TAB); if (indexOfTab == -1) { log.warn("No tab found in line: " + readLine); continue; } String key = Web1TUtil.getStartingLetters(readLine, indexOfTab); Writer writer = writerMap.get(key); if (writer == null) { log.warn("No writer found for key: " + key); key = key.substring(0, 1); writer = writerMap.get(key); if (writer == null) { log.warn("No writer for key: " + key); continue; } } writer.write(readLine); writer.write(LF); writer.flush(); } } finally { // Close reader IOUtils.closeQuietly(reader); // Close all writers for (Writer writer : writerMap.values()) { IOUtils.closeQuietly(writer); } } }
From source file:com.joliciel.csvLearner.features.BestFeatureFinder.java
public void writeBestFeatures(Writer writer, Map<String, Collection<NameValuePair>> bestFeatures) { try {//from w w w . j av a 2s. co m for (Entry<String, Collection<NameValuePair>> entry : bestFeatures.entrySet()) { writer.append(CSVFormatter.format(entry.getKey()) + ","); for (NameValuePair pair : entry.getValue()) { if (!pair.getName().equals(TOTAL_ENTROPY)) writer.append(CSVFormatter.format(pair.getName()) + ","); writer.append(CSVFormatter.format(pair.getValue()) + ","); } writer.append("\n"); writer.flush(); } } catch (IOException ioe) { throw new RuntimeException(ioe); } }
From source file:net.pandoragames.far.ui.FARConfigurationFactory.java
/** * Adds a decent header for property files * @param stream to be written to/* w w w .ja v a 2 s . c o m*/ * @param comment may span multiple lines * @throws IOException in case of */ private void writeCommentHeader(OutputStream stream, String comment) throws IOException { Writer writer = new OutputStreamWriter(stream, "ISO-8859-1"); String[] commentLines = comment.split("\\n"); writer.write("##\n"); for (String line : commentLines) { writer.write("# "); writer.write(line); writer.write("\n"); } writer.write("##\n"); writer.flush(); }
From source file:org.artifactory.engine.SuccessfulDeploymentResponseHelper.java
/** * Writes the spec implementation response * * @param repoService Instance of repo service * @param response Response object/*from www.j av a2 s . co m*/ * @param repoPath Repo path of deployed artifact * @param url Final reachable URI of deployed file */ public void writeSuccessfulDeploymentResponse(InternalRepositoryService repoService, ArtifactoryResponse response, RepoPath repoPath, String url, boolean isDirectory) throws IOException { Writer writer = response.getWriter(); response.setHeader(HttpHeaders.LOCATION, url); response.setStatus(HttpStatus.SC_CREATED); response.setContentType(ArtifactRestConstants.MT_ITEM_CREATED); RestBaseStorageInfo storageInfo; if (isDirectory) { storageInfo = getFolderInfo(repoService, repoPath, url); } else { storageInfo = getFileInfo(repoService, repoPath, url); } JsonGenerator jsonGenerator = JacksonFactory.createJsonGenerator(writer); jsonGenerator.writeObject(storageInfo); jsonGenerator.close(); writer.flush(); }
From source file:com.sun.faban.harness.webclient.CLIServlet.java
private void sendStatus(String[] reqC, HttpServletResponse response) throws IOException { if (reqC.length < 2) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing RunId."); return;//from ww w . j a v a 2 s .com } String runId = reqC[1]; String status = RunResult.getStatus(new RunId(runId)); if (status == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "No such runId: " + runId); } else { Writer w = response.getWriter(); w.write(status + '\n'); w.flush(); w.close(); } }