List of usage examples for java.io OutputStreamWriter flush
public void flush() throws IOException
From source file:org.opendatakit.odktables.entity.serialization.SimpleHTMLMessageWriter.java
@Override public void writeTo(T o, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> map, OutputStream rawStream) throws IOException, WebApplicationException { String encoding = getCharsetAsString(mediaType); try {//from w w w . ja va2 s . c o m if (!encoding.equalsIgnoreCase(DEFAULT_ENCODING)) { throw new IllegalArgumentException("charset for the response is not utf-8"); } // write it to a byte array ByteArrayOutputStream bas = new ByteArrayOutputStream(8192); OutputStreamWriter w = new OutputStreamWriter(bas, Charset.forName(ApiConstants.UTF8_ENCODE)); w.write("<html><head></head><body>"); w.write(mapper.writeValueAsString(o)); w.write("</body></html>"); w.flush(); w.close(); // get the array byte[] bytes = bas.toByteArray(); map.putSingle(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION); map.putSingle("Access-Control-Allow-Origin", "*"); map.putSingle("Access-Control-Allow-Credentials", "true"); rawStream.write(bytes); rawStream.flush(); rawStream.close(); } catch (Exception e) { throw new IOException(e); } }
From source file:org.apache.orc.tools.FileDump.java
static void printJsonData(final Reader reader) throws IOException, JSONException { PrintStream printStream = System.out; OutputStreamWriter out = new OutputStreamWriter(printStream, "UTF-8"); RecordReader rows = reader.rows();//from w ww .ja v a2s . c o m try { TypeDescription schema = reader.getSchema(); VectorizedRowBatch batch = schema.createRowBatch(); while (rows.nextBatch(batch)) { for (int r = 0; r < batch.size; ++r) { JSONWriter writer = new JSONWriter(out); printRow(writer, batch, schema, r); out.write("\n"); out.flush(); if (printStream.checkError()) { throw new IOException("Error encountered when writing to stdout."); } } } } finally { rows.close(); } }
From source file:org.huahinframework.manager.rest.service.PigService.java
/** * @param out// www . j a v a 2 s . com * @param status * @throws IOException */ private void error(OutputStreamWriter out, String status) throws IOException { Map<String, String> m = new HashMap<String, String>(); m.put(Response.STATUS, status); out.write(new JSONObject(m).toString()); out.flush(); out.close(); return; }
From source file:org.apache.olingo.fit.utils.FSManager.java
public void putInMemory(final ResWrap<Entity> container, final String relativePath) throws IOException, ODataSerializerException { ByteArrayOutputStream content = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING); new AtomSerializer(true).write(writer, container); writer.flush(); putInMemory(new ByteArrayInputStream(content.toByteArray()), getAbsolutePath(relativePath, Accept.ATOM)); content.reset();// w w w .j ava 2 s . co m new JsonSerializer(true, ContentType.JSON_FULL_METADATA).write(writer, container); writer.flush(); putInMemory(new ByteArrayInputStream(content.toByteArray()), getAbsolutePath(relativePath, Accept.JSON_FULLMETA)); }
From source file:com.commerce4j.storefront.controllers.CartController.java
@SuppressWarnings("unchecked") public void update(HttpServletRequest request, HttpServletResponse response) { Gson gson = new GsonBuilder().create(); List<Message> errors = new ArrayList<Message>(); Map<String, Object> responseModel = new HashMap<String, Object>(); List<CartDTO> cartEntries = getCart(request); Iterator inputSet = request.getParameterMap().keySet().iterator(); while (inputSet.hasNext()) { String paramName = (String) inputSet.next(); if (StringUtils.contains(paramName, "qty")) { String paramValue = request.getParameter(paramName); String paramId = StringUtils.substring(paramName, 4, paramName.length()); if (paramId != null && StringUtils.isNumeric(paramId)) { for (CartDTO cartEntry : cartEntries) { int entryId = cartEntry.getItem().getItemId().intValue(); int itemId = new Integer(paramId).intValue(); int cartQuantity = new Integer(paramValue).intValue(); if (entryId == itemId) { cartEntry.setCartQuantity(cartQuantity); cartEntry.setCartSubTotal(cartEntry.getItem().getItemPrice() * cartQuantity); break; }/*from w w w . j a v a2s. co m*/ } } } } // fill response model if (errors.isEmpty()) { responseModel.put("responseCode", SUCCESS); responseModel.put("responseMessage", "Cart succesfully updated"); } else { responseModel.put("responseCode", FAILURE); responseModel.put("responseMessage", "Error, Cart was not updated"); responseModel.put("errors", errors); } // serialize output try { response.setContentType("application/json"); OutputStreamWriter os = new OutputStreamWriter(response.getOutputStream()); String data = gson.toJson(responseModel); os.write(data); os.flush(); os.close(); } catch (IOException e) { logger.fatal(e); } }
From source file:org.apache.olingo.fit.utils.XMLElement.java
public InputStream toStream() { InputStream res;/*www. j a va 2 s . co m*/ try { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final OutputStreamWriter osw = new OutputStreamWriter(bos, Constants.ENCODING); getStart().writeAsEncodedUnicode(osw); IOUtils.copy(getContent(), osw, Constants.ENCODING); getEnd().writeAsEncodedUnicode(osw); osw.flush(); osw.close(); res = new ByteArrayInputStream(bos.toByteArray()); } catch (IOException e) { LOG.error("Error serializing element", e); res = null; } catch (XMLStreamException e) { LOG.error("Error serializing element", e); res = null; } return res; }
From source file:com.commerce4j.storefront.controllers.CartController.java
/** * @param request// w w w. j a va 2 s . c om * @param response */ public void add(HttpServletRequest request, HttpServletResponse response) { Gson gson = new GsonBuilder().create(); List<Message> errors = new ArrayList<Message>(); Map<String, Object> responseModel = new HashMap<String, Object>(); String item = request.getParameter("item"); String quantity = request.getParameter("quantity"); if (StringUtils.isEmpty(item)) { errors.add(newError("item", getString("errors.notEmpty"), new Object[] { "item" })); } // find item ItemDTO itemDTO = getItemDSO().findById(new Integer(item)); if (item == null) errors.add(newError("item", getString("errors.notEmpty"), new Object[] { "item" })); // check cart in session List<CartDTO> cartEntries = getCart(request); // create cart entry String cartId = request.getSession().getId(); Integer iQuantity = new Integer(quantity); Double subtotal = itemDTO.getItemPrice() * iQuantity; CartDTO cartDTO = new CartDTO(cartId, itemDTO, iQuantity, subtotal); cartEntries.add(cartDTO); // persist session request.getSession().setAttribute("cart", cartEntries); // fill response model if (errors.isEmpty()) { responseModel.put("responseCode", SUCCESS); responseModel.put("responseMessage", "Item Added to Cart"); } else { responseModel.put("responseCode", FAILURE); responseModel.put("responseMessage", "Error, item was not added"); responseModel.put("errors", errors); } // serialize output try { response.setContentType("application/json"); OutputStreamWriter os = new OutputStreamWriter(response.getOutputStream()); String data = gson.toJson(responseModel); os.write(data); os.flush(); os.close(); } catch (IOException e) { logger.fatal(e); } }
From source file:org.wcy123.ProtobufMessageConverter.java
@Override protected void writeInternal(Message message, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { MediaType contentType = outputMessage.getHeaders().getContentType(); Charset charset = getCharset(contentType); if (MediaType.TEXT_HTML.isCompatibleWith(contentType)) { throw new UnsupportedOperationException("not supported yet"); } else if (MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) { final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset); printer.appendTo(message, outputStreamWriter); outputStreamWriter.flush(); } else if (MediaType.TEXT_PLAIN.isCompatibleWith(contentType)) { final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset); TextFormat.print(message, outputStreamWriter); outputStreamWriter.flush();/* w w w .ja v a 2 s. c om*/ } else if (MediaType.APPLICATION_XML.isCompatibleWith(contentType)) { throw new UnsupportedOperationException("not supported yet"); } else if (PROTOBUF.isCompatibleWith(contentType)) { setProtoHeader(outputMessage, message); FileCopyUtils.copy(message.toByteArray(), outputMessage.getBody()); } }
From source file:eu.comvantage.dataintegration.SparulSimulationServlet.java
private void simulateEvent(String eventID, String endpoint) { //container for the final SPARUL update command including header information String body = ""; //additional body information for the SPARUL update command //try to encode the SPARUL update command string with UTF-8 String temp = ""; Gson gson = new Gson(); //simulation of a correct request if (eventID.equalsIgnoreCase("sparul1")) { temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, " + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket0070071239swd\"}, " + "{\"name\":\"person\", \"value\":\"ex:nn00110011\"}]" + "}"; }/*from ww w. j a v a 2s. c om*/ //simulation of invalid template id for client else if (eventID.equalsIgnoreCase("sparul2")) { temp = "{ " + "\"Template\" : 8, " + "\"Client\" : 1, " + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket008008123swd\"}, " + "{\"name\":\"person\", \"value\":\"ex:nn1234567\"}]" + "}"; } //simulation of invalid client id else if (eventID.equalsIgnoreCase("sparul3")) { temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 3, " + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket000000000swd\"}, " + "{\"name\":\"person\", \"value\":\"ex:nn55555\"}]" + "}"; } //simulation of invalid parameter for specified template else if (eventID.equalsIgnoreCase("sparul4")) { temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, " + "\"Params\" : [{\"name\":\"bla\", \"value\":\"ex:Ticket98761234swd\"}, " + "{\"name\":\"person\", \"value\":\"ex:nn223344\"}]" + "}"; } //simulation of invalid parameter for specified template else if (eventID.equalsIgnoreCase("sparul5")) { temp = "{ " + "\"Templates\" : 1, " + "\"Clients\" : 1, " + "\"Param\" : [{\"name\":\"bla\", \"value\":\"ex:Ticket98761234swd\"}, " + "{\"name\":\"person\", \"value\":\"ex:nn223344\"}]" + "}"; } //malformed json else if (eventID.equalsIgnoreCase("sparul6")) { temp = "blabla"; } //simulation of a correct request else if (eventID.equalsIgnoreCase("sparul7")) { temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, " + "\"Params\" : [{\"name\":\"templateId\", \"value\":\"tee:Ticket0070071239swd\"}], " + "}"; //test of the long statement parameters of file client1_test0 } else if (eventID.equalsIgnoreCase("sparul8")) { temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, " + "\"Params\" : [{\"name\":\"templateId\", \"value\":\"tee:test1\"}, " + "{\"name\":\"reportId\", \"value\":\"1\"}," + "{\"name\":\"device1\", \"value\":\"tee:test2\"}," + "{\"name\":\"device2\", \"value\":\"tee:test3\"}," + "{\"name\":\"device3\", \"value\":\"tee:test4\"}]" + "}"; } //body = gson.toJson(temp); body = temp; //try to execute the SPARUL update command try { //insertion is done by a manual HTTP post HttpPost httpPost = new HttpPost(endpoint); //put SPARUL update command to output stream ByteArrayOutputStream b_out = new ByteArrayOutputStream(); OutputStreamWriter wr = new OutputStreamWriter(b_out); wr.write(body); wr.flush(); //transform output stream and modify header information for HTTP post byte[] bytes = b_out.toByteArray(); AbstractHttpEntity reqEntity = new ByteArrayEntity(bytes); reqEntity.setContentType("application/x-www-form-urlencoded"); reqEntity.setContentEncoding(HTTP.UTF_8); httpPost.setEntity(reqEntity); httpPost.setHeader("role", "http://www.comvantage.eu/ontologies/ac-schema/cv_wp6_comau_employee"); HttpClient httpclient = new DefaultHttpClient(); // //set proxy if defined // if(System.getProperty("http.proxyHost") != null) { // HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost"), Integer.valueOf(System.getProperty("http.proxyPort")), "http"); // httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); // } try { //execute the HTTP put System.out.println( "SparulSimulationServlet: Event '" + eventID + "' simulated at endpoint " + endpoint); HttpResponse response = httpclient.execute(httpPost); //handle different server responses and failures int responseCode = response.getStatusLine().getStatusCode(); String responseMessage = response.getStatusLine().getReasonPhrase(); System.out.println("SparulSimulationServlet: Response = " + responseCode + ", " + responseMessage); //close the output stream wr.close(); } catch (IOException ex) { throw new Exception(ex); } } catch (Exception e) { e.printStackTrace(); } }