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;
}
Addict{ed}
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;
}