Example usage for javax.activation DataHandler writeTo

List of usage examples for javax.activation DataHandler writeTo

Introduction

In this page you can find the example usage for javax.activation DataHandler writeTo.

Prototype

public void writeTo(OutputStream os) throws IOException 

Source Link

Document

Write the data to an 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.

Usage

From source file:org.wso2.carbon.reporting.custom.ui.servlet.BDReportServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String dataSource = request.getParameter("dataSource");
    String reportName = request.getParameter("reportName");
    String reportType = request.getParameter("reportType");
    String params = request.getParameter("hidden_param");

    String downloadFileName = null;

    if (reportType.equals("pdf")) {
        response.setContentType("application/pdf");
        downloadFileName = reportName + ".pdf";
    } else if (reportType.equals("excel")) {
        response.setContentType("application/vnd.ms-excel");
        downloadFileName = reportName + ".xls";
    } else if (reportType.equals("html")) {
        response.setContentType("text/html");
    } else {/*w  ww  . j a  v a2  s  .  co  m*/
        throw new ReportingException("requested report type can not be support");
    }

    if (downloadFileName != null) {
        response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
    }
    ReportBean reportBean = new ReportBean();
    reportBean.setTemplateName(reportName);
    reportBean.setReportType(reportType);
    reportBean.setDataSourceName(dataSource);

    String serverURL = CarbonUIUtil.getServerURL(request.getSession().getServletContext(),
            request.getSession());
    ConfigurationContext configurationContext = (ConfigurationContext) request.getSession().getServletContext()
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
    String cookie = (String) request.getSession().getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    DBReportingServiceClient dbReportingServiceClient = null;
    try {
        dbReportingServiceClient = new DBReportingServiceClient(cookie, serverURL, configurationContext);
    } catch (AxisFault axisFault) {
        axisFault.printStackTrace();
    }
    List<ReportParamMap> reportParamMapsList = new ArrayList<ReportParamMap>();
    String[] parmCollection = params.split("\\|");

    for (String inputParam : parmCollection) {
        if (inputParam != null && !"".equals(inputParam)) {
            ReportParamMap reportParamMap = new ReportParamMap();
            String[] input = inputParam.split("\\=");
            reportParamMap.setParamKey(input[0]);
            reportParamMap.setParamValue(input[1]);
            reportParamMapsList.add(reportParamMap);
        }
    }

    try {
        DataHandler dataHandler = null;
        if (dbReportingServiceClient != null) {
            dataHandler = dbReportingServiceClient.getReport(reportBean,
                    reportParamMapsList.toArray(new ReportParamMap[reportParamMapsList.size()]));
        }
        ServletOutputStream outputStream = response.getOutputStream();
        if (dataHandler != null) {
            dataHandler.writeTo(outputStream);
        }
    } catch (Exception e) {
        log.error("Failed to handle report request ", e);
        throw e;
    }

}

From source file:org.apache.synapse.transport.passthru.util.ExpandingMessageFormatter.java

private void findAndWrite2OutputStream(MessageContext messageContext, OutputStream out, boolean preserve)
        throws AxisFault {
    try {/*  ww  w .  j  av  a2s .  co m*/
        SOAPEnvelope envelope = messageContext.getEnvelope();
        OMElement contentEle = envelope.getBody().getFirstElement();
        if (contentEle != null) {
            OMNode node = contentEle.getFirstOMChild();
            if (!(node instanceof OMText)) {
                String msg = "Wrong Input for the Validator, "
                        + "the content of the first child element of the Body " + "should have the zip file";
                log.error(msg);
                throw new AxisFault(msg);
            }
            OMText binaryDataNode = (OMText) node;
            DataHandler dh = (DataHandler) binaryDataNode.getDataHandler();

            DataSource dataSource = dh.getDataSource();
            //Ask the data source to stream, if it has not already cached the request
            if (!preserve && dataSource instanceof StreamingOnRequestDataSource) {
                ((StreamingOnRequestDataSource) dataSource).setLastUse(true);
            }
            dh.writeTo(out);
        }
    } catch (OMException e) {
        log.error(e);
        throw AxisFault.makeFault(e);
    } catch (IOException e) {
        log.error(e);
        throw AxisFault.makeFault(e);
    }
}

From source file:com.francetelecom.clara.cloud.mvn.consumer.maven.MavenDeployer.java

public DeployResult deployBin(MavenReference mavenReference, DataHandler binaryContent) {
    Validate.notNull(mavenReference, "Shoud not be null");
    Validate.notNull(binaryContent, "Shoud not be null");

    File projectDirectory = getProjectDirectory(mavenReference);
    File artifact = new File(projectDirectory, mavenReference.getArtifactName());
    try {/*  w  w  w.  j av a2s . co  m*/
        binaryContent.writeTo(new FileOutputStream(artifact));
    } catch (IOException e) {
        logger.error("failure storing artifact stream " + mavenReference, e);
        throw new TechnicalException(e);
    }
    return install(mavenReference, artifact, projectDirectory);
}

From source file:org.wso2.carbon.ui.transports.fileupload.AbstractFileUploadExecutor.java

private void copyFile(File src, File dst) throws IOException {
    String dstAbsPath = dst.getAbsolutePath();
    String dstDir = dstAbsPath.substring(0, dstAbsPath.lastIndexOf(File.separator));
    File dir = new File(dstDir);
    if (!dir.exists() && !dir.mkdirs()) {
        log.warn("Could not create " + dir.getAbsolutePath());
    }//from w w w.  ja v a 2  s .co m
    DataHandler dh = new DataHandler(src.toURL());
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(dst);
        dh.writeTo(out);
        out.flush();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:org.wso2.carbon.registry.resource.services.ResourceService.java

public boolean addExtension(String name, DataHandler content) throws Exception {
    File extension = new File(RegistryUtils.getExtensionLibDirectoryPath() + File.separator + name);
    File extensionsDirectory = extension.getParentFile();
    if (extensionsDirectory.exists() || extensionsDirectory.mkdir()) {
        OutputStream os = new FileOutputStream(extension);
        try {/* ww  w. ja  v  a  2s .c om*/
            content.writeTo(os);
        } finally {
            os.close();
        }
    }
    return true;
}

From source file:org.wso2.carbon.appfactory.utilities.storage.FileArtifactStorage.java

@Override
public void storeArtifact(String applicationId, String version, String revision, DataHandler data,
        String fileName) throws AppFactoryException {
    String path = getApplicationStorageDirectoryPath(applicationId, version, revision) + File.separator
            + fileName;//from w  ww.j a  v a  2 s . c  om
    try {
        File destFile = new File(path);

        if (destFile.exists() == true) {
            destFile.delete();
        }

        if (!destFile.getParentFile().exists()) {
            if (!destFile.getParentFile().mkdirs()) {
                throw new IOException("Failed to create directory structure.");
            }
        }

        FileOutputStream fileOutputStream = new FileOutputStream(destFile);
        data.writeTo(fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();

    } catch (IOException e) {
        log.error("Error storing the artifact file : " + e.getMessage(), e);
        throw new AppFactoryException("Error storing the artifact file : " + e.getMessage(), e);
    }
}

From source file:com.clustercontrol.monitor.dialog.EventReportDialog.java

protected boolean output() {
    boolean flag = false;
    // Write event file
    File file = new File(this.filePath);
    FileOutputStream fOut = null;
    try {/*from   w  ww  .  ja va2s  . com*/
        if (!file.createNewFile()) {
            m_log.warn("file is already exist.");
        }

        fOut = new FileOutputStream(file);

        DataHandler handler = null;

        Property condition = this.getInputData();

        // ?
        PropertyUtil.deletePropertyDefine(condition);
        EventFilterInfo filter = EventFilterPropertyUtil.property2dto(condition);
        MonitorEndpointWrapper wrapper = MonitorEndpointWrapper.getWrapper(this.managerName);
        String language = Locale.getDefault().getLanguage();
        handler = wrapper.downloadEventFile(this.facilityId, filter, this.fileName, language);
        handler.writeTo(fOut);

        // Start download file
        if (ClusterControlPlugin.isRAP()) {
            FileDownloader.openBrowser(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                    this.filePath, this.fileName);
        }

        flag = true;
    } catch (InvalidRole_Exception e) {
        // ??????
        MessageDialog.openInformation(null, Messages.getString("message"),
                Messages.getString("message.accesscontrol.16"));
    } catch (MonitorNotFound_Exception e) {
        MessageDialog.openError(null, Messages.getString("message"),
                Messages.getString("message.monitor.66") + ", " + HinemosMessage.replace(e.getMessage()));
    } catch (HinemosUnknown_Exception e) {
        MessageDialog.openError(null, Messages.getString("message"),
                Messages.getString("message.monitor.66") + ", " + HinemosMessage.replace(e.getMessage()));
    } catch (Exception e) {
        m_log.warn("run() downloadEventFile, " + e.getMessage(), e);
        MessageDialog.openError(null, Messages.getString("failed"),
                Messages.getString("message.hinemos.failure.unexpected") + ", "
                        + HinemosMessage.replace(e.getMessage()));
    } finally {
        try {
            if (fOut != null) {
                fOut.close();
            }
            if (ClusterControlPlugin.isRAP()) {
                // Clean up temporary file
                FileDownloader.cleanup(this.filePath);
            }
        } catch (IOException e) {
            m_log.warn("output() fileOutputStream.close(), " + e.getMessage(), e);
        }
        try {
            MonitorEndpointWrapper wrapper = MonitorEndpointWrapper.getWrapper(this.managerName);
            wrapper.deleteEventFile(this.fileName);
        } catch (Exception e) {
            m_log.warn("output() deleteEventFile, " + e.getMessage(), e);
        }
    }
    return flag;
}

From source file:org.apache.synapse.transport.fix.FIXUtils.java

private void generateFIXBody(OMElement node, FieldMap message, MessageContext msgCtx, boolean withNs,
        String nsURI, String nsPrefix) throws IOException {

    Iterator bodyElements = node.getChildElements();
    while (bodyElements.hasNext()) {
        OMElement bodyNode = (OMElement) bodyElements.next();
        String nodeLocalName = bodyNode.getLocalName();

        //handle repeating groups
        if (nodeLocalName.equals(FIXConstants.FIX_GROUPS)) {
            int groupsKey = Integer.parseInt(bodyNode.getAttributeValue(new QName(FIXConstants.FIX_FIELD_ID)));
            Group group;/*from   w  w w . j a  v  a 2  s.c o m*/
            Iterator groupElements = bodyNode.getChildElements();
            while (groupElements.hasNext()) {
                OMElement groupNode = (OMElement) groupElements.next();
                Iterator groupFields = groupNode.getChildrenWithName(new QName(FIXConstants.FIX_FIELD));
                List<Integer> idList = new ArrayList<Integer>();
                while (groupFields.hasNext()) {
                    OMElement fieldNode = (OMElement) groupFields.next();
                    idList.add(Integer
                            .parseInt(fieldNode.getAttributeValue(new QName(FIXConstants.FIX_FIELD_ID))));
                }

                int[] order = new int[idList.size()];
                for (int i = 0; i < order.length; i++) {
                    order[i] = idList.get(i);
                }

                group = new Group(groupsKey, order[0], order);
                generateFIXBody(groupNode, group, msgCtx, withNs, nsURI, nsPrefix);
                message.addGroup(group);
            }

        } else {
            String tag;
            if (withNs) {
                tag = bodyNode.getAttributeValue(new QName(nsURI, FIXConstants.FIX_FIELD_ID, nsPrefix));
            } else {
                tag = bodyNode.getAttributeValue(new QName(FIXConstants.FIX_FIELD_ID));
            }

            String value = null;
            OMElement child = bodyNode.getFirstElement();
            if (child != null) {
                String href;
                if (withNs) {
                    href = bodyNode.getFirstElement()
                            .getAttributeValue(new QName(nsURI, FIXConstants.FIX_FIELD_ID, nsPrefix));
                } else {
                    href = bodyNode.getFirstElement()
                            .getAttributeValue(new QName(FIXConstants.FIX_MESSAGE_REFERENCE));
                }

                if (href != null) {
                    DataHandler binaryDataHandler = msgCtx.getAttachment(href.substring(4));
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    binaryDataHandler.writeTo(outputStream);
                    value = new String(outputStream.toByteArray());
                }
            } else {
                value = bodyNode.getText();
            }

            if (value != null) {
                message.setString(Integer.parseInt(tag), value);
            }
        }
    }
}

From source file:org.apache.synapse.transport.fix.FIXUtils.java

/**
 * Extract the FIX message embedded in an Axis2 MessageContext
 *
 * @param msgCtx the Axis2 MessageContext
 * @return a FIX message/* ww  w .  j a v  a2s  .co m*/
 * @throws java.io.IOException the exception thrown when handling erroneous binary content
 */
public Message createFIXMessage(MessageContext msgCtx) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug(
                "Extracting FIX message from the message context (Message ID: " + msgCtx.getMessageID() + ")");
    }

    boolean withNs = false;
    String nsPrefix = null;
    String nsURI = null;

    Message message = new Message();
    SOAPBody soapBody = msgCtx.getEnvelope().getBody();

    //find namespace information embedded in the FIX payload
    OMNamespace ns = getNamespaceOfFIXPayload(soapBody);
    if (ns != null) {
        withNs = true;
        nsPrefix = ns.getPrefix();
        nsURI = ns.getNamespaceURI();
    }

    OMElement messageNode;
    if (withNs) {
        messageNode = soapBody.getFirstChildWithName(new QName(nsURI, FIXConstants.FIX_MESSAGE, nsPrefix));
    } else {
        messageNode = soapBody.getFirstChildWithName(new QName(FIXConstants.FIX_MESSAGE));
    }

    Iterator messageElements = messageNode.getChildElements();

    while (messageElements.hasNext()) {
        OMElement node = (OMElement) messageElements.next();
        //create FIX header
        if (node.getQName().getLocalPart().equals(FIXConstants.FIX_HEADER)) {
            Iterator headerElements = node.getChildElements();
            while (headerElements.hasNext()) {
                OMElement headerNode = (OMElement) headerElements.next();
                String tag;
                if (withNs) {
                    tag = headerNode.getAttributeValue(new QName(nsURI, FIXConstants.FIX_FIELD_ID, nsPrefix));
                } else {
                    tag = headerNode.getAttributeValue(new QName(FIXConstants.FIX_FIELD_ID));
                }
                String value = null;

                OMElement child = headerNode.getFirstElement();
                if (child != null) {
                    String href;
                    if (withNs) {
                        href = headerNode.getFirstElement().getAttributeValue(
                                new QName(nsURI, FIXConstants.FIX_MESSAGE_REFERENCE, nsPrefix));
                    } else {
                        href = headerNode.getFirstElement()
                                .getAttributeValue(new QName(FIXConstants.FIX_MESSAGE_REFERENCE));
                    }

                    if (href != null) {
                        DataHandler binaryDataHandler = msgCtx.getAttachment(href.substring(4));
                        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                        binaryDataHandler.writeTo(outputStream);
                        value = new String(outputStream.toByteArray());
                    }
                } else {
                    value = headerNode.getText();
                }

                if (value != null) {
                    message.getHeader().setString(Integer.parseInt(tag), value);
                }
            }

        } else if (node.getQName().getLocalPart().equals(FIXConstants.FIX_BODY)) {
            //create FIX body
            generateFIXBody(node, message, msgCtx, withNs, nsURI, nsPrefix);

        } else if (node.getQName().getLocalPart().equals(FIXConstants.FIX_TRAILER)) {
            //create FIX trailer
            Iterator trailerElements = node.getChildElements();
            while (trailerElements.hasNext()) {
                OMElement trailerNode = (OMElement) trailerElements.next();
                String tag;
                if (withNs) {
                    tag = trailerNode.getAttributeValue(new QName(nsURI, FIXConstants.FIX_FIELD_ID, nsPrefix));
                } else {
                    tag = trailerNode.getAttributeValue(new QName(FIXConstants.FIX_FIELD_ID));
                }
                String value = null;

                OMElement child = trailerNode.getFirstElement();
                if (child != null) {
                    String href;
                    if (withNs) {
                        href = trailerNode.getFirstElement()
                                .getAttributeValue(new QName(nsURI, FIXConstants.FIX_FIELD_ID, nsPrefix));
                    } else {
                        href = trailerNode.getFirstElement()
                                .getAttributeValue(new QName(FIXConstants.FIX_MESSAGE_REFERENCE));
                    }
                    if (href != null) {
                        DataHandler binaryDataHandler = msgCtx.getAttachment(href.substring(4));
                        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                        binaryDataHandler.writeTo(outputStream);
                        value = new String(outputStream.toByteArray());
                    }
                } else {
                    value = trailerNode.getText();
                }

                if (value != null) {
                    message.getTrailer().setString(Integer.parseInt(tag), value);
                }
            }
        }
    }
    return message;
}

From source file:org.wso2.carbon.appfactory.utilities.storage.FileArtifactStorage.java

@Override
public void storeArtifact(String applicationId, String version, String revision, String buildId,
        DataHandler data, String fileName) throws AppFactoryException {
    //String path = getStoragePathForArtifact(applicationId, version, buildId) + File.separator + fileName;
    String path = getApplicationStorageDirectoryPath(applicationId, version, revision) + File.separator
            + fileName;//from w  w  w  .j av  a2  s .c  om
    try {
        File destFile = new File(path);

        if (destFile.exists() == true) {
            if (destFile.isDirectory()) {
                FileUtils.deleteDirectory(destFile);
            } else {
                destFile.delete();
            }

        }

        if (!destFile.getParentFile().exists()) {
            if (!destFile.getParentFile().mkdirs()) {
                throw new IOException("Failed to create directory structure.");
            }
        }

        FileOutputStream fileOutputStream = new FileOutputStream(destFile);
        data.writeTo(fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();

    } catch (IOException e) {
        log.error("Error storing the artifact file : " + e.getMessage(), e);
        throw new AppFactoryException("Error storing the artifact file : " + e.getMessage(), e);
    }
}