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:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * Attaches a file as a body part to the multipart message
 *
 * @param attachment/*from w  w  w. j a v a 2  s . co  m*/
 * @throws MessagingException
 */
private MimeBodyPart createAttachmentPart(Attachment attachment) throws MessagingException {
    DataSource source = attachment.getDataSource();
    MimeBodyPart attachPart = new MimeBodyPart();

    attachPart.setDataHandler(new DataHandler(source));
    attachPart.setFileName(attachment.getFilename());

    if (attachment.getContentTypeHeader() != null) {
        attachPart.setHeader("Content-Type", attachment.getContentTypeHeader());
    }

    if (attachment.getContentDispositionHeader() != null) {
        attachPart.setHeader("Content-Disposition", attachment.getContentDispositionHeader());
    }

    return attachPart;
}

From source file:org.liveSense.service.email.EmailServiceImpl.java

/**
 * {@inheritDoc}//from  w w w  . j  a  v a2s  . com
 */
@Override
public void sendEmailFromTemplateString(Session session, String template, Node resource, String subject,
        Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc,
        HashMap<String, Object> variables) throws Exception {
    boolean haveSession = false;

    try {
        if (session != null && session.isLive()) {
            haveSession = true;
        } else {
            session = repository.loginAdministrative(null);
        }

        if (template == null) {
            throw new RepositoryException("Template is null");
        }
        String html = templateNode(Md5Encrypter.encrypt(template), resource, template, variables);
        if (html == null)
            throw new RepositoryException("Template is empty");

        // create the messge.
        MimeMessage mimeMessage = new MimeMessage((javax.mail.Session) null);

        MimeMultipart rootMixedMultipart = new MimeMultipart("mixed");
        mimeMessage.setContent(rootMixedMultipart);

        MimeMultipart nestedRelatedMultipart = new MimeMultipart("related");
        MimeBodyPart relatedBodyPart = new MimeBodyPart();
        relatedBodyPart.setContent(nestedRelatedMultipart);
        rootMixedMultipart.addBodyPart(relatedBodyPart);

        MimeMultipart messageBody = new MimeMultipart("alternative");
        MimeBodyPart bodyPart = null;
        for (int i = 0; i < nestedRelatedMultipart.getCount(); i++) {
            BodyPart bp = nestedRelatedMultipart.getBodyPart(i);
            if (bp.getFileName() == null) {
                bodyPart = (MimeBodyPart) bp;
            }
        }
        if (bodyPart == null) {
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            nestedRelatedMultipart.addBodyPart(mimeBodyPart);
            bodyPart = mimeBodyPart;
        }
        bodyPart.setContent(messageBody, "text/alternative");

        // Create the plain text part of the message.
        MimeBodyPart plainTextPart = new MimeBodyPart();
        plainTextPart.setText(extractTextFromHtml(html), configurator.getEncoding());
        messageBody.addBodyPart(plainTextPart);

        // Create the HTML text part of the message.
        MimeBodyPart htmlTextPart = new MimeBodyPart();
        htmlTextPart.setContent(html, "text/html;charset=" + configurator.getEncoding()); // ;charset=UTF-8
        messageBody.addBodyPart(htmlTextPart);

        // Check if resource have nt:file childs adds as attachment
        if (resource != null && resource.hasNodes()) {
            NodeIterator iter = resource.getNodes();
            while (iter.hasNext()) {
                Node n = iter.nextNode();
                if (n.getPrimaryNodeType().isNodeType("nt:file")) {
                    // Part two is attachment
                    MimeBodyPart attachmentBodyPart = new MimeBodyPart();
                    InputStream fileData = n.getNode("jcr:content").getProperty("jcr:data").getBinary()
                            .getStream();
                    String mimeType = n.getNode("jcr:content").getProperty("jcr:mimeType").getString();
                    String fileName = n.getName();

                    DataSource source = new StreamDataSource(fileData, fileName, mimeType);
                    attachmentBodyPart.setDataHandler(new DataHandler(source));
                    attachmentBodyPart.setFileName(fileName);
                    attachmentBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
                    attachmentBodyPart.setContentID(fileName);
                    rootMixedMultipart.addBodyPart(attachmentBodyPart);
                }
            }
        }

        prepareMimeMessage(mimeMessage, resource, template, subject, replyTo, from, date, to, cc, bcc,
                variables);
        sendEmail(session, mimeMessage);

        //
    } finally {
        if (!haveSession && session != null) {
            if (session.hasPendingChanges()) {
                try {
                    session.save();
                } catch (Throwable th) {
                }
            }
            session.logout();
        }
    }
}

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

/**Decrypts the data of a message with all given certificates etc
 * @param info MessageInfo, the encryption algorith will be stored in the encryption type of this info
 * @param rawMessageData encrypted data, will be decrypted
 * @param contentType contentType of the data
 * @param privateKey receivers private key
 * @param certificate receivers certificate
 *//*  w w w . j  av  a  2  s .  c  o m*/
public byte[] decryptData(AS2Message message, byte[] data, String contentType, PrivateKey privateKeyReceiver,
        X509Certificate certificateReceiver, String receiverCryptAlias) throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    MimeBodyPart encryptedBody = new MimeBodyPart();
    encryptedBody.setHeader("content-type", contentType);
    encryptedBody.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    RecipientId recipientId = new JceKeyTransRecipientId(certificateReceiver);
    SMIMEEnveloped enveloped = new SMIMEEnveloped(encryptedBody);
    BCCryptoHelper helper = new BCCryptoHelper();
    String algorithm = helper.convertOIDToAlgorithmName(enveloped.getEncryptionAlgOID());
    if (algorithm.equals(BCCryptoHelper.ALGORITHM_3DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_3DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC2)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC2_UNKNOWN);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_128)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_128);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_192)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_192);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_256)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_256);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC4)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC4_UNKNOWN);
    } else {
        info.setEncryptionType(AS2Message.ENCRYPTION_UNKNOWN_ALGORITHM);
    }
    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    enveloped = null;
    encryptedBody = null;
    RecipientInformation recipient = recipients.get(recipientId);
    if (recipient == null) {
        //give some details about the required and used cert for the decryption
        Collection recipientList = recipients.getRecipients();
        Iterator iterator = recipientList.iterator();
        while (iterator.hasNext()) {
            RecipientInformation recipientInfo = (RecipientInformation) iterator.next();
            if (this.logger != null) {
                this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.inforequired",
                        new Object[] { info.getMessageId(), recipientInfo.getRID() }), info);
            }
        }
        if (this.logger != null) {
            this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.infoassigned",
                    new Object[] { info.getMessageId(), receiverCryptAlias, recipientId }), info);
        }
        throw new AS2Exception(AS2Exception.AUTHENTIFICATION_ERROR,
                "Error decrypting the message: Recipient certificate does not match.", message);
    }
    //Streamed decryption. Its also possible to use in memory decryption using getContent but that uses
    //far more memory.
    InputStream contentStream = recipient
            .getContentStream(new JceKeyTransEnvelopedRecipient(privateKeyReceiver).setProvider("BC"))
            .getContentStream();
    //InputStream contentStream = recipient.getContentStream(privateKeyReceiver, "BC").getContentStream();
    //threshold set to 20 MB: if the data is less then 20MB perform the operaion in memory else stream to disk
    DeferredFileOutputStream decryptedOutput = new DeferredFileOutputStream(20 * 1024 * 1024, "as2decryptdata_",
            ".mem", null);
    this.copyStreams(contentStream, decryptedOutput);
    decryptedOutput.flush();
    decryptedOutput.close();
    contentStream.close();
    byte[] decryptedData = null;
    //size of the data was < than the threshold
    if (decryptedOutput.isInMemory()) {
        decryptedData = decryptedOutput.getData();
    } else {
        //data has been written to a temp file: reread and return
        ByteArrayOutputStream memOut = new ByteArrayOutputStream();
        decryptedOutput.writeTo(memOut);
        memOut.flush();
        memOut.close();
        //finally delete the temp file
        boolean deleted = decryptedOutput.getFile().delete();
        decryptedData = memOut.toByteArray();
    }
    if (this.logger != null) {
        this.logger.log(Level.INFO,
                this.rb.getResourceString("decryption.done.alias",
                        new Object[] { info.getMessageId(), receiverCryptAlias,
                                this.rbMessage.getResourceString("encryption." + info.getEncryptionType()) }),
                info);
    }
    return (decryptedData);
}

From source file:org.enlacerh.util.FileUploadController.java

/**
 * Mtodo que enva los recibos de pago a cada usuario
 * @throws IOException //from   w  w  w.j av  a 2  s.c  o  m
 * @throws NumberFormatException 
 * **/
public void enviarRP(String to, String laruta, String file) throws NumberFormatException, IOException {
    try {
        //System.out.println("Enviando recibo");
        //System.out.println(jndimail());
        Context initContext = new InitialContext();
        Session session = (Session) initContext.lookup(jndimail());
        // Crear el mensaje a enviar
        MimeMessage mm = new MimeMessage(session);

        // Establecer las direcciones a las que ser enviado
        // el mensaje (test2@gmail.com y test3@gmail.com en copia
        // oculta)
        // mm.setFrom(new
        // InternetAddress("opennomina@dvconsultores.com"));
        mm.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Establecer el contenido del mensaje
        mm.setSubject(getMessage("mailRP"));
        //mm.setText(getMessage("mailContent"));

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setContent(getMessage("mailRPcontent"), "text/html; charset=utf-8");

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = laruta + File.separator + file + ".pdf";
        javax.activation.DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(file + ".pdf");
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        mm.setContent(multipart);

        // Enviar el correo electrnico
        Transport.send(mm);
        //System.out.println("Correo enviado exitosamente a :" + to);
        //System.out.println("Fin recibo");
    } catch (Exception e) {
        msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage() + ": " + to, "");
        FacesContext.getCurrentInstance().addMessage(null, msj);
        e.printStackTrace();
    }
}

From source file:com.photon.phresco.util.Utility.java

public static void sendTemplateEmail(String[] toAddr, String fromAddr, String user, String subject, String body,
        String username, String password, String host, String screen, String build) throws PhrescoException {

    List<String> lists = Arrays.asList(toAddr);
    if (fromAddr == null) {
        fromAddr = "phresco.do.not.reply@gmail.com";
        username = "phresco.do.not.reply@gmail.com";
        password = "phresco123";
    }//from  w  w w  .  java2 s . co m
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    Session session = Session.getDefaultInstance(props, new LoginAuthenticator(username, password));
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddr));
        List<Address> emailsList = getEmailsList(lists);
        Address[] dsf = new Address[emailsList.size()];
        message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf));
        message.setSubject(subject);
        DataSource source = new FileDataSource(body);
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("Error.txt");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();
        DataSource source2 = new FileDataSource(screen);
        messageBodyPart2.setDataHandler(new DataHandler(source2));
        messageBodyPart2.setFileName("Error.jpg");
        multipart.addBodyPart(messageBodyPart2);
        MimeBodyPart mainPart = new MimeBodyPart();
        String content = "<b>Phresco framework error report<br><br>User Name:&nbsp;&nbsp;" + user
                + "<br> Email Address:&nbsp;&nbsp;" + fromAddr + "<br>Build No:&nbsp;&nbsp;" + build;
        mainPart.setContent(content, "text/html");
        multipart.addBodyPart(mainPart);
        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException e) {
        throw new PhrescoException(e);
    }
}

From source file:org.jlibrary.core.axis.client.AxisRepositoryDelegate.java

public void importRepository(Ticket ticket, byte[] content, String name)
        throws RepositoryException, SecurityException {

    try {/*from  w  ww.java  2  s  . c om*/
        call.removeAllParameters();

        call.setTargetEndpointAddress(new java.net.URL(endpoint));
        call.setOperationName("importRepository");
        call.addParameter("ticket", XMLType.XSD_ANY, ParameterMode.IN);
        call.addParameter("content", XMLType.SOAP_BASE64BINARY, ParameterMode.IN);
        call.addParameter("name", XMLType.XSD_STRING, ParameterMode.IN);

        DataHandler handler = new DataHandler(new ByteArrayDataSource(content, "application/octet-stream"));
        call.addAttachmentPart(handler);

        call.setReturnType(XMLType.AXIS_VOID);
        call.invoke(new Object[] { ticket, new byte[] {}, name });

    } catch (Exception e) {
        // I don't know if there is a better way to do this
        AxisFault fault = (AxisFault) e;
        if (fault.getFaultString().indexOf("SecurityException") != -1) {
            throw new SecurityException(fault.getFaultString());
        } else if (fault.getFaultString().indexOf("RepositoryAlreadyExistsException") != -1) {
            throw new RepositoryAlreadyExistsException();
        } else {
            throw new RepositoryException(fault.getFaultString());
        }
    }
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

private MimeMessage createForwardMimeMessage(Address from, Address to, String subject, String body,
        List<DBMailAttachment> attachments, MailerResult result) {

    try {/*w  w w  .ja  v a2 s  . c o m*/
        Address convertedFrom = getRawEmailFromAddress(from);
        MimeMessage msg = createMessage(convertedFrom);
        msg.setFrom(from);
        msg.setSubject(subject, "utf-8");

        if (to != null) {
            msg.addRecipient(RecipientType.TO, to);
        }

        if (attachments != null && !attachments.isEmpty()) {
            // with attachment use multipart message
            Multipart multipart = new MimeMultipart();
            // 1) add body part
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multipart.addBodyPart(messageBodyPart);
            // 2) add attachments
            for (DBMailAttachment attachment : attachments) {
                // abort if attachment does not exist
                if (attachment == null || attachment.getSize() <= 0) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    logError("Tried to send mail wit attachment that does not exist::"
                            + (attachment == null ? null : attachment.getName()), null);
                    return msg;
                }
                messageBodyPart = new MimeBodyPart();

                VFSLeaf data = getAttachmentDatas(attachment);
                DataSource source = new VFSDataSource(attachment.getName(), attachment.getMimetype(), data);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(attachment.getName());
                multipart.addBodyPart(messageBodyPart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            // without attachment everything is easy, just set as text
            msg.setText(body, "utf-8");
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (MessagingException e) {
        logError("", e);
        return null;
    }
}

From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java

private void sendToDl(DispatchContext sInfo, BIObject biobj, byte[] response, String retCT, String fileExt,
        String toBeAppendedToName, String toBeAppendedToDescription) {
    logger.debug("IN");
    try {/*ww w . j ava2 s . co m*/

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";
        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        if ((user == null) || user.trim().equals(""))
            throw new Exception("Smtp user not configured");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
        if ((pass == null) || pass.trim().equals(""))
            throw new Exception("Smtp password not configured");

        String mailTos = "";
        List dlIds = sInfo.getDlIds();
        Iterator it = dlIds.iterator();
        while (it.hasNext()) {

            Integer dlId = (Integer) it.next();
            DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);

            List emails = new ArrayList();
            emails = dl.getEmails();
            Iterator j = emails.iterator();
            while (j.hasNext()) {
                Email e = (Email) j.next();
                String email = e.getEmail();
                String userTemp = e.getUserId();
                IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
                if (ObjectsAccessVerifier.canSee(biobj, userProfile)) {
                    if (j.hasNext()) {
                        mailTos = mailTos + email + ",";
                    } else {
                        mailTos = mailTos + email;
                    }
                }

            }
        }

        if ((mailTos == null) || mailTos.trim().equals("")) {
            throw new Exception("No recipient address found");
        }

        String[] recipients = mailTos.split(",");
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.auth", "true");
        // create autheticator object
        Authenticator auth = new SMTPAuthenticator(user, pass);
        // open session
        Session session = Session.getDefaultInstance(props, auth);
        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
        String subject = biobj.getName() + toBeAppendedToName;
        msg.setSubject(subject);
        // create and fill the first message part
        //MimeBodyPart mbp1 = new MimeBodyPart();
        //mbp1.setText(mailTxt);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message
        SchedulerDataSource sds = new SchedulerDataSource(response, retCT,
                biobj.getName() + toBeAppendedToName + fileExt);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.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);
        // send message
        Transport.send(msg);
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
    } finally {
        logger.debug("OUT");
    }
}

From source file:it.cnr.icar.eric.client.ui.swing.RegistryBrowser.java

/**
 * Import RegistryObjects defined in an XML file within a ebRS
 * SubmitObjectsRequest and publish them to the registry user current user
 * context.//from w  ww.j  a  va  2 s.co  m
 */
private void importFromFile() {
    if (isAuthenticated()) {
        try {
            int returnVal = fileChooser.showOpenDialog(this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File requestFile = fileChooser.getSelectedFile();
                File parentDirectory = requestFile.getParentFile();
                Unmarshaller unmarshaller = BindingUtility.getInstance().getJAXBContext().createUnmarshaller();

                SubmitObjectsRequest submitRequest = (SubmitObjectsRequest) unmarshaller.unmarshal(requestFile);
                HashMap<String, Object> attachMap = new HashMap<String, Object>(); // id
                // to
                // attachments
                // map

                // Look for special temporary Slot on ExtrinsicObjects to
                // resolve to RepositoryItem
                // If a file in same directory is found with filename same
                // as slot value
                // then assume it is the matching RepositoryItem

                // List ros =
                // submitRequest.getRegistryObjectList().getIdentifiable();
                //List<IdentifiableType> ebIdentifiableTypeList = (List<IdentifiableType>) BindingUtility
                //      .getInstance().getIdentifiableTypeList(submitRequest.getRegistryObjectList());

                // Iterator iter=ros.iterator();
                //Iterator<IdentifiableType> iter = ebIdentifiableTypeList.iterator();

                List<?> ros = submitRequest.getRegistryObjectList().getIdentifiable();
                Iterator<?> iter = ros.iterator();

                while (iter.hasNext()) {
                    Object obj = iter.next();
                    if (obj instanceof ExtrinsicObjectType) {
                        ExtrinsicObjectType eo = (ExtrinsicObjectType) obj;
                        @SuppressWarnings("rawtypes")
                        HashMap slotsMap = BindingUtility.getInstance().getSlotsFromRegistryObject(eo);
                        @SuppressWarnings("static-access")
                        String slotName = BindingUtility
                                .getInstance().CANONICAL_SLOT_EXTRINSIC_OBJECT_REPOSITORYITEM_URL;
                        String riURLStr = null;
                        if (slotsMap.containsKey(slotName)) {
                            riURLStr = (String) slotsMap.get(slotName);

                            // Remove transient slot
                            slotsMap.remove(slotName);
                            eo.getSlot().clear();
                            BindingUtility.getInstance().addSlotsToRegistryObject(eo, slotsMap);
                        } else if (slotsMap.containsKey(BindingUtility.CANONICAL_SLOT_CONTENT_LOCATOR)) {
                            riURLStr = (String) slotsMap.get(BindingUtility.CANONICAL_SLOT_CONTENT_LOCATOR);
                            if (isExternalURL(riURLStr)) {
                                // Dont import a repository item if URL is
                                // external
                                riURLStr = null;
                            }
                        }

                        if (riURLStr != null) {
                            File riFile = new File(parentDirectory, riURLStr);
                            DataHandler riDataHandler = new DataHandler(new FileDataSource(riFile));
                            attachMap.put(eo.getId(), riDataHandler);
                        }
                    }
                }
                LifeCycleManagerImpl lcm = (LifeCycleManagerImpl) (client.getBusinessLifeCycleManager());
                ClientRequestContext context = new ClientRequestContext("RegistryBrowser:importFromFile",
                        submitRequest);
                context.setRepositoryItemsMap(attachMap);
                BulkResponse br = lcm.doSubmitObjectsRequest(context);
                JAXRUtility.checkBulkResponse(br);
                displayInfo(resourceBundle.getString("message.info.ImportSuccessful"));
            }
        } catch (JAXBException e) {
            RegistryBrowser.displayError(resourceBundle.getString("message.error.InvalidEbRRSyntax"), e);
        } catch (Exception e) {
            RegistryBrowser.displayError(e);
        }
    } else {
        RegistryBrowser.displayError(resourceBundle.getString("message.error.mustBeLoggedIn"));
    }
}

From source file:es.pode.catalogadorWeb.presentacion.catalogadorBasico.CatBasicoControllerImpl.java

public String submitImportar(ActionMapping mapping, SubmitImportarForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String accion = form.getAccion();
    String resAction = "";
    ResourceBundle datosResources = I18n.getInstance().getResource("application-resources",
            (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE));
    if (datosResources.getString("catalogadorBasico.importar.aceptar").equals(accion)) {
        resAction = "Aceptar";

        if (form.getFichero() == null || form.getFichero().getFileName().equals(""))
            throw new ValidatorException("{catalogadorBasico.importar.error.ficherovacio}");

        //crear el datahandler
        InternetHeaders ih = new InternetHeaders();
        MimeBodyPart mbp = null;/*ww  w.j av  a 2 s .c o m*/
        DataSource source = null;
        DataHandler dh = null;
        try {
            FormFile ff = (FormFile) form.getFichero();
            mbp = new MimeBodyPart(ih, ff.getFileData());
            source = new MimePartDataSource(mbp);
            dh = new DataHandler(source);
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("error al crear el datahandler");
            }
            throw new ValidatorException("{catalogadorBasico.importar.error}");
        }

        //validar el fichero
        Boolean valido = new Boolean(false);
        try {
            valido = this.getSrvValidadorService().obtenerValidacionLomes(dh);
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("error al llamar al servicio de validacin");
            }
            throw new ValidatorException("{catalogadorBasico.importar.error.novalido}");
        }

        if (!valido.booleanValue())
            throw new ValidatorException("{catalogadorBasico.importar.error.novalido}");

        //agregar el datahandler a sesion
        this.getCatalogadorBSession(request).setLomesImportado(dh);

    } else if (datosResources.getString("catalogadorBasico.importar.cancelar").equals(accion)) {
        resAction = "Cancelar";
    }

    return resAction;

}