DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
  • submit to reddit
//Adding Attachments to a New Email Message

public static void main(String[] args)
{
    // Base folder for reading and writing files
    String strBaseFolder = "D:\\Data\\Aspose\\resources\\";

    //Initialize and Load an existing MSG file by specifying the MessageFormat
    MailMessage email = MailMessage.load(strBaseFolder + "anEmail.msg", MessageFormat.getMsg());

    //Initialize a String variable to get the Email Subject
    String subject = email.getSubject();
    //Append some more information to Subject
    subject = subject + " This text is added to the existing subject";
    //Set the Email Subject
    email.setSubject(subject);

    //Initialize a String variable to get the Email's HTML Body
    String body = email.getHtmlBody();
    //Apppend some more information to the Body variable
    body = body + "<br> This text is added to the existing body";
    //Set the Email Body
    email.setHtmlBody(body);

    //Initialize MailAddressCollection object
    MailAddressCollection contacts = new MailAddressCollection();

    //Retrieve Email's TO list
    contacts = email.getTo();
    //Check if TO list has some values
    if (contacts.size() > 0)
    {
        //Remove the first email address
        contacts.remove(0);
        //Add another email address to collection
        contacts.add("to1@domain.com");
    }
    //Set the collection as Email's TO list
    email.setTo(contacts);

    //Initialize MailAddressCollection
    contacts = new MailAddressCollection();

    //Retrieve Email's CC list
    contacts = email.getCC();
    //Add another email address to collection
    contacts.add("cc2@domain.com");
    //Set the collection as Email's CC list
    email.setCC(contacts);

    //Save the Email message to disk by specifying the MessageFormat
    email.save(strBaseFolder + "message.msg", MailMessageSaveType.getOutlookMessageFormat());
}

//Loading a Message with Load Options

//To load a message with specific load options, Aspose.Email provides the MessageLoadOptions class that can be used as follow:

MesageLoadOptions options = new MesageLoadOptions();
options.PrefferedTextEncoding = Encoding.getEncoding(1252);
options.setMessageFormat(MessageFormat.getMsg());
MailMessage eml = MailMessage.Load("EMAIL_497563\\test3.msg", options);

Michael Crump09/10/14
3141 views
0 replies

How to Run HTML files in your Browser from GitHub

If you have a .html file in a GitHub repository and want to view that page directly, you would typically download or clone the repo to your local hard drive and run it from there. There is an easier way.

Alec Noller09/10/14
10372 views
0 replies

Dev of the Week: Adam Diaz

Every week at DZone, we feature a new developer/blogger to catch up and find out what he or she is working on now and what's coming next. This week we're talking to Adam Diaz, Hadoop Architect at the Teradata Big Data Center of Excellence and featured author in DZone's upcoming 2014 Guide to Big Data.

Alec Noller09/10/14
12242 views
0 replies

The Best of DZone: September 3 - September 10

If you missed anything on DZone this week, now's your chance to catch up! This week's best include the reasons why Vaadin is a Passat, named parameters in Java, mobile gaming with Haskell and SDL, NoSQL job trends, and more.

Quinten De Swaef09/10/14
14503 views
0 replies

Event driven programming using Spring Boot and Reactor

This article will teach you how you can setup an environment to develop in an event-driven fashion using Spring Boot and the Reactor framework.

Rob Galanakis09/10/14
2939 views
2 replies

Can you quantify trust?

Bad managers, who are by definition less trusted, can easily rationalize away any attempt at quantification. One quantifiable measure would be employee turnover.

Andrew Fuqua09/09/14
8143 views
1 replies

Don't Estimate Stories In Sprint Planning

I don’t estimate stories in sprint planning. Nor do I re-estimate stories in sprint planning. I estimate stories in a separate estimating meeting and usually at least a couple sprints in advance, if not more. There are a few reasons why (re)estimating during sprint planning is a dangerous practice:

Allan Kelly09/09/14
6521 views
3 replies

Agile outside of software

While not every Agile practice can be taken out of software development and used someplace else the roots of Agile mean that the principles, values and ideas which Agile is built on can be. In your domain Agile as now known might work quite well, but in someone else’s domain there may be more need to think deeper.

Chris Odell09/09/14
5103 views
0 replies

SOHO Agile: Is agile relevant to the SOHO developer?

Agile is often seen as a team process, and certainly agile lends itself to team activities. So can you apply agile to the Sole Home Office developer?

Mike Bushong09/09/14
5436 views
2 replies

On building teams: experience or talent?

Obviously when you hire, you want to find a good mix of experience and talent. But a perfectly balanced straddle between the two is impossible. So when forced to choose between them, which do you choose: experience or talent?

Mateusz Haligowski09/08/14
34102 views
16 replies

Programmer, know thy tools!

On the importance on non-programming skills in the job of a programmer.

import java.io.IOException;
import java.util.Scanner;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class filter
 * @author prgrmmr.aben [at] gmail (dot) com
 * http://fivesnippets.blogspot.com/2014/08/servlet-filter-for-ddos-spam-etc.html
 * please give back a small donation if you find
 * this little educational snippet of code useful 
 */
@WebFilter("/filter")
public class filter implements Filter {

    /**
     * Default constructor. 
     */
    public filter() {
        // TODO Auto-generated constructor stub
    }

 /**
  * @see Filter#destroy()
  */
 public void destroy() {
  // TODO Auto-generated method stub
 }

 /**
  * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
  */
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  HttpSession session;
  System.out.println("being filtered"); //you can use logging instead
  HttpServletRequest req = (HttpServletRequest)request;
  HttpServletResponse res = (HttpServletResponse)response;
                res.addHeader("X-FRAME-OPTIONS", "DENY" ); 
  String requestedPath = req.getRequestURI().substring(req.getContextPath().length());
                // I was using the test bellow when developing the app
  /*Scanner verify = new Scanner(System.in);
  if(verify.nextInt()==0){
   req.getSession().invalidate();
  }*/
  session = req.getSession(false);
  if(req.getSession(false) == null){
   session = req.getSession(true);
   sessionInit(session);
   req.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
  }else{
   long timeElapsed =  System.currentTimeMillis() - (long) session.getAttribute("lastTime"); 
   System.out.println(timeElapsed);
   System.out.println("seen");
   if(session.getAttribute("spam").equals(true))
    System.out.println("spams are not allowed"); //you can use logging instead
   else if (timeElapsed<2000) {
    session.setAttribute("spam", true);
    System.out.println("spam need to be blocked");
   }else if (session.getAttribute("logged").equals(false)) {
    session.setAttribute("lastTime", System.currentTimeMillis());
    req.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
   System.out.println(2);
   }else{//if session.getAttribute("logged").equals(true) which should be set to true after user is logged
    System.out.println(requestedPath);
    session.setAttribute("lastTime", System.currentTimeMillis());
    if(requestedPath.equals("/login.jsp"))
     req.getServletContext().getRequestDispatcher("/main.jsp").forward(request, response);
    else
     req.getServletContext().getRequestDispatcher(requestedPath).forward(request, response);
   }
  }
  

  //chain.doFilter(request, response);
 }

 private void sessionInit(HttpSession session) {
  // TODO Auto-generated method stub
  System.out.println("init");
  session.setAttribute("spam", false);
  session.setAttribute("logged", true);
  session.setAttribute("lastTime", System.currentTimeMillis());
  
 }

 /**
  * @see Filter#init(FilterConfig)
  */
 public void init(FilterConfig fConfig) throws ServletException {
  // TODO Auto-generated method stub

 }

}
CREATE TABLE IF NOT EXISTS `session` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  /*`refUser` int(11) DEFAULT NULL COMMENT 'references user number',*/
  `IP` int(39) DEFAULT NULL,
  `creation` datetime NOT NULL TIMESTAMP DEFAULT CURRENT_TIMESTAMP  COMMENT 'creation time',
  `expiry` datetime DEFAULT NULL  COMMENT 'expiry time',
  `secretToken` varchar(10) NOT NULL,
  `type` enum('guest','client') NOT NULL DEFAULT 'guest',
  PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='don''t need to be a real session in memory' AUTO_INCREMENT=1 ;
CREATE TABLE cachedSession ENGINE=MEMORY SELECT * FROM session;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cacheSessions`()
    NO SQL
BEGIN
DELETE FROM cachedsession WHERE 1;
INSERT INTO cachedsession SELECT * FROM session WHERE `expiry`<NOW();
SELECT row_count();
end$$
 
CREATE DEFINER=`root`@`localhost` PROCEDURE `cleanSession`()
    NO SQL
    COMMENT 'clean sessions expired @hours ago'
BEGIN
DELETE FROM `session` WHERE  TIMESTAMPDIFF(MINUTE, expiry, NOW())>0;
SELECT row_count();
end$$
Lucas Saldanha09/05/14
7056 views
4 replies

Pitfalls of Agile Software Development

In this post I discuss three pitfalls of agile software development faced by developers when trying to make changes in the development process at "non-agile" companies.

Pierre-yves Saumont09/05/14
9646 views
4 replies

Do it in Java 8: recursive and corecursive Fibonacci

Calculating the Fibonacci suite is one of the ubiquitous examples we can find on the Internet. Java 8 offers us new possibility to solve this problem using recursion or corecursion.

Maarten Ectors09/05/14
4580 views
0 replies

Instant Big Data Stream Processing = Instant Storm

Every 6 months at Canonical, the company behind Ubuntu, I work on something technical to test our tools first hand and to show others new ideas. This time around I created an Instant Big Data solution, more concretely “Instant Storm”.

Paul Underwood09/04/14
3630 views
0 replies

Getting Started With Composer In PHP

In this tutorial we are going to learn about composer and how we can use it to develop our PHP applications.

Michael Mccandless09/04/14
4235 views
0 replies

Scoring tennis using finite-state automata

For some reason, the scoring system for tennis is very strange. Fortunately, the convoluted logic is easy to express as a finite-state automaton (FSA). If you build this Automaton in Lucene and minimize it, you'll discover that there are some wasted states! This means 20 states is overkill when deciding who won the game.

Mark Needham09/04/14
6612 views
0 replies

R: dplyr - group_by dynamic or programmatic field

In my last blog post I showed how to group timestamp based data by week, month and quarter. I wanted to pull this code out into a function. It turns out if we want to do this then we actually want the regroup function rather than group_by:

Trevor Parsons09/04/14
4159 views
0 replies

What is Syslog?

Syslog has been around for a number of decades and provides a protocol used for transporting event messages between computer systems and software applications. The protocol utilizes a layered architecture, which allows the use of any number of transport protocols for transmission of syslog messages.