List of usage examples for java.io ByteArrayOutputStream flush
public void flush() throws IOException
From source file:com.cloudmaster.cmp.util.AlarmSystem.transfer.HttpSender.java
public ResponseObject send(TransportObject object) throws Exception { ResponseObject rs = new ResponseObject(); ByteArrayOutputStream bOs = null; DataOutputStream dOs = null;//from www . java 2 s . c om DataInputStream dIs = null; HttpClient client; PostMethod meth = null; byte[] rawData; try { bOs = new ByteArrayOutputStream(); dOs = new DataOutputStream(bOs); object.toStream(dOs); bOs.flush(); rawData = bOs.toByteArray(); client = new HttpClient(); client.setConnectionTimeout(this.timeout); client.setTimeout(this.datatimeout); client.setHttpConnectionFactoryTimeout(this.timeout); meth = new PostMethod(object.getValue(SERVER_URL)); // meth = new UTF8PostMethod(url); meth.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ENCODING); // meth.addParameter(SERVER_ARGS, new String(rawData,"UTF-8")); // meth.setRequestBody(new String(rawData)); // meth.setRequestBody(new String(rawData,"UTF-8")); byte[] base64Array = Base64.encode(rawData).getBytes(); meth.setRequestBody(new String(base64Array)); // System.out.println(new String(rawData)); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); client.executeMethod(meth); dIs = new DataInputStream(meth.getResponseBodyAsStream()); if (meth.getStatusCode() == HttpStatus.SC_OK) { Header errHeader = meth.getResponseHeader(HDR_ERROR); if (errHeader != null) { rs.setError(meth.getResponseBodyAsString()); return rs; } rs = ResponseObject.fromStream(dIs); return rs; } else { meth.releaseConnection(); throw new IOException("Connection failure: " + meth.getStatusLine().toString()); } } finally { if (meth != null) { meth.releaseConnection(); } if (bOs != null) { bOs.close(); } if (dOs != null) { dOs.close(); } if (dIs != null) { dIs.close(); } } }
From source file:dk.dma.msinm.web.rest.LocationRestService.java
/** * Parse the KML file of the uploaded .kmz or .kml file and returns a JSON list of locations * * @param request the servlet request//w w w . java 2 s. c o m * @return the corresponding list of locations */ @POST @javax.ws.rs.Path("/upload-kml") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("application/json;charset=UTF-8") public List<LocationVo> uploadKml(@Context HttpServletRequest request) throws FileUploadException, IOException { FileItemFactory factory = RepositoryService.newDiskFileItemFactory(servletContext); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { try { // .kml file if (item.getName().toLowerCase().endsWith(".kml")) { // Parse the KML and return the corresponding locations return parseKml(IOUtils.toString(item.getInputStream())); } // .kmz file else if (item.getName().toLowerCase().endsWith(".kmz")) { // Parse the .kmz file as a zip file ZipInputStream zis = new ZipInputStream(new BufferedInputStream(item.getInputStream())); ZipEntry entry; // Look for the first zip entry with a .kml extension while ((entry = zis.getNextEntry()) != null) { if (!entry.getName().toLowerCase().endsWith(".kml")) { continue; } log.info("Unzipping: " + entry.getName()); int size; byte[] buffer = new byte[2048]; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); while ((size = zis.read(buffer, 0, buffer.length)) != -1) { bytes.write(buffer, 0, size); } bytes.flush(); zis.close(); // Parse the KML and return the corresponding locations return parseKml(new String(bytes.toByteArray(), "UTF-8")); } } } catch (Exception ex) { log.error("Error extracting kmz", ex); } } } // Return an empty result return new ArrayList<>(); }
From source file:de.zweipunktfuenf.crypdroid.activities.ActionChooserActivity.java
@Deprecated private byte[] readDataFile() { FileInputStream fis = null;//from w ww . j a v a 2 s. com try { fis = openFileInput(CrypdroidActivity.FILE_TEMP_OUT); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int size; byte[] buffer = new byte[4096]; while (-1 != (size = fis.read(buffer))) baos.write(buffer, 0, size); baos.flush(); return baos.toByteArray(); } catch (FileNotFoundException e) { Toast.makeText(this, R.string.error_internal, Toast.LENGTH_LONG).show(); Log.e("ActionChooserActivity#readDataFile", "" + e.getClass(), e); return null; } catch (IOException e) { Toast.makeText(this, R.string.error_internal, Toast.LENGTH_LONG).show(); Log.e("ActionChooserActivity#readDataFile", "" + e.getClass(), e); return null; } finally { if (null != fis) try { fis.close(); } catch (IOException e) { Log.d("ActionChooserActivity#readDataFile", "error while closing internal_out", e); } } }
From source file:com.patrolpro.servlet.UploadJasperReportServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w . j a v a2s.c om * * @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 processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String companyId = request.getParameter("companyId"); FileItem fileData = null; Integer mobileFormId = null; List<FileItem> fields = upload.parseRequest(request); for (int f = 0; f < fields.size(); f++) { if (fields.get(f).getFieldName().equals("file_data")) { fileData = fields.get(f); } else if (fields.get(f).getFieldName().equals("mobileFormId")) { mobileFormId = Integer.parseInt(fields.get(f).getString()); } } if (fileData == null || !fileData.getName().endsWith(".jrxml")) { out.write("{\"error\": \"Invalid file type! Please select a jrxml (Jasper Report) file!\"}"); out.flush(); } else { InputStream iStream = fileData.getInputStream(); MobileFormService mobileService = new MobileFormService(companyId); ByteArrayOutputStream bOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bufCount = 0; while ((bufCount = iStream.read(buffer)) > -1) { bOutput.write(buffer, 0, bufCount); } bOutput.flush(); byte[] rawData = bOutput.toByteArray(); JasperReport jasperReport = JasperCompileManager.compileReport(new ByteArrayInputStream(rawData)); JRParameter[] params = jasperReport.getParameters(); HashMap<String, Class> reportParams = new HashMap<String, Class>(); for (int p = 0; p < params.length; p++) { JRParameter param = params[p]; int searchPos = -1; for (int a = 0; a < MobileForms.getReservedIdentifiers().length; a++) { if (MobileForms.getReservedIdentifiers()[a].equals(param.getName())) { searchPos = a; } } if (!param.isSystemDefined() && searchPos < 0 && !param.getName().startsWith("nfc_l_") && !param.getName().endsWith("_loc")) { reportParams.put(param.getName(), param.getValueClass()); } } ByteArrayOutputStream oStream = new ByteArrayOutputStream(); JasperCompileManager.writeReportToXmlStream(jasperReport, oStream); //JasperCompileManager.compileReportToStream(new ByteArrayInputStream(rawData), oStream); MobileForms selectedForm = mobileService.getForm(mobileFormId); selectedForm.setReportData(oStream.toByteArray()); mobileService.saveForm(selectedForm); Iterator<String> keyIterator = reportParams.keySet().iterator(); ArrayList<MobileFormData> currData = mobileService.getFormData(selectedForm.getMobileFormsId()); int numberInserted = 1; while (keyIterator.hasNext()) { String key = keyIterator.next(); boolean hasData = false; for (int d = 0; d < currData.size(); d++) { if (currData.get(d).getDataLabel().equals(key) && currData.get(d).getActive()) { hasData = true; } } if (!hasData) { MobileFormData formData = new MobileFormData(); formData.setActive(true); formData.setMobileFormsId(selectedForm.getMobileFormsId()); formData.setDataLabel(key); if (reportParams.get(key) == Date.class) { formData.setDateType(5); } else if (reportParams.get(key) == InputStream.class) { formData.setDateType(8); } else if (reportParams.get(key) == Boolean.class) { formData.setDateType(3); } else { formData.setDateType(1); } formData.setOrdering(currData.size() + numberInserted); mobileService.saveFormData(formData); numberInserted++; } } out.write("{}"); out.flush(); } } catch (JRException jr) { out.write("{\"error\": \"" + jr.getMessage().replaceAll("\n", "").replaceAll(":", "").replaceAll("\t", "") + "\"}"); out.flush(); } catch (Exception e) { out.write("{\"error\": \"Exception uploading report, " + e + "\"}"); out.flush(); } finally { out.close(); } }
From source file:com.ar.dev.tierra.api.controller.UsuariosController.java
@RequestMapping(value = "/updatePhoto", method = RequestMethod.POST) public @ResponseBody ResponseEntity<?> updateUsuario(@RequestParam("file") MultipartFile file, OAuth2Authentication authentication) { try {/* w w w . ja v a 2 s. c o m*/ User user = (User) authentication.getPrincipal(); Usuarios u = facadeService.getUsuariosDAO().findUsuarioByUsername(user.getUsername()); if (file.getName().isEmpty() == false) { InputStream inputStream = file.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] bytes = new byte[16384]; while ((nRead = inputStream.read(bytes, 0, bytes.length)) != -1) { buffer.write(bytes, 0, nRead); } buffer.flush(); u.setImagen(buffer.toByteArray()); facadeService.getUsuariosDAO().updateUsuario(u); } } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(HttpStatus.OK); }
From source file:com.google.api.ads.adwords.awreporting.processors.onmemory.ReportProcessorOnMemoryTest.java
private byte[] getReporDatafromCsv(ReportDefinitionReportType reportType) throws Exception { byte[] reportData = reportDataMap.get(reportType); if (reportData == null) { FileInputStream fis = new FileInputStream(getReportDataFileName(reportType)); ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); GZIPOutputStream gzipOut = new GZIPOutputStream(baos); FileUtil.copy(fis, gzipOut);/*from w ww . j a v a 2 s . c o m*/ gzipOut.flush(); gzipOut.close(); reportData = baos.toByteArray(); reportDataMap.put(reportType, reportData); baos.flush(); baos.close(); } return reportData; }
From source file:com.wabacus.util.Tools.java
public static byte[] getBytesArrayFromInputStream(InputStream is) { try {/* w ww . ja v a 2 s.c om*/ if (is == null) return null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } is.close(); baos.flush(); baos.close(); return baos.toByteArray(); } catch (IOException e) { log.error("??", e); return null; } }
From source file:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdClient.java
/** * Unzips all elements in the file represented by byte[] data. * Needed by retrieveRawJudgments which will retrieve a zip-file with a single JSON * @param data//w w w .j av a 2 s . c om * @return unzipped data * @throws IOException */ byte[] unzip(final byte[] data) throws IOException { final InputStream input = new ByteArrayInputStream(data); final byte[] buffer = new byte[1024]; final ZipInputStream zip = new ZipInputStream(input); final ByteArrayOutputStream out = new ByteArrayOutputStream(data.length); int count = 0; if (zip.getNextEntry() != null) { while ((count = zip.read(buffer)) != -1) { out.write(buffer, 0, count); } } out.flush(); zip.close(); out.close(); return out.toByteArray(); }
From source file:net.bioclipse.pubchem.business.PubChemManager.java
private String downloadAsString(String URL, String accepts, IProgressMonitor monitor) throws IOException, BioclipseException, CoreException { if (monitor == null) monitor = new NullProgressMonitor(); String fileContent = ""; try {//from w w w . j a v a 2s .com monitor.subTask("Downloading from " + URL); HttpClient client = new HttpClient(); GetMethod method = new GetMethod(URL); if (accepts != null) { method.setRequestHeader("Accept", accepts); method.setRequestHeader("Content-Type", accepts); } client.executeMethod(method); InputStream responseStream = method.getResponseBodyAsStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = responseStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); responseStream.close(); method.releaseConnection(); fileContent = new String(buffer.toByteArray()); monitor.worked(1); } catch (PatternSyntaxException exception) { exception.printStackTrace(); throw new BioclipseException("Invalid Pattern.", exception); } catch (MalformedURLException exception) { exception.printStackTrace(); throw new BioclipseException("Invalid URL.", exception); } return fileContent; }
From source file:PNGDecoder.java
public byte[] getImageData() { try {//from w w w . j a v a 2s. co m ByteArrayOutputStream out = new ByteArrayOutputStream(); // Write all the IDAT data into the array. for (int i = 0; i < mNumberOfChunks; i++) { PNGChunk chunk = mChunks[i]; if (chunk.getTypeString().equals("IDAT")) { out.write(chunk.getData()); } } out.flush(); // Now deflate the data. InflaterInputStream in = new InflaterInputStream(new ByteArrayInputStream(out.toByteArray())); ByteArrayOutputStream inflatedOut = new ByteArrayOutputStream(); int readLength; byte[] block = new byte[8192]; while ((readLength = in.read(block)) != -1) inflatedOut.write(block, 0, readLength); inflatedOut.flush(); byte[] imageData = inflatedOut.toByteArray(); // Compute the real length. int width = (int) getWidth(); int height = (int) getHeight(); int bitsPerPixel = getBitsPerPixel(); int length = width * height * bitsPerPixel / 8; byte[] prunedData = new byte[length]; // We can only deal with non-interlaced images. if (getInterlace() == 0) { int index = 0; for (int i = 0; i < length; i++) { if ((i * 8 / bitsPerPixel) % width == 0) { index++; // Skip the filter byte. } prunedData[i] = imageData[index++]; } } else System.out.println("Couldn't undo interlacing."); return prunedData; } catch (IOException ioe) { } return null; }