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;
}
Integer Validation
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
- Choose File > New Project (Ctrl-Shift-N) from the main menu.
- Select Enterprise Application from the Java EE category and click Next.
- Right-click the EJB module in the Projects window and choose New > Other to open the New File wizard.
- From the Persistence category, select Entity Class and click Next.
- Type ejb for the Package.
- Leave the Primary Key Type as Long in the New Entity Class wizard.
- Select Create Persistence Unit. Click Next.
- Keep the default Persistence Unit Name.
- For the Persistence Provider, choose EclipseLink (JPA2.0)(default).
- For the Data Source, choose a data source (for example, select jdbc/sample if you want to use JavaDB)
- Right-click the EJB module in the Projects window and choose New > Other to open the New File wizard.
- From the Enterprise JavaBeans category, select the Message-Driven Bean file type. Click Next.
- Type NewMessage for the EJB Name.
- Select ejb from the Package drop-down list.
- Click the Add button next to the Project Destination field to open the Add Message Destination
- dialog box.
- In the Add Message Destination dialog box, type jms/NewMessage and select Queue for the
- destination type. Click OK.
- Confirm that the project destination is correct. Click Finish.
right click -> insert Code -> callEnterpriseBean and select the facade in ejb package
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>");
Mongo DB Functions
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;
}
Encryption and Decryption ii
public class CaesarCrypt {
private final String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+-gfuifyuvfyifrghvhyifyutcyi";
public String encrypt(String plainText,int shiftKey)
{
// plainText = plainText.toLowerCase();
String cipherText="";
int charPosition;
int keyVal;
char replaceVal;
for(int i=0; i < plainText.length(); i++)
{
charPosition = chars.indexOf(plainText.charAt(i));
keyVal = (charPosition + shiftKey) % chars.length();
replaceVal = this.chars.charAt(keyVal);
cipherText += replaceVal;
}
return cipherText;
}
public String decrypt(String cipherText, int shiftKey)
{
// cipherText = cipherText.toLowerCase();
String plainText="";
int charPosition;
int keyVal;
char replaceVal;
for(int i=0;i<cipherText.length();i++)
{
charPosition = this.chars.indexOf(cipherText.charAt(i));
keyVal = charPosition - shiftKey;
if(keyVal < 0)
{
keyVal = this.chars.length() + keyVal;
}
replaceVal = this.chars.charAt(keyVal);
plainText += replaceVal;
}
return plainText;
}
}
Encryption and Decryption
import javax.crypto.Cipher;import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public static void main(String[] args) {
// TODO code application logic here
try
{
String plainData = "This is a secret text";
String cipherText;
String decryptedText;
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
cipherText = encrypt(plainData, secretKey);
System.out.println("Plain Text :"+plainData);
System.out.println("cypher text : "+cipherText);
decryptedText = decrypt(cipherText, secretKey);
System.out.println("decrypted text : "+decryptedText);
} catch (Exception e)
{
e.printStackTrace();
}
}
public static String encrypt(String plainData, SecretKey secretKey) throws Exception
{
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] byteDataToEncrypt = plainData.getBytes();
byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
return new BASE64Encoder().encode(byteCipherText);
}
public static String decrypt(String cipherData, SecretKey secretKey) throws Exception
{
byte[] data = new BASE64Decoder().decodeBuffer(cipherData);
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] plainData = aesCipher.doFinal(data);
return new String(plainData);
}
Hibernate One to Many
<class name="hibernatetest2.Person" table="PERSON">
<id column="personid" name="personid">
<generator class="increment"/>
</id>
<property column="name" name="name"/>
<property column="age" name="age"/>
<set cascade="all" name="hats" table="HAT">
<key column="personid"/>
<one-to-many class="hibernatetest2.Hat"/>
</set>
</class>
Hat.Hbm
<class name="hibernatetest2.Hat" table="HAT">
<id column="hatid" name="hatid">
<generator class="increment"/>
</id>
<property column="personid" name="personid"/>
<property column="color" name="color"/>
<property column="size" name="size"/>
</class>
Person.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hibernatetest2;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
*
* @author Kamal
*/
public class Person {
private int personid;
private String name;
private int age;
private Set<Hat> hats;
// Generate Getters and Setters for the above
// Properties
public Person() {
hats = new HashSet<Hat>();
}
public int getPersonid() {
return personid;
}
public void setPersonid(int personid) {
this.personid = personid;
}
public String getName() {
return name;
}
public Set<Hat> getHats() {
return hats;
}
public void setHats(Set<Hat> hats) {
this.hats = hats;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
String personString = "Person: " + getPersonid()
+ " Name: " + getName()
+ " Age: " + getAge();
String hatString = "";
for (Hat hat : hats) {
hatString = hatString + "\t\t" + hat.toString() + "\n";
}
return personString + "\n" + hatString;
}
}
hat.java
private int hatid;
private String color;
private String size;
private int personid;
// Getters and Setters
public int getHatid() {
return hatid;
}
public void setHatid(int hatid) {
this.hatid = hatid;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public int getPersonid() {
return personid;
}
public void setPersonid(int personid) {
this.personid = personid;
}
public String toString() {
return "Hat: " + getHatid()
+ " Color: " + getColor()
+ " Size: " + getSize();
}
Main.java
public static void main(String[] args) {
// TODO code application logic
Person p1 = new Person();
p1.setName("Saman With Hats");
p1.setAge(30);
Hat h1 = new Hat();
h1.setColor("Black");
h1.setSize("Small");
Hat h2 = new Hat();
h2.setColor("White");
h2.setSize("Large");
p1.getHats().add(h1);
p1.getHats().add(h2);
createPerson(p1);
listPerson();
}
private static void listPerson() {
Session session = NewHibernateUtil.getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
List persons = session.createQuery(
"select p from Person as p").list();
System.out.println("*** Content of the Person Table ***");
System.out.println("*** Start ***");
// ------------- Query
// Query q = session.createQuery("select p from Person as p where p.age >:age");
// Person fooPerson = new Person();
// fooPerson.setAge(age);
// q.setProperties(fooPerson);
// List persons = q.list
//-------------------------
for (Iterator iter = persons.iterator(); iter.hasNext();) {
Person element = (Person) iter.next();
System.out.println(element);
}
System.out.println("*** End ***");
session.getTransaction().commit();
} catch (RuntimeException e) {
}
}
private static void deletePerson(Person person) {
Session session = NewHibernateUtil.getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
session.delete(person);
session.getTransaction().commit();
} catch (RuntimeException e) {
}
}
private static void createPerson(Person person) {
Session session = NewHibernateUtil.getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
session.save(person);
session.getTransaction().commit();
} catch (RuntimeException e) {
}
}
private static void updatePerson(Person person) {
Session session = NewHibernateUtil.getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
session.update(person);
session.getTransaction().commit();
} catch (RuntimeException e) {
}
}
Hibernate Many to Many
<class name="hibernatetest.Employee" table="EMPLOYEE">
<id name="employeeId" column="EMPLOYEE_ID">
<generator class="increment" />
</id>
<property name="firstname" />
<set name="meetings" table="EMPLOYEE_MEETING"
inverse="false" lazy="true" fetch="select" cascade="all">
<key column="EMPLOYEE_ID" />
<many-to-many column="MEETING_ID" class="hibernatetest.Meeting" />
</set>
</class>
Meeting.hbm
<class name="hibernatetest.Meeting" table="MEETING">
<id name="meetingId" column="MEETING_ID">
<generator class="increment" />
</id>
<property name="subject" column="SUBJECT" />
<set name="employees" table="EMPLOYEE_MEETING"
inverse="true" lazy="true" fetch="select">
<key column="EMPLOYEE_ID" />
<many-to-many column="MEETING_ID" class="hibernatetest.Meeting" />
</set>
</class>
Employee.java
private int employeeId;
private String firstname;
private Set<Meeting> meetings = new HashSet<Meeting>();
public Employee() {
}
public Employee(String firstname) {
this.firstname = firstname;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
Meeting.java
private int meetingId;
private String subject;
private Set<Employee> employees = new HashSet<Employee>();
public Meeting(String subject) {
this.subject = subject;
}
public int getMeetingId() {
return meetingId;
}
public void setMeetingId(int meetingId) {
this.meetingId = meetingId;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
Main.Java
SessionFactory sf = NewHibernateUtil.getSessionFactory();Session session = sf.openSession();
session.beginTransaction();
Meeting meeting1 = new Meeting("Quaterly Sales meeting");
Meeting meeting2 = new Meeting("Weekly Status meeting");
Employee employee1 = new Employee("Sergey");
Employee employee2 = new Employee("Larry");
employee1.getMeetings().add(meeting1);
employee1.getMeetings().add(meeting2);
employee2.getMeetings().add(meeting1);
session.save(employee1);
session.save(employee2);
session.getTransaction().commit();
session.close();