List of usage examples for java.io ByteArrayOutputStream flush
public void flush() throws IOException
From source file:com.cloudant.tests.AttachmentsTest.java
@Test public void attachmentStandalone() throws IOException, URISyntaxException { byte[] bytesToDB = "binary data".getBytes(); ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesToDB); Response response = db.saveAttachment(bytesIn, "foo.txt", "text/plain"); Document doc = db.find(Document.class, response.getId()); assertTrue(doc.getAttachments().containsKey("foo.txt")); HttpConnection conn = Http/*from w w w . ja va2 s. com*/ .GET(new DatabaseURIHelper(db.getDBUri()).attachmentUri(response.getId(), "foo.txt")); InputStream in = clientResource.get().executeRequest(conn).responseAsInputStream(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); int n; while ((n = in.read()) != -1) { bytesOut.write(n); } bytesOut.flush(); in.close(); byte[] bytesFromDB = bytesOut.toByteArray(); assertArrayEquals(bytesToDB, bytesFromDB); }
From source file:com.sishistorico.sv.SvCadastraEleitor.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww.j av a 2 s .c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF8"); response.setContentType("text/html;charset=UTF-8"); List<FileItem> items = null; byte[] foto = null; try { items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { InputStream imageInput = item.getInputStream(); Image image = ImageIO.read(imageInput); BufferedImage thumb = Imagem.redimensionar(image, 400, 500); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(thumb, "JPG", baos); baos.flush(); foto = baos.toByteArray(); baos.close(); } } //dados do formulrio e metodos para salvar DateFormat formatter; Date date; formatter = new SimpleDateFormat("dd/MM/yyyy"); date = (Date) formatter.parse(items.get(1).getString()); // fim do tratamento Eleitor el = new Eleitor(); Endereco end = new Endereco(); el.setNome(items.get(0).getString("UTF-8").trim()); el.setData_nascimento(date); el.setCpf(items.get(2).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim()); el.setRg(items.get(3).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim()); el.setSus(items.get(4).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim()); el.setEmail(items.get(5).getString("UTF-8")); el.setTelefone(items.get(6).getString("UTF-8").replaceAll("\\(|\\)|\\-|\\ ", "").trim()); el.setWhats(items.get(7).getString("UTF-8").replaceAll("\\(|\\)|\\-|\\ ", "").trim()); el.setObs(items.get(8).getString("UTF-8").trim()); el.setReferencia_pessoal(items.get(9).getString("UTF-8").trim()); end.setRua(items.get(11).getString("UTF-8").trim()); end.setBairro(items.get(12).getString("UTF-8").trim()); end.setN(items.get(13).getString("UTF-8").trim()); end.setCidade(items.get(14).getString("UTF-8").trim()); end.setCep(items.get(15).getString("UTF-8").trim()); end.setLocalidade(Integer.parseInt(items.get(16).getString("UTF-8").trim())); el.setTipo(Integer.parseInt(items.get(17).getString("UTF-8").trim())); el.setPertence(Integer.parseInt(items.get(18).getString("UTF-8").trim())); el.setEnd(end); DaoEleitor daoEleitor = new DaoEleitor(); DaoFoto daoFoto = new DaoFoto(); int idretorno = daoEleitor.Eleitor_Salvar(el); daoFoto.inserirImagem(foto, idretorno); response.sendRedirect("cadastro_eleitor.jsp?msgok"); } catch (FileUploadException ex) { Logger.getLogger(SvCadastraEleitor.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(SvCadastraEleitor.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(SvCadastraEleitor.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(SvCadastraEleitor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.adaptris.util.TestMultipartInput.java
private byte[] buildPayload() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); txtProps.store(out, PROPERTY_FILE_HEADER); out.flush(); return out.toByteArray(); }
From source file:com.google.dataconnector.client.fetchrequest.HttpFetchStrategy.java
/** * Implements the strategy method of processing the request and filling in the * reply with results of processing.// w w w.ja v a 2s . c o m * * @param request The request. * @param replyBuilder The reply to fill in. */ @Override public void process(FetchRequest request, FetchReply.Builder replyBuilder) throws StrategyException { HttpResponse response = getHttpResponse(request); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); replyBuilder.setStatus(statusCode); HttpEntity entity = response.getEntity(); if (entity != null) { try { ByteArrayOutputStream buff = new ByteArrayOutputStream(); entity.writeTo(buff); buff.flush(); buff.close(); if (buff.size() > 0) { replyBuilder.setContents(ByteString.copyFrom(buff.toByteArray())); } } catch (IOException e) { throw new StrategyException(request.getId() + " while copying content:", e); } } // Copy the headers for (Header h : response.getAllHeaders()) { replyBuilder.addHeaders(MessageHeader.newBuilder().setKey(h.getName()).setValue(h.getValue()).build()); } LOG.info(request.getId() + ": Got response from resource:" + statusLine); }
From source file:ch.unifr.pai.twice.widgets.mpProxyScreenShot.server.ReadOnlyPresentation.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = req.getParameter("url"); //e.g.: http://www.sbb.ch Object uuidObj = req.getSession().getAttribute(Constants.uuidCookie); String uuid = uuidObj != null ? uuidObj.toString() : null; BufferedReader reader = req.getReader(); ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream(); int b;//from w ww . j ava 2 s. c o m while ((b = reader.read()) != -1) { byteArrOS.write(b); } byteArrOS.flush(); byteArrOS.close(); reader.close(); String html = new String(byteArrOS.toByteArray(), "UTF-8"); if (!html.isEmpty() && url != null && !url.isEmpty()) uuidToScreenshot.put(uuid, new Screenshot(html, url, req.getParameter("height"), req.getParameter("width"), req.getParameter("top"), req.getParameter("left"))); }
From source file:nc.noumea.mairie.organigramme.services.exportGraphML.impl.AbstractExportGraphMLService.java
/** * Permet d'ajouter le logo de la mairie au fichier d'export * // w ww .j ava 2s . com * @param graph * : l'lment graph * @throws IOException * : si le logo ne peux pas tre lu ou ajout au fichier */ protected void ajoutLogoMairie(Element graph) throws IOException { Element elKeyResource = graph.getParent().addElement("data").addAttribute("key", "d13"); Element elResource = elKeyResource.addElement("y:Resources").addElement("y:Resource"); elResource.addAttribute("id", "1").addAttribute("type", "java.awt.image.BufferedImage"); InputStream is = this.getClass().getClassLoader().getResourceAsStream("logo-mairie.jpg"); BufferedImage img = ImageIO.read(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(img, "jpg", baos); baos.flush(); String encodedImage = Base64.encodeBase64String(baos.toByteArray()); baos.close(); elResource.setText(encodedImage); Element el = graph.addElement("node").addAttribute("id", "0"); Element elD6 = el.addElement("data").addAttribute("key", "d6"); Element elImageNode = elD6.addElement("y:ImageNode"); elImageNode.addElement("y:Geometry").addAttribute("height", "136.3").addAttribute("width", "143.0") .addAttribute("x", "256.0").addAttribute("y", "-291.0"); elImageNode.addElement("y:Image").addAttribute("alphaImage", "true").addAttribute("refid", "1"); }
From source file:com.adaptris.core.mail.attachment.MimeMailCreator.java
/** * @see com.adaptris.core.mail.attachment.MailContentCreator#createBody(com.adaptris.core.AdaptrisMessage) *///from w ww .j a v a 2 s . c om @Override public MailContent createBody(AdaptrisMessage msg) throws MailException { if (bodySelector == null) { throw new MailException("No way of selecting the body"); } MailContent result = null; try { BodyPartIterator mp = MimeHelper.createBodyPartIterator(msg); MimeBodyPart part = bodySelector.select(mp); if (part == null) { throw new CoreException("No part selected as the body"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamUtil.copyStream(part.getInputStream(), out); out.flush(); result = new MailContent(out.toByteArray(), getContentType(part)); } catch (Exception e) { throw new MailException(e); } return result; }
From source file:com.sishistorico.sv.SvEditarEleitor.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w .ja v a 2 s . c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF8"); response.setContentType("text/html;charset=UTF-8"); List<FileItem> items = null; byte[] foto = null; long vazio = 0; try { items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { vazio = item.getSize(); System.out.println("tamanho/:::::::::::::::::::: " + vazio); InputStream imageInput = item.getInputStream(); Image image = ImageIO.read(imageInput); BufferedImage thumb = Imagem.redimensionar(image, 400, 500); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(thumb, "JPG", baos); baos.flush(); foto = baos.toByteArray(); baos.close(); } } //dados do formulrio e metodos para salvar DateFormat formatter; Date date; formatter = new SimpleDateFormat("dd/MM/yyyy"); date = (Date) formatter.parse(items.get(1).getString()); // fim do tratamento Eleitor el = new Eleitor(); Endereco end = new Endereco(); el.setId(Integer.parseInt(items.get(19).getString("UTF-8").trim())); el.setNome(items.get(0).getString("UTF-8").trim()); el.setData_nascimento(date); el.setCpf(items.get(2).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim()); el.setRg(items.get(3).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim()); el.setSus(items.get(4).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim()); el.setEmail(items.get(5).getString("UTF-8")); el.setTelefone(items.get(6).getString("UTF-8").replaceAll("\\(|\\)|\\-|\\ ", "").trim()); el.setWhats(items.get(7).getString("UTF-8").replaceAll("\\(|\\)|\\-|\\ ", "").trim()); el.setObs(items.get(8).getString("UTF-8").trim()); el.setReferencia_pessoal(items.get(9).getString("UTF-8").trim()); end.setRua(items.get(11).getString("UTF-8").trim()); end.setBairro(items.get(12).getString("UTF-8").trim()); end.setN(items.get(13).getString("UTF-8").trim()); end.setCidade(items.get(14).getString("UTF-8").trim()); end.setCep(items.get(15).getString("UTF-8").trim()); end.setLocalidade(Integer.parseInt(items.get(16).getString("UTF-8").trim())); el.setTipo(Integer.parseInt(items.get(17).getString("UTF-8").trim())); el.setPertence(Integer.parseInt(items.get(18).getString("UTF-8").trim())); el.setEnd(end); DaoEleitor daoEleitor = new DaoEleitor(); DaoFoto daoFoto = new DaoFoto(); int idretorno = daoEleitor.Eleitor_Editar(el); if (vazio > 1) { daoFoto.atualizarImagem(foto, idretorno); } response.sendRedirect("editar_eleitor.jsp?id=" + el.getId() + "&msgok=Editado com sucesso!"); } catch (FileUploadException ex) { Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.apifest.BasicTest.java
public String readInputStream(InputStream in) throws IOException { byte[] buf = new byte[4096]; ByteArrayOutputStream out = new ByteArrayOutputStream(); String res = ""; try {//from w w w . j ava 2 s . co m int c; while ((c = in.read(buf)) > 0) { out.write(buf); } out.flush(); res = out.toString("UTF-8"); } catch (IOException e) { log.error("cannot read input", e); } finally { out.close(); } return res.trim(); }
From source file:org.apache.hadoop.hbase.mapred.TestSerialization.java
@Test public void testLargeResult() throws Exception { Result res = Result.create(new KeyValue[] { new KeyValue(row, family, qualifier, 0L, value) }); ResultSerialization serialization = new ResultSerialization(); Serializer<Result> serializer = serialization.getSerializer(Result.class); Deserializer<Result> deserializer = serialization.getDeserializer(Result.class); ByteArrayOutputStream os = new ByteArrayOutputStream(); ByteArrayInputStream is = null; try {// ww w. j a v a 2 s . com serializer.open(os); serializer.serialize(res); os.flush(); is = new ByteArrayInputStream(os.toByteArray()); deserializer.open(is); deserializer.deserialize(null); } catch (InvalidProtocolBufferException e) { assertTrue("Got InvalidProtocolBufferException in " + name.getMethodName(), e.getCause() instanceof InvalidProtocolBufferException); } catch (Exception e) { fail("Got an invalid exception: " + e); } }