Example usage for javax.activation DataHandler getContentType

List of usage examples for javax.activation DataHandler getContentType

Introduction

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

Prototype

public String getContentType() 

Source Link

Document

Return the MIME type of this object as retrieved from the source object.

Usage

From source file:org.wso2.carbon.service.mgt.ui.ServiceAdminClient.java

public void downloadServiceArchive(String serviceGroupName, String serviceType, HttpServletResponse response)
        throws AxisFault {
    try {/*from w  ww  .  j  ava  2  s .com*/
        ServletOutputStream out = response.getOutputStream();
        ServiceDownloadData downloadData = stub.downloadServiceArchive(serviceGroupName);
        if (downloadData != null) {
            DataHandler handler = downloadData.getServiceFileData();
            response.setHeader("Content-Disposition", "fileName=" + downloadData.getFileName());
            response.setContentType(handler.getContentType());
            InputStream in = handler.getDataSource().getInputStream();
            int nextChar;
            while ((nextChar = in.read()) != -1) {
                out.write((char) nextChar);
            }
            out.flush();
            in.close();
        } else {
            out.write("The requested service archive was not found on the server".getBytes());
        }
    } catch (RemoteException e) {
        handleException("error.downloading.service", e);
    } catch (IOException e) {
        handleException("error.downloading.service", e);
    }
}

From source file:org.apache.axis.attachments.DimeBodyPart.java

/**
 * Create a DIME Attachment Part./*from  w  w  w.  ja v a 2 s.  c om*/
 * @param dh the data for the attachment as a JAF datahadler.
 *    The type and foramt is derived from the DataHandler.
 * @param id  the ID for the DIME part.
 *
 */
public DimeBodyPart(DataHandler dh, String id) {
    this(dh, DimeTypeNameFormat.MIME, dh.getContentType(), id);

    String ct = dh.getContentType();

    if (ct != null) {
        ct = ct.trim();
        if (ct.toLowerCase().startsWith("application/uri")) {
            StringTokenizer st = new StringTokenizer(ct, " \t;");
            String t = st.nextToken(" \t;");

            if (t.equalsIgnoreCase("application/uri")) {
                for (; st.hasMoreTokens();) {
                    t = st.nextToken(" \t;");
                    if (t.equalsIgnoreCase("uri")) {
                        t = st.nextToken("=");
                        if (t != null) {
                            t = t.trim();
                            if (t.startsWith("\""))
                                t = t.substring(1);

                            if (t.endsWith("\""))
                                t = t.substring(0, t.length() - 1);
                            this.type = t.getBytes();
                            this.dtnf = DimeTypeNameFormat.URI;
                        }
                        return;
                    } else if (t.equalsIgnoreCase("uri=")) {
                        t = st.nextToken(" \t;");
                        if (null != t && t.length() != 0) {
                            t = t.trim();
                            if (t.startsWith("\""))
                                t = t.substring(1);
                            if (t.endsWith("\""))
                                t = t.substring(0, t.length() - 1);
                            this.type = t.getBytes();
                            this.dtnf = DimeTypeNameFormat.URI;
                            return;
                        }
                    } else if (t.toLowerCase().startsWith("uri=")) {
                        if (-1 != t.indexOf('=')) {
                            t = t.substring(t.indexOf('=')).trim();
                            if (t.length() != 0) {
                                t = t.trim();
                                if (t.startsWith("\""))
                                    t = t.substring(1);

                                if (t.endsWith("\""))
                                    t = t.substring(0, t.length() - 1);
                                this.type = t.getBytes();
                                this.dtnf = DimeTypeNameFormat.URI;
                                return;

                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> postFile(String httpsURL, String title, DataHandler attachment) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(httpsURL);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    // Get extension of attachment
    TikaConfig config = TikaConfig.getDefaultConfig();
    MimeTypes allTypes = config.getMimeRepository();
    String ext = allTypes.forName(attachment.getContentType()).getExtension();
    if (ext.equals("")) {
        ContentTypeEnum contentTypeEnum = ContentTypeEnum
                .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase());
        ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse("");
    }//from   ww w.j  a  va  2s  . c  o  m

    // Create file
    InputStream fis = attachment.getInputStream();
    byte[] bytes = IOUtils.toByteArray(fis);
    File f = new File(System.getProperty("user.dir") + "/fileTemp/" + title + ext);
    FileUtils.writeByteArrayToFile(f, bytes);
    builder.addBinaryBody("media", f);

    // Post to wechat
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    CloseableHttpResponse httpResponse = httpClient.execute(post);
    String content = "";
    try {
        HttpEntity _entity = httpResponse.getEntity();
        content = EntityUtils.toString(_entity);
        EntityUtils.consume(_entity);
    } finally {
        httpResponse.close();
    }
    f.delete();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> postFile(String httpsURL, DataHandler attachment) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(httpsURL);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    // Get extension of attachment
    TikaConfig config = TikaConfig.getDefaultConfig();
    MimeTypes allTypes = config.getMimeRepository();
    String ext = allTypes.forName(attachment.getContentType()).getExtension();
    if (ext.equals("")) {
        ContentTypeEnum contentTypeEnum = ContentTypeEnum
                .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase());
        ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse("");
    }//from w ww.  ja v a2 s  .co  m

    // Create file
    InputStream fis = attachment.getInputStream();
    byte[] bytes = IOUtils.toByteArray(fis);
    File f = new File(
            System.getProperty("user.dir") + "/fileTemp/" + attachment.getName().replace(ext, "") + ext);
    FileUtils.writeByteArrayToFile(f, bytes);
    builder.addBinaryBody("media", f);

    // Post to wechat
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    CloseableHttpResponse httpResponse = httpClient.execute(post);
    String content = "";
    try {
        HttpEntity _entity = httpResponse.getEntity();
        content = EntityUtils.toString(_entity);
        EntityUtils.consume(_entity);
    } finally {
        httpResponse.close();
    }
    f.delete();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

From source file:org.apache.axis.attachments.AttachmentPart.java

/**
 * Bulds a new <code>AttachmentPart</code> with a <code>DataHandler</code>.
 *
 * @param dh the <code>DataHandler</code>
 *///from   w  w  w  .  j a va 2 s .  c o m
public AttachmentPart(javax.activation.DataHandler dh) {
    setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, SessionUtils.generateSessionId());
    datahandler = dh;
    if (dh != null) {
        setMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE, dh.getContentType());
        javax.activation.DataSource ds = dh.getDataSource();
        if (ds instanceof ManagedMemoryDataSource) {
            extractFilename((ManagedMemoryDataSource) ds); //and get the filename if appropriate

        }
    }
}

From source file:org.wso2.carbon.bpel.core.ode.integration.axis2.receivers.BPELMessageReceiver.java

private TAttachment createAttachmentDTO(DataHandler attachmentHandler) {
    TAttachment attachment = new TAttachment();

    String attachmentName = attachmentHandler.getName();
    attachment.setName(attachmentName);//from   w ww.  j  a  v a2s.  c  om

    log.warn("Couldn't determine the name of BPEL client. So the owner of the attachment:" + attachmentName
            + " " + "will be the default bpel client"
            + org.wso2.carbon.bpel.core.BPELConstants.DAFAULT_BPEL_CLIENT);
    attachment.setCreatedBy(org.wso2.carbon.bpel.core.BPELConstants.DAFAULT_BPEL_CLIENT);

    attachment.setContentType(attachmentHandler.getContentType());
    //As well there are some other parameters to be set.
    attachment.setContent(attachmentHandler);

    return attachment;
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> postFile(String httpsURL, String title, String introduction, DataHandler attachment)
        throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(httpsURL);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    // Get extension of attachment
    TikaConfig config = TikaConfig.getDefaultConfig();
    MimeTypes allTypes = config.getMimeRepository();
    String ext = allTypes.forName(attachment.getContentType()).getExtension();
    if (ext.equals("")) {
        ContentTypeEnum contentTypeEnum = ContentTypeEnum
                .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase());
        ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse("");
    }/*from  ww  w  .j  a v  a  2  s .  c o  m*/

    // Create file
    InputStream fis = attachment.getInputStream();
    byte[] bytes = IOUtils.toByteArray(fis);
    File f = new File(System.getProperty("user.dir") + "/fileTemp/" + title + ext);
    FileUtils.writeByteArrayToFile(f, bytes);

    // Create JSON
    JSONObject obj = new JSONObject();
    obj.put("title", title);
    obj.put("introduction", introduction);
    ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
    builder.addBinaryBody("media", f);
    builder.addTextBody("description", obj.toString(), contentType);

    // Post to wechat
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    CloseableHttpResponse httpResponse = httpClient.execute(post);
    String content = "";
    try {
        HttpEntity _entity = httpResponse.getEntity();
        content = EntityUtils.toString(_entity);
        EntityUtils.consume(_entity);
    } finally {
        httpResponse.close();
    }
    f.delete();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

From source file:org.apache.axis.attachments.AttachmentPart.java

/**
 * Sets the given <CODE>DataHandler</CODE> object as the
 * data handler for this <CODE>AttachmentPart</CODE> object.
 * Typically, on an incoming message, the data handler is
 * automatically set. When a message is being created and
 * populated with content, the <CODE>setDataHandler</CODE>
 * method can be used to get data from various data sources into
 * the message.//from  ww  w .j a v  a2s.  co  m
 * @param  datahandler  <CODE>DataHandler</CODE> object to
 *     be set
 * @throws java.lang.IllegalArgumentException if
 *     there was a problem with the specified <CODE>
 *     DataHandler</CODE> object
 */
public void setDataHandler(DataHandler datahandler) {
    if (datahandler == null) {
        throw new java.lang.IllegalArgumentException(Messages.getMessage("illegalArgumentException00"));
    }
    this.datahandler = datahandler;
    setMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE, datahandler.getContentType());
    //now look at the source of the data
    javax.activation.DataSource ds = datahandler.getDataSource();
    if (ds instanceof ManagedMemoryDataSource) {
        //and get the filename if appropriate
        extractFilename((ManagedMemoryDataSource) ds);
    }

}

From source file:com.aipo.social.opensocial.spi.AipoStorageService.java

@Override
public String getContentType(String filePath, SecurityToken paramSecurityToken)
        throws ProtocolException, FileNotFoundException {
    String contenType = null;//w  ww  .ja va 2s .  c  om
    File file = new File(filePath);
    DataHandler hData = new DataHandler(new FileDataSource(file));

    if (hData != null) {
        contenType = hData.getContentType();
    }
    return contenType;
}

From source file:org.wso2.carbon.webapp.list.ui.WebappAdminClient.java

public void downloadWarFileHandler(String fileName, String hostName, String webappType,
        HttpServletResponse response) throws AxisFault {
    try {/* w ww .j a va2 s.c  om*/
        ServletOutputStream out = response.getOutputStream();
        DataHandler handler = stub.downloadWarFileHandler(fileName, hostName, webappType);
        if (handler != null) {
            if ("jaggeryWebapp".equals(webappType)) {
                if (!fileName.endsWith(".zip")) {
                    fileName = fileName.concat(".zip");
                }
            } else if (!fileName.endsWith(".war")) {
                fileName = fileName.concat(".war");
            }
            response.setHeader("Content-Disposition", "fileName=" + fileName);
            response.setContentType(handler.getContentType());
            InputStream in = handler.getDataSource().getInputStream();
            int nextChar;
            while ((nextChar = in.read()) != -1) {
                out.write((char) nextChar);
            }
            out.flush();
            in.close();
        } else {
            out.write("The requested webapp was not found on the server".getBytes());
        }
    } catch (RemoteException e) {
        handleException("error.downloading.war", e);
    } catch (IOException e) {
        handleException("error.downloading.war", e);
    }
}