Java 类javax.activation.DataHandler 实例源码

项目:ats-framework    文件:MimePackage.java   
/**
 * 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);
    }
}
项目:parabuild-ci    文件:EchoAttachmentsService.java   
/**
 * 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;
}
项目:unitimes    文件:JavaMailWrapper.java   
@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);
}
项目:parabuild-ci    文件:EchoAttachmentsService.java   
/**
 * 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;
}
项目:OpenJSharp    文件:ServerSOAPHandlerTube.java   
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;

        }
    }
项目:OpenJSharp    文件:ServerLogicalHandlerTube.java   
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;
    }
}
项目:jwala    文件:ResourceServiceRestImplTest.java   
@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());
}
项目:dswork    文件:EmailUtil.java   
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 "";
}
项目:OpenJSharp    文件:ResponseContext.java   
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;
}
项目:openjdk-jdk10    文件:SaajStaxWriterEx.java   
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;
}
项目:OpenJSharp    文件:MtomCodec.java   
@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
    }
}
项目:openjdk-jdk10    文件:ResponseBuilder.java   
/**
 * 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);
    }
}
项目:parabuild-ci    文件:Tester.java   
/**
 * 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) {
    }
}
项目:kettle_support_kettle8.0    文件:Message.java   
/**
 * 增加发送附件
 * 
 * @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;
}
项目:marshalsec    文件:JDKUtil.java   
@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);
}
项目:iBase4J-Common    文件:EmailSender.java   
/**
 * 设置附件
 * 
 * @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;
    }
}
项目:automat    文件:EmailSender.java   
/**
 * 设置附件
 * 
 * @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;
    }
}
项目:spr    文件:SendMail.java   
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);       

}
项目:logistimo-web-service    文件:EmailService.java   
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);
}
项目:openjdk-jdk10    文件:ClientSOAPHandlerTube.java   
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;
    }
项目:lams    文件:MimeMessageHelper.java   
/**
 * 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);
    }
}
项目:iBase4J    文件:EmailSender.java   
/**
 * 设置附件
 * 
 * @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;
    }
}
项目:Log4Reports    文件:EmailUtil.java   
/**
  * @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;
  }
项目:Log4Reports    文件:EmailUtil.java   
/**
  * @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;
  }
项目:jwala    文件:ResourceServiceRestImplTest.java   
@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());
}
项目:openjdk-jdk10    文件:MtomCodec.java   
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;
}
项目:OpenJSharp    文件:AttachmentMarshallerImpl.java   
@Override
public String addSwaRefAttachment(DataHandler data) {
    String cid = encodeCid(null);
    Attachment att = new DataHandlerAttachment(cid, data);
    attachments.add(att);
    cid = "cid:" + cid;
    return cid;
}
项目:openjdk-jdk10    文件:MessageFiller.java   
/**
 * 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);
    }
}
项目:OpenJSharp    文件:SAAJMessage.java   
/**
 * Gets the attachment as a {@link javax.activation.DataHandler}.
 */
public DataHandler asDataHandler() {
    try {
        return ap.getDataHandler();
    } catch (SOAPException e) {
        throw new WebServiceException(e);
    }
}
项目:parabuild-ci    文件:TestRef.java   
/**
 *  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;
}
项目:OpenJSharp    文件:ClientMessageHandlerTube.java   
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;
}
项目:openjdk-jdk10    文件:RuntimeBuiltinLeafInfoImpl.java   
public DataHandler parse(CharSequence text) {
    if(text instanceof Base64Data)
        return ((Base64Data)text).getDataHandler();
    else
        return new DataHandler(new ByteArrayDataSource(decodeBase64(text),
            UnmarshallingContext.getInstance().getXMIMEContentType()));
}
项目:OpenJSharp    文件:ClientSOAPHandlerTube.java   
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;
    }
项目:openjdk-jdk10    文件:MessageImpl.java   
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);
}
项目:OpenJSharp    文件:MessageFiller.java   
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);
}
项目:SkyEye    文件:MailService.java   
/**
 * 添加附件
 * @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);
    }
}
项目:OpenJSharp    文件:MtomCodec.java   
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;
}
项目:OpenJSharp    文件:MtomCodec.java   
@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);
}
项目:OpenJSharp    文件:MtomCodec.java   
@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;
}
项目:OpenJSharp    文件:MimeMultipartParser.java   
@Override
public DataHandler asDataHandler() {
    if (streamingDataHandler == null) {
        streamingDataHandler = (buf != null)
            ? new DataSourceStreamingDataHandler(new ByteArrayDataSource(buf,getContentType()))
            : new MIMEPartStreamingDataHandler(part);
    }
    return streamingDataHandler;
}