List of usage examples for java.io ByteArrayInputStream close
public void close() throws IOException
From source file:net.sqs2.translator.impl.SQSToPDFTranslator.java
synchronized public void translate(byte[] sqsSourceBytes, ByteArrayInputStream foInputStream, String systemId, OutputStream pdfOutputStream) throws TranslatorException { try {// w w w . ja v a2s . c o m ByteArrayOutputStream pdfRawDataOutputStream = new ByteArrayOutputStream(65536); FOUserAgent userAgent = getTranslatorCore().getUserAgent(); userAgent.setBaseURL(systemId); synchronized (SQSToPDFTranslator.class) { Fop fop = getTranslatorCore().createFop(pdfRawDataOutputStream); render(fop.getDefaultHandler(), foInputStream, systemId); } pdfRawDataOutputStream.flush(); byte[] pdfRawDataBytes = pdfRawDataOutputStream.toByteArray(); foInputStream.close(); foInputStream = null; combinePDFData(userAgent, sqsSourceBytes, pdfRawDataBytes, pdfOutputStream, getBasename()); pdfRawDataOutputStream.close(); pdfRawDataOutputStream = null; pdfOutputStream.flush(); } catch (FOPException ex) { ex.printStackTrace(); throw new TranslatorException(ex); } catch (IOException ex) { ex.printStackTrace(); throw new TranslatorException(ex); } }
From source file:org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPTransport.java
/** * Receives the bytes from the last web service invocation. This is used by WSE's default * SOAP transport.//from w w w.j a va2 s . com * * @return A byte array. * @throws IOException */ byte[] receiveBytes() throws IOException { if (httpResponse != null) { byte[] payload = httpResponse.getPayload(); if (CHUNKED.equalsIgnoreCase(httpResponse.getHeader(HTTP_HEADER_TRANSFER_ENCODEING.toLowerCase()))) { ByteArrayInputStream bais = new ByteArrayInputStream(payload); ChunkedInputStream cis = new ChunkedInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte b; while ((b = (byte) cis.read()) != -1) baos.write(b); baos.close(); cis.close(); bais.close(); return baos.toByteArray(); } else { return payload; } } return null; }
From source file:org.openmrs.module.sana.mediaviewer.web.servlet.ComplexObsServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("doGet"); String obsId = request.getParameter("obsId"); String type = request.getParameter("obsType"); String view = request.getParameter("view"); String viewType = request.getParameter("viewType"); HttpSession session = request.getSession(); if (obsId == null || obsId.length() == 0) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.null"); return;/*from w ww . j a v a 2 s . c o m*/ } if (!Context.hasPrivilege(OpenmrsConstants.PRIV_VIEW_OBS)) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Privilege required: " + OpenmrsConstants.PRIV_VIEW_OBS); session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, request.getRequestURI() + "?" + request.getQueryString()); response.sendRedirect(request.getContextPath() + "/login.htm"); return; } Obs complexObs = Context.getObsService().getComplexObs(Integer.valueOf(obsId), view); ComplexData cd = complexObs.getComplexData(); Object data = cd.getData(); if ("DOWNLOAD".equals(viewType)) { response.setHeader("Content-Disposition", "attachment; filename=" + cd.getTitle()); response.setHeader("Pragma", "no-cache"); } if (data instanceof byte[]) { ByteArrayInputStream stream = new ByteArrayInputStream((byte[]) data); OpenmrsUtil.copyFile(stream, response.getOutputStream()); } else if (BufferedImage.class.isAssignableFrom(data.getClass())) { BufferedImage img = (BufferedImage) data; String[] parts = cd.getTitle().split("."); String extension = "jpg"; if (parts.length > 0) { extension = parts[parts.length - 1]; } ImageIO.write(img, extension, response.getOutputStream()); } else if (InputStream.class.isAssignableFrom(data.getClass())) { InputStream stream = (InputStream) data; OpenmrsUtil.copyFile(stream, response.getOutputStream()); stream.close(); } else { //throw new ServletException("Couldn't serialize complex obs data for obsId=" + obsId + " of type " // + data.getClass()); String title = complexObs.getComplexData().getTitle(); log.error("name type: " + title); // FIXME: This is a very hacky way to deal with mime types Hashtable<String, String> mimes = new Hashtable<String, String>(); //support for audio/video files mimes.put("3gp", "audio/3gpp"); mimes.put("mp3", "audio/mpeg"); mimes.put("mp4", "video/mp4"); mimes.put("mpg", "video/mpeg"); mimes.put("flv", "video/x-flv"); //support for text files mimes.put("txt", "text/plain"); mimes.put("doc", "application/msword"); mimes.put(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); // FIXME: This is a very hacky way to deal with mime types for (String mime : mimes.keySet()) { if (title.contains("." + mime)) { response.setContentType(mimes.get(mime)); } } // Write the file to response FileInputStream f = new FileInputStream((File) data); InputStream in = null; OutputStream out = null; try { in = f; out = response.getOutputStream(); while (true) { int dataFromStream = in.read(); if (dataFromStream == -1) { break; } out.write(dataFromStream); } in.close(); out.close(); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
From source file:im.r_c.android.fusioncache.DiskCache.java
@Override public Serializable getSerializable(String key) { byte[] byteArray = getBytes(key); if (byteArray == null || byteArray.length == 0) { return null; }/*from w ww .j a v a 2 s.c o m*/ ByteArrayInputStream bais = null; ObjectInputStream ois = null; Object result = null; try { bais = new ByteArrayInputStream(byteArray); ois = new ObjectInputStream(bais); result = ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } finally { if (bais != null) { try { bais.close(); } catch (IOException ignored) { } } if (ois != null) { try { ois.close(); } catch (IOException ignored) { } } } if (result == null || !(result instanceof Serializable)) { return null; } else { return (Serializable) result; } }
From source file:org.paxle.gui.impl.servlets.ConfigView.java
public void writeImage(HttpServletRequest request, HttpServletResponse response, Context context) throws Exception { final String pid = request.getParameter("pid"); if (pid == null) { response.sendError(501, "No pid supplied."); return;/*from www . j ava2 s .co m*/ } final String bundleID = request.getParameter("bundleID"); if (bundleID == null) { response.sendError(501, "No bundle-ID supplied."); return; } final ConfigTool configTool = (ConfigTool) context.get(ConfigTool.TOOL_NAME); if (configTool == null) { response.sendError(501, "Config-Tool not found."); return; } final Configurable configurabel = configTool.getConfigurable(Integer.valueOf(bundleID), pid); if (configurabel == null) { response.sendError(501, String .format("No configurable component found for bundle-ID '%s' and PID '%s'.", bundleID, pid)); return; } // loading metadata final ObjectClassDefinition ocd = configurabel.getObjectClassDefinition(); if (ocd == null) { response.sendError(501, String.format("No ObjectClassDefinition found for service with PID '%s'.", pid)); return; } try { // trying to find a proper icon final int[] sizes = new int[] { 16, 32, 64, 128, 256 }; BufferedImage img = null; for (int size : sizes) { // trying to find an icon InputStream in = ocd.getIcon(size); if (in == null) { if (size == sizes[sizes.length - 1]) { // fallback to the default image in = this.getClass().getResourceAsStream("/resources/images/cog.png"); } else continue; } // loading date final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); bout.close(); in.close(); // trying to detect the mimetype of the image ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); String contentType = URLConnection.guessContentTypeFromStream(bin); bin.close(); Iterator<ImageReader> readers = null; if (contentType != null) { readers = ImageIO.getImageReadersByMIMEType(contentType); } else { readers = ImageIO.getImageReadersByFormatName("png"); } while (readers.hasNext() && img == null) { // trying the next reader final ImageReader reader = readers.next(); InputStream input = null; try { input = new ByteArrayInputStream(bout.toByteArray()); reader.setInput(ImageIO.createImageInputStream(input)); img = reader.read(0); } catch (Exception e) { this.log("Unable to read image for pid " + pid, e); } finally { if (input != null) input.close(); } } if (img != null) { response.setHeader("Content-Type", "image/png"); ImageIO.write(img, "png", response.getOutputStream()); return; } } // no icon found. response.sendError(404); } catch (Throwable e) { response.sendError(404, e.getMessage()); return; } }
From source file:net.sf.jasperreports.repo.JasperDesignCache.java
/** * /*from w ww .ja v a 2 s. c o m*/ */ private JasperDesignReportResource getResource(String uri) { JasperDesignReportResource resource = cachedResourcesMap.get(uri); if (resource != null) { JasperDesign jasperDesign = resource.getJasperDesign(); JasperReport jasperReport = resource.getReport(); if (jasperDesign == null) { if (jasperReport == null) { throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_INVALID_ENTRY, new Object[] { "JasperDesignCache" }); } else { ByteArrayInputStream bais = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { new JRXmlWriter(jasperReportsContext).write(jasperReport, baos, "UTF-8"); bais = new ByteArrayInputStream(baos.toByteArray()); jasperDesign = JRXmlLoader.load(bais); resource.setJasperDesign(jasperDesign); } catch (JRException e) { throw new JRRuntimeException(e); } finally { try { baos.close(); if (bais != null) { bais.close(); } } catch (IOException e) { } } } } else { if (jasperReport == null) { try { jasperReport = reportCompiler.compile(jasperDesign); resource.setReport(jasperReport); } catch (JRException e) { throw new JRRuntimeException(e); } } else { //nothing to do? } } } return resource; }
From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.NDBRMStateStore.java
private void loadRMDelegationKeyState(RMState rmState) throws Exception { //Retrieve all DelegationKeys from NDB List<DelegationKey> delKeys = RMUtilities.getDelegationKeys(); if (delKeys != null) { for (DelegationKey hopDelKey : delKeys) { ByteArrayInputStream is = new ByteArrayInputStream(hopDelKey.getDelegationkey()); DataInputStream fsIn = new DataInputStream(is); try { org.apache.hadoop.security.token.delegation.DelegationKey key = new org.apache.hadoop.security.token.delegation.DelegationKey(); key.readFields(fsIn);/*ww w . ja v a 2 s. c o m*/ rmState.rmSecretManagerState.masterKeyState.add(key); } finally { is.close(); } } } }
From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java
/**Returns the created header for the sent data*/ public Properties upload(HttpConnectionParameter connectionParameter, AS2Message message, Partner sender, Partner receiver) throws Exception { NumberFormat formatter = new DecimalFormat("0.00"); AS2Info as2Info = message.getAS2Info(); MessageAccessDB messageAccess = null; MDNAccessDB mdnAccess = null;/* w w w . j a v a2s .c om*/ if (this.runtimeConnection != null && messageAccess == null && !as2Info.isMDN()) { messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection); messageAccess.initializeOrUpdateMessage((AS2MessageInfo) as2Info); } else if (this.runtimeConnection != null && as2Info.isMDN()) { mdnAccess = new MDNAccessDB(this.configConnection, this.runtimeConnection); mdnAccess.initializeOrUpdateMDN((AS2MDNInfo) as2Info); } if (this.clientserver != null) { this.clientserver.broadcastToClients(new RefreshClientMessageOverviewList()); } long startTime = System.currentTimeMillis(); //sets the global requestHeader int returnCode = this.performUpload(connectionParameter, message, sender, receiver); long size = message.getRawDataSize(); long transferTime = System.currentTimeMillis() - startTime; float bytePerSec = (float) ((float) size * 1000f / (float) transferTime); float kbPerSec = (float) (bytePerSec / 1024f); if (returnCode == HttpServletResponse.SC_OK) { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("returncode.ok", new Object[] { as2Info.getMessageId(), String.valueOf(returnCode), AS2Tools.getDataSizeDisplay(size), AS2Tools.getTimeDisplay(transferTime), formatter.format(kbPerSec), }), as2Info); } } else if (returnCode == HttpServletResponse.SC_ACCEPTED || returnCode == HttpServletResponse.SC_CREATED || returnCode == HttpServletResponse.SC_NO_CONTENT || returnCode == HttpServletResponse.SC_RESET_CONTENT || returnCode == HttpServletResponse.SC_PARTIAL_CONTENT) { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("returncode.accepted", new Object[] { as2Info.getMessageId(), String.valueOf(returnCode), AS2Tools.getDataSizeDisplay(size), AS2Tools.getTimeDisplay(transferTime), formatter.format(kbPerSec), }), as2Info); } } else { //the system was unable to connect the partner if (returnCode < 0) { throw new NoConnectionException( this.rb.getResourceString("error.noconnection", as2Info.getMessageId())); } if (this.runtimeConnection != null) { if (messageAccess == null) { messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection); } messageAccess.setMessageState(as2Info.getMessageId(), AS2Message.STATE_STOPPED); } throw new Exception(as2Info.getMessageId() + ": HTTP " + returnCode); } if (this.configConnection != null) { //inc the sent data size, this is for new connections (as2 messages, async mdn) AS2Server.incRawSentData(size); if (message.getAS2Info().isMDN()) { AS2MDNInfo mdnInfo = (AS2MDNInfo) message.getAS2Info(); //ASYNC MDN sent: insert an entry into the statistic table QuotaAccessDB.incReceivedMessages(this.configConnection, this.runtimeConnection, mdnInfo.getSenderId(), mdnInfo.getReceiverId(), mdnInfo.getState(), mdnInfo.getRelatedMessageId()); } } if (this.configConnection != null) { MessageStoreHandler messageStoreHandler = new MessageStoreHandler(this.configConnection, this.runtimeConnection); messageStoreHandler.storeSentMessage(message, sender, receiver, this.requestHeader); } //inform the server of the result if a sync MDN has been requested if (!message.isMDN()) { AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info(); if (messageInfo.requestsSyncMDN()) { //perform a check if the answer really contains a MDN or is just an empty HTTP 200 with some header data //this check looks for the existance of some key header values boolean as2FromExists = false; boolean as2ToExists = false; for (int i = 0; i < this.getResponseHeader().length; i++) { String key = this.getResponseHeader()[i].getName(); if (key.toLowerCase().equals("as2-to")) { as2ToExists = true; } else if (key.toLowerCase().equals("as2-from")) { as2FromExists = true; } } if (!as2ToExists) { throw new Exception(this.rb.getResourceString("answer.no.sync.mdn", new Object[] { as2Info.getMessageId(), "as2-to" })); } //send the data to the as2 server. It does not care if the MDN has been sync or async anymore GenericClient client = new GenericClient(); CommandObjectIncomingMessage commandObject = new CommandObjectIncomingMessage(); //create temporary file to store the data File tempFile = AS2Tools.createTempFile("SYNCMDN_received", ".bin"); FileOutputStream outStream = new FileOutputStream(tempFile); ByteArrayInputStream memIn = new ByteArrayInputStream(this.responseData); this.copyStreams(memIn, outStream); memIn.close(); outStream.flush(); outStream.close(); commandObject.setMessageDataFilename(tempFile.getAbsolutePath()); for (int i = 0; i < this.getResponseHeader().length; i++) { String key = this.getResponseHeader()[i].getName(); String value = this.getResponseHeader()[i].getValue(); commandObject.addHeader(key.toLowerCase(), value); if (key.toLowerCase().equals("content-type")) { commandObject.setContentType(value); } } //compatibility issue: some AS2 systems do not send a as2-from in the sync case, even if //this if _NOT_ RFC conform //see RFC 4130, section 6.2: The AS2-To and AS2-From header fields MUST be //present in all AS2 messages and AS2 MDNs whether asynchronous or synchronous in nature, //except for asynchronous MDNs, which are sent using SMTP. if (!as2FromExists) { commandObject.addHeader("as2-from", AS2Message.escapeFromToHeader(receiver.getAS2Identification())); } ErrorObject errorObject = client.send(commandObject); if (errorObject.getErrors() > 0) { messageAccess.setMessageState(as2Info.getMessageId(), AS2Message.STATE_STOPPED); } tempFile.delete(); } } return (this.requestHeader); }
From source file:com.dilmus.dilshad.scabi.core.DFile.java
public int copy(String fileName1, String fileName2) throws IOException, DScabiClientException, DScabiException, java.text.ParseException { long time1;// w w w . java2 s.c o m long time2; if (false == DMUtil.isNamespaceURLStr(fileName2)) throw new DScabiClientException("fileName2 is not proper namespace URL string", "DFE.PBN.1"); String strNamespace2 = DMUtil.getNamespaceStr(fileName2); String strResourceName2 = DMUtil.getResourceName(fileName2); DNamespace namespace2 = m_meta.getNamespace(strNamespace2, DNamespace.FILE); /* if (false == namespace2.getType().equals("File")) { throw new DScabiClientException("Namespace type is not File type. Actual type : " + namespace2.getType(), "DFE.SNE2.2"); } */ time1 = System.currentTimeMillis(); if (DMUtil.isNamespaceURLStr(fileName1)) { String strNamespace1 = DMUtil.getNamespaceStr(fileName1); String strResourceName1 = DMUtil.getResourceName(fileName1); DNamespace namespace1 = m_meta.getNamespace(strNamespace1, DNamespace.FILE); /* if (false == namespace1.getType().equals("File")) { throw new DScabiClientException("Namespace type is not File type. Actual type : " + namespace1.getType(), "DFE.SNE2.2"); } */ DDB ddb2 = new DDB(namespace2.getHost(), namespace2.getPort(), namespace2.getSystemSpecificName()); DBackFile dbfile2 = new DBackFile(ddb2); DDB ddb1 = new DDB(namespace1.getHost(), namespace1.getPort(), namespace1.getSystemSpecificName()); DBackFile dbfile1 = new DBackFile(ddb1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); dbfile2.get(strResourceName2, baos); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); baos.close(); dbfile1.put(strResourceName1, bais, "File", "File"); bais.close(); dbfile1.close(); ddb1.close(); dbfile2.close(); ddb2.close(); } else { /* if (m_firstTime) { if (null == m_namespace) { throw new DScabiClientException("Namespace is not set", "DFE.PUT2.1"); } m_ddb = new DDB(m_namespace.getHost(), m_namespace.getPort(), m_namespace.getSystemSpecificName()); m_dbfile = new DBackFile(m_ddb); m_firstTime = false; } */ if (null == m_namespace) { throw new DScabiClientException("Namespace is not set", "DFE.PUT2.1"); } DDB ddb2 = new DDB(namespace2.getHost(), namespace2.getPort(), namespace2.getSystemSpecificName()); DBackFile dbfile2 = new DBackFile(ddb2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); dbfile2.get(strResourceName2, baos); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); baos.close(); m_dbfile.put(fileName1, bais, "File", "File"); bais.close(); dbfile2.close(); ddb2.close(); } time2 = System.currentTimeMillis(); log.debug("put() Upload time taken : time2 - time1 : " + (time2 - time1)); return 0; }
From source file:com.gigaspaces.persistency.metadata.DefaultSpaceDocumentMapper.java
private Object deserializeObject(DBObject bson) { Object result = null;//from w ww . j a v a 2s . co m try { ByteArrayInputStream bis = new ByteArrayInputStream((byte[]) bson.get(Constants.VALUE)); ObjectInputStream in = new ObjectInputStream(bis); try { result = in.readObject(); } finally { in.close(); bis.close(); } } catch (IOException e1) { throw new SpaceMongoException("can not deserialize object", e1); } catch (ClassNotFoundException e) { throw new SpaceMongoException("can not deserialize object", e); } return result; }