Integer Validation

public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}

Email Validation

public boolean isValidEmailAddress(String email) {
String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
java.util.regex.Matcher m = p.matcher(email);
return m.matches();
}

Web Service


private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.DataSource = Enum.GetValues(typeof(Proxy.Currency));
            comboBox2.DataSource = Enum.GetValues(typeof(Proxy.Currency));
            comboBox1.SelectedIndex = 1;
            comboBox2.SelectedIndex = 1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Proxy.CurrencyConvertorSoapClient proxy = new Proxy.CurrencyConvertorSoapClient("CurrencyConvertorSoap");

           double rate = proxy.ConversionRate((Proxy.Currency)comboBox1.SelectedValue, (Proxy.Currency)comboBox2.SelectedValue);

           textBox2.Text = (Double.Parse(textBox1.Text) * rate ).ToString();
        }




Currency Converter WSDL :- http://www.webservicex.com/CurrencyConvertor.asmx?wsdl

Find More WebServices :- http://www.service-repository.com

Encryption iv

static void Main(string[] args) { 

   string charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
   
   string decriptString = "FDYMHQDCFIDJBIPWDKR"; 
   
   int indexOfInput; 

   string orginal = ""; 
  
   int invers = 1; 

   int temp = 0; 

  while (temp != 1) {
     temp = (7 * invers) % 26; 
     invers++;
  }

  invers -= 1; 
  Console.WriteLine("Invers of 7 : "+invers);

  for (int i = 0; i < decriptString.Length; i++) {
     
     indexOfInput = charSet.IndexOf(decriptString[i]);
     
     int point = invers * (indexOfInput - 3) % 26;
    
     if (point < 0) {
              point = (point + charSet.Length);
     }
     
     orginal += charSet[point]; 
 }

  Console.WriteLine("Orginal Text : "+orginal); Console.ReadLine(); 
 }

Encryption and Decryption iii

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package aesexample;

import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;

/**
*
* @author Whiz
*/
public class AESWithGivenKEy {
    public static void main(String[] args) {
    try {

      String key = "ThiSIsASecretKey";
      byte[] ciphertext = encrypt(key, "Hey There");
      String x=new BASE64Encoder().encode(ciphertext);
        System.out.println("encrypted :"+x);
      System.out.println("decrypted value:" + (decrypt(key, ciphertext)));
     
     
      String key1 = "ThiSIsASEcretKey";
      int x123 =323;
       byte[] ciphertext1 = encrypt(key1, "Hey There");
      String x1=new BASE64Encoder().encode(ciphertext1);
        System.out.println("encrypted :"+x1);
      System.out.println("decrypted value:" + (decrypt(key1, ciphertext1)));
//
//      String key1 = "ThisIsASEcretKey";
//      byte[] ciphertext1 = encrypt(key, "HeyThere");
//      String xx=new BASE64Encoder().encode(ciphertext1);
//        System.out.println("encrypted :"+xx);
//      System.out.println("decrypted value:" + (decrypt(key1, ciphertext1)));
    } catch (GeneralSecurityException e) {
      e.printStackTrace();
    }
  }

  public static byte[] encrypt(String key, String value)
      throws GeneralSecurityException {

    byte[] raw = key.getBytes(Charset.forName("US-ASCII"));
    if (raw.length != 16) {
      throw new IllegalArgumentException("Invalid key size.");
    }

    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec,
        new IvParameterSpec(new byte[16]));
    return cipher.doFinal(value.getBytes(Charset.forName("US-ASCII")));
  }

  public static String decrypt(String key, byte[] encrypted)
      throws GeneralSecurityException {

    byte[] raw = key.getBytes(Charset.forName("US-ASCII"));
    if (raw.length != 16) {
      throw new IllegalArgumentException("Invalid key size.");
    }
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec,
        new IvParameterSpec(new byte[16]));
    byte[] original = cipher.doFinal(encrypted);

    return new String(original, Charset.forName("US-ASCII"));
  }
}

Enterprise Java Beans :P

How to create a project 

  1. Choose File > New Project (Ctrl-Shift-N) from the main menu.
  2. Select Enterprise Application from the Java EE category and click Next.

Creating the Entity Class

  1. Right-click the EJB module in the Projects window and choose New > Other to open the New File wizard.
  2. From the Persistence category, select Entity Class and click Next.
  3. Type ejb for the Package.
  4. Leave the Primary Key Type as Long in the New Entity Class wizard.
  5. Select Create Persistence Unit. Click Next.
  6.  Keep the default Persistence Unit Name.
  7. For the Persistence Provider, choose EclipseLink (JPA2.0)(default).
  8. For the Data Source, choose a data source (for example, select jdbc/sample if you want to use JavaDB)
 Inside the class put these variables 


     private String title;

     private String body;

     
     then also generate their getters and setters  

Creating the Message-Driven Bean

  1. Right-click the EJB module in the Projects window and choose New > Other to open the New File wizard.
  2. From the Enterprise JavaBeans category, select the Message-Driven Bean file type. Click Next.
  3. Type NewMessage for the EJB Name.
  4. Select ejb from the Package drop-down list.
  5. Click the Add button next to the Project Destination field to open the Add Message Destination
  6. dialog box.
  7. In the Add Message Destination dialog box, type jms/NewMessage and select Queue for the
  8. destination type. Click OK.
  9. Confirm that the project destination is correct. Click Finish.
 Add this line soon after the class deceleration
    
    @Resource
    private MessageDrivenContext mdc; 

  after that select insert code and call Use Entity Manager

  change the persist method to change the name to save

  add this code to onMessage
  
  ObjectMessage msg = null;
  try {
    if (message instanceof ObjectMessage) {
           msg = (ObjectMessage) message;
           NewsEntity e = (NewsEntity) msg.getObject();
           save(e);
    }
 } catch (JMSException e) {
     e.printStackTrace();
     mdc.setRollbackOnly();
 } catch (Throwable te) {
     te.printStackTrace();
}

Creating the Session Facade


create the session facade, perform the following steps:
1. Right-click the EJB module and choose New > Other.
2. From the Persistence category, select Session Beans for Entity Classes. Click Next.
3. Select ejb.NewsEntity from the list of available entity classes and click Add to move the
class to the Selected Entity Classes pane. Click Next.
4. Check that the Package is set to ejb. Click Finish.


Coding the Web Module

ListNews Servelet

   right click -> insert Code -> callEnterpriseBean and select the facade in ejb package   

    @EJB
    private NewsFacade newsFacade;

    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ListNews</title>");
            out.println("</head>");
            out.println("<body>");
            List news = newsFacade.findAll();
            for (int i = 0; i < news.size(); i++) {
                News e = (News) news.get(i);

                out.println(e.getTitle() + "-" + e.getBody());
                out.println("<a href='EditMessage?id=" + e.getId() + "'>edit</a>");
                out.println("<a href='DeleteMessage?id=" + e.getId() + "'>delete</a>");
                out.println("<br/>");
            }
            out.println("<br/>");
            out.println("<a href='PostMessage'>Add new message</a>");
            out.println("</body>");
            out.println("</html>");
        }
    }


postMessage Servlet - using MessageDrivenBean

Only add the bold codes at correct places

@WebServlet(name="PostMessage", urlPatterns={"/PostMessage"})
public class PostMessage extends HttpServlet {

        @Resource(mappedName="jms/NewMessageFactory")
        private ConnectionFactory connectionFactory;
        @Resource(mappedName="jms/NewMessage")

        private Queue queue;

        response.setContentType("text/html;charset=UTF-8");
        // Add the following code to send the JMS message
       String title=request.getParameter("title");
       String body=request.getParameter("body");
       if ((title!=null) && (body!=null)) {
       try {
        Connection connection = connectionFactory.createConnection();
        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        MessageProducer messageProducer =
        session.createProducer(queue);
        ObjectMessage message = session.createObjectMessage();
        // here we create NewsEntity, that will be sent in JMS message
        NewsEntity e = new NewsEntity();
        e.setTitle(title);
        e.setBody(body);
        message.setObject(e);
        messageProducer.send(message);
        messageProducer.close();
        connection.close();
        response.sendRedirect("ListNews");
        } catch (JMSException ex) {
          ex.printStackTrace();
        }
        }

       out.println("Servlet PostMessage at " + request.getContextPath() +"</h1>");
       // The following code adds the form to the web page
       out.println("<form>");
       out.println("Title: <input type='text' name='title'><br/>");
       out.println("Message: <textarea name='body'></textarea><br/>");
       out.println("<input type='submit'><br/>");
       out.println("</form>");

       out.println("</body>");

PostMessage Servlet - using facade 



    @EJB
    private NewsEntityFacade entityFacade;

    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JMSException {
        response.setContentType("text/html;charset=UTF-8");

        String title = request.getParameter("title");
        String body = request.getParameter("body");
        if ((title != null) && (body != null)) {
            NewsEntity e = new NewsEntity();
            e.setTitle(title);
            e.setBody(body);

            entityFacade.create(e);

            response.sendRedirect("ListNews");
        }

        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet PostMessage</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet PostMessage at " + request.getContextPath() + "</h1>");
            out.println("<form>");
            out.println("Title: <input type='text' name='title'><br/>");
            out.println("Message: <textarea name='body'></textarea><br/>");
            out.println("<input type='submit'><br/>");
            
            out.println("</form>");
            out.println("</body>");
            out.println("</html>");
        }
    }


DeleteMessage Servlet


    @EJB
    private NewsEntityFacade newsEntityFacade;

    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        String title = request.getParameter("title");
        String body = request.getParameter("body");
        Long _id = Long.parseLong(request.getParameter("id"));
        if ((title != null) && (body != null)) {
            NewsEntity e = new NewsEntity();
            e.setId(_id);
            e.setTitle(title);
            e.setBody(body);
            
            newsEntityFacade.remove(e);
            
            response.sendRedirect("ListNews");
        }
        
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet DeleteMessage</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet DeleteMessage at " + request.getContextPath() + "</h1>");
            out.println("<form>");
            NewsEntity news = newsEntityFacade.find(_id);
            out.println("Title: <input type='text' name='title' value='" + news.getTitle() + "'><br/>");
            out.println("Body: <input type='text' name='body' value='" + news.getBody() + "'><br/>");
            out.println("<input type='hidden' name='id' value='" + _id + "'/>");
            out.println("<input type='submit'><br/>");
            out.println("</form>");
            out.println("</body>");
            out.println("</html>");
        }
    }


Edit Message Servelet


    @EJB
    private NewsEntityFacade newsEntityFacade;

   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        Long _id = Long.parseLong(request.getParameter("id"));
        
        String title = request.getParameter("title");
        String body = request.getParameter("body");
        
        if ((title != null) && (body != null)) {
            NewsEntity e = new NewsEntity();
            e.setId(_id);
            e.setTitle(title);
            e.setBody(body);

            newsEntityFacade.edit(e);

            response.sendRedirect("ListNews");
        }

        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet EditMessage</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet EditMessage at " + request.getContextPath() + "</h1>");
            out.println("<form>");
            NewsEntity news = newsEntityFacade.find(_id);
            out.println("Title: <input type='text' name='title' value='" + news.getTitle() + "'><br/>");
            out.println("Body: <input type='text' name='body' value='" + news.getBody() + "'><br/>");
            out.println("<input type='hidden' name='id' value='" + _id + "'/>");
            out.println("<input type='submit'><br/>");
            out.println("</form>");
            out.println("</body>");
            out.println("</html>");
        }
    }



Mongo DB Functions

DBManager.java


private static DB database;

public static DB getDatabase() {
        if (database == null) {
            try {
                MongoClient mongo;

                mongo = new MongoClient("localhost", 27017);
                database = mongo.getDB("usermanager");
            } catch (UnknownHostException ex) {
                Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return database;
    }



Insert Object 

Code inside the button cliked

        User user = new User();
        user.setId(Integer.parseInt(jTextField1.getText().toString()));
        user.setFirstName(jTextField2.getText().toString());
        user.setLastName(jTextField3.getText().toString());
        user.setEmail(jTextField4.getText().toString());

        DBObject doc = createDBObject(user);
        DB useDb = DBManager.getDatabase();

        DBCollection col = useDb.getCollection("user");


        WriteResult result = col.insert(doc);


create a this method in ur main class

 private static DBObject createDBObject(User user) {
        BasicDBObjectBuilder b = BasicDBObjectBuilder.start();
        b.append("_id", user.getId());
        b.append("firstName", user.getFirstName());
        b.append("lastName", user.getLastName());
        b.append("email", user.getEmail());

        return b.get();

    }


Update Object


        User user = new User();
        user.setId(Integer.parseInt(jTextField1.getText().toString()));
        user.setFirstName(jTextField2.getText().toString());
        user.setLastName(jTextField3.getText().toString());
        user.setEmail(jTextField4.getText().toString());


        updatePerson(user);


        private static void updatePerson(User user) {

        DB db = DBManager.getDatabase();
        DBCollection collection = db.getCollection("user");

        BasicDBObject newUser = new BasicDBObject();

        newUser.append("firstName", user.getFirstName());
        newUser.append("lastName", user.getLastName());
        newUser.append("email", user.getEmail());

        BasicDBObject updateOb = new BasicDBObject("$set", newUser);

        BasicDBObject searchQuery = new BasicDBObject().append("_id",
                user.getId());

        collection.update(searchQuery, updateOb);


        }


Delete Object

        int id = Integer.parseInt(jTextField1.getText().toString());

        deleteUser(id); 


        public void deleteUser(int userID) {

        DB db = DBManager.getDatabase();
        DBCollection collection = db.getCollection("user");
        BasicDBObject remOb = new BasicDBObject();

        remOb.put("_id", userID);

        collection.remove(remOb);

        }

Search Object

        int id = Integer.parseInt(jTextField5.getText().toString());
        Vector v = selectOneExample(id);
        
        
        for(int i=0;i<v.size();i++)
        {
            Vector v1 = (Vector) v.get(i);
            jTextField1.setText(v1.get(0).toString());
            jTextField2.setText(v1.get(1).toString());
            jTextField3.setText(v1.get(2).toString());
            jTextField4.setText(v1.get(3).toString());
            
            
        } 

        private static Vector<Vector<String>> selectOneExample(int id) {
        DB db = DBManager.getDatabase();
        DBCollection collection = db.getCollection("user");
        BasicDBObject query = new BasicDBObject("_id", id);
        DBCursor cursor = collection.find(query);

        Vector<Vector<String>> detailsVector = new Vector<Vector<String>>();
        try {
            List<DBObject> li = cursor.toArray();
            for (int i = 0; i < li.size(); i++) {
                Vector<String> v = new Vector<String>();
                v.add(li.get(i).get("_id").toString());
                v.add(li.get(i).get("firstName").toString());
                v.add(li.get(i).get("lastName").toString());
                v.add(li.get(i).get("email").toString());

                detailsVector.add(v);
            }

        } catch (Exception e) {
            System.out.println(e);
        }
        return detailsVector;

      }