List of usage examples for java.io OutputStreamWriter flush
public void flush() throws IOException
From source file:net.facework.core.http.ModAssetServer.java
@Override public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { AbstractHttpEntity body = null;//from w w w .j av a 2 s. c o m final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } final String url = URLDecoder.decode(request.getRequestLine().getUri()); if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length); } final String location = "www" + (url.equals("/") ? "/index.htm" : url); response.setStatusCode(HttpStatus.SC_OK); try { Log.i(TAG, "Requested: \"" + url + "\""); // Compares the Last-Modified date header (if present) with the If-Modified-Since date if (request.containsHeader("If-Modified-Since")) { try { Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue()); if (date.compareTo(mServer.mLastModified) <= 0) { // The file has not been modified response.setStatusCode(HttpStatus.SC_NOT_MODIFIED); return; } } catch (DateParseException e) { e.printStackTrace(); } } // We determine if the asset is compressed try { AssetFileDescriptor afd = mAssetManager.openFd(location); // The asset is not compressed FileInputStream fis = new FileInputStream(afd.getFileDescriptor()); fis.skip(afd.getStartOffset()); body = new InputStreamEntity(fis, afd.getDeclaredLength()); Log.d(TAG, "Serving uncompressed file " + "www" + url); } catch (FileNotFoundException e) { // The asset may be compressed // AAPT compresses assets so first we need to uncompress them to determine their length InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING); ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000); byte[] tmp = new byte[4096]; int length = 0; while ((length = stream.read(tmp)) != -1) buffer.write(tmp, 0, length); body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size()); stream.close(); Log.d(TAG, "Serving compressed file " + "www" + url); } body.setContentType(getMimeMediaType(url) + "; charset=UTF-8"); response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified)); } catch (IOException e) { // File does not exist response.setStatusCode(HttpStatus.SC_NOT_FOUND); body = new EntityTemplate(new ContentProducer() { @Override public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write("<html><body><h1>"); writer.write("File "); writer.write("www" + url); writer.write(" not found"); writer.write("</h1></body></html>"); writer.flush(); } }); Log.d(TAG, "File " + "www" + url + " not found"); body.setContentType("text/html; charset=UTF-8"); } response.setEntity(body); }
From source file:net.sf.jabref.importer.fileformat.FreeCiteImporter.java
public ParserResult importEntries(String text) { // URLencode the string for transmission String urlencodedCitation = null; try {/*from w w w. ja va2 s. c o m*/ urlencodedCitation = URLEncoder.encode(text, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { LOGGER.warn("Unsupported encoding", e); } // Send the request URL url; URLConnection conn; try { url = new URL("http://freecite.library.brown.edu/citations/create"); conn = url.openConnection(); } catch (MalformedURLException e) { LOGGER.warn("Bad URL", e); return new ParserResult(); } catch (IOException e) { LOGGER.warn("Could not download", e); return new ParserResult(); } try { conn.setRequestProperty("accept", "text/xml"); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); String data = "citation=" + urlencodedCitation; // write parameters writer.write(data); writer.flush(); } catch (IllegalStateException e) { LOGGER.warn("Already connected.", e); } catch (IOException e) { LOGGER.warn("Unable to connect to FreeCite online service.", e); return ParserResult .fromErrorMessage(Localization.lang("Unable to connect to FreeCite online service.")); } // output is in conn.getInputStream(); // new InputStreamReader(conn.getInputStream()) List<BibEntry> res = new ArrayList<>(); XMLInputFactory factory = XMLInputFactory.newInstance(); try { XMLStreamReader parser = factory.createXMLStreamReader(conn.getInputStream()); while (parser.hasNext()) { if ((parser.getEventType() == XMLStreamConstants.START_ELEMENT) && "citation".equals(parser.getLocalName())) { parser.nextTag(); StringBuilder noteSB = new StringBuilder(); BibEntry e = new BibEntry(); // fallback type EntryType type = BibtexEntryTypes.INPROCEEDINGS; while (!((parser.getEventType() == XMLStreamConstants.END_ELEMENT) && "citation".equals(parser.getLocalName()))) { if (parser.getEventType() == XMLStreamConstants.START_ELEMENT) { String ln = parser.getLocalName(); if ("authors".equals(ln)) { StringBuilder sb = new StringBuilder(); parser.nextTag(); while (parser.getEventType() == XMLStreamConstants.START_ELEMENT) { // author is directly nested below authors assert "author".equals(parser.getLocalName()); String author = parser.getElementText(); if (sb.length() == 0) { // first author sb.append(author); } else { sb.append(" and "); sb.append(author); } assert parser.getEventType() == XMLStreamConstants.END_ELEMENT; assert "author".equals(parser.getLocalName()); parser.nextTag(); // current tag is either begin:author or // end:authors } e.setField(FieldName.AUTHOR, sb.toString()); } else if (FieldName.JOURNAL.equals(ln)) { // we guess that the entry is a journal // the alternative way is to parse // ctx:context-objects / ctx:context-object / ctx:referent / ctx:metadata-by-val / ctx:metadata / journal / rft:genre // the drawback is that ctx:context-objects is NOT nested in citation, but a separate element // we would have to change the whole parser to parse that format. type = BibtexEntryTypes.ARTICLE; e.setField(ln, parser.getElementText()); } else if ("tech".equals(ln)) { type = BibtexEntryTypes.TECHREPORT; // the content of the "tech" field seems to contain the number of the technical report e.setField(FieldName.NUMBER, parser.getElementText()); } else if (FieldName.DOI.equals(ln) || "institution".equals(ln) || "location".equals(ln) || FieldName.NUMBER.equals(ln) || "note".equals(ln) || FieldName.TITLE.equals(ln) || FieldName.PAGES.equals(ln) || FieldName.PUBLISHER.equals(ln) || FieldName.VOLUME.equals(ln) || FieldName.YEAR.equals(ln)) { e.setField(ln, parser.getElementText()); } else if ("booktitle".equals(ln)) { String booktitle = parser.getElementText(); if (booktitle.startsWith("In ")) { // special treatment for parsing of // "In proceedings of..." references booktitle = booktitle.substring(3); } e.setField("booktitle", booktitle); } else if ("raw_string".equals(ln)) { // raw input string is ignored } else { // all other tags are stored as note noteSB.append(ln); noteSB.append(':'); noteSB.append(parser.getElementText()); noteSB.append(Globals.NEWLINE); } } parser.next(); } if (noteSB.length() > 0) { String note; if (e.hasField("note")) { // "note" could have been set during the parsing as FreeCite also returns "note" note = e.getFieldOptional("note").get().concat(Globals.NEWLINE) .concat(noteSB.toString()); } else { note = noteSB.toString(); } e.setField("note", note); } // type has been derived from "genre" // has to be done before label generation as label generation is dependent on entry type e.setType(type); // autogenerate label (BibTeX key) LabelPatternUtil.makeLabel( JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext().getMetaData(), JabRefGUI.getMainFrame().getCurrentBasePanel().getDatabase(), e, Globals.prefs); res.add(e); } parser.next(); } parser.close(); } catch (IOException | XMLStreamException ex) { LOGGER.warn("Could not parse", ex); return new ParserResult(); } return new ParserResult(res); }
From source file:com.cellbots.logger.localServer.LocalHttpServer.java
public void handle(final HttpServerConnection conn, final HttpContext context) throws HttpException, IOException { HttpRequest request = conn.receiveRequestHeader(); HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK"); String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST") && !method.equals("PUT")) { throw new MethodNotSupportedException(method + " method not supported"); }/*from w w w . j a va 2s . c om*/ // Get the requested target. This is the string after the domain name in // the URL. If the full URL was http://mydomain.com/test.html, target // will be /test.html. String target = request.getRequestLine().getUri(); // Log.w(TAG, "*** Request target: " + target); // Gets the requested resource name. For example, if the full URL was // http://mydomain.com/test.html?x=1&y=2, resource name will be // test.html final String resName = getResourceNameFromTarget(target); UrlParams params = new UrlParams(target); // Log.w(TAG, "*** Request LINE: " + // request.getRequestLine().toString()); // Log.w(TAG, "*** Request resource: " + resName); if (method.equals("POST") || method.equals("PUT")) { byte[] entityContent = null; // Gets the content if the request has an entity. if (request instanceof HttpEntityEnclosingRequest) { conn.receiveRequestEntity((HttpEntityEnclosingRequest) request); HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { entityContent = EntityUtils.toByteArray(entity); } } response.setStatusCode(HttpStatus.SC_OK); if (serverListener != null) { serverListener.onRequest(resName, params.keys, params.values, entityContent); } } else if (dataMap.containsKey(resName)) { // The requested resource is // a byte array response.setStatusCode(HttpStatus.SC_OK); response.setHeader("Content-Type", dataMap.get(resName).contentType); response.setEntity(new ByteArrayEntity(dataMap.get(resName).resource)); } else { // Return sensor readings String contentType = resourceMap.containsKey(resName) ? resourceMap.get(resName).contentType : "text/html"; response.setStatusCode(HttpStatus.SC_OK); EntityTemplate body = new EntityTemplate(new ContentProducer() { @Override public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write(serverListener.getLoggerStatus()); writer.flush(); } }); body.setContentType(contentType); response.setEntity(body); } conn.sendResponseHeader(response); conn.sendResponseEntity(response); conn.flush(); conn.shutdown(); }
From source file:com.cloudera.flume.master.FlumeMaster.java
/** * Used by internal web app for generating web page with master status * information./*from w ww .j a v a 2 s. co m*/ */ public String reportHtml() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter w = new OutputStreamWriter(baos); reportHtml(w); w.flush(); return baos.toString(); } catch (IOException e) { LOG.error("html report generation failed", e); } return ""; }
From source file:de.akquinet.engineering.vaadinator.timesheet.service.AbstractCouchDbService.java
protected JSONObject putCouch(String urlPart, JSONObject content) throws IOException, MalformedURLException, JSONException { HttpURLConnection couchConn = null; BufferedReader couchRead = null; OutputStreamWriter couchWrite = null; try {/*from w w w . j a va 2 s .c o m*/ couchConn = (HttpURLConnection) (new URL(couchUrl + (couchUrl.endsWith("/") ? "" : "/") + urlPart)) .openConnection(); couchConn.setRequestMethod("PUT"); couchConn.setDoInput(true); couchConn.setDoOutput(true); couchWrite = new OutputStreamWriter(couchConn.getOutputStream()); couchWrite.write(content.toString()); couchWrite.flush(); couchRead = new BufferedReader(new InputStreamReader(couchConn.getInputStream())); StringBuffer jsonBuf = new StringBuffer(); String line = couchRead.readLine(); while (line != null) { jsonBuf.append(line); line = couchRead.readLine(); } JSONObject couchObj = new JSONObject(jsonBuf.toString()); return couchObj; } finally { if (couchRead != null) { couchRead.close(); } if (couchWrite != null) { couchWrite.close(); } if (couchConn != null) { couchConn.disconnect(); } } }
From source file:com.doomy.padlock.MainFragment.java
public void superUserReboot(String mCommand) { Runtime mRuntime = Runtime.getRuntime(); Process mProcess = null;//from w w w. j av a 2 s . c o m OutputStreamWriter mWrite = null; try { mProcess = mRuntime.exec("su"); mWrite = new OutputStreamWriter(mProcess.getOutputStream()); mWrite.write(mCommand + "\n"); mWrite.flush(); mWrite.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.xpn.xwiki.plugin.packaging.AbstractPackageTest.java
private byte[] getEncodedByteArray(String content, String charset) throws IOException { StringReader rdr = new StringReader(content); BufferedReader bfr = new BufferedReader(rdr); ByteArrayOutputStream ostr = new ByteArrayOutputStream(); OutputStreamWriter os = new OutputStreamWriter(ostr, charset); // Voluntarily ignore the first line... as it's the xml declaration String line = bfr.readLine(); os.append("<?xml version=\"1.0\" encoding=\"" + charset + "\"?>\n"); line = bfr.readLine();/*from ww w .ja va 2 s . co m*/ while (null != line) { os.append(line); os.append("\n"); line = bfr.readLine(); } os.flush(); os.close(); return ostr.toByteArray(); }
From source file:org.dspace.license.CCLookup.java
/** * Passes a set of "answers" to the web service and retrieves a license. * * @param licenseId The identifier of the license class being requested. * @param answers A Map containing the answers to the license fields; * each key is the identifier of a LicenseField, with the value * containing the user-supplied answer. * @param lang The language to request localized elements in. * * @throws IOException//from w w w . ja va2 s. c om * * @see CCLicense * @see Map */ public void issue(String licenseId, Map answers, String lang) throws IOException { // Determine the issue URL String issueUrl = this.cc_root + "/license/" + licenseId + "/issue"; // Assemble the "answers" document String answer_doc = "<answers>\n<locale>" + lang + "</locale>\n" + "<license-" + licenseId + ">\n"; Iterator keys = answers.keySet().iterator(); try { String current = (String) keys.next(); while (true) { answer_doc += "<" + current + ">" + (String) answers.get(current) + "</" + current + ">\n"; current = (String) keys.next(); } } catch (NoSuchElementException e) { // exception indicates we've iterated through the // entire collection; just swallow and continue } // answer_doc += "<jurisdiction></jurisidiction>\n"; FAILS with jurisdiction argument answer_doc += "</license-" + licenseId + ">\n</answers>\n"; String post_data; try { post_data = URLEncoder.encode("answers", "UTF-8") + "=" + URLEncoder.encode(answer_doc, "UTF-8"); } catch (UnsupportedEncodingException e) { return; } URL post_url; try { post_url = new URL(issueUrl); } catch (MalformedURLException e) { return; } URLConnection connection = post_url.openConnection(); // this will not be needed after I'm done TODO: remove connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(post_data); writer.flush(); // end TODO try { // parsing document from input stream java.io.InputStream stream = connection.getInputStream(); this.license_doc = this.parser.build(stream); } catch (JDOMException jde) { log.warn(jde.getMessage()); } catch (Exception e) { log.warn(e.getCause()); } return; }
From source file:org.apache.wiki.ui.WikiJSPFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { WatchDog w = m_engine.getCurrentWatchDog(); try {/*from www . j a v a 2 s . c o m*/ NDC.push(m_engine.getApplicationName() + ":" + ((HttpServletRequest) request).getRequestURI()); w.enterState("Filtering for URL " + ((HttpServletRequest) request).getRequestURI(), 90); HttpServletResponseWrapper responseWrapper; if (m_useOutputStream) { log.debug("Using ByteArrayResponseWrapper"); responseWrapper = new ByteArrayResponseWrapper((HttpServletResponse) response, m_wiki_encoding); } else { log.debug("Using MyServletResponseWrapper"); responseWrapper = new MyServletResponseWrapper((HttpServletResponse) response, m_wiki_encoding); } // fire PAGE_REQUESTED event String pagename = DefaultURLConstructor.parsePageFromURL((HttpServletRequest) request, response.getCharacterEncoding()); fireEvent(WikiPageEvent.PAGE_REQUESTED, pagename); super.doFilter(request, responseWrapper, chain); // The response is now complete. Lets replace the markers now. // WikiContext is only available after doFilter! (That is after // interpreting the jsp) try { w.enterState("Delivering response", 30); WikiContext wikiContext = getWikiContext(request); String r = filter(wikiContext, responseWrapper); if (m_useOutputStream) { OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), response.getCharacterEncoding()); out.write(r); out.flush(); out.close(); } else { response.getWriter().write(r); } // Clean up the UI messages and loggers if (wikiContext != null) { wikiContext.getWikiSession().clearMessages(); } // fire PAGE_DELIVERED event fireEvent(WikiPageEvent.PAGE_DELIVERED, pagename); } finally { w.exitState(); } } finally { w.exitState(); NDC.pop(); NDC.remove(); } }
From source file:io.mapzone.arena.geocode.GeocodeServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/*from w w w.j ava 2 s .c om*/ EventManager.instance().publish(new ServletRequestEvent(getServletContext(), req)); if (req.getParameterMap().isEmpty()) { resp.sendError(400, "No parameters found! Please specify at least 'text'."); return; } GeocodeQuery query = extractQuery(req); // perform search List<Address> addresses = service.geocode(query); resp.setStatus(HttpStatus.SC_OK); resp.setContentType("application/json;charset=utf-8"); handleCors(req, resp); // convert addresses to result json OutputStreamWriter outputStreamWriter = new OutputStreamWriter(resp.getOutputStream()); JSONWriter writer = new JSONWriter(outputStreamWriter); writer.object(); writer.key("results"); writer.array(); for (Address address : addresses) { writer.value(toJSON(address)); } writer.endArray(); writer.endObject(); outputStreamWriter.flush(); outputStreamWriter.close(); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }