Java Code Examples for javax.activation.DataHandler

The following are top voted examples for showing how to use javax.activation.DataHandler. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: dswork   File: EmailUtil.java   Source Code and License 8 votes vote down vote up
public static String addAttachment(MimeMultipart mm, String path)
{
	if(count == Integer.MAX_VALUE)
	{
		count = 0;
	}
	int cid = count++;
       try
	{
   		java.io.File file = new java.io.File(path);
   		MimeBodyPart mbp = new MimeBodyPart();
   		mbp.setDisposition(MimeBodyPart.INLINE);
   		mbp.setContent(new MimeMultipart("mixed"));
   		mbp.setHeader("Content-ID", "<" + cid + ">");
		mbp.setDataHandler(new DataHandler(new FileDataSource(file)));
        mbp.setFileName(new String(file.getName().getBytes("GBK"), "ISO-8859-1"));
        mm.addBodyPart(mbp);
        return String.valueOf(cid);
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
       return "";
}
 
Example 2
Project: ats-framework   File: MimePackage.java   Source Code and License 6 votes vote down vote up
/**
 * Add the specified file as an attachment
 *
 * @param fileName
 *            name of the file
 * @throws PackageException
 *             on error
 */
@PublicAtsApi
public void addAttachment(
                           String fileName ) throws PackageException {

    try {
        // add attachment to multipart content
        MimeBodyPart attPart = new MimeBodyPart();
        FileDataSource ds = new FileDataSource(fileName);
        attPart.setDataHandler(new DataHandler(ds));
        attPart.setDisposition(MimeBodyPart.ATTACHMENT);
        attPart.setFileName(ds.getName());

        addPart(attPart, PART_POSITION_LAST);
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
Example 3
Project: parabuild-ci   File: EchoAttachmentsService.java   Source Code and License 6 votes vote down vote up
/**
 * This method implements a web service that sends back
 * any attachment it receives.
 */
public DataHandler echo( DataHandler dh) {
    System.err.println("In echo");

    //Attachments are sent by default back as a MIME stream if no attachments were
    // received.  If attachments are received the same format that was received will
    // be the default stream type for any attachments sent.

    //The following two commented lines would force any attachments sent back.
    //  to be in DIME format.

    //Message rspmsg=AxisEngine.getCurrentMessageContext().getResponseMessage();
    //rspmsg.getAttachmentsImpl().setSendType(org.apache.axis.attachments.Attachments.SEND_TYPE_DIME);
    
    if (dh == null ) System.err.println("dh is null");
    else System.err.println("Received \""+dh.getClass().getName()+"\".");
    return dh;
}
 
Example 4
Project: unitimes   File: JavaMailWrapper.java   Source Code and License 6 votes vote down vote up
@Override
protected void addAttachment(String name, DataHandler data) throws MessagingException {
       BodyPart attachment = new MimeBodyPart();
       attachment.setDataHandler(data);
       attachment.setFileName(name);
       attachment.setHeader("Content-ID", "<" + name + ">");
       iBody.addBodyPart(attachment);
}
 
Example 5
Project: parabuild-ci   File: EchoAttachmentsService.java   Source Code and License 6 votes vote down vote up
/**
 * This method implements a web service that sends back
 * an array of attachment it receives.
 */
public DataHandler[] echoDir( DataHandler[] attachments) {
    System.err.println("In echoDir");

    //Attachments are sent by default back as a MIME stream if no attachments were
    // received.  If attachments are received the same format that was received will
    // be the default stream type for any attachments sent.

    //The following two commented lines would force any attachments sent back.
    //  to be in DIME format.

    //Message rspmsg=AxisEngine.getCurrentMessageContext().getResponseMessage();
    //rspmsg.getAttachmentsImpl().setSendType(org.apache.axis.attachments.Attachments.SEND_TYPE_DIME);

    if (attachments == null ) System.err.println("attachments is null!");
    else System.err.println("Got " + attachments.length + " attachments!");
    return attachments;
}
 
Example 6
Project: OpenJSharp   File: ServerSOAPHandlerTube.java   Source Code and License 6 votes vote down vote up
void callHandlersOnResponse(MessageUpdatableContext context, boolean handleFault) {

        //Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
        Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
        AttachmentSet attSet = context.packet.getMessage().getAttachments();
        for (Map.Entry<String, DataHandler> entry : atts.entrySet()) {
            String cid = entry.getKey();
            if (attSet.get(cid) == null) { // Otherwise we would be adding attachments twice
                Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
                attSet.add(att);
            }
        }

        try {
            //SERVER-SIDE
            processor.callHandlersResponse(HandlerProcessor.Direction.OUTBOUND, context, handleFault);

        } catch (WebServiceException wse) {
            //no rewrapping
            throw wse;
        } catch (RuntimeException re) {
            throw re;

        }
    }
 
Example 7
Project: OpenJSharp   File: ServerLogicalHandlerTube.java   Source Code and License 6 votes vote down vote up
void callHandlersOnResponse(MessageUpdatableContext context, boolean handleFault) {
    //Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
    Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
    AttachmentSet attSet = context.packet.getMessage().getAttachments();
    for (Entry<String, DataHandler> entry : atts.entrySet()) {
        String cid = entry.getKey();
        Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
        attSet.add(att);
    }

    try {
        //SERVER-SIDE
        processor.callHandlersResponse(HandlerProcessor.Direction.OUTBOUND, context, handleFault);

    } catch (WebServiceException wse) {
        //no rewrapping
        throw wse;
    } catch (RuntimeException re) {
        throw re;
    }
}
 
Example 8
Project: jwala   File: ResourceServiceRestImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCreateTemplate() throws IOException {
    List<Attachment> attachmentList = new ArrayList<>();
    Attachment json = mock(Attachment.class);
    Attachment tpl = mock(Attachment.class);
    attachmentList.add(json);
    attachmentList.add(tpl);
    DataHandler jsonDataHandler = mock(DataHandler.class);
    DataHandler tplDataHandler = mock(DataHandler.class);
    when(json.getDataHandler()).thenReturn(jsonDataHandler);
    when(tpl.getDataHandler()).thenReturn(tplDataHandler);
    when(jsonDataHandler.getName()).thenReturn("test-target.json");
    when(tplDataHandler.getName()).thenReturn("test-target.tpl");
    String jsonContent = "{}";
    when(jsonDataHandler.getInputStream()).thenReturn(new ByteArrayInputStream(jsonContent.getBytes()));
    String tplContent = "template content";
    when(tplDataHandler.getInputStream()).thenReturn(new ByteArrayInputStream(tplContent.getBytes()));

    when(impl.createTemplate(any(InputStream.class), any(InputStream.class), anyString(), any(User.class))).thenReturn(new CreateResourceResponseWrapper(new ConfigTemplate()));
    Response response = cut.createTemplate(attachmentList, "test-target-name", authenticatedUser);

    assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
}
 
Example 9
Project: OpenJSharp   File: ResponseContext.java   Source Code and License 6 votes vote down vote up
public Object get(Object key) {
    if(packet.supports(key))
        return packet.get(key);    // strongly typed

    if(packet.getHandlerScopePropertyNames(true).contains(key))
        return null;            // no such application-scope property

    Object value =  packet.invocationProperties.get(key);

    //add the attachments from the Message to the corresponding attachment property
    if(key.equals(MessageContext.INBOUND_MESSAGE_ATTACHMENTS)){
        Map<String, DataHandler> atts = (Map<String, DataHandler>) value;
        if(atts == null)
            atts = new HashMap<String, DataHandler>();
        AttachmentSet attSet = packet.getMessage().getAttachments();
        for(Attachment att : attSet){
            atts.put(att.getContentId(), att.asDataHandler());
        }
        return atts;
    }
    return value;
}
 
Example 10
Project: openjdk-jdk10   File: SaajStaxWriterEx.java   Source Code and License 6 votes vote down vote up
private String addBinaryText(DataHandler data) {
    String hrefOrCid = null;
    if (data instanceof StreamingDataHandler) {
        hrefOrCid = ((StreamingDataHandler) data).getHrefCid();
    }
    if (hrefOrCid == null) hrefOrCid = encodeCid();

    String prefixedCid = (hrefOrCid.startsWith("cid:")) ? hrefOrCid : "cid:" + hrefOrCid;
    // Should we do the threshold processing on DataHandler ? But that would be
    // expensive as DataHolder need to read the data again from its source
  //binaryText = BinaryTextImpl.createBinaryTextFromDataHandler((MessageImpl) soap, prefixedCid, currentElement.getOwnerDocument(), data);
  //currentElement.appendChild(binaryText);
    if (currentElement instanceof MtomEnabled) {
        binaryText = ((MtomEnabled) currentElement).addBinaryText(prefixedCid, data);
    } else {
        throw new IllegalStateException("The currentElement is not MtomEnabled " + currentElement);
    }
    return hrefOrCid;
}
 
Example 11
Project: OpenJSharp   File: MtomCodec.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("resource")
private void writeNonMtomAttachments(AttachmentSet attachments,
        OutputStream out, String boundary) throws IOException {

    for (Attachment att : attachments) {

        DataHandler dh = att.asDataHandler();
        if (dh instanceof StreamingDataHandler) {
            StreamingDataHandler sdh = (StreamingDataHandler) dh;
            // If DataHandler has href Content-ID, it is MTOM, so skip.
            if (sdh.getHrefCid() != null)
                continue;
        }

        // build attachment frame
        writeln("--" + boundary, out);
        writeMimeHeaders(att.getContentType(), att.getContentId(), out);
        att.writeTo(out);
        writeln(out); // write \r\n
    }
}
 
Example 12
Project: openjdk-jdk10   File: ResponseBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an AttachmentBuilder based on the parameter type
 *
 * @param param
 *      runtime Parameter that abstracts the annotated java parameter
 * @param setter
 *      specifies how the obtained value is set into the argument. Takes
 *      care of Holder arguments.
 */
public static ResponseBuilder createAttachmentBuilder(ParameterImpl param, ValueSetter setter) {
    Class type = (Class)param.getTypeInfo().type;
    if (DataHandler.class.isAssignableFrom(type)) {
        return new DataHandlerBuilder(param, setter);
    } else if (byte[].class==type) {
        return new ByteArrayBuilder(param, setter);
    } else if(Source.class.isAssignableFrom(type)) {
        return new SourceBuilder(param, setter);
    } else if(Image.class.isAssignableFrom(type)) {
        return new ImageBuilder(param, setter);
    } else if(InputStream.class==type) {
        return new InputStreamBuilder(param, setter);
    } else if(isXMLMimeType(param.getBinding().getMimeType())) {
        return new JAXBBuilder(param, setter);
    } else if(String.class.isAssignableFrom(type)) {
        return new StringBuilder(param, setter);
    } else {
        throw new UnsupportedOperationException("Unexpected Attachment type ="+type);
    }
}
 
Example 13
Project: parabuild-ci   File: Tester.java   Source Code and License 6 votes vote down vote up
/**
 * Method addBodyPart
 * 
 * @param mp 
 * @param dh 
 */
private static void addBodyPart(MimeMultipart mp, DataHandler dh) {
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    try {
        messageBodyPart.setDataHandler(dh);
        String contentType = dh.getContentType();
        if ((contentType == null) || (contentType.trim().length() == 0)) {
            contentType = "application/octet-stream";
        }
        System.out.println("Content type: " + contentType);
        messageBodyPart.setHeader(HEADER_CONTENT_TYPE, contentType);
        messageBodyPart.setHeader(
                HEADER_CONTENT_TRANSFER_ENCODING,
                "binary");    // Safe and fastest for anything other than mail
        mp.addBodyPart(messageBodyPart);
    } catch (javax.mail.MessagingException e) {
    }
}
 
Example 14
Project: kettle_support_kettle8.0   File: Message.java   Source Code and License 5 votes vote down vote up
/**
 * 增加发送附件
 * 
 * @param filename
 *            邮件附件的地址,只能是本机地址而不能是网络地址,否则抛出异常
 * @return
 */
public static boolean addFileAffix(String filename) {
	try {
		BodyPart bp = new MimeBodyPart();
		FileDataSource fileds = new FileDataSource(filename);
		bp.setDataHandler(new DataHandler(fileds));
		bp.setFileName(MimeUtility.encodeText(fileds.getName(), "utf-8",
				null)); // 解决附件名称乱码
		mp.addBodyPart(bp);// 添加附件
		attachment.add(fileds);
	} catch (Exception e) {
		return false;
	}
	return true;
}
 
Example 15
Project: marshalsec   File: JDKUtil.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings ( "resource" )
public static Object makeIteratorTriggerNative ( UtilFactory uf, Object it ) throws Exception, ClassNotFoundException, NoSuchMethodException,
        InstantiationException, IllegalAccessException, InvocationTargetException {
    Cipher m = Reflections.createWithoutConstructor(NullCipher.class);
    Reflections.setFieldValue(m, "serviceIterator", it);
    Reflections.setFieldValue(m, "lock", new Object());

    InputStream cos = new CipherInputStream(null, m);

    Class<?> niCl = Class.forName("java.lang.ProcessBuilder$NullInputStream"); //$NON-NLS-1$
    Constructor<?> niCons = niCl.getDeclaredConstructor();
    niCons.setAccessible(true);

    Reflections.setFieldValue(cos, "input", niCons.newInstance());
    Reflections.setFieldValue(cos, "ibuffer", new byte[0]);

    Object b64Data = Class.forName("com.sun.xml.internal.bind.v2.runtime.unmarshaller.Base64Data").newInstance();
    DataSource ds = (DataSource) Reflections
            .createWithoutConstructor(Class.forName("com.sun.xml.internal.ws.encoding.xml.XMLMessage$XmlDataSource")); //$NON-NLS-1$
    Reflections.setFieldValue(ds, "is", cos);
    Reflections.setFieldValue(b64Data, "dataHandler", new DataHandler(ds));
    Reflections.setFieldValue(b64Data, "data", null);

    Object nativeString = Reflections.createWithoutConstructor(Class.forName("jdk.nashorn.internal.objects.NativeString"));
    Reflections.setFieldValue(nativeString, "value", b64Data);
    return uf.makeHashCodeTrigger(nativeString);
}
 
Example 16
Project: iBase4J-Common   File: EmailSender.java   Source Code and License 5 votes vote down vote up
/**
 * 设置附件
 * 
 * @param filename
 * @return
 */
public boolean addFileAffix(String filename) {
	logger.info(Resources.getMessage("EMAIL.ADD_ATTEND"), filename);
	try {
		BodyPart bp = new MimeBodyPart();
		FileDataSource fileds = new FileDataSource(filename);
		bp.setDataHandler(new DataHandler(fileds));
		bp.setFileName(MimeUtility.encodeText(fileds.getName()));
		mp.addBodyPart(bp);
		return true;
	} catch (Exception e) {
		logger.error(filename, e);
		return false;
	}
}
 
Example 17
Project: automat   File: EmailSender.java   Source Code and License 5 votes vote down vote up
/**
 * 设置附件
 * 
 * @param name String
 * @param pass String
 */
public boolean addFileAffix(String filename) {
	logger.info(Resources.getMessage("EMAIL.ADD_ATTEND"), filename);
	try {
		BodyPart bp = new MimeBodyPart();
		FileDataSource fileds = new FileDataSource(filename);
		bp.setDataHandler(new DataHandler(fileds));
		bp.setFileName(MimeUtility.encodeText(fileds.getName()));
		mp.addBodyPart(bp);
		return true;
	} catch (Exception e) {
		logger.error(filename, e);
		return false;
	}
}
 
Example 18
Project: spr   File: SendMail.java   Source Code and License 5 votes vote down vote up
public static void sendEmail(String host, String port,
        final String userName, final String password, String toAddress,
        String subject, String message, String nombreArchivoAdj, String urlArchivoAdj)
        		throws AddressException, MessagingException {
 
    // sets SMTP server properties
    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
 
    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    };
 
    Session session = Session.getInstance(properties, auth);

    //Se crea la parte del cuerpo del mensaje.
    BodyPart texto = new MimeBodyPart();
    texto.setText(message);        
    BodyPart adjunto = new MimeBodyPart();
    
    if(nombreArchivoAdj != null ){	        
     adjunto.setDataHandler(new DataHandler(new FileDataSource(urlArchivoAdj)));
     adjunto.setFileName(nombreArchivoAdj);
    }
    
    //Juntar las dos partes
    MimeMultipart multiParte = new MimeMultipart();
    multiParte.addBodyPart(texto);
    if (nombreArchivoAdj != null) multiParte.addBodyPart(adjunto);
    
    // creates a new e-mail message
    Message msg = new MimeMessage(session);
 
    msg.setFrom(new InternetAddress(userName));
    InternetAddress[] toAddresses = null;
    toAddresses = InternetAddress.parse(toAddress, false);

    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    //msg.setText(message);
    msg.setContent(multiParte);
 
    // sends the e-mail
    Transport.send(msg);       

}
 
Example 19
Project: logistimo-web-service   File: EmailService.java   Source Code and License 5 votes vote down vote up
private void addAttachment(Multipart mp, byte[] attachmentData, String mimeType, String filename)
    throws MessagingException {
  if (mp == null) {
    return;
  }
  ByteArrayDataSource dataSrc = new ByteArrayDataSource(attachmentData, mimeType);
  MimeBodyPart attachment = new MimeBodyPart();
  attachment.setFileName(filename);
  attachment.setDataHandler(new DataHandler(dataSrc));
  ///attachment.setContent( attachmentData, mimeType );
  mp.addBodyPart(attachment);
}
 
Example 20
Project: openjdk-jdk10   File: ClientSOAPHandlerTube.java   Source Code and License 5 votes vote down vote up
boolean callHandlersOnRequest(MessageUpdatableContext context, boolean isOneWay) {

        boolean handlerResult;
        //Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
        Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
        AttachmentSet attSet = context.packet.getMessage().getAttachments();
        for (Entry<String, DataHandler> entry : atts.entrySet()) {
            String cid = entry.getKey();
            if (attSet.get(cid) == null) {  // Otherwise we would be adding attachments twice
                Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
                attSet.add(att);
            }
        }

        try {
            //CLIENT-SIDE
            handlerResult = processor.callHandlersRequest(HandlerProcessor.Direction.OUTBOUND, context, !isOneWay);
        } catch (WebServiceException wse) {
            remedyActionTaken = true;
            //no rewrapping
            throw wse;
        } catch (RuntimeException re) {
            remedyActionTaken = true;

            throw new WebServiceException(re);

        }
        if (!handlerResult) {
            remedyActionTaken = true;
        }
        return handlerResult;
    }
 
Example 21
Project: lams   File: MimeMessageHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Add an attachment to the MimeMessage, taking the content from a
 * {@code javax.activation.DataSource}.
 * <p>Note that the InputStream returned by the DataSource implementation
 * needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
 * {@code getInputStream()} multiple times.
 * @param attachmentFilename the name of the attachment as it will
 * appear in the mail (the content type will be determined by this)
 * @param dataSource the {@code javax.activation.DataSource} to take
 * the content from, determining the InputStream and the content type
 * @throws MessagingException in case of errors
 * @see #addAttachment(String, org.springframework.core.io.InputStreamSource)
 * @see #addAttachment(String, java.io.File)
 */
public void addAttachment(String attachmentFilename, DataSource dataSource) throws MessagingException {
	Assert.notNull(attachmentFilename, "Attachment filename must not be null");
	Assert.notNull(dataSource, "DataSource must not be null");
	try {
		MimeBodyPart mimeBodyPart = new MimeBodyPart();
		mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
		mimeBodyPart.setFileName(MimeUtility.encodeText(attachmentFilename));
		mimeBodyPart.setDataHandler(new DataHandler(dataSource));
		getRootMimeMultipart().addBodyPart(mimeBodyPart);
	}
	catch (UnsupportedEncodingException ex) {
		throw new MessagingException("Failed to encode attachment filename", ex);
	}
}
 
Example 22
Project: iBase4J   File: EmailSender.java   Source Code and License 5 votes vote down vote up
/**
 * 设置附件
 * 
 * @param name String
 * @param pass String
 */
public boolean addFileAffix(String filename) {
	logger.info(Resources.getMessage("EMAIL.ADD_ATTEND"), filename);
	try {
		BodyPart bp = new MimeBodyPart();
		FileDataSource fileds = new FileDataSource(filename);
		bp.setDataHandler(new DataHandler(fileds));
		bp.setFileName(MimeUtility.encodeText(fileds.getName()));
		mp.addBodyPart(bp);
		return true;
	} catch (Exception e) {
		logger.error(filename, e);
		return false;
	}
}
 
Example 23
Project: Log4Reports   File: EmailUtil.java   Source Code and License 5 votes vote down vote up
/**
  * @Method: createAttachMail
  * @Description: ����һ����������ʼ�
  * @param session
  * @return
  * @throws Exception
  */ 
  public static MimeMessage createAttachMail(String subject, String content, String filePath) throws Exception{
      MimeMessage message = new MimeMessage(session);
      
      message.setFrom(new InternetAddress(username));
      if(recipients.contains(";")){
	List<InternetAddress> list = new ArrayList<InternetAddress>();
	String []median=recipients.split(";");
	for(int i=0;i<median.length;i++){
		list.add(new InternetAddress(median[i]));
	}
	InternetAddress[] address =list.toArray(new InternetAddress[list.size()]);
	message.setRecipients(Message.RecipientType.TO,address);
}else{
	message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
}
      message.setSubject(subject);
      MimeBodyPart text = new MimeBodyPart();
      text.setContent(content, "text/html;charset=UTF-8");
      
      MimeBodyPart attach = new MimeBodyPart();
      DataHandler dh = new DataHandler(new FileDataSource(filePath));
      attach.setDataHandler(dh);
      attach.setFileName(dh.getName());

      MimeMultipart mp = new MimeMultipart();
      mp.addBodyPart(text);
      mp.addBodyPart(attach);
      mp.setSubType("mixed");
      
      message.setContent(mp);
      message.saveChanges();
      return message;
  }
 
Example 24
Project: Log4Reports   File: EmailUtil.java   Source Code and License 5 votes vote down vote up
/**
  * @Method: createImageMail
  * @Description: ����һ���ʼ����Ĵ�ͼƬ���ʼ�
  * @param session
  * @return
  * @throws Exception
  */ 
  public static MimeMessage createImageMail(String subject, String content, String imagePath) throws Exception {

      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(username));
      if(recipients.contains(";")){
	List<InternetAddress> list = new ArrayList<InternetAddress>();
	String []median=recipients.split(";");
	for(int i=0;i<median.length;i++){
		list.add(new InternetAddress(median[i]));
	}
	InternetAddress[] address =list.toArray(new InternetAddress[list.size()]);
	message.setRecipients(Message.RecipientType.TO,address);
}else{
	message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
}
      message.setSubject(subject);
      MimeBodyPart text = new MimeBodyPart();
      text.setContent(content, "text/html;charset=UTF-8");
      MimeBodyPart image = new MimeBodyPart();
      DataHandler dh = new DataHandler(new FileDataSource(imagePath));
      image.setDataHandler(dh);
      image.setContentID("xxx.jpg");
      MimeMultipart mm = new MimeMultipart();
      mm.addBodyPart(text);
      mm.addBodyPart(image);
      mm.setSubType("related");

      message.setContent(mm);
      message.saveChanges();
      return message;
  }
 
Example 25
Project: jwala   File: ResourceServiceRestImplTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCreateResource() throws IOException {
    final CreateResourceParam createResourceParam = new CreateResourceParam();
    createResourceParam.setWebServer("someWebServer");

    // Deploy path
    final DataHandler deployPathDataHandler = mock(DataHandler.class);
    when(deployPathDataHandler.getName()).thenReturn("deployPath");
    when(deployPathDataHandler.getInputStream()).thenReturn(IOUtils.toInputStream("c:/tmp"));

    final Attachment deployPathAttachment = mock(Attachment.class);
    when(deployPathAttachment.getDataHandler()).thenReturn(deployPathDataHandler);

    // assign to JVMs
    final DataHandler assignToJvmsDataHandler = mock(DataHandler.class);
    when(assignToJvmsDataHandler.getName()).thenReturn("assignToJvms");
    when(assignToJvmsDataHandler.getInputStream()).thenReturn(IOUtils.toInputStream("true", Charset.defaultCharset()));

    final Attachment assignToJvmsPathAttachment = mock(Attachment.class);
    when(assignToJvmsPathAttachment.getDataHandler()).thenReturn(assignToJvmsDataHandler);

    // File attachment
    final DataHandler fileAttachmentDataHandler = mock(DataHandler.class);
    when(fileAttachmentDataHandler.getName()).thenReturn("sample-resource.tpl");
    when(fileAttachmentDataHandler.getInputStream()).thenReturn(this.getClass().getClassLoader().getResourceAsStream("sample-resource.tpl"));

    final Attachment fileAttachment = mock(Attachment.class);
    when(fileAttachment.getDataHandler()).thenReturn(fileAttachmentDataHandler);
    when(fileAttachment.getHeader(eq("Content-Type"))).thenReturn("application/octet-stream");

    final List<Attachment> attachmentList = new ArrayList<>();
    attachmentList.add(fileAttachment);
    attachmentList.add(deployPathAttachment);
    attachmentList.add(assignToJvmsPathAttachment);

    final Response response = cut.createResource("httpd.conf", createResourceParam, attachmentList);
    assertEquals("0", ((ApplicationResponse) response.getEntity()).getMsgCode());
}
 
Example 26
Project: openjdk-jdk10   File: MtomCodec.java   Source Code and License 5 votes vote down vote up
ByteArrayBuffer(@NotNull DataHandler dh, String b) {
    this.dh = dh;
    String cid = null;
    if (dh instanceof StreamingDataHandler) {
        StreamingDataHandler sdh = (StreamingDataHandler) dh;
        if (sdh.getHrefCid() != null)
            cid = sdh.getHrefCid();
    }
    this.contentId = cid != null ? cid : encodeCid();
    boundary = b;
}
 
Example 27
Project: OpenJSharp   File: AttachmentMarshallerImpl.java   Source Code and License 5 votes vote down vote up
@Override
public String addSwaRefAttachment(DataHandler data) {
    String cid = encodeCid(null);
    Attachment att = new DataHandlerAttachment(cid, data);
    attachments.add(att);
    cid = "cid:" + cid;
    return cid;
}
 
Example 28
Project: openjdk-jdk10   File: MessageFiller.java   Source Code and License 5 votes vote down vote up
/**
 * Creates an MessageFiller based on the parameter type
 *
 * @param param
 *      runtime Parameter that abstracts the annotated java parameter
 * @param getter
 *      Gets a value from an object that represents a parameter passed
 *      as a method argument.
 */
public static MessageFiller createAttachmentFiller(ParameterImpl param, ValueGetter getter) {
    Class type = (Class)param.getTypeInfo().type;
    if (DataHandler.class.isAssignableFrom(type) || Source.class.isAssignableFrom(type)) {
        return new DataHandlerFiller(param, getter);
    } else if (byte[].class==type) {
        return new ByteArrayFiller(param, getter);
    } else if(isXMLMimeType(param.getBinding().getMimeType())) {
        return new JAXBFiller(param, getter);
    } else {
        return new DataHandlerFiller(param, getter);
    }
}
 
Example 29
Project: OpenJSharp   File: SAAJMessage.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the attachment as a {@link javax.activation.DataHandler}.
 */
public DataHandler asDataHandler() {
    try {
        return ap.getDataHandler();
    } catch (SOAPException e) {
        throw new WebServiceException(e);
    }
}
 
Example 30
Project: parabuild-ci   File: TestRef.java   Source Code and License 5 votes vote down vote up
/**
 *  Return an array of datahandlers for each file in the dir. 
 *  @param the name of the directory
 *  @return return an array of datahandlers.
 */

protected DataHandler[] getAttachmentsFromDir(String dirName) {
    java.util.LinkedList retList = new java.util.LinkedList();
    DataHandler[] ret = new DataHandler[0];// empty

    java.io.File sourceDir = new java.io.File(dirName);

    java.io.File[] files = sourceDir.listFiles();

    for ( int i = files.length - 1; i >= 0; --i) {
        java.io.File cf = files[i];

        if (cf.isFile() && cf.canRead()) {
            String fname = null;

            try {
                fname = cf.getAbsoluteFile().getCanonicalPath();
            }
            catch ( java.io.IOException e) {
                System.err.println("Couldn't get file \"" + fname + "\" skipping...");
                continue;
            }
            retList.add( new DataHandler( new FileDataSource( fname )));
        }
    }
    if (!retList.isEmpty()) {
        ret = new DataHandler[ retList.size()];
        ret = (DataHandler[]) retList.toArray(ret);
    }

    return ret;
}
 
Example 31
Project: OpenJSharp   File: ClientMessageHandlerTube.java   Source Code and License 5 votes vote down vote up
boolean callHandlersOnRequest(MessageUpdatableContext context, boolean isOneWay) {
    boolean handlerResult;

    //Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
    Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
    AttachmentSet attSet = context.packet.getMessage().getAttachments();
    for (Entry<String, DataHandler> entry : atts.entrySet()) {
        String cid = entry.getKey();
        if (attSet.get(cid) == null) {  // Otherwise we would be adding attachments twice
            Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
            attSet.add(att);
        }
    }

    try {
        //CLIENT-SIDE
        handlerResult = processor.callHandlersRequest(HandlerProcessor.Direction.OUTBOUND, context, !isOneWay);
    } catch (WebServiceException wse) {
        remedyActionTaken = true;
        //no rewrapping
        throw wse;
    } catch (RuntimeException re) {
        remedyActionTaken = true;

        throw new WebServiceException(re);

    }
    if (!handlerResult) {
        remedyActionTaken = true;
    }
    return handlerResult;
}
 
Example 32
Project: openjdk-jdk10   File: RuntimeBuiltinLeafInfoImpl.java   Source Code and License 5 votes vote down vote up
public DataHandler parse(CharSequence text) {
    if(text instanceof Base64Data)
        return ((Base64Data)text).getDataHandler();
    else
        return new DataHandler(new ByteArrayDataSource(decodeBase64(text),
            UnmarshallingContext.getInstance().getXMIMEContentType()));
}
 
Example 33
Project: OpenJSharp   File: ClientSOAPHandlerTube.java   Source Code and License 5 votes vote down vote up
boolean callHandlersOnRequest(MessageUpdatableContext context, boolean isOneWay) {

        boolean handlerResult;
        //Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
        Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
        AttachmentSet attSet = context.packet.getMessage().getAttachments();
        for (Entry<String, DataHandler> entry : atts.entrySet()) {
            String cid = entry.getKey();
            if (attSet.get(cid) == null) {  // Otherwise we would be adding attachments twice
                Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
                attSet.add(att);
            }
        }

        try {
            //CLIENT-SIDE
            handlerResult = processor.callHandlersRequest(HandlerProcessor.Direction.OUTBOUND, context, !isOneWay);
        } catch (WebServiceException wse) {
            remedyActionTaken = true;
            //no rewrapping
            throw wse;
        } catch (RuntimeException re) {
            remedyActionTaken = true;

            throw new WebServiceException(re);

        }
        if (!handlerResult) {
            remedyActionTaken = true;
        }
        return handlerResult;
    }
 
Example 34
Project: openjdk-jdk10   File: MessageImpl.java   Source Code and License 5 votes vote down vote up
private void initializeAttachment(MimeMultipart multiPart, int i)
    throws Exception {
    MimeBodyPart currentBodyPart = multiPart.getBodyPart(i);
    AttachmentPartImpl attachmentPart = new AttachmentPartImpl();

    DataHandler attachmentHandler = currentBodyPart.getDataHandler();
    attachmentPart.setDataHandler(attachmentHandler);

    AttachmentPartImpl.copyMimeHeaders(currentBodyPart, attachmentPart);
    addAttachmentPart(attachmentPart);
}
 
Example 35
Project: OpenJSharp   File: MessageFiller.java   Source Code and License 5 votes vote down vote up
public void fillIn(Object[] methodArgs, Object returnValue, Message msg) {
    String contentId = getContentId();
    Object obj = (methodPos == -1) ? returnValue : getter.get(methodArgs[methodPos]);
    DataHandler dh = (obj instanceof DataHandler) ? (DataHandler)obj : new DataHandler(obj,mimeType);
    Attachment att = new DataHandlerAttachment(contentId, dh);
    msg.getAttachments().add(att);
}
 
Example 36
Project: SkyEye   File: MailService.java   Source Code and License 5 votes vote down vote up
/**
 * 添加附件
 * @param files
 * @param multipart
 */
public void addTach(List<FileDto> files, Multipart multipart) throws IOException, MessagingException {
    for (FileDto file: files) {
        MimeBodyPart mailArchieve = new MimeBodyPart();
        File f = new File("/tmp/mail/" + file.getFileName());
        FileCopyUtils.copy(file.getFileBytes(), f);
        FileDataSource fd = new FileDataSource(f);
        mailArchieve.setDataHandler(new DataHandler(fd));
        mailArchieve.setFileName(MimeUtility.encodeText(fd.getName(), "utf-8", "B"));
        multipart.addBodyPart(mailArchieve);
    }
}
 
Example 37
Project: OpenJSharp   File: MtomCodec.java   Source Code and License 5 votes vote down vote up
ByteArrayBuffer(@NotNull DataHandler dh, String b) {
    this.dh = dh;
    String cid = null;
    if (dh instanceof StreamingDataHandler) {
        StreamingDataHandler sdh = (StreamingDataHandler) dh;
        if (sdh.getHrefCid() != null)
            cid = sdh.getHrefCid();
    }
    this.contentId = cid != null ? cid : encodeCid();
    boundary = b;
}
 
Example 38
Project: OpenJSharp   File: MtomCodec.java   Source Code and License 5 votes vote down vote up
@Override
public void writeBinary(byte[] data, int start, int len, String contentType) throws XMLStreamException {
    //check threshold and if less write as base64encoded value
    if(myMtomFeature.getThreshold() > len){
        writeCharacters(DatatypeConverterImpl._printBase64Binary(data, start, len));
        return;
    }
    ByteArrayBuffer bab = new ByteArrayBuffer(new DataHandler(new ByteArrayDataSource(data, start, len, contentType)), boundary);
    writeBinary(bab);
}
 
Example 39
Project: OpenJSharp   File: MtomCodec.java   Source Code and License 5 votes vote down vote up
@Override
public int next() throws XMLStreamException {
    int event = reader.next();
    if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals(XOP_LOCALNAME) && reader.getNamespaceURI().equals(XOP_NAMESPACEURI)) {
        //its xop reference, take the URI reference
        String href = reader.getAttributeValue(null, "href");
        try {
            xopHref = href;
            Attachment att = getAttachment(href);
            if(att != null){
                DataHandler dh = att.asDataHandler();
                if (dh instanceof StreamingDataHandler) {
                    ((StreamingDataHandler)dh).setHrefCid(att.getContentId());
                }
                base64AttData = new Base64Data();
                base64AttData.set(dh);
            }
            xopReferencePresent = true;
        } catch (IOException e) {
            throw new WebServiceException(e);
        }
        //move to the </xop:Include>
        XMLStreamReaderUtil.nextElementContent(reader);
        return XMLStreamConstants.CHARACTERS;
    }
    if(xopReferencePresent){
        xopReferencePresent = false;
        base64EncodedText = null;
        xopHref = null;
    }
    return event;
}
 
Example 40
Project: OpenJSharp   File: MimeMultipartParser.java   Source Code and License 5 votes vote down vote up
@Override
public DataHandler asDataHandler() {
    if (streamingDataHandler == null) {
        streamingDataHandler = (buf != null)
            ? new DataSourceStreamingDataHandler(new ByteArrayDataSource(buf,getContentType()))
            : new MIMEPartStreamingDataHandler(part);
    }
    return streamingDataHandler;
}
 
Example 41
Project: openjdk-jdk10   File: MtomCodec.java   Source Code and License 5 votes vote down vote up
@Override
public int next() throws XMLStreamException {
    int event = reader.next();
    if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals(XOP_LOCALNAME) && reader.getNamespaceURI().equals(XOP_NAMESPACEURI)) {
        //its xop reference, take the URI reference
        String href = reader.getAttributeValue(null, "href");
        try {
            xopHref = href;
            Attachment att = getAttachment(href);
            if(att != null){
                DataHandler dh = att.asDataHandler();
                if (dh instanceof StreamingDataHandler) {
                    ((StreamingDataHandler)dh).setHrefCid(att.getContentId());
                }
                base64AttData = new Base64Data();
                base64AttData.set(dh);
            }
            xopReferencePresent = true;
        } catch (IOException e) {
            throw new WebServiceException(e);
        }
        //move to the </xop:Include>
        XMLStreamReaderUtil.nextElementContent(reader);
        return XMLStreamConstants.CHARACTERS;
    }
    if(xopReferencePresent){
        xopReferencePresent = false;
        base64EncodedText = null;
        xopHref = null;
    }
    return event;
}
 
Example 42
Project: openjdk-jdk10   File: SAAJMessage.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the attachment as a {@link javax.activation.DataHandler}.
 */
public DataHandler asDataHandler() {
    try {
        return ap.getDataHandler();
    } catch (SOAPException e) {
        throw new WebServiceException(e);
    }
}
 
Example 43
Project: OpenJSharp   File: MessageImpl.java   Source Code and License 5 votes vote down vote up
private void initializeAttachment(MimeMultipart multiPart, int i)
    throws Exception {
    MimeBodyPart currentBodyPart = multiPart.getBodyPart(i);
    AttachmentPartImpl attachmentPart = new AttachmentPartImpl();

    DataHandler attachmentHandler = currentBodyPart.getDataHandler();
    attachmentPart.setDataHandler(attachmentHandler);

    AttachmentPartImpl.copyMimeHeaders(currentBodyPart, attachmentPart);
    addAttachmentPart(attachmentPart);
}
 
Example 44
Project: OpenJSharp   File: MimeBodyPart.java   Source Code and License 5 votes vote down vote up
/**
 * This method provides the mechanism to set this body part's content.
 * The given DataHandler object should wrap the actual content.
 *
 * @param   dh      The DataHandler for the content
 * @exception       IllegalStateException if this body part is
 *                  obtained from a READ_ONLY folder.
 */
public void setDataHandler(DataHandler dh) {
    if (mimePart != null) {
        mimePart = null;
    }
    this.dh = dh;
    this.content = null;
    this.contentStream = null;
    removeHeader("Content-Type");
    removeHeader("Content-Transfer-Encoding");
}
 
Example 45
Project: openjdk-jdk10   File: MessageFiller.java   Source Code and License 5 votes vote down vote up
public void fillIn(Object[] methodArgs, Object returnValue, Message msg) {
    String contentId = getContentId();
    Object obj = (methodPos == -1) ? returnValue : getter.get(methodArgs[methodPos]);
    DataHandler dh = (obj instanceof DataHandler) ? (DataHandler)obj : new DataHandler(obj,mimeType);
    Attachment att = new DataHandlerAttachment(contentId, dh);
    msg.getAttachments().add(att);
}
 
Example 46
Project: jwala   File: ResourceServiceRestImplTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCreateTemplateHasIncorrectNumberOfAttachments() throws IOException {
    List<Attachment> attachmentList = new ArrayList<>();
    Attachment json = mock(Attachment.class);
    attachmentList.add(json);
    DataHandler jsonDataHandler = mock(DataHandler.class);
    when(json.getDataHandler()).thenReturn(jsonDataHandler);
    when(jsonDataHandler.getName()).thenReturn("test-target.json");

    when(impl.createTemplate(any(InputStream.class), any(InputStream.class), anyString(), any(User.class))).thenReturn(new CreateResourceResponseWrapper(new ConfigTemplate()));
    Response response = cut.createTemplate(attachmentList, "test-target-name", authenticatedUser);

    assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
}
 
Example 47
Project: CustomAndroidOneSheeld   File: EmailShield.java   Source Code and License 5 votes vote down vote up
public static MimeMessage createEmailWithAttachment(String to, String from, String subject,
                                      String bodyText,String filePath) throws MessagingException{
    File file = new File(filePath);
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage email = new MimeMessage(session);
    Multipart multipart = new MimeMultipart();
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);
    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);
    if (file.exists()) {
        source = new FileDataSource(filePath);
        messageFilePart = new MimeBodyPart();
        messageBodyPart = new MimeBodyPart();
        try {
            messageBodyPart.setText(bodyText);
            messageFilePart.setDataHandler(new DataHandler(source));
            messageFilePart.setFileName(file.getName());

            multipart.addBodyPart(messageBodyPart);
            multipart.addBodyPart(messageFilePart);
            email.setContent(multipart);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }else
        email.setText(bodyText);
    return email;
}
 
Example 48
Project: Fetax-AI   File: EmailHelper.java   Source Code and License 5 votes vote down vote up
public static void sendTextEmail(String recvEmail) {
	try { 
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", "smtp.qq.com");
		props.setProperty("mail.smtp.auth", "true");
		props.put("mail.smtp.ssl.enable", "true");
		props.put("mail.smtp.socketFactory.port",  "994");
		Session session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("463112653", "manllfvunnfwbjhh");
			}
		});
		session.setDebug(true);
		Message msg = new MimeMessage(session);
		msg.setSubject("Hello Vme");
		//整个邮件的MultiPart(不能直接加入内容,需要在bodyPart中加入)
		Multipart emailPart = new MimeMultipart();
		MimeBodyPart attr1 = new MimeBodyPart();
		attr1.setDataHandler(new DataHandler(new FileDataSource("E:/workspaces/Archon/src/main/webapp/uploadfile/head_img/2601169057.png")));
		attr1.setFileName("tip.pic");
		
		MimeBodyPart attr2 = new MimeBodyPart();
		attr2.setDataHandler(new DataHandler(new FileDataSource("E:/workspaces/Archon/src/main/webapp/uploadfile/head_img/1724836491.png")));
		attr2.setFileName(MimeUtility.encodeText("哦图像"));
		
		MimeBodyPart content = new MimeBodyPart();
		MimeMultipart contentPart = new MimeMultipart();
		
		MimeBodyPart imgPart = new MimeBodyPart();
		imgPart.setDataHandler(new DataHandler(new FileDataSource("E:/workspaces/Archon/src/main/webapp/uploadfile/head_img/1724836491.png")));
		imgPart.setContentID("pic");
		
		MimeBodyPart htmlPart = new MimeBodyPart();
		htmlPart.setContent("<h1><a href='www.baidu.com'>百度一下</a><img src='cid:pic'/></h1>", "text/html;charset=utf-8");
		
		contentPart.addBodyPart(imgPart);
		contentPart.addBodyPart(htmlPart);
		content.setContent(contentPart);
		
		emailPart.addBodyPart(attr1);
		emailPart.addBodyPart(attr2);
		emailPart.addBodyPart(content);
		msg.setContent(emailPart);
		
		msg.setFrom(new InternetAddress("[email protected]"));
		msg.setRecipients(RecipientType.TO, InternetAddress.parse("[email protected],[email protected]"));
		msg.setRecipients(RecipientType.CC, InternetAddress.parse("[email protected],[email protected]"));
		Transport.send(msg);
	} catch (Exception e) {
		e.printStackTrace();
	} 
}
 
Example 49
Project: desktop-gmail-client   File: GmailOperations.java   Source Code and License 4 votes vote down vote up
public static Message createMessage(String to, String from, String sub, String bodyText, boolean isHtml, List<File> attachments) throws MessagingException, IOException {
    if (to == null || from == null) {
        System.out.println("Fields cannot be empty");
        return null;
    }
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    if (!from.equals(""))
        email.setFrom(new InternetAddress(from));
    if (!to.equals(""))
        email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    //if (!sub.equals(""))
        email.setSubject(sub);

    if (attachments == null || attachments.isEmpty()) {
        if (isHtml)
            email.setContent(bodyText, "text/html");
        else
            email.setText(bodyText);
    } else {
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        if (isHtml)
            mimeBodyPart.setContent(bodyText, "text/plain");
        else
            mimeBodyPart.setContent(bodyText, "text/plain");

        for (File attachmentFile : attachments) {
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(mimeBodyPart);

            mimeBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachmentFile);

            mimeBodyPart.setDataHandler(new DataHandler(source));
            mimeBodyPart.setFileName(attachmentFile.getName());

            multipart.addBodyPart(mimeBodyPart);
            email.setContent(multipart);
        }
    }
    Message message = createFromMimeMessage(email);
    return message;
}
 
Example 50
Project: openjdk-jdk10   File: Base64Data.java   Source Code and License 4 votes vote down vote up
/**
 * Fills in the data object by a {@link DataHandler}.
 *
 * @param data DataHandler for the data
 */
public void set(DataHandler data) {
    assert data!=null;
    this.dataHandler = data;
    this.data = null;
}
 
Example 51
Project: openjdk-jdk10   File: ByteArrayAttachment.java   Source Code and License 4 votes vote down vote up
public DataHandler asDataHandler() {
    return new DataSourceStreamingDataHandler(new ByteArrayDataSource(data,start,len,getContentType()));
}
 
Example 52
Project: openjdk-jdk10   File: AttachmentMarshallerImpl.java   Source Code and License 4 votes vote down vote up
@Override
public String addMtomAttachment(DataHandler data, String elementNamespace, String elementLocalName) {
    // We don't use JAXB for handling XOP
    throw new IllegalStateException();
}
 
Example 53
Project: openjdk-jdk10   File: RuntimeBuiltinLeafInfoImpl.java   Source Code and License 4 votes vote down vote up
public Base64Data print(DataHandler v) {
    Base64Data bd = new Base64Data();
    bd.set(v);
    return bd;
}
 
Example 54
Project: alfresco-greenmail   File: GreenMailUtil.java   Source Code and License 4 votes vote down vote up
public static void sendAttachmentEmail(String to, String from, String subject, String msg, final byte[] attachment, final String contentType, final String filename, final String description, final ServerSetup setup) throws MessagingException, IOException {
    Session session = getSession(setup);

    Address[] tos = new InternetAddress[]{new InternetAddress(to)};
    Address[] froms = new InternetAddress[]{new InternetAddress(from)};
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setSubject(subject);
    mimeMessage.setFrom(froms[0]);

    MimeMultipart multiPart = new MimeMultipart();

    MimeBodyPart textPart = new MimeBodyPart();
    multiPart.addBodyPart(textPart);
    textPart.setText(msg);

    MimeBodyPart binaryPart = new MimeBodyPart();
    multiPart.addBodyPart(binaryPart);

    DataSource ds = new DataSource() {
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(attachment);
        }

        public OutputStream getOutputStream() throws IOException {
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            byteStream.write(attachment);
            return byteStream;
        }

        public String getContentType() {
            return contentType;
        }

        public String getName() {
            return filename;
        }
    };
    binaryPart.setDataHandler(new DataHandler(ds));
    binaryPart.setFileName(filename);
    binaryPart.setDescription(description);

    mimeMessage.setContent(multiPart);
    Transport.send(mimeMessage, tos);
}
 
Example 55
Project: opencps-v2   File: PaymentFileManagementImpl.java   Source Code and License 4 votes vote down vote up
/**
 * Update Payment File Approval of DossierId and referenceUid
 * 
 * @param form
 *            params
 * @return Response
 */
@Override
public Response updatePaymentFileApproval(HttpServletRequest request, HttpHeaders header, Company company,
		Locale locale, User user, ServiceContext serviceContext, String id, String referenceUid, Attachment file,
		String approveDatetime, String accountUserName, String govAgencyTaxNo, String invoiceTemplateNo,
		String invoiceIssueNo, String invoiceNo) {
	BackendAuth auth = new BackendAuthImpl();
	long groupId = GetterUtil.getLong(header.getHeaderString("groupId"));

	long dossierId = GetterUtil.getLong(id);

	// TODO get Dossier by referenceUid if dossierId = 0
	// String referenceUid = dossierId == 0 ? id : StringPool.BLANK;

	try {

		if (!auth.isAuth(serviceContext)) {
			throw new UnauthenticationException();
		}

		DataHandler dataHandler = null;

		if (file != null) {
			dataHandler = file.getDataHandler();
		}

		PaymentFileActions action = new PaymentFileActionsImpl();

		PaymentFile paymentFile = action.updateFileApproval(groupId, dossierId, referenceUid, approveDatetime,
				accountUserName, govAgencyTaxNo, invoiceTemplateNo, invoiceIssueNo, invoiceNo,
				dataHandler != null ? dataHandler.getName() : StringPool.BLANK, 0L,
				dataHandler != null ? dataHandler.getInputStream() : null, serviceContext);

		PaymentFileModel result = PaymentFileUtils.mappingToPaymentFileModel(paymentFile);

		return Response.status(200).entity(result).build();

	} catch (Exception e) {
		return processException(e);
	}
}
 
Example 56
Project: opencps-v2   File: DossierFileManagementImpl.java   Source Code and License 4 votes vote down vote up
@Override
public Response addDossierFileByDossierId(HttpServletRequest request, HttpHeaders header, Company company,
		Locale locale, User user, ServiceContext serviceContext, Attachment file, String id, String referenceUid,
		String dossierTemplateNo, String dossierPartNo, String fileTemplateNo, String displayName, String fileType,
		String isSync, String formData) {

	BackendAuth auth = new BackendAuthImpl();

	long groupId = GetterUtil.getLong(header.getHeaderString("groupId"));

	try {

		if (!auth.isAuth(serviceContext)) {
			throw new UnauthenticationException();
		}

		long dossierId = GetterUtil.getLong(id);

		Dossier dossier = null;

		if (dossierId != 0) {
			dossier = DossierLocalServiceUtil.fetchDossier(dossierId);
			if (Validator.isNull(dossier)) {
				dossier = DossierLocalServiceUtil.getByRef(groupId, id);
			}
		} else {
			dossier = DossierLocalServiceUtil.getByRef(groupId, id);
		}

		if (Validator.isNull(referenceUid)) {
			referenceUid = UUID.randomUUID().toString();
		}

		DataHandler dataHandler = file.getDataHandler();

		DossierFileActions action = new DossierFileActionsImpl();

		DossierFile dossierFile = action.addDossierFile(groupId, dossier.getDossierId(), referenceUid,
				dossierTemplateNo, dossierPartNo, fileTemplateNo, displayName, dataHandler.getName(), 0,
				dataHandler.getInputStream(), fileType, isSync, serviceContext);
		
		if(Validator.isNotNull(formData)) {
			dossierFile.setFormData(formData);
		}
		
		DossierFileLocalServiceUtil.updateDossierFile(dossierFile);

		DossierFileModel result = DossierFileUtils.mappingToDossierFileModel(dossierFile);

		return Response.status(200).entity(result).build();

	} catch (Exception e) {
		return processException(e);
	}
}
 
Example 57
Project: AndiCar   File: SendGMailTask.java   Source Code and License 4 votes vote down vote up
/**
     * Fetch a list of Gmail labels attached to the specified account.
     *
     * @return List of Strings labels.
     */
    private List<String> sendGMail() throws Exception {
        List<String> retVal = new ArrayList<>();
        if (debugLogFileWriter != null) {
            debugLogFileWriter.appendnl("sendGMail begin");
            debugLogFileWriter.flush();
        }

        //create the message
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage mimeMessage = new MimeMessage(session);

        mimeMessage.setFrom(new InternetAddress("me"));
        mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO,
                new InternetAddress(mEmailTo));
        mimeMessage.setSubject(mSubject);

        MimeBodyPart mimeBodyText = new MimeBodyPart();
        mimeBodyText.setContent(mMessage, "text/html");
        mimeBodyText.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mimeBodyText);

        if (mAttachments != null && mAttachments.size() > 0) {
            for (String attachment : mAttachments) {
                File attach = new File(attachment);
                if (!attach.exists()) {
                    throw new IOException("File not found");
                }

                MimeBodyPart mimeBodyAttachments = new MimeBodyPart();
                String fileName = attach.getName();
                FileInputStream is = new FileInputStream(attach);
                DataSource source = new ByteArrayDataSource(is, "application/zip");
                mimeBodyAttachments.setDataHandler(new DataHandler(source));
                mimeBodyAttachments.setFileName(fileName);
                mimeBodyAttachments.setHeader("Content-Type", "application/zip" + "; name=\"" + fileName + "\"");
                mimeBodyAttachments.setDisposition(MimeBodyPart.ATTACHMENT);
                mp.addBodyPart(mimeBodyAttachments);
            }
//            mimeBodyAttachments.setHeader("Content-Transfer-Encoding", "base64");
        }

        mimeMessage.setContent(mp);

//        mimeMessage.setText(mMessage);
        //encode in base64url string
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        mimeMessage.writeTo(bytes);
        String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());

        //create the message
        Message message = new Message();
        message.setRaw(encodedEmail);

        if (debugLogFileWriter != null) {
            debugLogFileWriter.appendnl("sending message using com.google.api.services.gmail.Gmail begin");
            debugLogFileWriter.flush();
        }

        //send the message ("me" => the current selected google account)
        Message result = mGmailService.users().messages().send("me", message).execute();

        if (debugLogFileWriter != null) {
            debugLogFileWriter.appendnl("sending message using com.google.api.services.gmail.Gmail ended with result:\n")
                    .append(result.toPrettyString());
            debugLogFileWriter.flush();
        }

        retVal.add(AndiCar.getAppResources().getString(R.string.gen_mail_sent));
        return retVal;
    }
 
Example 58
Project: mumu   File: SimpleEmailSender.java   Source Code and License 4 votes vote down vote up
/**
   * 发送邮件
   * @param email
   * @throws UnsupportedEncodingException
   * @throws MessagingException
   */
  public void send(SimpleEmail email) throws UnsupportedEncodingException, MessagingException{
 	 	// 创建mime类型邮件
      final MimeMessage message = new MimeMessage(session);
      // 设置发信人
      message.setFrom(new InternetAddress(authenticator.getUsername()));
      
      //设置收件人
      String[] recipients = email.getRecipients();
      if(recipients==null||recipients.length==0){
      	throw new IllegalArgumentException();
      }
      InternetAddress[] recipientsAddresses = new InternetAddress[recipients.length];
      for (int i = 0; i < recipients.length; i++) {
      	recipientsAddresses[i] = new InternetAddress(recipients[i]);
}
      message.setRecipients(Message.RecipientType.TO, recipientsAddresses);
      
      //设置抄件人
      String[] copyTos = email.getCopyTos();
      if(copyTos!=null&&copyTos.length>0){
      	InternetAddress[] copyTosAddresses = new InternetAddress[copyTos.length];
          for (int i = 0; i < copyTos.length; i++) {
          	copyTosAddresses[i] = new InternetAddress(copyTos[i]);
  		}
          message.setRecipients(Message.RecipientType.CC, copyTosAddresses);
      }
      
  	//设置附件
  	File[] multiparts = email.getMultiparts();
  	if(multiparts!=null&&multiparts.length>0){
  		MimeMultipart mp = new MimeMultipart();
      	for (File file : multiparts) {
      		BodyPart bp = new MimeBodyPart();
      		FileDataSource fileds = new FileDataSource(file);
      		bp.setDataHandler(new DataHandler(fileds));
      		bp.setFileName(MimeUtility.encodeText(fileds.getName()));
      		mp.addBodyPart(bp);
  		}
      	//添加附件
          message.setContent(mp);
  	}
      
      // 设置主题
      message.setSubject(email.getSubject());
      //设置邮件发送日期
      message.setSentDate(new Date());
      // 设置邮件内容
      message.setContent(email.getContent(), "text/html;charset=utf-8");
      // 发送
      Transport.send(message);
  }
 
Example 59
Project: geomapapp   File: Digitizer.java   Source Code and License 4 votes vote down vote up
@Override
protected Transferable createTransferable(JComponent c) {
   assert (c == table);
   table.addColumnSelectionInterval(0, table.getColumnCount()-1);
   return new DataHandler(new Integer(table.getSelectedRow()), localObjectFlavor.getMimeType());
}
 
Example 60
Project: unitimes   File: Email.java   Source Code and License 4 votes vote down vote up
public void addAttachment(File file, String name) throws Exception {
	addAttachment(name == null ? file.getName() : name, new DataHandler(new FileDataSource(file)));
}