Example usage for javax.activation DataHandler DataHandler

List of usage examples for javax.activation DataHandler DataHandler

Introduction

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

Prototype

public DataHandler(URL url) 

Source Link

Document

Create a DataHandler instance referencing a URL.

Usage

From source file:lucee.runtime.net.smtp.SMTPClient.java

private BodyPart toMimeBodyPart(MailPart part) throws MessagingException {
    MimeBodyPart mbp = new MimeBodyPart();
    mbp.setDataHandler(// w ww.  j av a2  s. c o  m
            new DataHandler(new StringDataSource(part.getBody(), part.getType(), part.getCharset(), 980)));
    //mbp.setHeader("Content-Transfer-Encoding", "7bit");
    //mbp.setHeader("Content-Type", TEXT_PLAIN+"; charset="+plainTextCharset);
    return mbp;
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server/*from   w w  w. j  a  v  a2 s.  c  o m*/
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static boolean sendMsgAsGMail(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, @SuppressWarnings("unused") final String port,
        @SuppressWarnings("unused") final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;
    Boolean fail = false;

    ArrayList<String> userAndPass = new ArrayList<String>();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host); //$NON-NLS-1$
    props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    boolean usingSSL = false;
    if (usingSSL) {
        props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
        props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    }

    Session session = Session.getInstance(props, null);

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
    }

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));
        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            InternetAddress[] address = { new InternetAddress(toEMailAddr) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

            // create the Multipart and add its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);

            // add the Multipart to the message
            msg.setContent(mp);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

        // set the Date: header
        msg.setSentDate(new Date());

        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                t.connect(host, userName, password);

                t.sendMessage(msg, msg.getAllRecipients());

                fail = false;
            } catch (MessagingException mex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
                instance.lastErrorMsg = mex.toString();

                Exception ex = null;
                if ((ex = mex.getNextException()) != null) {
                    ex.printStackTrace();
                    instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
                }

                //wrong username or password, get new one
                if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    fail = true;
                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) {//the user is done
                        return false;
                    }
                    // else
                    //try again
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }
            } finally {

                log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                t.close();
            }
        } while (fail && cnt < 6);

    } catch (MessagingException mex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        //mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return false;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex);
        ex.printStackTrace();
    }

    if (fail) {
        return false;
    } //else
    return true;
}

From source file:be.e_contract.dssp.client.DigitalSignatureServiceClient.java

private String addAttachment(String mimetype, byte[] data) {
    String contentId = UUID.randomUUID().toString();
    LOG.debug("adding attachment: " + contentId);
    DataSource dataSource = new ByteArrayDataSource(data, mimetype);
    DataHandler dataHandler = new DataHandler(dataSource);
    BindingProvider bindingProvider = (BindingProvider) this.dssPort;
    Map<String, Object> requestContext = bindingProvider.getRequestContext();
    Map<String, DataHandler> outputMessageAttachments = new HashMap<String, DataHandler>();
    requestContext.put(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS, outputMessageAttachments);
    outputMessageAttachments.put(contentId, dataHandler);
    return contentId;
}

From source file:com.clustercontrol.monitor.factory.SelectEvent.java

/**
 * ??????????// www  . j  a va 2  s  . co  m
 * <p>
 * <ol>
 * <li>?????????{@link com.clustercontrol.util.PropertyUtil}??????</li>
 * <li>?????????????</li>
 * <li>{@link com.clustercontrol.monitor.bean.ReportEventInfo}????</li>
 * <li>??????{@link ArrayList}?????<BR>
 * </ol>
 *
 * @param facilityId ??ID
 * @param property ?
 * @return {@link com.clustercontrol.monitor.bean.ReportEventInfo}?
 * @throws HinemosUnknown
 * @throws IOException
 *
 * @since 2.1.0
 *
 * @see com.clustercontrol.util.PropertyUtil#getPropertyValue(com.clustercontrol.bean.Property, java.lang.String)
 * @see com.clustercontrol.repository.session.RepositoryControllerBean#getFacilityIdList(String, int)
 * @see com.clustercontrol.monitor.ejb.entity.EventLogBean#ejbFindEvent(String[], Integer, Timestamp, Timestamp, Timestamp, Timestamp, String, String, Integer, boolean, Integer)
 * @see com.clustercontrol.monitor.bean.ReportEventInfo
 */
public DataHandler getEventFile(String facilityId, EventFilterInfo filter, String filename, String username,
        Locale locale) throws HinemosUnknown, IOException {

    Integer[] priorityList = null;
    Long outputFromDate = null;
    Long outputToDate = null;
    Long generationFromDate = null;
    Long generationToDate = null;
    String monitorId = null;
    String monitorDetailId = null;
    int facilityType = 0;
    String facilityTypeStr = "";
    String application = null;
    String message = null;
    Integer confirmFlg = null;
    String confirmStr = "";
    String confirmUser = null;
    String comment = null;
    String commentUser = null;
    String ownerRoleId = null;
    Boolean collectGraphFlg = null;
    String collectGraphStr = "";

    String exportDirectory = HinemosPropertyUtil.getHinemosPropertyStr("performance.export.dir",
            HinemosPropertyDefault.getString(HinemosPropertyDefault.StringKey.PERFORMANCE_EXPORT_DIR));
    String filepath = exportDirectory + "/" + filename;
    File file = new File(filepath);
    boolean UTF8_BOM = HinemosPropertyUtil.getHinemosPropertyBool("monitor.common.report.event.bom", true);
    if (UTF8_BOM) {
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(0xef);
        fos.write(0xbb);
        fos.write(0xbf);
        fos.close();
    }
    FileWriter filewriter = new FileWriter(file, true);

    try {
        //???
        if (filter.getPriorityList() != null && filter.getPriorityList().length > 0) {
            priorityList = filter.getPriorityList();
        }

        //?
        if (filter.getOutputDateFrom() != null) {
            outputFromDate = filter.getOutputDateFrom();
            outputFromDate -= (outputFromDate % 1000); //??0??
        }

        //?
        if (filter.getOutputDateTo() != null) {
            outputToDate = filter.getOutputDateTo();
            outputToDate += (999 - (outputToDate % 1000)); //??999??
        }

        //?
        if (filter.getGenerationDateFrom() != null) {
            generationFromDate = filter.getGenerationDateFrom();
            generationFromDate -= (generationFromDate % 1000); //??0??
        }

        //?
        if (filter.getGenerationDateTo() != null) {
            generationToDate = filter.getGenerationDateTo();
            generationToDate += (999 - (generationToDate % 1000)); //??999??
        }

        //ID?
        if (!"".equals(filter.getMonitorId())) {
            monitorId = filter.getMonitorId();
        }

        //?
        if (!"".equals(filter.getMonitorDetailId())) {
            monitorDetailId = filter.getMonitorDetailId();
        }

        //?
        if (filter.getFacilityType() != null) {
            facilityType = filter.getFacilityType();
        }
        facilityTypeStr = Messages.getString(FacilityTargetConstant.typeToMessageCode(facilityType), locale);

        //?
        if (!"".equals(filter.getApplication())) {
            application = filter.getApplication();
        }

        //?
        if (!"".equals(filter.getMessage())) {
            message = filter.getMessage();
        }

        // ??
        int confirmFlgType = filter.getConfirmFlgType();
        if (confirmFlgType != -1) {
            confirmFlg = confirmFlgType;
        }
        confirmStr = Messages.getString(ConfirmConstant.typeToMessageCode(confirmFlgType), locale);

        // ?
        if (!"".equals(filter.getConfirmedUser())) {
            confirmUser = filter.getConfirmedUser();
        }

        // 
        if (!"".equals(filter.getComment())) {
            comment = filter.getComment();
        }

        // 
        if (!"".equals(filter.getCommentUser())) {
            commentUser = filter.getCommentUser();
        }

        // 
        collectGraphFlg = filter.getCollectGraphFlg();
        if (collectGraphFlg == null) {
            collectGraphStr = "";
        } else {
            collectGraphStr = Messages.getString(CollectGraphFlgConstant.typeToMessageCode(collectGraphFlg),
                    locale);
        }

        // ID
        if (!"".equals(filter.getOwnerRoleId())) {
            ownerRoleId = filter.getOwnerRoleId();
        }

        // 
        /*
        ,,,,,,,,,,,,,
        ,2012/02/08 17:20:10,,,,,,,,,,,,
        ,Hinemos Administrator,,,,,,,,,,,,
        ??,?,,ID,,ID,?,?,,,,,,,
        ,,,,,,,,,,,,,
         */
        String SEPARATOR = HinemosPropertyUtil.getHinemosPropertyStr("MONITOR_COMMON_REPORT_EVENT_SEPARATOR",
                ",");
        String DATE_FORMAT = HinemosPropertyUtil.getHinemosPropertyStr("MONITOR_COMMON_REPORT_EVENT_FORMAT",
                "yyyy/MM/dd HH:mm:ss");

        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        sdf.setTimeZone(HinemosTime.getTimeZone());
        filewriter.write(Messages.getString("REPORT_TITLE_MONITOR_EVENT", locale) + "\n");
        filewriter.write(Messages.getString("REPORT_OUTPUT_DATE", locale) + SEPARATOR
                + sdf.format(HinemosTime.getDateInstance()) + "\n");
        filewriter.write(Messages.getString("REPORT_OUTPUT_USER", locale) + SEPARATOR + username + "\n");

        // ()
        filewriter.write(Messages.getString("DEF_RESULT", locale) + SEPARATOR + // ??
                Messages.getString("RECEIVE_TIME", locale) + SEPARATOR
                + Messages.getString("REPORT_OUTPUT_DATE", locale) + SEPARATOR
                + Messages.getString("MONITOR_ID", locale) + SEPARATOR
                + Messages.getString("MONITOR_DETAIL_ID", locale) + SEPARATOR
                + Messages.getString("FACILITY_ID", locale) + SEPARATOR
                + Messages.getString("APPLICATION", locale) + SEPARATOR
                + Messages.getString("CONFIRMED", locale) + SEPARATOR
                + Messages.getString("CONFIRM_USER", locale) + SEPARATOR + Messages.getString("MESSAGE", locale)
                + SEPARATOR + Messages.getString("COMMENT", locale) + SEPARATOR
                + Messages.getString("COMMENT_USER", locale) + SEPARATOR
                + Messages.getString("COLLECT_GRAPH_FLG", locale) + SEPARATOR
                + Messages.getString("OWNER_ROLE_ID", locale) + "\n");

        // ???
        StringBuilder priorityMsg = new StringBuilder();
        if (priorityList != null) {
            for (int i = 0; i < priorityList.length; i++) {
                priorityMsg.append(
                        Messages.getString(PriorityConstant.typeToMessageCode(priorityList[i]), locale) + " ");
            }
        }
        // 
        filewriter.write((priorityList == null ? "" : priorityMsg) + SEPARATOR
                + (outputFromDate == null ? "" : sdf.format(outputFromDate)) + " - "
                + (outputToDate == null ? "" : sdf.format(outputToDate)) + SEPARATOR
                + (generationFromDate == null ? "" : sdf.format(generationFromDate)) + " - "
                + (generationToDate == null ? "" : sdf.format(generationToDate)) + SEPARATOR
                + (monitorId == null ? "" : monitorId) + SEPARATOR
                + (monitorDetailId == null ? "" : monitorDetailId) + SEPARATOR + facilityTypeStr + SEPARATOR
                + (application == null ? "" : application) + SEPARATOR + (confirmFlg == null ? "" : confirmStr)
                + SEPARATOR + (confirmUser == null ? "" : confirmUser) + SEPARATOR
                + (message == null ? "" : message) + SEPARATOR + (comment == null ? "" : comment) + SEPARATOR
                + (commentUser == null ? "" : commentUser) + SEPARATOR
                + (collectGraphFlg == null ? "" : collectGraphStr) + SEPARATOR
                + (ownerRoleId == null ? "" : ownerRoleId) + "\n");

        // ?
        filewriter.write(Messages.getString("NUMBER", locale) + SEPARATOR
                + Messages.getString("DEF_RESULT", locale) + SEPARATOR
                + Messages.getString("RECEIVE_TIME", locale) + SEPARATOR
                + Messages.getString("REPORT_OUTPUT_DATE", locale) + SEPARATOR
                + Messages.getString("FACILITY_ID", locale) + SEPARATOR + Messages.getString("SCOPE", locale)
                + SEPARATOR + Messages.getString("MONITOR_ID", locale) + SEPARATOR
                + Messages.getString("MONITOR_DETAIL_ID", locale) + SEPARATOR
                + Messages.getString("PLUGIN_ID", locale) + SEPARATOR
                + Messages.getString("APPLICATION", locale) + SEPARATOR
                + Messages.getString("OWNER_ROLE_ID", locale) + SEPARATOR
                + Messages.getString("CONFIRMED", locale) + SEPARATOR
                + Messages.getString("CONFIRM_TIME", locale) + SEPARATOR
                + Messages.getString("CONFIRM_USER", locale) + SEPARATOR + Messages.getString("COMMENT", locale)
                + SEPARATOR + Messages.getString("COMMENT_DATE", locale) + SEPARATOR
                + Messages.getString("COMMENT_USER", locale) + SEPARATOR + Messages.getString("MESSAGE", locale)
                + SEPARATOR + Messages.getString("MESSAGE_ORG", locale) + SEPARATOR
                + Messages.getString("COLLECT_GRAPH_FLG", locale) + "\n");

        // ?ID?
        String[] facilityIds = null;

        int level = RepositoryControllerBean.ALL;
        if (FacilityTargetConstant.TYPE_BENEATH == facilityType) {
            level = RepositoryControllerBean.ONE_LEVEL;
        }

        ArrayList<String> facilityIdList = new RepositoryControllerBean().getFacilityIdList(facilityId, level);

        if (facilityIdList != null && facilityIdList.size() > 0) {
            // ??
            facilityIds = new String[facilityIdList.size()];
            facilityIdList.toArray(facilityIds);
        } else {
            // ??
            facilityIds = new String[1];
            facilityIds[0] = facilityId;
        }

        // ?CSV?????DB??

        List<EventLogEntity> ct = null;
        // ?
        ct = QueryUtil.getEventLogByFilter(facilityIds, priorityList, outputFromDate, outputToDate,
                generationFromDate, generationToDate, monitorId, monitorDetailId, application, message,
                confirmFlg, confirmUser, comment, commentUser, collectGraphFlg, ownerRoleId, true,
                HinemosPropertyUtil
                        .getHinemosPropertyNum("monitor.common.report.event.count", Long.valueOf(2000))
                        .intValue());

        // ??
        collectionToFile(ct, filewriter, locale);

    } finally {
        filewriter.close();
    }

    // ????
    FileDataSource source = new FileDataSource(file);
    DataHandler handler = new DataHandler(source);

    return handler;
}

From source file:com.panet.imeta.trans.steps.mail.Mail.java

private void addAttachedFilePart(FileObject file) throws Exception {
    // create a data source

    MimeBodyPart files = new MimeBodyPart();
    // create a data source
    URLDataSource fds = new URLDataSource(file.getURL());
    // get a data Handler to manipulate this file type;
    files.setDataHandler(new DataHandler(fds));
    // include the file in the data source
    files.setFileName(file.getName().getBaseName());
    // add the part with the file in the BodyPart();
    data.parts.addBodyPart(files);//  w ww .  j  a  v a2  s .  com
    if (log.isDetailed())
        log.logDetailed(toString(), Messages.getString("Mail.Log.AttachedFile", fds.getName()));

}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Computes the received content MIC and writes it to the message info object
 *///  w  w w. j  a va  2s. co m
public void computeReceivedContentMIC(byte[] rawMessageData, AS2Message message, Part partWithHeader,
        String contentType) throws Exception {
    AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
    boolean encrypted = messageInfo.getEncryptionType() != AS2Message.ENCRYPTION_NONE;
    boolean signed = messageInfo.getSignType() != AS2Message.SIGNATURE_NONE;
    boolean compressed = messageInfo.getCompressionType() != AS2Message.COMPRESSION_NONE;
    BCCryptoHelper helper = new BCCryptoHelper();
    String sha1digestOID = helper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1);
    //compute the MIC
    if (signed) {
        //compute the content-type for the signed part.
        //If the message was not encrypted the content-type should simply be taken from the header
        //else we have to look into the part
        String singedPartContentType = null;
        if (!encrypted) {
            singedPartContentType = contentType;
        } else {
            InputStream dataIn = message.getDecryptedRawDataInputStream();
            MimeBodyPart contentTypeTempPart = new MimeBodyPart(dataIn);
            dataIn.close();
            singedPartContentType = contentTypeTempPart.getContentType();
        }
        //ANY signed data
        //4.1 MIC Calculation For Signed Message
        //For any signed message, the MIC to be returned is calculated over
        //the same data that was signed in the original message as per [AS1].
        //The signed content will be a mime bodypart that contains either
        //compressed or uncompressed data.
        MimeBodyPart signedPart = new MimeBodyPart();
        signedPart.setDataHandler(
                new DataHandler(new ByteArrayDataSource(message.getDecryptedRawData(), contentType)));
        signedPart.setHeader("Content-Type", singedPartContentType);
        String digestOID = helper.getDigestAlgOIDFromSignature(signedPart);
        signedPart = null;
        String mic = helper.calculateMIC(partWithHeader, digestOID);
        String digestAlgorithmName = helper.convertOIDToAlgorithmName(digestOID);
        messageInfo.setReceivedContentMIC(mic + ", " + digestAlgorithmName);
    } else if (!signed && !compressed && !encrypted) {
        //uncompressed, unencrypted, unsigned: plaintext mic
        //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
        //4.3 MIC Calculation For Unencrypted, Unsigned Message
        //For unsigned, unencrypted messages, the MIC is calculated
        //over the uncompressed data content including all MIME header
        //fields and any applied Content-Transfer-Encoding.
        String mic = helper.calculateMIC(rawMessageData, sha1digestOID);
        messageInfo.setReceivedContentMIC(mic + ", sha1");
    } else if (!signed && compressed && !encrypted) {
        //compressed, unencrypted, unsigned: uncompressed data mic
        //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
        //4.3 MIC Calculation For Unencrypted, Unsigned Message
        //For unsigned, unencrypted messages, the MIC is calculated
        //over the uncompressed data content including all MIME header
        //fields and any applied Content-Transfer-Encoding.
        String mic = helper.calculateMIC(message.getDecryptedRawData(), sha1digestOID);
        messageInfo.setReceivedContentMIC(mic + ", sha1");
    } else if (!signed && encrypted) {
        //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
        //4.2 MIC Calculation For Encrypted, Unsigned Message
        //For encrypted, unsigned messages, the MIC to be returned is
        //calculated over the uncompressed data content including all
        //MIME header fields and any applied Content-Transfer-Encoding.
        String mic = helper.calculateMIC(message.getDecryptedRawData(), sha1digestOID);
        messageInfo.setReceivedContentMIC(mic + ", sha1");
    } else {
        //this should never happen:
        String mic = helper.calculateMIC(partWithHeader, sha1digestOID);
        messageInfo.setReceivedContentMIC(mic + ", sha1");
    }
}

From source file:edu.xtec.colex.client.beans.ColexRecordBean.java

/**
 * Calls the web service operation/*from  w  w w . jav  a 2s  .  co m*/
 * <I>importRecords(User,Owner,Collection,FILE) : void</I>
 *
 * @param fiImport the FileItem Zip of the Records to import
 * @throws java.lang.Exception when an Exception error occurs
 */
protected void importRecords(FileItem fiImport) throws Exception {
    User uRequest = new User(getUserId());
    Collection cRequest = new Collection(collection);
    File fTemp = null;

    try {
        smRequest = mf.createMessage();

        SOAPBody sbRequest = smRequest.getSOAPBody();

        Name n = sf.createName("importRecords");

        SOAPBodyElement sbeRequest = sbRequest.addBodyElement(n);

        sbeRequest.addChildElement(uRequest.toXml());

        if (owner != null) {
            Owner oRequest = new Owner(owner);
            sbeRequest.addChildElement(oRequest.toXml());
        }

        sbeRequest.addChildElement(cRequest.toXml());

        String sNomFitxer = Utils.getFileName(fiImport.getName());

        fTemp = File.createTempFile("attach", null);

        fiImport.write(fTemp);

        URL urlFile = new URL("file://" + fTemp.getPath());

        AttachmentPart ap = smRequest.createAttachmentPart(new DataHandler(urlFile));

        smRequest.addAttachmentPart(ap);

        smRequest.saveChanges();

        SOAPMessage smResponse = sendMessage(smRequest,
                this.getJspProperties().getProperty("url.servlet.record"));

        SOAPBody sbResponse = smResponse.getSOAPBody();

        if (sbResponse.hasFault()) {
            checkFault(sbResponse, "importRecords");
        } else {

        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (fTemp != null) {
            fTemp.delete();
        }
    }
}

From source file:com.collabnet.tracker.core.TrackerWebServicesClient.java

/**
 * Attach a file to a PT artifact//from w w  w .  j a  v a 2 s  . c  om
 * 
 * @param taskId
 * @param comment
 * @param attachment
 * @throws ServiceException
 * @throws WSException
 * @throws RemoteException
 */
public long postAttachment(String taskId, String comment, DataSource attachment)
        throws ServiceException, WSException, RemoteException {
    EngineConfiguration config = mClient.getEngineConfiguration();
    AttachmentService service = new AttachmentServiceLocator(config);
    URL portAddress = mClient.constructServiceURL("/tracker/Attachment");
    AttachmentManager theService = service.getAttachmentService(portAddress);
    DataHandler attachmentHandler = new DataHandler(attachment);

    theService.addAttachment(taskId, attachment.getName(), comment, attachment.getContentType(),
            attachmentHandler);
    long[] ids = theService.getAttachmentIds(taskId);
    Arrays.sort(ids);
    return ids[ids.length - 1];
}

From source file:com.panet.imeta.job.entries.mail.JobEntryMail.java

public Result execute(Result result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();

    File masterZipfile = null;/*from   w  w  w.j ava2 s  .c  o  m*/

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        log.logError(toString(), Messages.getString("JobMail.Error.HostNotSpecified"));

        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        if (secureConnectionType.equals("TLS")) {
            // Allow TLS authentication
            props.put("mail.smtp.starttls.enable", "true");
        } else {

            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version
            // Unknown
            props.put("mail.smtps.quitwait", "false");
        }

    }

    props.put("mail." + protocol + ".host", environmentSubstitute(server));
    if (!Const.isEmpty(port))
        props.put("mail." + protocol + ".port", environmentSubstitute(port));
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        props.put("mail.debug", "true");

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
         * authenticator = new Authenticator() { protected
         * PasswordAuthentication getPasswordAuthentication() { return new
         * PasswordAuthentication(
         * StringUtil.environmentSubstitute(Const.NVL(authenticationUser,
         * "")),
         * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword
         * , "")) ); } };
         */
    }

    Session session = Session.getInstance(props);
    session.setDebug(debug);

    try {
        // create a message
        Message msg = new MimeMessage(session);

        // set message priority
        if (usePriority) {
            String priority_int = "1";
            if (priority.equals("low")) {
                priority_int = "3";
            }
            if (priority.equals("normal")) {
                priority_int = "2";
            }

            msg.setHeader("X-Priority", priority_int); // (String)int
            // between 1= high
            // and 3 = low.
            msg.setHeader("Importance", importance);
            // seems to be needed for MS Outlook.
            // where it returns a string of high /normal /low.
        }

        // Set Mail sender (From)
        String sender_address = environmentSubstitute(replyAddress);
        if (!Const.isEmpty(sender_address)) {
            String sender_name = environmentSubstitute(replyName);
            if (!Const.isEmpty(sender_name))
                sender_address = sender_name + '<' + sender_address + '>';
            msg.setFrom(new InternetAddress(sender_address));
        } else {
            throw new MessagingException(Messages.getString("JobMail.Error.ReplyEmailNotFilled"));
        }

        // set Reply to addresses
        String reply_to_address = environmentSubstitute(replyToAddresses);
        if (!Const.isEmpty(reply_to_address)) {
            // Split the mail-address: space separated
            String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" ");
            InternetAddress[] address = new InternetAddress[reply_Address_List.length];
            for (int i = 0; i < reply_Address_List.length; i++)
                address[i] = new InternetAddress(reply_Address_List[i]);
            msg.setReplyTo(address);
        }

        // Split the mail-address: space separated
        String destinations[] = environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++)
            address[i] = new InternetAddress(destinations[i]);
        msg.setRecipients(Message.RecipientType.TO, address);

        if (!Const.isEmpty(destinationCc)) {
            // Split the mail-address Cc: space separated
            String destinationsCc[] = environmentSubstitute(destinationCc).split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++)
                addressCc[i] = new InternetAddress(destinationsCc[i]);

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        if (!Const.isEmpty(destinationBCc)) {
            // Split the mail-address BCc: space separated
            String destinationsBCc[] = environmentSubstitute(destinationBCc).split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++)
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }
        String realSubject = environmentSubstitute(subject);
        if (!Const.isEmpty(realSubject)) {
            msg.setSubject(realSubject);
        }

        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();

        if (comment != null) {
            messageText.append(environmentSubstitute(comment)).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment) {

            messageText.append(Messages.getString("JobMail.Log.Comment.Job")).append(Const.CR);
            messageText.append("-----").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobName") + "    : ")
                    .append(parentJob.getJobMeta().getName()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobDirectory") + "  : ")
                    .append(parentJob.getJobMeta().getDirectory()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobEntry") + "   : ").append(getName())
                    .append(Const.CR);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            messageText.append(Const.CR).append(Messages.getString("JobMail.Log.Comment.MsgDate") + ": ")
                    .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment && result != null) {
            messageText.append(Messages.getString("JobMail.Log.Comment.PreviousResult") + ":").append(Const.CR);
            messageText.append("-----------------").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobEntryNr") + "         : ")
                    .append(result.getEntryNr()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Errors") + "               : ")
                    .append(result.getNrErrors()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesRead") + "           : ")
                    .append(result.getNrLinesRead()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesWritten") + "        : ")
                    .append(result.getNrLinesWritten()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesInput") + "          : ")
                    .append(result.getNrLinesInput()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesOutput") + "         : ")
                    .append(result.getNrLinesOutput()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesUpdated") + "        : ")
                    .append(result.getNrLinesUpdated()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Status") + "  : ")
                    .append(result.getExitStatus()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Result") + "               : ")
                    .append(result.getResult()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson))
                || !Const.isEmpty(environmentSubstitute(contactPhone)))) {
            messageText.append(Messages.getString("JobMail.Log.Comment.ContactInfo") + " :").append(Const.CR);
            messageText.append("---------------------").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.PersonToContact") + " : ")
                    .append(environmentSubstitute(contactPerson)).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Tel") + "  : ")
                    .append(environmentSubstitute(contactPhone)).append(Const.CR);
            messageText.append(Const.CR);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append(Messages.getString("JobMail.Log.Comment.PathToJobentry") + ":")
                        .append(Const.CR);
                messageText.append("------------------------").append(Const.CR);

                addBacktracking(jobTracker, messageText);
            }
        }

        Multipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // 1st part

        if (useHTML) {
            if (!Const.isEmpty(getEncoding())) {
                part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding());
            } else {
                part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
            }

        }

        else
            part1.setText(messageText.toString());

        parts.addBodyPart(part1);

        if (includingFiles && result != null) {
            List<ResultFile> resultFiles = result.getResultFilesList();
            if (resultFiles != null && !resultFiles.isEmpty()) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (ResultFile resultFile : resultFiles) {
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                URLDataSource fds = new URLDataSource(file.getURL());

                                // get a data Handler to manipulate this
                                // file type;
                                files.setDataHandler(new DataHandler(fds));
                                // include the file in the data source
                                files.setFileName(file.getName().getBaseName());
                                // add the part with the file in the
                                // BodyPart();
                                parts.addBodyPart(files);

                                log.logBasic(toString(),
                                        "Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (ResultFile resultFile : resultFiles) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into
                                // this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        KettleVFS.getInputStream(file));
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                                log.logBasic(toString(), "Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        log.logError(toString(), "Error zipping attachement files into file ["
                                + masterZipfile.getPath() + "] : " + e.toString());
                        log.logError(toString(), Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                log.logError(toString(),
                                        "Unable to close attachement zip file archive : " + e.toString());
                                log.logError(toString(), Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in th e data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))),
                            environmentSubstitute(Const.NVL(authenticationUser, "")),
                            environmentSubstitute(Const.NVL(authenticationPassword, "")));
                } else {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            environmentSubstitute(Const.NVL(authenticationUser, "")),
                            environmentSubstitute(Const.NVL(authenticationPassword, "")));
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null)
                transport.close();
        }
    } catch (IOException e) {
        log.logError(toString(), "Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        log.logError(toString(), "Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    log.logError(toString(), "    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        log.logError(toString(), "         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    log.logError(toString(), "    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        log.logError(toString(), "         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    // System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        log.logError(toString(), "         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}

From source file:org.pentaho.di.trans.steps.mail.Mail.java

private void addAttachedFilePart(FileObject file) throws Exception {
    // create a data source

    MimeBodyPart files = new MimeBodyPart();
    // create a data source
    URLDataSource fds = new URLDataSource(file.getURL());
    // get a data Handler to manipulate this file type;
    files.setDataHandler(new DataHandler(fds));
    // include the file in the data source
    files.setFileName(file.getName().getBaseName());
    // insist on base64 to preserve line endings
    files.addHeader("Content-Transfer-Encoding", "base64");
    // add the part with the file in the BodyPart();
    data.parts.addBodyPart(files);//w ww.  j ava2  s  . c  om
    if (isDetailed()) {
        logDetailed(BaseMessages.getString(PKG, "Mail.Log.AttachedFile", fds.getName()));
    }

}