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.apache.axiom.attachments.Attachments.java

/**
 * Get the content type of the SOAP part of the MIME message.
 * //from ww w .j  a va 2  s .co m
 * @return the content type of the SOAP part
 * @throws OMException
 *             if the content type could not be determined
 */
public String getSOAPPartContentType() {
    if (!noStreams) {
        String soapPartContentID = getSOAPPartContentID();
        if (soapPartContentID == null) {
            throw new OMException("Unable to determine the content ID of the SOAP part");
        }
        DataHandler soapPart = getDataHandler(soapPartContentID);
        if (soapPart == null) {
            throw new OMException("Unable to locate the SOAP part; content ID was " + soapPartContentID);
        }
        return soapPart.getContentType();
    } else {
        throw new OMException("The attachments map was created programatically. Unsupported operation.");
    }
}

From source file:org.sciflex.plugins.synapse.esper.mediators.helpers.EPLStatementHelper.java

/**
 * Changes EPL query.//from  w  ww.  j  a va  2s .  c  o m
 *
 * @param query    EPL query.
 * @param registry Registry to use.
 */
public void setEPL(String query, Registry registry) {
    if (registryKey == null) {
        eplStatement = query;
        synchronized (statementLock) {
            statement = provider.getEPAdministrator().createEPL(eplStatement);
            queryActivityMonitor.notify(eplStatement);
        }
        if (listener != null)
            addListener(listener);
    } else if (registry == null) {
        log.error("Cannot lookup Registry");
    } else {
        // You can't fetch while updating. And if you try to do so
        // you may end up getting an incorrect result. Also, changes
        // to registryKey during the process is not allowed.
        synchronized (registryFetchLock) {
            OMNode eplNode = registry.lookup(registryKey);
            OMNode eplNodeNew = null;
            if (eplNode == null) {
                log.error("Registry lookup for EPL statement failed");
            } else if (eplNode instanceof OMElement) {
                ((OMElement) eplNode).getAttribute(new QName("value")).setAttributeValue(eplStatement);
                eplNodeNew = eplNode;
            } else if (eplNode instanceof OMText) {
                DataHandler dh = (DataHandler) (((OMText) eplNode).getDataHandler());
                if (dh == null) {
                    log.error("Error getting EPL statement");
                } else {
                    DataHandler dhNew = null;
                    try {
                        Object content = dh.getContent();
                        if (content instanceof InputStream) {
                            dhNew = new DataHandler(new ByteArrayInputStream(eplStatement.getBytes("UTF-8")),
                                    dh.getContentType());
                        } else if (content instanceof String)
                            dhNew = new DataHandler(eplStatement, dh.getContentType());
                        else {
                            log.error("Content fetched from Registry is not valid");
                        }
                        if (dhNew != null) {
                            OMFactory omFactory = OMAbstractFactory.getOMFactory();
                            eplNodeNew = omFactory.createOMText(dhNew, false);
                        } else {
                            log.error("Failed Creating Data Handler");
                        }
                    } catch (IOException e) {
                        log.error("An error occured while changing EPL statement " + e.getMessage());
                    }
                }
            } else
                log.error("Invalid EPL statement object retrieved");
            if (eplNodeNew == null) {
                log.error("An error occured while changing EPL statement");
            } else {
                updateRegistryResource(registryKey, eplNodeNew, registry);
                synchronized (expiryTimeLock) {
                    expiryTime = 0L;
                }
            }
        }
    }
    log.info("EPL Statement successfully changed");
}

From source file:com.aimluck.eip.gpdb.util.GpdbUtils.java

/**
 * ??//from   w w  w  .ja v a2 s . co  m
 * 
 * @param gpdbRecordId
 *          WebID
 * @return 
 */
public static List<FileuploadBean> getAttachmentFiles(int gpdbRecordId) {

    List<EipTGpdbRecordFile> fileList = getEipTGpdbRecordFileList(gpdbRecordId);

    if (fileList != null && fileList.size() > 0) {

        List<FileuploadBean> attachmentFileList = new ArrayList<FileuploadBean>();
        FileuploadBean filebean = null;
        EipTGpdbRecordFile file = null;

        int size = fileList.size();
        for (int i = 0; i < size; i++) {
            file = fileList.get(i);
            String realname = file.getFileName();
            javax.activation.DataHandler hData = new javax.activation.DataHandler(
                    new javax.activation.FileDataSource(realname));

            filebean = new FileuploadBean();
            filebean.setFileId(file.getFileId().intValue());
            filebean.setFileName(realname);
            if (hData != null) {
                filebean.setContentType(hData.getContentType());
            }
            filebean.setIsImage(FileuploadUtils.isImage(realname));
            attachmentFileList.add(filebean);
        }
        return attachmentFileList;
    }
    return new ArrayList<FileuploadBean>();
}

From source file:com.aimluck.eip.msgboard.MsgboardTopicSelectData.java

/**
 * ResultData ??????? <BR>/*  w  w  w .  j a va  2 s . co m*/
 *
 * @param obj
 * @return
 */
@Override
protected Object getResultDataDetail(EipTMsgboardTopic record)
        throws ALPageNotFoundException, ALDBErrorException {
    try {

        // ??????
        if (record.getParentId().intValue() == 0) {
            EipTMsgboardCategory category = record.getEipTMsgboardCategory();
            if ("T".equals(category.getPublicFlag())) {
                List<?> categoryMap = category.getEipTMsgboardCategoryMaps();
                int mapsize = categoryMap.size();
                for (int i = 0; i < mapsize; i++) {
                    EipTMsgboardCategoryMap map = (EipTMsgboardCategoryMap) categoryMap.get(i);
                    if ("A".equals(map.getStatus())) {
                        showReplyForm = true;
                    } else {
                        if (map.getUserId().intValue() == uid) {
                            // ????
                            showReplyForm = true;
                            break;
                        }
                    }

                }
            } else {
                // ?????
                // ?????
                showReplyForm = true;
            }
        }

        MsgboardTopicResultData rd = new MsgboardTopicResultData();
        rd.initField();
        rd.setTopicId(record.getTopicId().longValue());
        rd.setTopicName(record.getTopicName());
        rd.setParentId(record.getParentId().longValue());
        rd.setCategoryId(record.getEipTMsgboardCategory().getCategoryId().longValue());
        rd.setCategoryName(record.getEipTMsgboardCategory().getCategoryName());
        // /??
        rd.setPublicFlag("T".equals(record.getEipTMsgboardCategory().getPublicFlag()));
        rd.setOwnerId(record.getOwnerId().longValue());
        rd.setOwnerName(ALEipUtils.getUserFullName(record.getOwnerId().intValue()));
        ALEipUser user = ALEipUtils.getALEipUser(record.getOwnerId().intValue());
        if (user != null) {
            rd.setOwnerHasPhoto(user.hasPhoto());
        }
        rd.setNote(record.getNote());
        rd.setCreateDate(record.getCreateDate());
        rd.setUpdateDate(record.getUpdateDate());
        rd.setLoginUserId(uid);

        List<EipTMsgboardFile> list = getSelectQueryForFiles(record.getTopicId().intValue()).fetchList();
        if (list != null && list.size() > 0) {
            List<FileuploadBean> attachmentFileList = new ArrayList<FileuploadBean>();
            FileuploadBean filebean = null;
            EipTMsgboardFile file = null;
            int size = list.size();
            for (int i = 0; i < size; i++) {
                file = list.get(i);
                String realname = file.getFileName();
                javax.activation.DataHandler hData = new javax.activation.DataHandler(
                        new javax.activation.FileDataSource(realname));

                filebean = new FileuploadBean();
                filebean.setFileId(file.getFileId().intValue());
                filebean.setFileName(realname);
                if (hData != null) {
                    filebean.setContentType(hData.getContentType());
                }
                filebean.setIsImage(FileuploadUtils.isImage(realname));
                attachmentFileList.add(filebean);
            }
            rd.setAttachmentFiles(attachmentFileList);
        }

        return rd;
    } catch (Exception e) {
        logger.error("[MsgboardTopicSelectData]", e);
        throw new ALDBErrorException();
    }
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java

protected MultipartRequestEntity createMultiPart(MuleMessage msg, EntityEnclosingMethod method)
        throws Exception {
    Part[] parts;/*from  w w w .ja  v  a2s  .c  om*/
    int i = 0;
    if (msg.getPayload() instanceof NullPayload) {
        parts = new Part[msg.getOutboundAttachmentNames().size()];
    } else {
        parts = new Part[msg.getOutboundAttachmentNames().size() + 1];
        parts[i++] = new FilePart("payload", new ByteArrayPartSource("payload", msg.getPayloadAsBytes()));
    }

    for (final Iterator<String> iterator = msg.getOutboundAttachmentNames().iterator(); iterator
            .hasNext(); i++) {
        final String attachmentNames = iterator.next();
        String fileName = attachmentNames;
        final DataHandler dh = msg.getOutboundAttachment(attachmentNames);
        if (dh.getDataSource() instanceof StringDataSource) {
            final StringDataSource ds = (StringDataSource) dh.getDataSource();
            parts[i] = new StringPart(ds.getName(), IOUtils.toString(ds.getInputStream()));
        } else {
            if (dh.getDataSource() instanceof FileDataSource) {
                fileName = ((FileDataSource) dh.getDataSource()).getFile().getName();
            } else if (dh.getDataSource() instanceof URLDataSource) {
                fileName = ((URLDataSource) dh.getDataSource()).getURL().getFile();
                // Don't use the whole file path, just the file name
                final int x = fileName.lastIndexOf("/");
                if (x > -1) {
                    fileName = fileName.substring(x + 1);
                }
            }
            parts[i] = new FilePart(dh.getName(),
                    new ByteArrayPartSource(fileName, IOUtils.toByteArray(dh.getInputStream())),
                    dh.getContentType(), null);
        }
    }

    return new MultipartRequestEntity(parts, method.getParams());
}

From source file:org.apache.axis.handlers.MD5AttachHandler.java

public void invoke(MessageContext msgContext) throws AxisFault {
    log.debug("Enter: MD5AttachHandler::invoke");
    try {/*from   w w w .j  a  va 2  s  .  c  om*/
        // log.debug("IN MD5");        
        Message msg = msgContext.getRequestMessage();
        SOAPConstants soapConstants = msgContext.getSOAPConstants();
        org.apache.axis.message.SOAPEnvelope env = (org.apache.axis.message.SOAPEnvelope) msg.getSOAPEnvelope();
        org.apache.axis.message.SOAPBodyElement sbe = env.getFirstBody();//env.getBodyByName("ns1", "addedfile");
        org.w3c.dom.Element sbElement = sbe.getAsDOM();
        //get the first level accessor  ie parameter
        org.w3c.dom.Node n = sbElement.getFirstChild();

        for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling())
            ;
        org.w3c.dom.Element paramElement = (org.w3c.dom.Element) n;
        //Get the href associated with the attachment.
        String href = paramElement.getAttribute(soapConstants.getAttrHref());
        org.apache.axis.Part ap = msg.getAttachmentsImpl().getAttachmentByReference(href);
        javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils
                .getActivationDataHandler(ap);
        org.w3c.dom.Node timeNode = paramElement.getFirstChild();
        long startTime = -1;

        if (timeNode != null && timeNode instanceof org.w3c.dom.Text) {
            String startTimeStr = ((org.w3c.dom.Text) timeNode).getData();

            startTime = Long.parseLong(startTimeStr);
        }
        // log.debug("GOTIT");

        long receivedTime = System.currentTimeMillis();
        long elapsedTime = -1;

        // log.debug("startTime=" + startTime);
        // log.debug("receivedTime=" + receivedTime);            
        if (startTime > 0)
            elapsedTime = receivedTime - startTime;
        String elapsedTimeStr = elapsedTime + "";
        // log.debug("elapsedTimeStr=" + elapsedTimeStr);            

        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        java.io.InputStream attachmentStream = dh.getInputStream();
        int bread = 0;
        byte[] buf = new byte[64 * 1024];

        do {
            bread = attachmentStream.read(buf);
            if (bread > 0) {
                md.update(buf, 0, bread);
            }
        } while (bread > -1);
        attachmentStream.close();
        buf = null;
        //Add the mime type to the digest.
        String contentType = dh.getContentType();

        if (contentType != null && contentType.length() != 0) {
            md.update(contentType.getBytes("US-ASCII"));
        }

        sbe = env.getFirstBody();
        sbElement = sbe.getAsDOM();
        //get the first level accessor  ie parameter
        n = sbElement.getFirstChild();
        for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling())
            ;
        paramElement = (org.w3c.dom.Element) n;
        // paramElement.setAttribute(soapConstants.getAttrHref(), respHref);
        String MD5String = org.apache.axis.encoding.Base64.encode(md.digest());
        String senddata = " elapsedTime=" + elapsedTimeStr + " MD5=" + MD5String;

        // log.debug("senddata=" + senddata);            
        paramElement.appendChild(paramElement.getOwnerDocument().createTextNode(senddata));

        sbe = new org.apache.axis.message.SOAPBodyElement(sbElement);
        env.clearBody();
        env.addBodyElement(sbe);
        msg = new Message(env);

        msgContext.setResponseMessage(msg);
    } catch (Exception e) {
        log.error(Messages.getMessage("exception00"), e);
        throw AxisFault.makeFault(e);
    }

    log.debug("Exit: MD5AttachHandler::invoke");
}

From source file:com.collabnet.ccf.pi.cee.pt.v50.ProjectTrackerReader.java

@Override
public List<GenericArtifact> getArtifactAttachments(Document syncInfo, GenericArtifact artifactData) {
    String artifactId = artifactData.getSourceArtifactId();
    String artifactIdentifier = artifactId.substring(artifactId.lastIndexOf(":") + 1);
    Date lastModifiedDate = this.getLastModifiedDate(syncInfo);
    long fromTime = lastModifiedDate.getTime();
    // long toTime = System.currentTimeMillis();
    TrackerArtifactType trackerArtifactType = this.getTrackerArtifactTypeForArtifactId(syncInfo, artifactId);
    ArtifactType[] ata = new ArtifactType[1];
    ata[0] = new ArtifactType(trackerArtifactType.getTagName(), trackerArtifactType.getNamespace(),
            trackerArtifactType.getDisplayName());
    ArrayList<GenericArtifact> attachmentGAs = new ArrayList<GenericArtifact>();
    TrackerWebServicesClient twsclient = null;

    try {/*w  w w .  j a  v  a2s.  co m*/
        twsclient = this.getConnection(syncInfo);
        ArtifactHistoryList ahl = ProjectTrackerReader.artifactHistoryList.get();
        History historyList[] = null;
        if (ahl != null)
            historyList = ahl.getHistory();
        if (historyList != null) {
            for (History history : historyList) {
                HistoryTransaction[] transactions = history.getHistoryTransaction();
                int transactionsCount = transactions == null ? 0 : transactions.length;
                for (int i = 0; i < transactionsCount; i++) {
                    HistoryTransaction ht = transactions[i];
                    String modifiedBy = ht.getModifiedBy();
                    if ((!getConnectorUserDisplayName().equals(modifiedBy) || !isIgnoreConnectorUserUpdates())
                            && (!modifiedBy.equals(
                                    getResyncUserDisplayName() == null ? "" : getResyncUserDisplayName())
                                    || !isIgnoreConnectorUserUpdates())
                            && ht.getModifiedOn() > fromTime) {
                        HistoryActivity[] haa = ht.getHistoryActivity();
                        for (HistoryActivity ha : haa) {
                            String historyArtifactId = ha.getArtifactId();
                            if (historyArtifactId.equals(artifactIdentifier)) {
                                if (ha.getTagName().equals(ATTACHMENT_TAG_NAME)) {
                                    if (ha.getType().equals(ATTACHMENT_ADDED_HISTORY_ACTIVITY_TYPE)) {
                                        String[] attachmentIds = ha.getNewValue();
                                        for (String attachmentId : attachmentIds) {
                                            if (attachmentId == null || attachmentIDNameMap == null)
                                                continue;

                                            String attachmentName = null;
                                            String attachmentDescription = null;
                                            ClientArtifactAttachment attachment = attachmentIDNameMap
                                                    .get(attachmentId);
                                            if (attachment == null) {
                                                log.warn("Attachment with id " + attachmentId
                                                        + " does not exist!");
                                                continue;
                                            }
                                            attachmentName = attachment.getAttachmentName();
                                            attachmentDescription = attachment.getDescription();
                                            if (StringUtils.isEmpty(attachmentName)) {
                                                attachmentName = "PT-Attachment" + attachmentId + ".file";
                                                log.warn(
                                                        "Could not determine attachment name for attachment id "
                                                                + attachmentId);
                                            }

                                            GenericArtifact ga = new GenericArtifact();
                                            ga.setArtifactAction(GenericArtifact.ArtifactActionValue.CREATE);
                                            ga.setSourceArtifactLastModifiedDate(
                                                    artifactData.getSourceArtifactLastModifiedDate());
                                            ga.setArtifactMode(
                                                    GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY);
                                            ga.setArtifactType(GenericArtifact.ArtifactTypeValue.ATTACHMENT);
                                            ga.setDepParentSourceArtifactId(artifactId);
                                            ga.setSourceArtifactId(attachmentId);
                                            ga.setSourceArtifactVersion(
                                                    artifactData.getSourceArtifactVersion());
                                            GenericArtifactField contentTypeField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_TYPE,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            contentTypeField
                                                    .setFieldValue(AttachmentMetaData.AttachmentType.DATA);
                                            contentTypeField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            contentTypeField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);
                                            GenericArtifactField sourceURLField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_SOURCE_URL,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            sourceURLField
                                                    .setFieldValue(AttachmentMetaData.AttachmentType.LINK);
                                            sourceURLField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            sourceURLField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);

                                            GenericArtifactField nameField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_NAME,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            nameField.setFieldValue(attachmentName);
                                            nameField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            nameField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);

                                            GenericArtifactField descriptionField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_DESCRIPTION,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            descriptionField.setFieldValue(attachmentDescription);
                                            descriptionField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            descriptionField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);

                                            GenericArtifactField mimeTypeField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_MIME_TYPE,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            mimeTypeField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            mimeTypeField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);

                                            long size = 0;
                                            DataHandler handler = null;
                                            try {
                                                handler = twsclient.getDataHandlerForAttachment(
                                                        artifactIdentifier, attachmentId);
                                            } catch (WSException e) {
                                                int code = e.getCode();
                                                if (code == 214) {
                                                    continue;
                                                } else
                                                    throw e;
                                            }
                                            String contentType = handler.getContentType();
                                            mimeTypeField.setFieldValue(contentType);
                                            String axisFileName = handler.getName();
                                            File attachmentAxisFile = new File(axisFileName);
                                            size = attachmentAxisFile.length();
                                            long maxAttachmentSize = this.getMaxAttachmentSizePerArtifact();
                                            if (size > maxAttachmentSize) {
                                                log.warn("Attachment " + attachmentName + " is of size " + size
                                                        + " bytes."
                                                        + " This is more than the configured maximum attachment size"
                                                        + " that can be shipped in an artifact");
                                                continue;
                                            }
                                            if (!this.isShipAttachmentsWithArtifact()) {
                                                File tempFile = null;
                                                FileOutputStream fos = null;
                                                FileInputStream fis = null;
                                                try {
                                                    if (attachmentAxisFile.exists()) {
                                                        byte[] bytes = new byte[1024 * 3];
                                                        tempFile = File.createTempFile("PT_Attachment",
                                                                ".file");

                                                        String attachmentDataFile = tempFile.getAbsolutePath();
                                                        int readBytes = 0;
                                                        fos = new FileOutputStream(tempFile);
                                                        fis = new FileInputStream(attachmentAxisFile);
                                                        while ((readBytes = fis.read(bytes)) != -1) {
                                                            fos.write(bytes, 0, readBytes);
                                                        }
                                                        fos.close();
                                                        GenericArtifactField attachmentDataFileField = ga
                                                                .addNewField(
                                                                        AttachmentMetaData.ATTACHMENT_DATA_FILE,
                                                                        GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                                        attachmentDataFileField.setFieldValueType(
                                                                GenericArtifactField.FieldValueTypeValue.STRING);
                                                        attachmentDataFileField
                                                                .setFieldValue(attachmentDataFile);
                                                        attachmentDataFileField.setFieldAction(
                                                                GenericArtifactField.FieldActionValue.REPLACE);
                                                        bytes = null;
                                                    }
                                                } catch (IOException e) {
                                                    String message = "Could not write attachment content to temp file."
                                                            + " Shipping the attachment with the artifact.";
                                                    log.error(message, e);
                                                    throw new CCFRuntimeException(message, e);
                                                } finally {
                                                    if (fis != null) {
                                                        try {
                                                            fis.close();
                                                        } catch (IOException e) {
                                                            log.warn("Could not close input stream for "
                                                                    + attachmentAxisFile.getAbsolutePath());
                                                        }
                                                    }
                                                    if (fos != null) {
                                                        try {
                                                            fos.close();
                                                        } catch (IOException e) {
                                                            String filename = "";
                                                            if (tempFile != null) {
                                                                filename = tempFile.getAbsolutePath();
                                                            }
                                                            log.warn("Could not close output stream for "
                                                                    + filename);
                                                        }
                                                    }
                                                }
                                            } else {
                                                InputStream is = handler.getInputStream();
                                                byte[] bytes = new byte[(int) size];
                                                is.read(bytes);
                                                is.close();
                                                ga.setRawAttachmentData(bytes);
                                            }
                                            GenericArtifactField sizeField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_SIZE,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            sizeField.setFieldValue(size);
                                            sizeField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            sizeField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);
                                            populateSrcAndDestForAttachment(syncInfo, ga);
                                            attachmentGAs.add(ga);
                                        }
                                    } else if (ha.getType().equals(ATTACHMENT_DELETED_HISTORY_ACTIVITY_TYPE)) {
                                        String[] attachmentIds = ha.getOldValue();
                                        for (String attachmentId : attachmentIds) {
                                            if (attachmentId == null)
                                                continue;
                                            GenericArtifact ga = new GenericArtifact();
                                            ga.setArtifactAction(GenericArtifact.ArtifactActionValue.DELETE);
                                            ga.setSourceArtifactLastModifiedDate(
                                                    artifactData.getSourceArtifactLastModifiedDate());
                                            ga.setArtifactMode(
                                                    GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY);
                                            ga.setArtifactType(GenericArtifact.ArtifactTypeValue.ATTACHMENT);
                                            ga.setDepParentSourceArtifactId(artifactId);
                                            ga.setSourceArtifactId(attachmentId);
                                            ga.setSourceArtifactVersion(
                                                    artifactData.getSourceArtifactVersion());
                                            GenericArtifactField contentTypeField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_TYPE,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            contentTypeField
                                                    .setFieldValue(AttachmentMetaData.AttachmentType.DATA);
                                            contentTypeField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            contentTypeField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);
                                            populateSrcAndDestForAttachment(syncInfo, ga);
                                            attachmentGAs.add(ga);
                                        }
                                    } else if (ha.getType().equals(URL_ADDED_HISTORY_ACTIVITY_TYPE)) {
                                        String[] attachmentIds = ha.getNewValue();
                                        for (String attachmentId : attachmentIds) {
                                            if (linkIDNameMap == null || linkIDNameMap.size() == 0)
                                                continue;
                                            Set<Entry<String, ClientArtifactAttachment>> linkIDEntry = linkIDNameMap
                                                    .entrySet();
                                            Iterator<Entry<String, ClientArtifactAttachment>> linkEntryIt = linkIDEntry
                                                    .iterator();
                                            String attachmentName = null;
                                            String attachmentDescription = null;
                                            if (linkEntryIt.hasNext()) {
                                                Entry<String, ClientArtifactAttachment> entry = linkEntryIt
                                                        .next();
                                                ClientArtifactAttachment clientArtifactAttachment = entry
                                                        .getValue();
                                                attachmentName = clientArtifactAttachment.getAttachmentName();
                                                attachmentDescription = clientArtifactAttachment
                                                        .getDescription();
                                                attachmentId = entry.getKey();
                                            }

                                            GenericArtifact ga = new GenericArtifact();
                                            ga.setArtifactAction(GenericArtifact.ArtifactActionValue.CREATE);

                                            ga.setSourceArtifactLastModifiedDate(
                                                    artifactData.getSourceArtifactLastModifiedDate());

                                            ga.setArtifactMode(
                                                    GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY);
                                            ga.setArtifactType(GenericArtifact.ArtifactTypeValue.ATTACHMENT);
                                            ga.setDepParentSourceArtifactId(artifactId);
                                            ga.setSourceArtifactId(attachmentId);
                                            ga.setSourceArtifactVersion(
                                                    artifactData.getSourceArtifactVersion());

                                            GenericArtifactField contentTypeField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_TYPE,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            contentTypeField
                                                    .setFieldValue(AttachmentMetaData.AttachmentType.LINK);
                                            contentTypeField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            contentTypeField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);
                                            GenericArtifactField sourceURLField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_SOURCE_URL,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            sourceURLField.setFieldValue(attachmentName);
                                            sourceURLField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            sourceURLField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);

                                            GenericArtifactField descriptionField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_DESCRIPTION,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            descriptionField.setFieldValue(attachmentDescription);
                                            descriptionField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            descriptionField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);

                                            GenericArtifactField nameField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_NAME,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            nameField.setFieldValue(attachmentName);
                                            nameField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            nameField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);
                                            populateSrcAndDestForAttachment(syncInfo, ga);
                                            attachmentGAs.add(ga);
                                        }
                                    } else if (ha.getType().equals(URL_DELETED_HISTORY_ACTIVITY_TYPE)) {
                                        String[] attachmentIds = ha.getOldValue();
                                        for (String attachmentId : attachmentIds) {
                                            if (attachmentId == null)
                                                continue;
                                            GenericArtifact ga = new GenericArtifact();
                                            ga.setArtifactAction(GenericArtifact.ArtifactActionValue.DELETE);
                                            ga.setSourceArtifactLastModifiedDate(
                                                    artifactData.getSourceArtifactLastModifiedDate());

                                            ga.setArtifactMode(
                                                    GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY);
                                            ga.setArtifactType(GenericArtifact.ArtifactTypeValue.ATTACHMENT);
                                            ga.setDepParentSourceArtifactId(artifactId);
                                            ga.setSourceArtifactId(attachmentId);
                                            ga.setSourceArtifactVersion(
                                                    artifactData.getSourceArtifactVersion());
                                            GenericArtifactField contentTypeField = ga.addNewField(
                                                    AttachmentMetaData.ATTACHMENT_TYPE,
                                                    GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                            contentTypeField
                                                    .setFieldValue(AttachmentMetaData.AttachmentType.DATA);
                                            contentTypeField.setFieldAction(
                                                    GenericArtifactField.FieldActionValue.REPLACE);
                                            contentTypeField.setFieldValueType(
                                                    GenericArtifactField.FieldValueTypeValue.STRING);
                                            populateSrcAndDestForAttachment(syncInfo, ga);
                                            attachmentGAs.add(ga);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        String message = "Exception while getting the attachment data";
        log.error(message, e);
        throw new CCFRuntimeException(message, e);
    } finally {
        ProjectTrackerReader.artifactHistoryList.set(null);
        this.attachmentIDNameMap = null;
        this.linkIDNameMap = null;
        if (twsclient != null) {
            getConnectionManager().releaseConnection(twsclient);
            twsclient = null;
        }
    }
    return attachmentGAs;
}

From source file:org.apache.axis2.transport.mail.MailTransportSender.java

/**
 * Populate email with a SOAP formatted message
 * @param outInfo the out transport information holder
 * @param msgContext the message context that holds the message to be written
 * @throws AxisFault on error/*  w ww. ja v  a 2 s .c  o  m*/
 * @return id of the send mail message
 */
private String sendMail(MailOutTransportInfo outInfo, MessageContext msgContext)
        throws AxisFault, MessagingException, IOException {

    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    // Make sure that non textual attachements are sent with base64 transfer encoding
    // instead of binary.
    format.setProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS, true);

    MessageFormatter messageFormatter = BaseUtils.getMessageFormatter(msgContext);

    if (log.isDebugEnabled()) {
        log.debug(
                "Creating MIME message using message formatter " + messageFormatter.getClass().getSimpleName());
    }

    WSMimeMessage message = null;
    if (outInfo.getFromAddress() != null) {
        message = new WSMimeMessage(session, outInfo.getFromAddress().getAddress());
    } else {
        message = new WSMimeMessage(session, "");
    }

    Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (log.isDebugEnabled() && trpHeaders != null) {
        log.debug("Using transport headers: " + trpHeaders);
    }

    // set From address - first check if this is a reply, then use from address from the
    // transport out, else if any custom transport headers set on this message, or default
    // to the transport senders default From address        
    if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting From header to " + outInfo.getFromAddress().getAddress()
                    + " from OutTransportInfo");
        }
        message.setFrom(outInfo.getFromAddress());
        message.setReplyTo((new Address[] { outInfo.getFromAddress() }));
    } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) {
        InternetAddress from = new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM));
        if (log.isDebugEnabled()) {
            log.debug("Setting From header to " + from.getAddress() + " from transport headers");
        }
        message.setFrom(from);
        message.setReplyTo(new Address[] { from });
    } else {
        if (smtpFromAddress != null) {
            if (log.isDebugEnabled()) {
                log.debug("Setting From header to " + smtpFromAddress.getAddress()
                        + " from transport configuration");
            }
            message.setFrom(smtpFromAddress);
            message.setReplyTo(new Address[] { smtpFromAddress });
        } else {
            handleException("From address for outgoing message cannot be determined");
        }
    }

    // set To address/es to any custom transport header set on the message, else use the reply
    // address from the out transport information
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) {
        Address[] to = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO));
        if (log.isDebugEnabled()) {
            log.debug("Setting To header to " + InternetAddress.toString(to) + " from transport headers");
        }
        message.setRecipients(Message.RecipientType.TO, to);
    } else if (outInfo.getTargetAddresses() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting To header to " + InternetAddress.toString(outInfo.getTargetAddresses())
                    + " from OutTransportInfo");
        }
        message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses());
    } else {
        handleException("To address for outgoing message cannot be determined");
    }

    // set Cc address/es to any custom transport header set on the message, else use the
    // Cc list from original request message
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) {
        Address[] cc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC));
        if (log.isDebugEnabled()) {
            log.debug("Setting Cc header to " + InternetAddress.toString(cc) + " from transport headers");
        }
        message.setRecipients(Message.RecipientType.CC, cc);
    } else if (outInfo.getCcAddresses() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Cc header to " + InternetAddress.toString(outInfo.getCcAddresses())
                    + " from OutTransportInfo");
        }
        message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses());
    }

    // set Bcc address/es to any custom addresses set at the transport sender level + any
    // custom transport header
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) {
        InternetAddress[] bcc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC));
        if (log.isDebugEnabled()) {
            log.debug("Adding Bcc header values " + InternetAddress.toString(bcc) + " from transport headers");
        }
        message.addRecipients(Message.RecipientType.BCC, bcc);
    }
    if (smtpBccAddresses != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding Bcc header values " + InternetAddress.toString(smtpBccAddresses)
                    + " from transport configuration");
        }
        message.addRecipients(Message.RecipientType.BCC, smtpBccAddresses);
    }

    // set subject
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Subject header to '" + trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)
                    + "' from transport headers");
        }
        message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT));
    } else if (outInfo.getSubject() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Subject header to '" + outInfo.getSubject() + "' from transport headers");
        }
        message.setSubject(outInfo.getSubject());
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Generating default Subject header from SOAP action");
        }
        message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction());
    }

    //TODO: use a combined message id for smtp so that it generates a unique id while
    // being able to support asynchronous communication.
    // if a custom message id is set, use it
    //        if (msgContext.getMessageID() != null) {
    //            message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID());
    //            message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID());
    //        }

    // if this is a reply, set reference to original message
    if (outInfo.getRequestMessageID() != null) {
        message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID());
        message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID());

    } else {
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) {
            message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO));
        }
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) {
            message.setHeader(MailConstants.MAIL_HEADER_REFERENCES,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES));
        }
    }

    // set Date
    message.setSentDate(new Date());

    // set SOAPAction header
    message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());

    // write body
    MessageFormatterEx messageFormatterEx;
    if (messageFormatter instanceof MessageFormatterEx) {
        messageFormatterEx = (MessageFormatterEx) messageFormatter;
    } else {
        messageFormatterEx = new MessageFormatterExAdapter(messageFormatter);
    }

    DataHandler dataHandler = new DataHandler(
            messageFormatterEx.getDataSource(msgContext, format, msgContext.getSoapAction()));

    MimeMultipart mimeMultiPart = null;

    String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT);
    if (mFormat == null) {
        mFormat = defaultMailFormat;
    }

    if (log.isDebugEnabled()) {
        log.debug("Using mail format '" + mFormat + "'");
    }

    MimePart mainPart;
    if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) {
        mimeMultiPart = new MimeMultipart();
        MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
        mimeBodyPart1.setContent("Web Service Message Attached", "text/plain");
        MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
        mimeMultiPart.addBodyPart(mimeBodyPart1);
        mimeMultiPart.addBodyPart(mimeBodyPart2);
        message.setContent(mimeMultiPart);
        mainPart = mimeBodyPart2;
    } else if (MailConstants.TRANSPORT_FORMAT_ATTACHMENT.equals(mFormat)) {
        mimeMultiPart = new MimeMultipart();
        MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
        mimeBodyPart1.setContent("Web Service Message Attached", "text/plain");
        MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
        mimeMultiPart.addBodyPart(mimeBodyPart1);
        mimeMultiPart.addBodyPart(mimeBodyPart2);
        message.setContent(mimeMultiPart);

        String fileName = (String) msgContext.getProperty(MailConstants.TRANSPORT_FORMAT_ATTACHMENT_FILE);
        if (fileName != null) {
            mimeBodyPart2.setFileName(fileName);
        } else {
            mimeBodyPart2.setFileName("attachment");
        }

        mainPart = mimeBodyPart2;
    } else {
        mainPart = message;
    }

    try {
        mainPart.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
        mainPart.setDataHandler(dataHandler);

        // AXIOM's idea of what is textual also includes application/xml and
        // application/soap+xml (which JavaMail considers as binary). For these content types
        // always use quoted-printable transfer encoding. Note that JavaMail is a bit smarter
        // here because it can choose between 7bit and quoted-printable automatically, but it
        // needs to scan the entire content to determine this.
        if (msgContext.getOptions().getProperty("Content-Transfer-Encoding") != null) {
            mainPart.setHeader("Content-Transfer-Encoding",
                    (String) msgContext.getOptions().getProperty("Content-Transfer-Encoding"));
        } else {
            String contentType = dataHandler.getContentType().toLowerCase();
            if (!contentType.startsWith("multipart/") && CommonUtils.isTextualPart(contentType)) {
                mainPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
            }
        }

        //setting any custom headers defined by the user
        if (msgContext.getOptions().getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS) != null) {
            Map customTransportHeaders = (Map) msgContext.getOptions()
                    .getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS);
            for (Object header : customTransportHeaders.keySet()) {
                mainPart.setHeader((String) header, (String) customTransportHeaders.get(header));
            }
        }

        log.debug("Sending message");
        Transport.send(message);

        // update metrics
        metrics.incrementMessagesSent(msgContext);
        long bytesSent = message.getBytesSent();
        if (bytesSent != -1) {
            metrics.incrementBytesSent(msgContext, bytesSent);
        }

    } catch (MessagingException e) {
        metrics.incrementFaultsSending();
        handleException("Error creating mail message or sending it to the configured server", e);

    }
    return message.getMessageID();
}