List of usage examples for java.io ByteArrayOutputStream size
public synchronized int size()
From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java
void downloadImage(String address, boolean persistant) { if (mDB.hasImage(address)) { mDB.updateImageTime(address, new Date().getTime()); return;//from w w w . j a v a2s. c o m } try { // use apache http client lib to set parameters from feedStatus DefaultHttpClient client = new DefaultHttpClient(); // set up proxy handler ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); HttpGet request = new HttpGet(address); request.setHeader("User-Agent", USER_AGENT); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (entity != null && status.getStatusCode() == 200) { InputStream inputStream = entity.getContent(); // TODO - parse content-length here ByteArrayOutputStream data = new ByteArrayOutputStream(); byte bytes[] = new byte[512]; int count; while ((count = inputStream.read(bytes)) > 0) { data.write(bytes, 0, count); } if (data.size() > 0) { mDB.insertImage(address, new Date().getTime(), persistant, data.toByteArray()); } } } catch (IOException exc) { if (mLog.e()) mLog.e("error downloading image" + address, exc); } }
From source file:org.apache.myfaces.ov2021.application.jsp.JspStateManagerImpl.java
protected Object serializeView(FacesContext context, Object serializedView) { if (log.isLoggable(Level.FINEST)) log.finest("Entering serializeView"); if (isSerializeStateInSession(context)) { if (log.isLoggable(Level.FINEST)) log.finest("Processing serializeView - serialize state in session"); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); try {//from w w w . j av a2s . c om OutputStream os = baos; if (isCompressStateInSession(context)) { if (log.isLoggable(Level.FINEST)) log.finest("Processing serializeView - serialize compressed"); os.write(COMPRESSED_FLAG); os = new GZIPOutputStream(os, 1024); } else { if (log.isLoggable(Level.FINEST)) log.finest("Processing serializeView - serialize uncompressed"); os.write(UNCOMPRESSED_FLAG); } Object[] stateArray = (Object[]) serializedView; ObjectOutputStream out = new ObjectOutputStream(os); out.writeObject(stateArray[0]); out.writeObject(stateArray[1]); out.close(); baos.close(); if (log.isLoggable(Level.FINEST)) log.finest("Exiting serializeView - serialized. Bytes : " + baos.size()); return baos.toByteArray(); } catch (IOException e) { log.log(Level.SEVERE, "Exiting serializeView - Could not serialize state: " + e.getMessage(), e); return null; } } if (log.isLoggable(Level.FINEST)) log.finest("Exiting serializeView - do not serialize state in session."); return serializedView; }
From source file:br.gov.jfrj.siga.vraptor.ExDocumentoController.java
private byte[] getByteArrayFormPreenchimento(final String[] vars, final String[] campos) throws IOException { final String[] aVars = vars; final String[] aCampos = campos; final ArrayList<String> aFinal = new ArrayList<String>(); if (aVars != null && aVars.length > 0) { for (final String str : aVars) { aFinal.add(str);/*from w ww. j av a2 s .c o m*/ } } if (aCampos != null && aCampos.length > 0) { for (final String str : aCampos) { aFinal.add(str); } } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (aFinal != null && aFinal.size() > 0) { for (final String par : aFinal) { String s = "exDocumentoDTO.".concat(par); if (param(s) == null) { s = par; } if (param(s) != null && !param(s).trim().equals("") && !s.trim().equals("exDocumentoDTO.preenchimento") && !param(s).matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) { if (baos.size() > 0) { baos.write('&'); } baos.write(par.getBytes()); baos.write('='); // Deveria estar gravando como UTF-8 baos.write(URLEncoder.encode(param(s), "iso-8859-1").getBytes()); } } } return baos.toByteArray(); }
From source file:com.krawler.spring.exportFunctionality.exportDAOImpl.java
public void writeDataToFile(String filename, String heading, String fileType, ByteArrayOutputStream baos, HttpServletResponse response) throws ServiceException { try {//from w w w . j ava2 s. co m if (!StringUtil.isNullOrEmpty(heading)) { filename = heading + filename; } response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "." + fileType + "\""); response.setContentType("application/octet-stream"); response.setContentLength(baos.size()); response.getOutputStream().write(baos.toByteArray()); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { try { response.getOutputStream().println("{\"valid\": false}"); } catch (IOException ex) { log.warn("Error exporting file:" + ex.getMessage(), ex); } } }
From source file:com.krawler.spring.exportFunctionality.exportDAOImpl.java
public void createCsvFile(HttpServletRequest request, HttpServletResponse response, JSONObject obj) throws ServiceException { try {//from w ww .j a v a2 s .c o m String headers[] = null; String titles[] = null; JSONArray repArr = null; String xtype[] = null; if (request.getParameter("header") != null) { String head = request.getParameter("header").replace("$$", "#"); String xt = request.getParameter("xtype"); String tit = request.getParameter("title"); tit = URLDecoder.decode(tit); headers = (String[]) head.split(","); xtype = xt.split(","); titles = (String[]) tit.split(","); } else { headers = (String[]) obj.get("header"); xtype = (String[]) obj.get("xtype"); titles = (String[]) obj.get("title"); } StringBuilder reportSB = new StringBuilder(); if (obj.isNull("coldata")) { repArr = obj.getJSONArray("data"); } else { repArr = obj.getJSONArray("coldata"); } for (int h = 0; h < headers.length; h++) { String val = StringEscapeUtils.escapeCsv(titles[h]); if (h < headers.length - 1) { reportSB.append(StringEscapeUtils.escapeCsv(titles[h])).append(','); } else { reportSB.append(StringEscapeUtils.escapeCsv(titles[h])).append('\n'); } } for (int t = 0; t < repArr.length(); t++) { JSONObject temp = repArr.getJSONObject(t); for (int h = 0; h < headers.length; h++) { String str = temp.optString(headers[h], ""); try { if (xtype.length > 0) { str = formatValue(temp.optString(headers[h], ""), xtype[h]); } } catch (Exception e) { } if (h < headers.length - 1) { reportSB.append(StringEscapeUtils.escapeCsv(str)).append(','); } else { reportSB.append(StringEscapeUtils.escapeCsv(str)).append('\n'); } } } String heading = request.getParameter("heading"); String fname = request.getParameter("name"); ByteArrayOutputStream os = new ByteArrayOutputStream(); os.write(reportSB.toString().getBytes()); os.close(); if (!StringUtil.isNullOrEmpty(heading)) { fname = heading + fname; } response.setHeader("Content-Disposition", "attachment; filename=\"" + fname + ".csv\""); response.setContentType("application/octet-stream"); response.setContentLength(os.size()); response.getOutputStream().write(os.toByteArray()); response.getOutputStream().flush(); } catch (IOException ex) { errorMsg = ex.getMessage(); throw ServiceException.FAILURE("exportDAOImpl.createCsvFile : " + ex.getMessage(), ex); } catch (JSONException e) { errorMsg = e.getMessage(); throw ServiceException.FAILURE("exportDAOImpl.createCsvFile : " + e.getMessage(), e); } catch (Exception e) { errorMsg = e.getMessage(); throw ServiceException.FAILURE("exportDAOImpl.createCsvFile : " + e.getMessage(), e); } }
From source file:ar.com.qbe.siniestros.model.utils.MimeMagic.MagicParser.java
/** * replaces octal representations of bytes, written as \ddd to actual byte values. * * @param s a string with encoded octals * * @return string with all octals decoded *//* w w w .ja v a 2 s .c o m*/ private ByteBuffer convertOctals(String s) { int beg = 0; int end = 0; int c1; int c2; int c3; int chr; ByteArrayOutputStream buf = new ByteArrayOutputStream(); while ((end = s.indexOf('\\', beg)) != -1) { if (s.charAt(end + 1) != '\\') { //log.debug("appending chunk '"+s.substring(beg, end)+"'"); for (int z = beg; z < end; z++) { buf.write((int) s.charAt(z)); } //log.debug("found \\ at position "+end); //log.debug("converting octal '"+s.substring(end, end+4)+"'"); if ((end + 4) <= s.length()) { try { chr = Integer.parseInt(s.substring(end + 1, end + 4), 8); //log.debug("converted octal '"+s.substring(end+1,end+4)+"' to '"+chr); //log.debug("converted octal back to '"+Integer.toOctalString(chr)); //log.debug("converted '"+s.substring(end+1,end+4)+"' to "+chr+"/"+((char)chr)); buf.write(chr); beg = end + 4; end = beg; } catch (NumberFormatException nfe) { //log.debug("not an octal"); buf.write((int) '\\'); beg = end + 1; end = beg; } } else { //log.debug("not an octal, not enough chars left in string"); buf.write((int) '\\'); beg = end + 1; end = beg; } } else { //log.debug("appending \\"); buf.write((int) '\\'); beg = end + 1; end = beg; } } if (end < s.length()) { for (int z = beg; z < s.length(); z++) { buf.write((int) s.charAt(z)); } } try { log.debug("convertOctals(): returning buffer size '" + buf.size() + "'"); ByteBuffer b = ByteBuffer.allocate(buf.size()); return b.put(buf.toByteArray()); } catch (Exception e) { log.error("convertOctals(): error parsing string: " + e); return ByteBuffer.allocate(0); } }
From source file:org.apache.pig.builtin.Utf8StorageConverter.java
private Map<String, Object> consumeMap(PushbackInputStream in, ResourceFieldSchema fieldSchema) throws IOException { int buf;/*from w w w . j a v a 2s. c o m*/ boolean emptyMap = true; while ((buf = in.read()) != '[') { if (buf == -1) { throw new IOException("Unexpect end of map"); } } HashMap<String, Object> m = new HashMap<String, Object>(); ByteArrayOutputStream mOut = new ByteArrayOutputStream(BUFFER_SIZE); while (true) { // Read key (assume key can not contains special character such as #, (, [, {, }, ], ) while ((buf = in.read()) != '#') { // end of map if (emptyMap && buf == ']') { return m; } if (buf == -1) { throw new IOException("Unexpect end of map"); } emptyMap = false; mOut.write(buf); } String key = bytesToCharArray(mOut.toByteArray()); if (key.length() == 0) throw new IOException("Map key can not be null"); // Read value mOut.reset(); Deque<Character> level = new LinkedList<Character>(); // keep track of nested tuple/bag/map. We do not interpret, save them as bytearray while (true) { buf = in.read(); if (buf == -1) { throw new IOException("Unexpect end of map"); } if (buf == '[' || buf == '{' || buf == '(') { level.push((char) buf); } else if (buf == ']' && level.isEmpty()) // End of map break; else if (buf == ']' || buf == '}' || buf == ')') { if (level.isEmpty()) throw new IOException("Malformed map"); if (level.peek() == findStartChar((char) buf)) level.pop(); } else if (buf == ',' && level.isEmpty()) { // Current map item complete break; } mOut.write(buf); } Object value = null; if (fieldSchema != null && fieldSchema.getSchema() != null && mOut.size() > 0) { value = bytesToObject(mOut.toByteArray(), fieldSchema.getSchema().getFields()[0]); } else if (mOut.size() > 0) { // untyped map value = new DataByteArray(mOut.toByteArray()); } m.put(key, value); mOut.reset(); if (buf == ']') break; } return m; }