List of usage examples for javax.activation DataHandler writeTo
public void writeTo(OutputStream os) throws IOException
OutputStream
.If the DataHandler was created with a DataSource, writeTo retrieves the InputStream and copies the bytes from the InputStream to the OutputStream passed in.
From source file:org.wso2.carbon.registry.ws.api.utils.CommonUtil.java
public static byte[] makeBytesFromDataHandler(WSResource wsResource) throws IOException { DataHandler dataHandler = wsResource.getContentFile(); if (dataHandler == null) return null; ByteArrayOutputStream output = null; // OutputStream output = new FileOutputStream(tempFile); output = new ByteArrayOutputStream(); try {/*from w ww. j av a 2 s .com*/ dataHandler.writeTo(output); } catch (IOException e) { // TODO Auto-generated catch block throw e; } return output.toByteArray(); }
From source file:org.wso2.appserver.sample.mtom.services.MTOMService.java
private void writeFile(File fileToWrite, Base64Binary binaryData) throws IOException { OutputStream outStream = new FileOutputStream(fileToWrite); DataHandler dataHandler = binaryData.getBase64Binary(); dataHandler.writeTo(outStream); outStream.flush();//from w w w .ja v a 2 s . c o m outStream.close(); }
From source file:org.apache.axiom.attachments.impl.BufferUtils.java
/** * The method checks to see if attachment is eligble for optimization. * An attachment is eligible for optimization if and only if the size of * the attachment is greated then the optimzation threshold size limit. * if the Content represented by DataHandler has size less than the * optimize threshold size, the attachment will not be eligible for * optimization, instead it will be inlined. * @param dh//from w w w .j a v a2 s . co m * @param limit * @return 1 if DataHandler data is bigger than limit, 0 if DataHandler data is smaller or * -1 if an error occurs or unsupported. * @throws IOException */ public static int doesDataHandlerExceedLimit(DataHandler dh, int limit) { //If Optimized Threshold not set return true. if (limit == 0) { return -1; } long size = DataSourceUtils.getSize(dh.getDataSource()); if (size != -1) { return size > limit ? 1 : 0; } else { // In all other cases, we prefer DataHandler#writeTo over DataSource#getInputStream. // The reason is that if the DataHandler was constructed from an Object rather than // a DataSource, a call to DataSource#getInputStream() will start a new thread and // return a PipedInputStream. This is so for Geronimo's as well as Sun's JAF // implementaion. The reason is that DataContentHandler only has a writeTo and no // getInputStream method. Obviously starting a new thread just to check the size of // the data is an overhead that we should avoid. try { dh.writeTo(new SizeLimitedOutputStream(limit)); } catch (SizeLimitExceededException ex) { return 1; } catch (IOException ex) { log.warn(ex.getMessage()); return -1; } return 0; } }
From source file:org.broadleafcommerce.common.email.service.LoggingMailSender.java
@Override public void send(MimeMessagePreparator[] mimeMessagePreparators) throws MailException { for (MimeMessagePreparator preparator : mimeMessagePreparators) { try {/*from w ww .jav a2 s . c o m*/ MimeMessage mimeMessage = createMimeMessage(); preparator.prepare(mimeMessage); LOG.info("\"Sending\" email: "); if (mimeMessage.getContent() instanceof MimeMultipart) { MimeMultipart msg = (MimeMultipart) mimeMessage.getContent(); DataHandler dh = msg.getBodyPart(0).getDataHandler(); ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); dh.writeTo(baos); } catch (Exception e) { // Do nothing } finally { try { baos.close(); } catch (Exception e) { LOG.error("Couldn't close byte array output stream"); } } } else { LOG.info(mimeMessage.getContent()); } } catch (Exception e) { LOG.error("Could not create message", e); } } }
From source file:org.wso2.carbon.aarservices.ServiceUploader.java
private void writeToFileSystem(String path, String fileName, DataHandler dataHandler) throws Exception { File destFile = new File(path, fileName); FileOutputStream fos = null;//from w w w .j a v a 2 s. c o m try { fos = new FileOutputStream(destFile); dataHandler.writeTo(fos); fos.flush(); fos.close(); } finally { if (fos != null) { fos.close(); } } }
From source file:com.clustercontrol.infra.view.action.DownloadInfraFileAction.java
@Override public Object execute(ExecutionEvent event) throws ExecutionException { InfraFileManagerView view = getView(event); if (view == null) { m_log.info("execute: view is null"); return null; }/*from www . j av a2s .co m*/ InfraFileInfo info = InfraFileUtil.getSelectedInfraFileInfo(view); if (info == null) { return null; } String action = Messages.getString("download"); FileDialog fd = new FileDialog(window.getShell(), SWT.SAVE); String fileName = info.getFileName(); fd.setFileName(fileName); String selectedFilePath = null; try { selectedFilePath = fd.open(); } catch (Exception e) { m_log.error(e); InfraFileUtil.showFailureDialog(action, HinemosMessage.replace(e.getMessage())); return null; } // path is null when dialog cancelled if (null != selectedFilePath) { StructuredSelection selection = null; if (view.getComposite().getTableViewer().getSelection() instanceof StructuredSelection) { selection = (StructuredSelection) view.getComposite().getTableViewer().getSelection(); } String managerName = null; if (selection != null && selection.isEmpty() == false) { managerName = (String) ((ArrayList<?>) selection.getFirstElement()) .get(GetInfraFileManagerTableDefine.MANAGER_NAME); } InfraEndpointWrapper wrapper = InfraEndpointWrapper.getWrapper(managerName); FileOutputStream fos = null; try { DataHandler dh = wrapper.downloadInfraFile(info.getFileId(), fileName); fos = new FileOutputStream(new File(selectedFilePath)); dh.writeTo(fos); if (ClusterControlPlugin.isRAP()) { FileDownloader.openBrowser(window.getShell(), selectedFilePath, fileName); } else { InfraFileUtil.showSuccessDialog(action, info.getFileId()); } wrapper.deleteDownloadedInfraFile(fileName); } catch (Exception e) { m_log.error(e); InfraFileUtil.showFailureDialog(action, HinemosMessage.replace(e.getMessage())); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } } } return null; }
From source file:org.wso2.carbon.mediation.connector.file.AS4FileWriter.java
/** * Write the AS4 payloads to files//from ww w .j a v a 2s . c o m * @param messaging Messaging object */ public void saveAS4Payloads(Messaging messaging, org.apache.axis2.context.MessageContext axis2MsgContext, String dataInFolder) throws AS4Exception { String messageId = messaging.getUserMessage().getMessageInfo().getMessageId(); List<PartInfo> partInfoList = messaging.getUserMessage().getPayloadInfo().getPartInfo(); if (partInfoList != null) { for (PartInfo partInfo : partInfoList) { // Write attachment if (partInfo.getHref().startsWith(AS4Constants.ATTACHMENT_HREF_PREFIX)) { String cid = partInfo.getHref().substring(AS4Constants.ATTACHMENT_HREF_PREFIX.length()); DataHandler dataHandler = axis2MsgContext.getAttachment(cid); File partFile = new File(dataInFolder + File.separator + cid); try { dataHandler.writeTo(new FileOutputStream(partFile)); } catch (IOException e) { log.error("Error writing payload to file : " + cid, e); throw new AS4Exception("Error writing payload to file : " + cid, AS4ErrorMapper.ErrorCode.EBMS0004, messageId); } // Write soap body payload } else if (partInfo.getHref().startsWith(AS4Constants.SOAP_BODY_HREF_PREFIX)) { String cid = partInfo.getHref().substring(AS4Constants.SOAP_BODY_HREF_PREFIX.length()); OMElement payloadElement = axis2MsgContext.getEnvelope().getBody().getFirstElement(); if (payloadElement != null) { try { File partFile = new File(dataInFolder + File.separator + cid); FileOutputStream outputStream = new FileOutputStream(partFile); payloadElement.serialize(outputStream); } catch (Exception e) { log.error("Error writing payload to file : " + cid, e); throw new AS4Exception("Error writing payload to file : " + cid, AS4ErrorMapper.ErrorCode.EBMS0004, messageId); } } else { throw new AS4Exception("Payload not found in the soap body : " + cid, AS4ErrorMapper.ErrorCode.EBMS0001, messageId); } } } } }
From source file:com.clustercontrol.platform.infra.InfraJdbcExecutorSupport.java
public static void execInsertFileContent(String fileId, DataHandler handler) throws HinemosUnknown, InfraFileTooLarge { Connection conn = null;//ww w. j ava 2s . com JpaTransactionManager tm = null; PGCopyOutputStream pgStream = null; FileOutputStream fos = null; BufferedInputStream bis = null; File tempFile = null; try { tm = new JpaTransactionManager(); conn = tm.getEntityManager().unwrap(java.sql.Connection.class); conn.setAutoCommit(false); pgStream = new PGCopyOutputStream((PGConnection) conn, "COPY binarydata.cc_infra_file_content(file_id, file_content) FROM STDIN WITH (FORMAT BINARY)"); String exportDirectory = HinemosPropertyUtil.getHinemosPropertyStr("infra.export.dir", HinemosPropertyDefault.getString(HinemosPropertyDefault.StringKey.INFRA_EXPORT_DIR)); tempFile = new File(exportDirectory + fileId); fos = new FileOutputStream(tempFile); handler.writeTo(fos); long fileLength = tempFile.length(); int maxSize = HinemosPropertyUtil.getHinemosPropertyNum(MAX_FILE_KEY, Long.valueOf(1024 * 1024 * 64)) .intValue(); // 64MB if (fileLength > maxSize) { throw new InfraFileTooLarge(String.format("File size is larger than the limit size(%d)", maxSize)); } pgStream.write(HEADER_SIGN_PART); pgStream.write(HEADER_FLG_FIELD_PART); pgStream.write(HEADER_EX_PART); pgStream.write(TUPLE_FIELD_COUNT_PART); pgStream.write(ByteBuffer.allocate(4).putInt(fileId.getBytes().length).array()); pgStream.write(fileId.getBytes()); pgStream.write(ByteBuffer.allocate(4).putInt((int) fileLength).array()); bis = new BufferedInputStream(new FileInputStream(tempFile)); byte[] buf = new byte[1024 * 1024]; int read; while ((read = bis.read(buf)) != -1) { pgStream.write(buf, 0, read); } pgStream.write(FILETRAILER); pgStream.flush(); if (!tm.isNestedEm()) { conn.commit(); } } catch (InfraFileTooLarge e) { log.warn(e.getMessage()); try { pgStream.close(); } catch (IOException e1) { log.warn(e1); } try { conn.rollback(); } catch (SQLException e1) { log.warn(e1); } throw e; } catch (Exception e) { log.warn(e.getMessage(), e); try { if (pgStream != null) pgStream.close(); } catch (IOException e1) { log.warn(e1); } try { if (conn != null) conn.rollback(); } catch (SQLException e1) { log.warn(e1); } throw new HinemosUnknown(e.getMessage(), e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { log.warn(e.getMessage(), e); throw new HinemosUnknown(e.getMessage(), e); } } if (bis != null) { try { bis.close(); } catch (IOException e) { log.warn(e.getMessage(), e); throw new HinemosUnknown(e.getMessage(), e); } } if (pgStream != null) { try { pgStream.close(); } catch (IOException e) { log.warn(e.getMessage(), e); throw new HinemosUnknown(e.getMessage(), e); } } if (tm != null) { tm.close(); } if (tempFile == null) { log.debug("Fail to delete. tempFile is null"); } else if (!tempFile.delete()) { log.debug("Fail to delete " + tempFile.getAbsolutePath()); } } }
From source file:org.wso2.carbon.reporting.template.ui.servlet.ReportGenerator.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); String serverURL = CarbonUIUtil.getServerURL(getServletContext(), session); ConfigurationContext configContext = (ConfigurationContext) getServletContext() .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); ReportTemplateClient client;/*from w ww . j ava2s . c o m*/ String errorString = ""; client = new ReportTemplateClient(configContext, serverURL, cookie); String reportName = request.getParameter("reportName"); String reportType = request.getParameter("reportType"); String downloadFileName = null; if (reportType.equals("pdf")) { response.setContentType("application/pdf"); downloadFileName = reportName + ".pdf"; } else if (reportType.equals("xls")) { response.setContentType("application/vnd.ms-excel"); downloadFileName = reportName + ".xls"; } else if (reportType.equals("html")) { response.setContentType("text/html"); } if (downloadFileName != null) { response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\""); } DataHandler dataHandler = null; if (client != null) { dataHandler = client.generateReport(reportName, reportType); } ServletOutputStream outputStream = response.getOutputStream(); if (dataHandler != null) { dataHandler.writeTo(outputStream); } }
From source file:org.wso2.carbon.rule.ws.admin.RuleServiceFileUploadAdmin.java
private void writeToFileSystem(String path, String fileName, DataHandler dataHandler) throws Exception { final File directory = new File(path); if (!directory.exists()) { directory.mkdirs();/*from w w w.j av a 2s . co m*/ } final File destFile = new File(path, fileName); if (!destFile.exists()) { destFile.createNewFile(); } final FileOutputStream fos = new FileOutputStream(destFile); dataHandler.writeTo(fos); fos.flush(); fos.close(); }