Ejemplo n.º 1
0
  // FIXME: Should also use events!
  public void deleteAttachment(Attachment att) throws ProviderException {
    if (m_provider == null) return;

    m_provider.deleteAttachment(att);

    m_engine.getSearchManager().pageRemoved(att);

    m_engine.getReferenceManager().clearPageEntries(att.getName());
  }
Ejemplo n.º 2
0
 @JsonIgnore
 public ManyMap<String, Attachment> getAttachmentMap() {
   ManyMap<String, Attachment> map = new ManyMap<String, Attachment>();
   if (attachments != null && !attachments.isEmpty()) {
     for (Attachment attachment : attachments) {
       map.putOne(attachment.getName(), attachment);
     }
   }
   return map;
 }
Ejemplo n.º 3
0
 /** New attachment insertion */
 public Attachment updateAttachment(long noteId, Attachment attachment, SQLiteDatabase db) {
   ContentValues valuesAttachments = new ContentValues();
   valuesAttachments.put(
       KEY_ATTACHMENT_ID,
       attachment.getId() != null ? attachment.getId() : Calendar.getInstance().getTimeInMillis());
   valuesAttachments.put(KEY_ATTACHMENT_NOTE_ID, noteId);
   valuesAttachments.put(KEY_ATTACHMENT_URI, attachment.getUri().toString());
   valuesAttachments.put(KEY_ATTACHMENT_MIME_TYPE, attachment.getMime_type());
   valuesAttachments.put(KEY_ATTACHMENT_NAME, attachment.getName());
   valuesAttachments.put(KEY_ATTACHMENT_SIZE, attachment.getSize());
   valuesAttachments.put(KEY_ATTACHMENT_LENGTH, attachment.getLength());
   db.insertWithOnConflict(
       TABLE_ATTACHMENTS, KEY_ATTACHMENT_ID, valuesAttachments, SQLiteDatabase.CONFLICT_REPLACE);
   return attachment;
 }
Ejemplo n.º 4
0
 @Override
 public void nullSafeSet(
     PreparedStatement preparedStatement,
     Object value,
     int index,
     SessionImplementor sessionImplementor)
     throws HibernateException, SQLException {
   if (value != null) {
     Attachment attachment = (Attachment) value;
     preparedStatement.setString(index, attachment.getContentType());
     preparedStatement.setString(index + 1, attachment.getName());
     preparedStatement.setBytes(index + 2, attachment.getContent());
   } else {
     preparedStatement.setObject(index, null);
     preparedStatement.setObject(index + 1, null);
     preparedStatement.setObject(index + 2, null);
   }
 }
  /**
   * Save mail as a document
   *
   * @throws DocumentManagementServiceException
   * @throws IOException
   */
  private void saveEmailDocument() throws DocumentManagementServiceException, IOException {
    Folder processAttachmentsFolder =
        RepositoryUtility.getProcessAttachmentsFolder(processInstance);
    StringBuilder attachmentInfo = new StringBuilder("");
    JCRVersionTracker vt = null;

    if (!CollectionUtils.isEmpty(attachments)) {
      for (Attachment attachment : attachments) {
        attachmentInfo.append(attachment.getName());
        if (attachment.isContainsDocument()) {
          vt = new JCRVersionTracker(attachment.getDocument());
          attachmentInfo.append("(").append(vt.getCurrentVersionNo()).append(")");
        } else {
          createDocumentFromAttachment(attachment, processAttachmentsFolder);
        }
        attachmentInfo.append(";");
      }
    }
    createDocumentForMail(processAttachmentsFolder, attachmentInfo.toString());
  }
Ejemplo n.º 6
0
  /**
   * Stores an attachment directly from a stream. If the attachment did not exist previously, this
   * method will create it. If it did exist, it stores a new version.
   *
   * @param att Attachment to store this under.
   * @param in InputStream from which the attachment contents will be read.
   * @throws IOException If writing the attachment failed.
   * @throws ProviderException If something else went wrong.
   */
  public void storeAttachment(Attachment att, InputStream in)
      throws IOException, ProviderException {
    if (m_provider == null) {
      return;
    }

    //
    //  Checks if the actual, real page exists without any modifications
    //  or aliases.  We cannot store an attachment to a non-existant page.
    //
    if (!m_engine.getPageManager().pageExists(att.getParentName())) {
      // the caller should catch the exception and use the exception text as an i18n key
      throw new ProviderException("attach.parent.not.exist");
    }

    m_provider.putAttachmentData(att, in);

    m_engine.getReferenceManager().updateReferences(att.getName(), new java.util.Vector());

    WikiPage parent = new WikiPage(m_engine, att.getParentName());
    m_engine.updateReferences(parent);

    m_engine.getSearchManager().reindexPage(att);
  }
  public void testAddRemoveAttachment() throws Exception {
    Map vars = new HashMap();
    vars.put("users", users);
    vars.put("groups", groups);
    vars.put("now", new Date());

    String str =
        "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { createdOn = now, activationTime = now}), ";
    str += "deadlines = new Deadlines(),";
    str += "delegation = new Delegation(),";
    str += "peopleAssignments = new PeopleAssignments(),";
    str += "names = [ new I18NText( 'en-UK', 'This is my task name')] })";

    Task task = (Task) eval(new StringReader(str), vars);
    client.addTask(task, null);

    long taskId = task.getId();

    Attachment attachment = new Attachment();
    Date attachedAt = new Date(System.currentTimeMillis());
    attachment.setAttachedAt(attachedAt);
    attachment.setAttachedBy(users.get("luke"));
    attachment.setName("file1.txt");
    attachment.setAccessType(AccessType.Inline);
    attachment.setContentType("txt");

    byte[] bytes = "Ths is my attachment text1".getBytes();
    Content content = new Content();
    content.setContent(bytes);

    client.addAttachment(taskId, attachment, content);

    Task task1 = client.getTask(taskId);
    // For local clients this will be the same.. that's why is commented
    // assertNotSame(task, task1);
    // assertFalse(task.equals(task1));

    List<Attachment> attachments1 = task1.getTaskData().getAttachments();
    assertEquals(1, attachments1.size());
    Attachment returnedAttachment = attachments1.get(0);
    assertEquals(attachedAt, returnedAttachment.getAttachedAt());
    assertEquals(users.get("luke"), returnedAttachment.getAttachedBy());
    assertEquals(AccessType.Inline, returnedAttachment.getAccessType());
    assertEquals("txt", returnedAttachment.getContentType());
    assertEquals("file1.txt", returnedAttachment.getName());
    assertEquals(bytes.length, returnedAttachment.getSize());

    assertEquals((long) attachment.getId(), (long) returnedAttachment.getId());
    assertEquals((long) content.getId(), (long) returnedAttachment.getAttachmentContentId());

    // Make the same as the returned tasks, so we can test equals
    task.getTaskData().setAttachments(attachments1);
    task.getTaskData().setStatus(Status.Created);
    assertEquals(task, task1);

    content = client.getContent(returnedAttachment.getAttachmentContentId());
    assertEquals("Ths is my attachment text1", new String(content.getContent()));

    // test we can have multiple attachments

    attachment = new Attachment();
    attachedAt = new Date(System.currentTimeMillis());
    attachment.setAttachedAt(attachedAt);
    attachment.setAttachedBy(users.get("tony"));
    attachment.setName("file2.txt");
    attachment.setAccessType(AccessType.Inline);
    attachment.setContentType("txt");

    bytes = "Ths is my attachment text2".getBytes();
    content = new Content();
    content.setContent(bytes);

    client.addAttachment(taskId, attachment, content);

    task1 = client.getTask(taskId);
    // In local clients this will be the same object and we are reusing the tests
    // assertNotSame(task, task1);
    // assertFalse(task.equals(task1));

    List<Attachment> attachments2 = task1.getTaskData().getAttachments();
    assertEquals(2, attachments2.size());

    content = client.getContent(content.getId());
    assertEquals("Ths is my attachment text2", new String(content.getContent()));

    // make two collections the same and compare
    attachment.setSize(26);
    attachment.setAttachmentContentId(content.getId());
    attachments1.add(attachment);
    assertTrue(CollectionUtils.equals(attachments2, attachments1));

    client.deleteAttachment(taskId, attachment.getId(), content.getId());

    task1 = client.getTask(taskId);
    attachments2 = task1.getTaskData().getAttachments();
    assertEquals(1, attachments2.size());

    assertEquals("file1.txt", attachments2.get(0).getName());
  }
Ejemplo n.º 8
0
  /**
   * Send <strong><em>one</em></strong> mail to multiple recipients and multiple BCC recipients
   * <em>(in one mail)</em>.
   *
   * @param transport transport connection, if null transport is create inside the method
   * @param sender the "From" field
   * @param recipients the "To" field with multiple addresses.
   * @param bccRecipients the "Bcc" field with multiple addresses.
   * @param subject the Subject of the message
   * @param content the Content of the message
   * @param isHTML flag indicating wether the Content is html (<code>true</code>) or text (<code>
   *     false</code>)
   * @throws MessagingException Forwarded exception from javax.mail
   * @throws IllegalArgumentException if no recipient provided or no sender
   */
  public void sendMail(
      Transport transport,
      InternetAddress sender,
      List<InternetAddress> recipients,
      List<InternetAddress> ccRecipients,
      List<InternetAddress> bccRecipients,
      String subject,
      String content,
      String txtContent,
      boolean isHTML,
      Collection<Attachment> attachments)
      throws MessagingException {

    String recipientsStr = new LinkedList<InternetAddress>(recipients).toString();

    if (sender == null || recipients == null || recipients.size() == 0) {
      throw new IllegalArgumentException(
          "Sender null (sender: " + sender + ") or no recipient: " + recipients);
    }

    if (props != null) {
      logger.info(
          "Sending mail with subject: "
              + subject
              + " to: "
              + recipients.size()
              + " recipients: "
              + recipientsStr
              + "\n"
              + "Using smtp: "
              + props.getProperty(SMTP_HOST_PARAM, DEFAULT_SMTP_HOST)
              + " / "
              + props.getProperty(SMTP_USER_PARAM)
              + " / "
              + props.getProperty(SMTP_PASSWORD_PARAM));
    }

    Date sendDate = new Date();

    if (!DEBUG) {
      Session mailSession = Session.getDefaultInstance(props);

      MimeMessage msg = new MimeMessage(mailSession);
      msg.setSentDate(sendDate);
      msg.setFrom(sender);
      msg.setRecipients(
          Message.RecipientType.TO, recipients.toArray(new InternetAddress[recipients.size()]));
      if (ccRecipients != null && ccRecipients.size() > 0) {
        msg.setRecipients(
            Message.RecipientType.CC,
            ccRecipients.toArray(new InternetAddress[ccRecipients.size()]));
      }
      if (bccRecipients != null && bccRecipients.size() > 0) {
        msg.setRecipients(
            Message.RecipientType.BCC,
            bccRecipients.toArray(new InternetAddress[bccRecipients.size()]));
      }
      msg.setSubject(subject, ContentContext.CHARACTER_ENCODING);

      if (isHTML) {
        MimeBodyPart wrap = new MimeBodyPart();
        MimeMultipart cover = new MimeMultipart("alternative");

        MimeBodyPart bp = new MimeBodyPart();
        if (txtContent == null) {
          txtContent = StringHelper.html2txt(content);
        }
        bp.setText(txtContent, ContentContext.CHARACTER_ENCODING);
        cover.addBodyPart(bp);
        bp = new MimeBodyPart();
        bp.setText(content, ContentContext.CHARACTER_ENCODING, "html");
        cover.addBodyPart(bp);
        wrap.setContent(cover);

        MimeMultipart contentMail = new MimeMultipart("related");

        if (attachments != null) {
          for (Attachment attach : attachments) {
            String id = UUID.randomUUID().toString();
            /*
             * sb.append("<img src=\"cid:"); sb.append(id);
             * sb.append("\" alt=\"ATTACHMENT\"/>\n");
             */

            MimeBodyPart attachment = new MimeBodyPart();

            DataSource fds =
                new ByteArrayDataSource(
                    attach.getData(),
                    ResourceHelper.getFileExtensionToMineType(
                        StringHelper.getFileExtension(attach.getName())));
            attachment.setDataHandler(new DataHandler(fds));
            attachment.setHeader("Content-ID", "<" + id + ">");
            attachment.setFileName(attach.getName());

            contentMail.addBodyPart(attachment);
          }
        }

        contentMail.addBodyPart(wrap);
        msg.setContent(contentMail);
        msg.setSentDate(new Date());

      } else {
        assert attachments == null : "no attachements in text format.";
        msg.setText(content);
      }

      /*
       * if (isHTML) { msg.addHeader("Content-Type",
       * "text/html; charset=\"" + ContentContext.CHARACTER_ENCODING +
       * "\""); }
       */

      msg.saveChanges();

      if (transport == null || !transport.isConnected()) {
        transport = getMailTransport(staticConfig);
        try {
          transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
          transport.close();
        }
      } else {
        transport.sendMessage(msg, msg.getAllRecipients());
      }

    } else {
      FileOutputStream out = null;
      try {
        PrintStream w = System.out;
        if (tempDir != null && new File(tempDir).exists()) {
          File mailFile =
              new File(
                  tempDir,
                  "mail-debug/mail-"
                      + StringHelper.renderFileTime(sendDate)
                      + "-"
                      + StringHelper.stringToFileName(subject)
                      + ".txt");
          mailFile.getParentFile().mkdirs();
          out = new FileOutputStream(mailFile, true);
          w = new PrintStream(mailFile, ContentContext.CHARACTER_ENCODING);
        } else {
          w.println("");
        }

        w.println("FROM:");
        w.println(sender.toString());
        w.print("TO: #");
        w.println(Integer.toString(recipients.size()));
        for (InternetAddress recipient : recipients) {
          w.println(recipient.toString());
        }
        if (ccRecipients != null) {
          w.print("CC: #");
          w.println(Integer.toString(ccRecipients.size()));
          for (InternetAddress ccRecipient : ccRecipients) {
            w.println(ccRecipient.toString());
          }
        }
        if (bccRecipients != null) {
          w.print("BCC: #");
          w.println(Integer.toString(bccRecipients.size()));
          for (InternetAddress bccRecipient : bccRecipients) {
            w.println(bccRecipient.toString());
          }
        }
        w.println("SUBJECT:");
        w.println(subject);
        w.print("IS HTML: ");
        w.println(isHTML);
        w.println("CONTENT:");
        w.print("--BEGIN--");
        w.print(content);
        w.println("--END--");
        w.println("");
        w.flush();
      } catch (IOException e) {
        throw new RuntimeException("Exception when writing debug mail file.", e);
      } finally {
        ResourceHelper.safeClose(out);
      }
    }
    logger.info("Mail sent to: " + recipientsStr);
  }