Archive for the ‘ Java ’ Category

Implementing message level security in web service using XWSS

Hi All,

I started learning web services and implementing security into it. So i thought of sharing my experience with you.

I created a contract first web service, based on spring web service (more detail can be found on spring website) and implemented  a simple client using spring integration. When we do not have security implemented with WS then it is quiet easy to create and use, but once security comes then ohh my god. ewww..  what a rock ………….!!!!!!!!!!!!!!

We can implement security into web service 3 ways. Here I am trying to explain XWSS (XML web service security) implementation with spring web service. To implement xwss we need seciryt policy configuration, one interceptor which intercepts each incoming soap request and key store file if you are encrypting and decrypting soap request and response. Here i have taken example of key store files because in in this sample i am encrypting soap request at client side, decrypting soap incoming request using security policy and private key, processing the request, encrypting response, sending encrypted response back to client and decrypting response to see actual response at client end.

Basically security policy files are responsible for soap message encryption and decryption. <xwss: sign /> tag signs your message and <xwss:encrypt /> tag encrypts the message and <xwss:requiresEncryption /> tag decrypts encrypted message.

key store files can be generated using keytool utility. please see attached txt file for help.

I am attaching source code for client and web server.

Message Level Security

 

Advertisements

Creating a JNDI name on IBM WAS

Hi Mikael,

Here are the steps to setup JNDI name for WAS.
This JNDI name must match name given in MASHAService\src\META-INF\persistence.xml

Open WAS admin console.
Click on Resources->JDBC-JDBC Providers
Click New Button after selecting a proper scope.

Give DB2 Jars path. Containing d22jcc.jar, db2jcc_license_cu.jar and db2jcc_license_cisuz.jar

Now Click on Resources->JDBC->Data Sources. Click on data source name that you have created

Now Click on JAAS – J2C authentication data and click on New and fill in all the details
J2c Authentication data created, will look like given below .

Go Back to data source name that you have created earlier.
Fill in the settings, authentication alias, mapping configuration alias, and data source properties as show below.

Click ok and then Need to Save entire configuration by clicking on save link that will appear on top (middle) of the screen, (this is called master configuration).
After saving select data source name and click on Test connection. If it is successful then the data source can be used in the application running on WAS.


Regards,
Sunil Chauraha

Java interview questions

1. Define your profession and carrer skills.
2. What is the difference between struts and jsf.
3. What the scope of application and request.
4. What is AJAX.
5. Where will you rate yourself in SQL.
6. Do you know any design pattern? if yes describe.
7. What is value binding and component binding.
8. Define lifecycle of richfaces.
9. How does a request completes?
10. What is jsf components?
11. What is component and events in jsf?
12. What did you do for performance inprovement?
13. What is IOC?
14. What is transaction management?
15. What is the life cycle of spring bean?
16. How will you configure spring and hibernate?
17. What is sessionfactory and session?
18. What is generics?
19. what is run time polymerphism?
20. how will you integrate spring in jsf?
21. what is hibernate?
22. what is difference between load and get in hibernate?
23. what is save, update and merge?
24. what is factory pattern?
25. what is spring mvc?
26. how will you integrate hibernate with spring?
27. what is aop?
28. what is criteria?
29. What is criteria and detached criteria?
30. one sql query for group by operation.
31. select second highest salary of an employee from emp table.
32. What is difference between struts and spring.
33 what is difference between jsp and servlet.
34 what is the life cycle of jsp.
35 what is the difference between requestForward method of servlet context and servlet config.

36. How we can instantiate a bean of abstract class having 2 subclasses.

37. How can we maintain a collection having the same order of insertion and unique values of object.

38. How can we use JPA in spring.

39. We have a singleton class and constructor is private, how can we create a bean in spring.

40. What is the mechanism used by Java for maintaining set and HashSet objects.

41. What is the significance of equals and hashCode methods in java and object comparison.

Latest Questions on 16th June 2012.

1. hibernate object joins (per concret class…. etc)
2. list, bag, set, hashmap use in hibernate.
3. How to prevent concurant modification in hibernate.
4. if “null”  is showing in jsp text box. how we can prevent it.
5. how to set initParams in jsp.
6. How to handle runtime exception in jsp.
7. how to show exception on console from jsp.
8. can we pass instances in stateless session bean.
9. what are the importent methods of httprequest object.
10. what is synchronizer token.
11. how do we prevent multiple request submission in struts.
12. what is difference between perform() and execute();
13. What is signifance of SessionFactory in hibernate and Spring.
14. what is action-mapping in struts.
15. how do we pass request from one servlet to another servlet withing the application.
16. How do we use cookies.
17. Define all the operation of Cookies. add, delete, read, upddate and send.
18. How to write jsp custom tag.
19. What is synchronization.
20. What is sql joins.
21. how to get n’th  greatest elemebt from a table.

Ans: select salary from employee e1 where (N-1) = (select count(distinct(e2.salary)) from employee e2 where e2.salary > e1.salary) (N stands for count, which we want to retrieve)
22. What is upcasting and down casting.
23. what is bounded and unbounded in java generics.
24. What is agreegation in java.

Singleton design pattern

As the name says… Singleton -> means just single.

There are so many situations where we need to create many or one instance of our class.  Like we will have a single database connection manger.

There are many ways to create a singleton design (i.e. Using User Defined exception class, using static class).

rather there is the most useful way that most programmer uses.  That is static method having a private default constructor.

public class IsSingle {
static boolean instanceFlag = false;
private IsSingle(){}
public static IsSingle getInstance(){
if(!instanceFlag){
instanceFlag = true;
return new IsSingle();
}
else{
return null;
}
}
// finalize is needed here, because if object IsSingle is garbage collected then isInstance must be false to invoke new.
public void finalize(){
instanceFlag = false;
}
}

Reading a Doc file using Java

Hi by using a simple java IO we can’t read contents of a doc file.

Jakarta poi has some utilities to read contents of a file using its api.

Every line of the doc file is considered as a paragraph.

import java.io.FileInputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class ReadandWrite {
public static void readDocFile(String filePath) {
POIFSFileSystem fs = null;
try {
fs = new POIFSFileSystem(new FileInputStream(filePath));
HWPFDocument doc = new HWPFDocument(fs);
WordExtractor we = new WordExtractor(doc);
String[] paragraphs = we.getParagraphText();
System.out.println(“Word Document has ” + paragraphs.length+ ” paragraphs”);
for (int i = 0; i < paragraphs.length; i++) {
paragraphs[i] = paragraphs[i].replaceAll(“\\cM?”, “”);
System.out.println(paragraphs[i]);
}
} catch (Exception e) {
}
}
public static void main(String[] args) throws Throwable {
readDocFile(“yourfile.doc”);
}
}

For this i used  poi-3.0-FINAL.jar.

How to use Gmail as your SMTP server – JAVA

Hi Here is an interesting code to send an email using gmail smtp server.

This asks for the login and password of any gmail accound and uses gmail smtp to send emails…

**************************************************************************************

package com.sunil.mail;
import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

public class SimpleJavaMail {

private Session mailSession;
protected PasswordAuthentication authentication;
private String user = null;
private String password = null;
private Properties props;

public SimpleJavaMail(){
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
props = new Properties();
props.setProperty(“mail.transport.protocol”, “smtp”);
props.setProperty(“mail.host”, “smtp.gmail.com”);
props.put(“mail.smtp.auth”, “true”);
props.put(“mail.smtp.port”, “465”);
props.put(“mail.smtp.socketFactory.port”, “465”);
props.put(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);
props.put(“mail.smtp.socketFactory.fallback”, “false”);
props.put(“mail.user”, “xxxxxxx@gmail.com”);
props.put(“mail.password”, “xxxxx”);
props.setProperty(“mail.smtp.quitwait”, “false”);
}

public void initMail(String user, String password) {
this.user = user;
this.password = password;
mailSession = createMailSession();
}

private Session createMailSession() {
Session session = null;
try {
session = Session.getDefaultInstance(props,    new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user,password);
}
});
} catch (Exception e) {
e.printStackTrace();
}
return session;
}

public synchronized void sendMail(String subject, String body, String sender, String recipients)
throws Exception{
String host;
String mailUserName = (String) getProps().get(“mail.user”);
String mailPassword = (String) getProps().get(“mail.password”);
host = (String) getProps().get(“mail.host”);
host = host.toLowerCase();
initMail(mailUserName, mailPassword);
MimeMessage message = new MimeMessage(mailSession);
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setContent(body, “text/plain”);
if (recipients.indexOf(‘,’) > 0){
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
}else{
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
}
Transport.send(message);
}

public Properties getProps() {
return props;
}

public void setProps(Properties props) {
this.props = props;
}

public static void main(String[] args) {
try{
String subject = “Test mail…”;
String body = “Hi Buddy…”;
String sender = “noname@noname.com”;
String recipients = “sunilxxxx@gmail.com”;
SimpleJavaMail mailJava = new SimpleJavaMail();
mailJava.sendMail(subject, body, sender, recipients);
} catch (Exception e) {
Logger.getLogger(SimpleJavaMail.class.getName()).error(e);
e.printStackTrace();
}
System.out.println(“Mail sent!”);
}

}

Running DOS command using java!

Hi…

Here is a small example.

We can use to run a dos command using java code.

/***************Code ******************/

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

class SunilCmd {

static public void main(String args[]) {
try {
StringBuffer sb = new StringBuffer();
BufferedReader buff = new BufferedReader(new InputStreamReader(    Runtime.getRuntime().exec(“cmd.exe /C dir”).getInputStream()));
/* Here Runtime.getRuntime creates environment to run the command */
/* .exec executes the parameters given inside the method */

/*
* here “cmd.exe /C” will invoke the DOS in exclusive mode and “dir”
* is a command that will be executed…..
*/

String line = buff.readLine();
while (line != null) {
sb.append(line + “\n”);
line = buff.readLine();
}
System.out.println(sb);
File f = new File(“output.txt”);
/**
*All the output will be written into output.txt file
*/
FileOutputStream fos = new FileOutputStream(f);
fos.write(sb.toString().getBytes());
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}

}