Example #1
0
  public static final int writeStreamToFile(InputStream in, File file, long maxSize)
      throws IOException {
    int countByte = 0;

    if (file.getParentFile() != null && !file.getParentFile().exists()) {
      file.getParentFile().mkdirs();
    }

    if (!file.exists()) {
      file.createNewFile();
    }
    OutputStream out = null;
    try {
      out = new FileOutputStream(file);
      countByte = writeStreamToStream(in, out, maxSize);
      if (countByte < 0) {
        ResourceHelper.closeResource(out);
        file.delete();
        return -1;
      }
    } finally {
      ResourceHelper.closeResource(out);
    }

    return countByte;
  }
Example #2
0
  public static final File writeFileItemToFolder(
      FileItem fileItem, File folder, boolean overwrite, boolean rename) throws IOException {
    if (!folder.isDirectory()) {
      return null;
    }
    File file =
        new File(
            URLHelper.mergePath(
                folder.getAbsolutePath(),
                StringHelper.createFileName(StringHelper.getFileNameFromPath(fileItem.getName()))));

    if (!file.exists()) {
      file.createNewFile();
    } else {
      if (!overwrite && !rename) {
        throw new FileExistsException("File already exists.");
      }
      if (rename) {
        file = ResourceHelper.getFreeFileName(file);
      }
    }
    InputStream in = null;
    try {
      in = fileItem.getInputStream();
      writeStreamToFile(in, file);
      return file;
    } catch (IOException e) {
      ResourceHelper.closeResource(in);
      file.delete();
      throw e;
    } finally {
      ResourceHelper.closeResource(in);
    }
  }
Example #3
0
  /**
   * extract a relative path from a full path.
   *
   * @param application the servlet context.
   * @param fullPath a full path
   * @return retrun a relative path (sample: /var/data/static/test.png -> /static/test.png)
   */
  public static String extractNotStaticDir(
      StaticConfig staticConfig, GlobalContext globalContext, String fullPath) {
    String realPath = globalContext.getDataFolder();

    realPath = ResourceHelper.getLinuxPath(realPath);
    fullPath = ResourceHelper.getLinuxPath(fullPath);

    if (fullPath.startsWith(realPath)) {
      return fullPath.substring(realPath.length());
    }
    return fullPath;
  }
Example #4
0
 public static final int writeFileToStream(File fileIn, OutputStream out) throws IOException {
   InputStream in = null;
   try {
     in = new FileInputStream(fileIn);
     return writeStreamToStream(in, out);
   } finally {
     ResourceHelper.closeResource(in);
   }
 }
Example #5
0
 public static Properties loadProperties(File file) throws IOException {
   Properties properties = new Properties();
   InputStream in = new FileInputStream(file);
   try {
     properties.load(in);
   } finally {
     ResourceHelper.closeResource(in);
   }
   return properties;
 }
Example #6
0
  public static String downloadResourceAsString(URL workURL) throws IOException {
    InputStream in = workURL.openStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
      byte[] buffer = new byte[8192];
      int len, b = in.read();
      while (b >= 0) {
        out.write(b);
        len = in.read(buffer);
        out.write(buffer, 0, len);

        b = in.read();
      }
      return new String(out.toByteArray());
    } finally {
      ResourceHelper.closeResource(in);
      ResourceHelper.closeResource(out);
    }
  }
Example #7
0
  public static final String loadStringFromStream(InputStream in, Charset encoding)
      throws IOException {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(outStream);

    BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding));
    try {
      String line = reader.readLine();
      while (line != null) {
        out.println(line);
        line = reader.readLine();
      }
    } finally {
      ResourceHelper.closeResource(reader);
    }

    out.close();
    return new String(outStream.toByteArray());
  }
Example #8
0
 public static void downloadResource(
     String localDir, String baseURL, Collection<Resource> resources) throws IOException {
   for (Resource resource : resources) {
     URL url = new URL(URLHelper.mergePath(baseURL, resource.getUri()));
     File localFile = new File(URLHelper.mergePath(localDir, resource.getUri()));
     if (!localFile.exists()) {
       InputStream in = null;
       try {
         in = url.openStream();
         ResourceHelper.writeStreamToFile(in, localFile);
         logger.info("download resource : " + url + " in " + localFile);
       } finally {
         if (in != null) {
           in.close();
         }
       }
     } else {
       logger.warning("download url error : file already exists in local : " + localFile);
     }
   }
 }
Example #9
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);
  }