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.apache.synapse.transport.fix.message.FIXMessageBuilder.java

/**
 * Constructs the XML infoset for the FIX message body
 * //from w w w  .  j  a  v  a2  s.  c  o m
 * @param message
 *            the FIX message
 * @param body
 *            the body element of the XML infoset
 * @param soapFactory
 *            the SOAP factory to create XML elements
 * @param msgCtx
 *            the Axis2 Message context
 * @throws AxisFault
 *             on error
 */
private void convertFIXBodyToXML(FieldMap message, OMElement body, SOAPFactory soapFactory,
        MessageContext msgCtx) throws AxisFault {

    if (log.isDebugEnabled()) {
        log.debug("Generating FIX message body (Message ID: " + msgCtx.getMessageID() + ")");
    }

    Iterator<quickfix.Field<?>> iter = message.iterator();
    if (iter != null) {
        while (iter.hasNext()) {
            quickfix.Field<?> field = iter.next();
            OMElement msgField = soapFactory.createOMElement(FIXConstants.FIX_FIELD, null);
            msgField.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_FIELD_ID, null,
                    String.valueOf(field.getTag())));
            Object value = field.getObject();

            if (value instanceof byte[]) {
                DataSource dataSource = new ByteArrayDataSource((byte[]) value);
                DataHandler dataHandler = new DataHandler(dataSource);
                String contentID = msgCtx.addAttachment(dataHandler);
                OMElement binaryData = soapFactory.createOMElement(FIXConstants.FIX_BINARY_FIELD, null);
                String binaryCID = "cid:" + contentID;
                binaryData.addAttribute(FIXConstants.FIX_MESSAGE_REFERENCE, binaryCID, null);
                msgField.addChild(binaryData);
            } else {
                soapFactory.createOMText(msgField, value.toString(), OMElement.CDATA_SECTION_NODE);
            }

            body.addChild(msgField);
        }
    }

    // process FIX repeating groups
    Iterator<Integer> groupKeyItr = message.groupKeyIterator();
    if (groupKeyItr != null) {
        while (groupKeyItr.hasNext()) {
            int groupKey = groupKeyItr.next();
            OMElement groupsField = soapFactory.createOMElement(FIXConstants.FIX_GROUPS, null);
            groupsField.addAttribute(FIXConstants.FIX_FIELD_ID, String.valueOf(groupKey), null);
            List<Group> groupList = message.getGroups(groupKey);
            Iterator<Group> groupIterator = groupList.iterator();

            while (groupIterator.hasNext()) {
                Group msgGroup = groupIterator.next();
                OMElement groupField = soapFactory.createOMElement(FIXConstants.FIX_GROUP, null);
                // rec. call the method to process the repeating groups
                convertFIXBodyToXML(msgGroup, groupField, soapFactory, msgCtx);
                groupsField.addChild(groupField);
            }
            body.addChild(groupsField);
        }
    }
}

From source file:org.bimserver.shared.json.JsonConverter.java

public Object fromJson(SClass definedType, SClass genericType, Object object)
        throws ConvertException, IOException {
    try {/*from w w  w .j a  va 2 s.  co m*/
        if (object instanceof JsonObject) {
            JsonObject jsonObject = (JsonObject) object;
            if (jsonObject.has("__type")) {
                String type = jsonObject.get("__type").getAsString();
                SClass sClass = servicesMap.getType(type);
                SBase newObject = sClass.newInstance();
                for (SField field : newObject.getSClass().getAllFields()) {
                    if (jsonObject.has(field.getName())) {
                        newObject.sSet(field, fromJson(field.getType(), field.getGenericType(),
                                jsonObject.get(field.getName())));
                    }
                }
                return newObject;
            } else {
                if (jsonObject.entrySet().size() != 0) {
                    throw new ConvertException("Missing __type field in " + jsonObject.toString());
                } else {
                    return null;
                }
            }
        } else if (object instanceof JsonArray) {
            JsonArray array = (JsonArray) object;
            if (definedType.isList()) {
                List<Object> list = new ArrayList<Object>();
                for (int i = 0; i < array.size(); i++) {
                    list.add(fromJson(definedType, genericType, array.get(i)));
                }
                return list;
            } else if (definedType.isSet()) {
                Set<Object> set = new HashSet<Object>();
                for (int i = 0; i < array.size(); i++) {
                    set.add(fromJson(definedType, genericType, array.get(i)));
                }
                return set;
            }
        } else if (object instanceof JsonNull) {
            return null;
        } else if (definedType.isByteArray()) {
            if (object instanceof JsonPrimitive) {
                JsonPrimitive jsonPrimitive = (JsonPrimitive) object;
                return Base64.decodeBase64(jsonPrimitive.getAsString().getBytes(Charsets.UTF_8));
            }
        } else if (definedType.isDataHandler()) {
            if (object instanceof JsonPrimitive) {
                JsonPrimitive jsonPrimitive = (JsonPrimitive) object;
                byte[] data = Base64.decodeBase64(jsonPrimitive.getAsString().getBytes(Charsets.UTF_8));
                return new DataHandler(new ByteArrayDataSource(null, data));
            }
        } else if (definedType.isInteger()) {
            if (object instanceof JsonPrimitive) {
                return ((JsonPrimitive) object).getAsInt();
            }
        } else if (definedType.isLong()) {
            if (object instanceof JsonPrimitive) {
                return ((JsonPrimitive) object).getAsLong();
            }
        } else if (definedType.isEnum()) {
            JsonPrimitive primitive = (JsonPrimitive) object;
            for (Object enumConstantObject : definedType.getInstanceClass().getEnumConstants()) {
                Enum<?> enumConstant = (Enum<?>) enumConstantObject;
                if (enumConstant.name().equals(primitive.getAsString())) {
                    return enumConstant;
                }
            }
        } else if (definedType.isDate()) {
            if (object instanceof JsonPrimitive) {
                return new Date(((JsonPrimitive) object).getAsLong());
            }
        } else if (definedType.isString()) {
            if (object instanceof JsonPrimitive) {
                return ((JsonPrimitive) object).getAsString();
            } else if (object instanceof JsonNull) {
                return null;
            }
        } else if (definedType.isBoolean()) {
            if (object instanceof JsonPrimitive) {
                return ((JsonPrimitive) object).getAsBoolean();
            }
        } else if (definedType.isList()) {
            if (genericType.isLong()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsLong();
                }
            } else if (genericType.isInteger()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsInt();
                }
            } else if (genericType.isString()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsString();
                }
            } else if (genericType.isDouble()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsDouble();
                }
            }
        } else if (definedType.isSet()) {
            if (genericType.isLong()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsLong();
                }
            } else if (genericType.isInteger()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsInt();
                }
            } else if (genericType.isString()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsString();
                }
            }
        } else if (definedType.isDouble()) {
            if (object instanceof JsonPrimitive) {
                return ((JsonPrimitive) object).getAsDouble();
            }
        } else if (definedType.isFloat()) {
            if (object instanceof JsonPrimitive) {
                return ((JsonPrimitive) object).getAsFloat();
            }
        } else if (definedType.isVoid()) {
            return null;
        }
    } catch (NumberFormatException e) {
        throw new ConvertException(e);
    }
    throw new UnsupportedOperationException(object.toString());
}

From source file:nl.nn.adapterframework.extensions.cxf.SOAPProviderBase.java

@Override
public SOAPMessage invoke(SOAPMessage request) {
    String result;//from w ww  . j a  v a 2  s.com
    PipeLineSessionBase pipelineSession = new PipeLineSessionBase();
    String correlationId = Misc.createSimpleUUID();
    log.debug(getLogPrefix(correlationId) + "received message");

    if (request == null) {
        String faultcode = "soap:Server";
        String faultstring = "SOAPMessage is null";
        String httpRequestMethod = (String) webServiceContext.getMessageContext()
                .get(MessageContext.HTTP_REQUEST_METHOD);
        if (!"POST".equals(httpRequestMethod)) {
            faultcode = "soap:Client";
            faultstring = "Request was send using '" + httpRequestMethod + "' instead of 'POST'";
        }
        result = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "<soap:Body><soap:Fault>" + "<faultcode>" + faultcode + "</faultcode>" + "<faultstring>"
                + faultstring + "</faultstring>" + "</soap:Fault></soap:Body></soap:Envelope>";
    } else {
        // Make mime headers in request available as session key
        @SuppressWarnings("unchecked")
        Iterator<MimeHeader> mimeHeaders = request.getMimeHeaders().getAllHeaders();
        String mimeHeadersXml = getMimeHeadersXml(mimeHeaders).toXML();
        pipelineSession.put("mimeHeaders", mimeHeadersXml);

        // Make attachments in request (when present) available as session keys
        int i = 1;
        XmlBuilder attachments = new XmlBuilder("attachments");
        @SuppressWarnings("unchecked")
        Iterator<AttachmentPart> attachmentParts = request.getAttachments();
        while (attachmentParts.hasNext()) {
            try {
                InputStreamAttachmentPart attachmentPart = new InputStreamAttachmentPart(
                        attachmentParts.next());

                XmlBuilder attachment = new XmlBuilder("attachment");
                attachments.addSubElement(attachment);
                XmlBuilder sessionKey = new XmlBuilder("sessionKey");
                sessionKey.setValue("attachment" + i);
                attachment.addSubElement(sessionKey);
                pipelineSession.put("attachment" + i, attachmentPart.getInputStream());
                log.debug(getLogPrefix(correlationId) + "adding attachment [attachment" + i + "] to session");

                @SuppressWarnings("unchecked")
                Iterator<MimeHeader> attachmentMimeHeaders = attachmentPart.getAllMimeHeaders();
                attachment.addSubElement(getMimeHeadersXml(attachmentMimeHeaders));
            } catch (SOAPException e) {
                e.printStackTrace();
                log.warn("Could not store attachment in session key", e);
            }
            i++;
        }
        pipelineSession.put("attachments", attachments.toXML());

        // Transform SOAP message to string
        String message;
        try {
            message = XmlUtils.nodeToString(request.getSOAPPart());
            log.debug(getLogPrefix(correlationId) + "transforming from SOAP message");
        } catch (TransformerException e) {
            String m = "Could not transform SOAP message to string";
            log.error(m, e);
            throw new WebServiceException(m, e);
        }

        // Process message via WebServiceListener
        ISecurityHandler securityHandler = new WebServiceContextSecurityHandler(webServiceContext);
        pipelineSession.setSecurityHandler(securityHandler);
        pipelineSession.put(IPipeLineSession.HTTP_REQUEST_KEY,
                webServiceContext.getMessageContext().get(MessageContext.SERVLET_REQUEST));
        pipelineSession.put(IPipeLineSession.HTTP_RESPONSE_KEY,
                webServiceContext.getMessageContext().get(MessageContext.SERVLET_RESPONSE));

        try {
            log.debug(getLogPrefix(correlationId) + "processing message");
            result = processRequest(correlationId, message, pipelineSession);
        } catch (ListenerException e) {
            String m = "Could not process SOAP message: " + e.getMessage();
            log.error(m);
            throw new WebServiceException(m, e);
        }
    }

    // Transform result string to SOAP message
    SOAPMessage soapMessage = null;
    try {
        log.debug(getLogPrefix(correlationId) + "transforming to SOAP message");
        soapMessage = getMessageFactory().createMessage();
        StreamSource streamSource = new StreamSource(new StringReader(result));
        soapMessage.getSOAPPart().setContent(streamSource);
    } catch (SOAPException e) {
        String m = "Could not transform string to SOAP message";
        log.error(m);
        throw new WebServiceException(m, e);
    }

    String multipartXml = (String) pipelineSession.get(attachmentXmlSessionKey);
    log.debug(getLogPrefix(correlationId) + "building multipart message with MultipartXmlSessionKey ["
            + multipartXml + "]");
    if (StringUtils.isNotEmpty(multipartXml)) {
        Element partsElement;
        try {
            partsElement = XmlUtils.buildElement(multipartXml);
        } catch (DomBuilderException e) {
            String m = "error building multipart xml";
            log.error(m, e);
            throw new WebServiceException(m, e);
        }
        Collection<Node> parts = XmlUtils.getChildTags(partsElement, "part");
        if (parts == null || parts.size() == 0) {
            log.warn(getLogPrefix(correlationId) + "no part(s) in multipart xml [" + multipartXml + "]");
        } else {
            Iterator<Node> iter = parts.iterator();
            while (iter.hasNext()) {
                Element partElement = (Element) iter.next();
                //String partType = partElement.getAttribute("type");
                String partName = partElement.getAttribute("name");
                String partSessionKey = partElement.getAttribute("sessionKey");
                String partMimeType = partElement.getAttribute("mimeType");
                Object partObject = pipelineSession.get(partSessionKey);
                if (partObject instanceof InputStream) {
                    InputStream fis = (InputStream) partObject;

                    DataHandler dataHander = null;
                    try {
                        dataHander = new DataHandler(new ByteArrayDataSource(fis, partMimeType));
                    } catch (IOException e) {
                        String m = "Unable to add session key '" + partSessionKey + "' as attachment";
                        log.error(m, e);
                        throw new WebServiceException(m, e);
                    }
                    AttachmentPart attachmentPart = soapMessage.createAttachmentPart(dataHander);
                    attachmentPart.setContentId(partName);
                    soapMessage.addAttachmentPart(attachmentPart);

                    log.debug(getLogPrefix(correlationId) + "appended filepart [" + partSessionKey
                            + "] with value [" + partObject + "] and name [" + partName + "]");
                } else { //String
                    String partValue = (String) partObject;

                    DataHandler dataHander = new DataHandler(new ByteArrayDataSource(partValue, partMimeType));
                    AttachmentPart attachmentPart = soapMessage.createAttachmentPart(dataHander);
                    attachmentPart.setContentId(partName);
                    soapMessage.addAttachmentPart(attachmentPart);

                    log.debug(getLogPrefix(correlationId) + "appended stringpart [" + partSessionKey
                            + "] with value [" + partValue + "]");
                }
            }
        }
    }

    return soapMessage;
}

From source file:Implement.Service.AdminServiceImpl.java

@Override
public boolean sendPackageApprovedEmail(PackageApprovedEmailData emailData) throws MessagingException {
    String path = System.getProperty("catalina.base");
    MimeBodyPart logo = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/logoIcon.png"));
    logo.setDataHandler(new DataHandler(source));
    logo.setFileName("logoIcon.png");
    logo.setDisposition(MimeBodyPart.INLINE);
    logo.setHeader("Content-ID", "<logo_Icon>"); // cid:image_cid

    MimeBodyPart facebook = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/facebookIcon.png"));
    facebook.setDataHandler(new DataHandler(source));
    facebook.setFileName("facebookIcon.png");
    facebook.setDisposition(MimeBodyPart.INLINE);
    facebook.setHeader("Content-ID", "<fb_Icon>"); // cid:image_cid

    MimeBodyPart twitter = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/twitterIcon.png"));
    twitter.setDataHandler(new DataHandler(source));
    twitter.setFileName("twitterIcon.png");
    twitter.setDisposition(MimeBodyPart.INLINE);
    twitter.setHeader("Content-ID", "<twitter_Icon>"); // cid:image_cid

    MimeBodyPart insta = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/instaIcon.png"));
    insta.setDataHandler(new DataHandler(source));
    insta.setFileName("instaIcon.png");
    insta.setDisposition(MimeBodyPart.INLINE);
    insta.setHeader("Content-ID", "<insta_Icon>"); // cid:image_cid

    MimeBodyPart youtube = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/youtubeIcon.png"));
    youtube.setDataHandler(new DataHandler(source));
    youtube.setFileName("youtubeIcon.png");
    youtube.setDisposition(MimeBodyPart.INLINE);
    youtube.setHeader("Content-ID", "<yt_Icon>"); // cid:image_cid

    MimeBodyPart pinterest = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/pinterestIcon.png"));
    pinterest.setDataHandler(new DataHandler(source));
    pinterest.setFileName("pinterestIcon.png");
    pinterest.setDisposition(MimeBodyPart.INLINE);
    pinterest.setHeader("Content-ID", "<pin_Icon>"); // cid:image_cid

    String content = "<div style=' width: 507px;background-color: #f2f2f4;'>"
            + "    <div style='padding: 30px 0;text-align: center; color: #fff; background-color: #ff514e;font-size: 30px;font-weight: bold;'>"
            + "        <img style=' text-align:center;' width=57 height=57 src='cid:logo_Icon'/>"
            + "        <p style='margin:25px 0px 0px 0px;'> Package Approved! </p>" + "    </div>"
            + "    <div style=' padding: 50px;margin-bottom: 20px;'>" + "        <div id='email-form'>"
            + "            <div style='margin-bottom: 20px'>" + "                Hi " + emailData.getLastName()
            + " ,<br/>" + "                Your package " + emailData.getLastestPackageName()
            + " has been approved" + "            </div>" + "            <div style='margin-bottom: 20px'>"
            + "                Thanks,<br/>" + "                Youtripper team\n" + "            </div>"
            + "        </div>" + "        <div style='border-top: solid 1px #c4c5cc;text-align:center;'>"
            + "            <p style='text-align: center; color: #3b3e53;margin-top: 10px;margin-bottom: 0px;font-size: 10px;'>Sent from Youtripper.com</p>"
            + "            <div>"
            + "                <a href='https://www.facebook.com/youtrippers/'><img style='margin:10px;' src='cid:fb_Icon' alt=''/></a>"
            + "                <a href='https://twitter.com/youtrippers'><img style='margin:10px;' src='cid:twitter_Icon' alt=''/></a>"
            + "                <a href='https://www.instagram.com/youtrippers/'><img style='margin:10px;' src='cid:insta_Icon' alt=''/></a>"
            + "                <a href='https://www.youtube.com/channel/UCtd4xd_SSjRR9Egug7tXIWA'><img style='margin:10px;' src='cid:yt_Icon' alt=''/></a>"
            + "                <a href='https://www.pinterest.com/youtrippers/'><img style='margin:10px;' src='cid:pin_Icon' alt=''/></a>"
            + "            </div>"
            + "            <p>Youtripper Ltd., 56 Soi Seri Villa, Srinakarin Rd., Nongbon,"
            + "                <br>Pravet, Bangkok, Thailand 10250</p>" + "        </div>" + "    </div>"
            + "</div>";

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);//from  w w w.  ja v a2 s . co m
    mp.addBodyPart(logo);
    mp.addBodyPart(facebook);
    mp.addBodyPart(twitter);
    mp.addBodyPart(insta);
    mp.addBodyPart(youtube);
    mp.addBodyPart(pinterest);

    final String username = "noreply@youtripper.com";
    final String password = "Tripper190515";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("noreply@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailData.getEmail()));
    message.setSubject("Package Approved!");
    message.setContent(mp);
    message.saveChanges();
    Transport.send(message);
    return true;
}

From source file:bo.com.offercruzmail.imp.InterpretadorMensajeGenerico.java

protected Multipart enviarPlantilla(boolean plantillaNueva, String idCargar)
        throws MessagingException, IOException {
    String nombreArchivoOrigen;// www .  j  a  v  a 2s  . c o  m
    String nombreAdjunto;
    List<T> lista = null;
    mensajesError = null;
    T entidad = null;
    getObjetoNegocio().setIdUsuario(idUsuario);
    getObjetoNegocio().setComandoPermiso(nombreEntidad);
    try {
        if (!plantillaNueva) {
            if ("todos".equals(idCargar)) {
                lista = getObjetoNegocio().obtenerTodos();
                nombreArchivoOrigen = nombreEntidad + "-" + "lista";
                nombreAdjunto = "lista_" + nombreEntidad + ".xlsx";
            } else {
                ID id;
                try {
                    id = convertirId(idCargar);
                } catch (Exception ex) {
                    return FormadorMensajes.enviarIdCargarNoValido();
                }
                entidad = getObjetoNegocio().recuperarPorId(id);
                if (entidad == null) {
                    return FormadorMensajes.enviarEntidadNoExiste(idCargar);
                }
                nombreArchivoOrigen = nombreEntidad;
                nombreAdjunto = nombreEntidad + "_" + idCargar + ".xlsx";
            }
        } else {
            nombreArchivoOrigen = nombreEntidad;
            nombreAdjunto = "plantilla_" + nombreEntidad + ".xlsx";
            //            if (this instanceof IInterpretadorFormularioDasometrico) {
            //                if (cargarPlantillaFormularios) {
            //                    nombreArchivoOrigen = "plantillafrm";
            //                }
            //            }
        }
        String nombreArchivoOriginal = "plantillas/" + nombreArchivoOrigen + ".xlsx";
        File archivoCopia = UtilitariosMensajes.reservarNombre(nombreEntidad);
        UtilitariosMensajes.copiarArchivo(new File(nombreArchivoOriginal), archivoCopia);
        archivosTemporales.add(archivoCopia);
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            Workbook libro;
            fis = new FileInputStream(archivoCopia);
            libro = WorkbookFactory.create(fis);
            hojaActual = new HojaExcelHelper(libro.getSheetAt(0));
            if (plantillaNueva) {
                preparPlantillaAntesDeEnviar(libro);
            } else {
                if (lista != null) {
                    mostrarLista(lista);
                } else {
                    mostrarEntidad(entidad, libro);
                }
            }
            if (mensajesError != null) {
                return FormadorMensajes.enviarErroresNegocio(mensajesError);
            }
            //Guardamos cambio
            os = new FileOutputStream(archivoCopia);
            libro.write(os);
        } catch (InvalidFormatException ex) {

        } finally {
            if (fis != null) {
                fis.close();
            }
            if (os != null) {
                os.close();
            }
        }
        String textoMensaje;
        if (plantillaNueva) {
            textoMensaje = escapeHtml4("La plantilla est adjunta a este mensaje.");
        } else if (lista != null) {
            textoMensaje = "La consulta ha devuelto " + lista.size() + " registro(s).";
        } else {
            textoMensaje = escapeHtml4("El registro solicitado est adjunto a este mensaje");
        }
        Multipart cuerpo = new MimeMultipart();
        BodyPart adjunto = new MimeBodyPart();
        DataSource origen = new FileDataSource(archivoCopia);
        adjunto.setDataHandler(new DataHandler(origen));
        adjunto.setFileName(nombreAdjunto);
        cuerpo.addBodyPart(FormadorMensajes.getBodyPartEnvuelto(textoMensaje));
        cuerpo.addBodyPart(adjunto);
        return cuerpo;
    } catch (PermisosInsuficientesException ex) {
        appendException(new BusinessExceptionMessage(ex.getMessage(), "Autentificacion"));
    }
    if (mensajesError != null) {
        return FormadorMensajes.enviarErroresNegocio(mensajesError);
    }
    return null;
}

From source file:de.kp.ames.web.function.bulletin.PostingLCM.java

/**
 * Submit posting for a certain recipient; a posting is an 
 * extrinsic object that is classified as posting and contained
 * within the respective positing container; 
 * //from ww  w. jav  a2s . co  m
 * the association to the addressed recipient is mapped onto an 
 * association instance
 * 
 * @param recipient
 * @param data
 * @return
 * @throws Exception 
 */
public String submitPosting(String recipient, String data) throws Exception {

    /*
     * Create or retrieve registry package that is 
     * responsible for managing posting
     */
    RegistryPackageImpl container = null;
    JaxrDQM dqm = new JaxrDQM(jaxrHandle);

    List<RegistryPackageImpl> list = dqm.getRegistryPackage_ByClasNode(ClassificationConstants.FNC_ID_Posting);
    if (list.size() == 0) {
        /*
         * Create container
         */
        container = createPostingPackage();

    } else {
        /*
         * Retrieve container
         */
        container = list.get(0);

    }

    /* 
     * A posting is a certain extrinsic object that holds all relevant
     * and related information in a single JSON repository item
     */
    ExtrinsicObjectImpl eo = null;
    JaxrTransaction transaction = new JaxrTransaction();

    /* 
     * Create extrinsic object that serves as a container for
     * the respective posting
     */
    eo = createExtrinsicObject();
    if (eo == null)
        throw new JAXRException();

    /* 
     * Identifier
     */
    String eid = JaxrIdentity.getInstance().getPrefixUID(FncConstants.POSTING_PRE);

    /*
    * Name & description using default locale
    */
    JSONObject jPosting = new JSONObject(data);

    /*
     * Name is the 'name' of the recipient
     */
    String name = "[POST] " + jPosting.getString(JaxrConstants.RIM_NAME);
    String desc = "[SUBJ] " + jPosting.getString(JaxrConstants.RIM_SUBJECT);

    /* 
     * Home url
     */
    String home = jaxrHandle.getEndpoint().replace("/saml", "");

    /*
     * Set properties
     */
    setProperties(eo, eid, name, desc, home);

    /* 
     * Mime type & handler
     */
    String mimetype = GlobalConstants.MT_JSON;
    eo.setMimeType(mimetype);

    byte[] bytes = data.getBytes(GlobalConstants.UTF_8);

    DataHandler handler = new DataHandler(FileUtil.createByteArrayDataSource(bytes, mimetype));
    eo.setRepositoryItem(handler);

    /*
     * Create classification
     */
    ClassificationImpl c = createClassification(ClassificationConstants.FNC_ID_Posting);
    c.setName(createInternationalString(Locale.US, "Posting Classification"));

    /* 
     * Associate classification and posting container
     */
    eo.addClassification(c);

    /* 
     * Add extrinsic object to container
     */
    container.addRegistryObject(eo);

    /*
     * Create association
     */
    String aid = JaxrIdentity.getInstance().getPrefixUID(FncConstants.POSTING_PRE);
    AssociationImpl a = this.createAssociation_RelatedTo(eo);
    /*
     * Set properties
     */
    setProperties(a, aid, "Recipient Link",
            "This is a directed association between a recipient and the respective posting.", home);

    /*
     * Source object (could be User or Organization)
     */

    RegistryObject so = (RegistryObject) jaxrHandle.getDQM().getRegistryObject(recipient);

    so.addAssociation(a);

    /*
     * Add association to container
     */
    container.addRegistryObject(a);

    /*
     * Save objects
     */
    confirmAssociation(a);

    /*
     * Only the registryPackage needs to be added for save
     * All dependent objects will be added automatically 
     */
    transaction.addObjectToSave(container);
    saveObjects(transaction.getObjectsToSave(), false, false);

    /*
     * Supply reactor
     */
    ReactorParams reactorParams = new ReactorParams(jaxrHandle, eo, ClassificationConstants.FNC_ID_Posting,
            RAction.C_INDEX);
    ReactorImpl.onSubmit(reactorParams);

    /*
     * Retrieve response message
     */
    JSONObject jResponse = transaction.getJResponse(eid, FncMessages.POSTING_CREATED);
    return jResponse.toString();

}

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  www  . jav a2  s  .  c  om
 * @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 ErrorType sendMsg(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, final String port, final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;

    if (StringUtils.isEmpty(toEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR");
        return ErrorType.Error;
    }

    if (StringUtils.isEmpty(fromEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR");
        return ErrorType.Error;
    }

    //if (isGmailEmail())
    //{
    //    return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment);
    //}

    Boolean fail = false;
    ArrayList<String> userAndPass = new ArrayList<String>();

    boolean isSSL = security.equals("SSL");

    String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable",
            "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback",
            "mail.imap.auth.plain.disable", };
    Properties props = System.getProperties();
    for (String key : keys) {
        props.remove(key);
    }

    props.put("mail.smtp.host", host); //$NON-NLS-1$

    if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) {
        props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        props.remove("mail.smtp.port");
    }

    if (StringUtils.isNotEmpty(security)) {
        if (security.equals("TLS")) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
            props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

        } else if (isSSL) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$

            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.imap.auth.plain.disable", "true");
        }
    }

    Session session = null;
    if (isSSL) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uName, pWord);
            }
        });

    } else {
        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$
        log.debug("Port:     " + port); //$NON-NLS-1$
        log.debug("Security: " + security); //$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 {
            try {
                InternetAddress[] address = { new InternetAddress(toEMailAddr) };
                msg.setRecipients(Message.RecipientType.TO, address);

            } catch (javax.mail.internet.AddressException ex) {
                UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr);
                return ErrorType.Error;
            }
        }
        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);
        }

        final int TRIES = 1;

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

        Exception exception = null;
        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                if (isSSL) {
                    Transport.send(msg);

                } else {
                    t.connect(host, userName, password);
                    t.sendMessage(msg, msg.getAllRecipients());
                }

                fail = false;

            } catch (SendFailedException mex) {
                mex.printStackTrace();
                exception = mex;

            } catch (MessagingException mex) {
                if (mex.getCause() instanceof UnknownHostException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host);

                } else if (mex.getCause() instanceof ConnectException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError(
                            "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port);

                } else {
                    mex.printStackTrace();
                    exception = mex;
                }

            } catch (Exception mex) {
                mex.printStackTrace();
                exception = mex;

            } finally {
                if (t != null) {
                    log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                    t.close();
                }
            }

            if (exception != null) {
                fail = true;

                instance.lastErrorMsg = exception.toString();

                //wrong username or password, get new one
                if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName);

                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) { //the user is done
                        instance.lastErrorMsg = null;
                        return ErrorType.Cancel;
                    }
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }

            }
            exception = null;

        } while (fail && cnt < TRIES);

    } catch (Exception 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 (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return ErrorType.Error;

    }

    if (fail) {
        return ErrorType.Error;
    } //else

    return ErrorType.OK;
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailAnda(String from, String to1, String subject, String filename)
        throws FileNotFoundException, IOException {
    //Get properties object    
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }//from w  ww.  j  av a2  s.  co  m
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        //message.setContent(multipart);

        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        message.setContent(writer.toString(), "text/html");

        //send message  
        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.apache.synapse.config.SynapseConfigUtils.java

/**
 * Helper method to handle non-XMl resources
 *
 * @param url The resource url/*from   www  .  ja  va2s . com*/
 * @return The content as an OMNode
 */
public static OMNode readNonXML(URL url) {

    try {
        // Open a new connection
        URLConnection newConnection = getURLConnection(url);
        if (newConnection == null) {
            if (log.isDebugEnabled()) {
                log.debug("Cannot create a URLConnection for given URL : " + url);
            }
            return null;
        }

        BufferedInputStream newInputStream = new BufferedInputStream(newConnection.getInputStream());

        OMFactory omFactory = OMAbstractFactory.getOMFactory();
        return omFactory.createOMText(
                new DataHandler(new SynapseBinaryDataSource(newInputStream, newConnection.getContentType())),
                true);

    } catch (IOException e) {
        handleException("Error when getting a stream from resource's content", e);
    }
    return null;
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Send a HTML formated message./*from   w w  w .ja va 2  s  .c  o  m*/
 * @param strRecipientsTo
 *            The list of the main recipients email.Every recipient must be
 *            separated by the mail separator defined in config.properties
 * @param strRecipientsCc
 *            The recipients list of the carbon copies .
 * @param strRecipientsBcc
 *            The recipients list of the blind carbon copies .
 * @param strSenderName
 *            The sender name.
 * @param strSenderEmail
 *            The sender email address.
 * @param strSubject
 *            The message subject.
 * @param strMessage
 *            The message.
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occured during sending
 * @throws MessagingException
 *             If a messaging error occured
 */
protected static void sendMessageHtml(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc,
        String strSenderName, String strSenderEmail, String strSubject, String strMessage, Transport transport,
        Session session) throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);

    msg.setHeader(HEADER_NAME, HEADER_VALUE);
    // Message body formated in HTML
    msg.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));

    sendMessage(msg, transport);
}