Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, June 16, 2010

Caution while using "and" and "or" operator in standard visual snippet

The "and" & “or” operator from standard visual snippet doesn't execute the way it is getting executed in Java. In visual snippet case it does differently

The translated code

java.lang.String __result__1 = null;
input1 = __result__1;
boolean __result__4 = input1.trim().length() != 0;
boolean __result__3 = input1 != null;
boolean __result__5;
{// and
__result__5 = __result__3 && __result__4;
}

In the above snippet the string is null, when using the "and" & “or” operator. It executes the left and right hand side conditions separately and stores in a variable and then does an 'and' operation on the variable.

While executing you will get a null pointer exception, because the string is null on top of that we are trying to trim().length()


The visual snippet operator will unnecessarily execute both the left and right hand side conditions which we don't want to do


To avoid this use the 'and' logical operator '&&' in the visual snippet.

boolean __result__6 = input1 != null && input1.trim().length() != 0;

In this case it executes as it does it in Java the safer way. :-)

Wednesday, October 21, 2009

WebSphere Technical Exchange Web cast

There is web cast organised by IBM on Mediation Module Development in WebSphere Integration Developer (WID). The main contents that to be discussed are creating a Mediation flow, re-using Mediation logic in subflow components, XPath builder, transforming messages, invoking external services using CallOut component, and aggregating and broadcasting messages using Fan-out, Fan-in components.

Web conference URL: link

Password/Conference ID: wste27oct

View presentation click here

For more info click here

Timing : October 27, 2009 11 AM EDT

Tuesday, February 24, 2009

Error "org.omg.CORBA.portable.UnknownException: vmcid: 0x0 minor code: 0 completed: Maybe]"

I was bugged by this error yesterday. I didn't have any clue. I tried to do clean build on WID (WebSphere Integeration Developer). Its doesn't help. Restarted the server couple of times, removed from the server and published again no way & no improvements not even a single step forward.

Exception stack trace: javax.naming.NamingException: Error during resolve [Root exception is org.omg.CORBA.portable.UnknownException: vmcid: 0x0 minor code: 0 completed: Maybe]
at com.ibm.ws.naming.jndicos.CNContextImpl.doLookup(CNContextImpl.java:1939)
at com.ibm.ws.naming.jndicos.CNContextImpl.doLookup(CNContextImpl.java:1862)
at com.ibm.ws.naming.jndicos.CNContextImpl.lookupExt(CNContextImpl.java:1552)
at com.ibm.ws.naming.jndicos.CNContextImpl.lookup(CNContextImpl.java:1354)
at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:172)
at javax.naming.InitialContext.lookup(InitialContext.java:363)
at com.ibm.ws.sca.internal.ejb.util.EJBLocator$JndiLocator.locate(EJBLocator.java:464)
at com.ibm.ws.sca.internal.ejb.util.EJBLocator.locate(EJBLocator.java:442)
at com.ibm.ws.sca.internal.ejb.util.EJBObjectFactory.createStub(EJBObjectFactory.java:72)
at com.ibm.ws.sca.internal.ejb.util.EJBStubAdapter.getStub(EJBStubAdapter.java:87)
at com.ibm.ws.sca.internal.ejb.util.EJBStubHelper.lookup(EJBStubHelper.java:89)
at com.ibm.ws.sca.internal.ejb.util.EJBStubHelper.lookup(EJBStubHelper.java:82)
at com.ibm.ws.sca.internal.binding.handler.SCAImportBindingHandler.getExportEJBStub(SCAImportBindingHandler.java:146)
at com.ibm.ws.sca.internal.binding.handler.SCAImportBindingHandler.processMessage(SCAImportBindingHandler.java:221)
at com.ibm.ws.sca.internal.message.impl.MessageDispatcherImpl.processMessageWithPCI(MessageDispatcherImpl.java:725)
at com.ibm.ws.sca.internal.message.impl.MessageDispatcherImpl.processMessage(MessageDispatcherImpl.java:1166)
at com.ibm.ws.sca.internal.message.impl.ManagedMessageImpl.process(ManagedMessageImpl.java:843)
at com.ibm.wsspi.sca.ejb.module.impl.ModuleSessionBean.processUOWMessage(ModuleSessionBean.java:338)
at com.ibm.wsspi.sca.ejb.module.impl.ModuleSessionBean.transactionNotSupportedActivitySessionNotSupported(ModuleSessionBean.java:287)
at com.ibm.wsspi.sca.ejb.module.EJSLocalStatelessModule_43132892.transactionNotSupportedActivitySessionNotSupported(EJSLocalStatelessModule_43132892.java:131)
at com.ibm.ws.sca.internal.uow.handler.UOWStrategyImpl.transactionLocalActivitySessionFalse(UOWStrategyImpl.java:386)
at com.ibm.ws.sca.internal.uow.handler.JoinUOWHandler.processMessage(JoinUOWHandler.java:131)
at com.ibm.ws.sca.internal.message.impl.MessageDispatcherImpl.processMessageWithPCI(MessageDispatcherImpl.java:725)
at com.ibm.ws.sca.internal.message.impl.MessageDispatcherImpl.processMessage(MessageDispatcherImpl.java:1166)
at com.ibm.ws.sca.internal.message.impl.ManagedMessageImpl.process(ManagedMessageImpl.java:834)
at com.ibm.ws.sibx.mediation.flowaction.impl.sca.SCAInvocationAction.invokeSync(SCAInvocationAction.java:531)
at com.ibm.ws.sibx.mediation.flowaction.impl.sca.RetryControl.invokeByStyle(RetryControl.java:327)
at com.ibm.ws.sibx.mediation.flowaction.impl.sca.RetryControl.invokeWithRetry(RetryControl.java:221)
at com.ibm.ws.sibx.mediation.flowaction.impl.sca.ServiceInvocation.complete(ServiceInvocation.java:124)
at com.ibm.ws.sibx.mediation.flowaction.impl.sca.FlowActionFactoryImpl.create(FlowActionFactoryImpl.java:667)
at com.ibm.ws.sibx.mediation.primitives.serviceinvoke.ServiceInvokeMediation.invokeFlowAction(ServiceInvokeMediation.java:469)
at com.ibm.ws.sibx.mediation.primitives.serviceinvoke.ServiceInvokeMediation.mediate(ServiceInvokeMediation.java:390)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.performInvocation(JavaMediationPrimitive.java:323)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.invoke(JavaMediationPrimitive.java:217)
at com.ibm.ws.sibx.scax.mediation.engine.SIBXJavaMediationPrimitive.invoke(SIBXJavaMediationPrimitive.java:93)
at com.ibm.ws.sibx.scax.mediation.engine.MediationPrimitive.invokeConnections(MediationPrimitive.java:311)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.fireOutputTerminals(JavaMediationPrimitive.java:419)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.performInvocation(JavaMediationPrimitive.java:345)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.invoke(JavaMediationPrimitive.java:217)
at com.ibm.ws.sibx.scax.mediation.engine.MediationPrimitive.invokeConnections(MediationPrimitive.java:311)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.fireOutputTerminals(JavaMediationPrimitive.java:419)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.performInvocation(JavaMediationPrimitive.java:345)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.invoke(JavaMediationPrimitive.java:217)
at com.ibm.ws.sibx.scax.mediation.engine.MediationPrimitive.invokeConnections(MediationPrimitive.java:311)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.fireOutputTerminals(JavaMediationPrimitive.java:419)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.performInvocation(JavaMediationPrimitive.java:345)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.invoke(JavaMediationPrimitive.java:217)
at com.ibm.ws.sibx.scax.mediation.engine.SIBXJavaMediationPrimitive.invoke(SIBXJavaMediationPrimitive.java:93)
at com.ibm.ws.sibx.scax.mediation.engine.MediationPrimitive.invokeConnections(MediationPrimitive.java:311)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.fireOutputTerminals(JavaMediationPrimitive.java:419)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.performInvocation(JavaMediationPrimitive.java:345)
at com.ibm.ws.sibx.scax.mediation.engine.JavaMediationPrimitive.invoke(JavaMediationPrimitive.java:217)
at com.ibm.ws.sibx.scax.mediation.engine.MediationPrimitive.invokeConnections(MediationPrimitive.java:311)
at com.ibm.ws.sibx.scax.mediation.engine.Input.invoke(Input.java:137)
at com.ibm.ws.sibx.scax.mediation.engine.RequestFlow.invokeFlow(RequestFlow.java:132)
at com.ibm.ws.sibx.scax.mediation.engine.MediationFlow.invokeRequestFlow(MediationFlow.java:135)
at com.ibm.wsspi.sibx.mediation.flow.ejb.MediationFlowBean.invokeRequestFlow(MediationFlowBean.java:230)
at com.ibm.wsspi.sibx.mediation.flow.ejb.EJSLocalStatelessMediationFlow_f5ad87fe.invokeRequest
Flow(EJSLocalStatelessMediationFlow_f5ad87fe.java:127)

I got tensed thinking of the whole day, will go in vain in debugging this issue. Search didn't give us much information. Then got some clue from devworks forum. Oops there were lot of unanswered questions, few of them got some suggestions same as clean+build and deploy.

I tried a different combination, removed the project from server. (checked in the admin console). Delete all the projects which are generated by WID (App,EJB and WEB Projects). Then do a clean build and deploy application. Mostly this works b'coz it worked for me.

Note : Even after the below steps your facing the problem check in devworks or open a PMR with IBM.

Thursday, February 19, 2009

BO Map Failure at runtime with null pointer Exception

The issue is the BO Map was failing at runtime giving null ponter exception at a custom map, i got really confused looked every thing in the custom map. All the value was checked to null or it is intialized to default. After doing all this again the same error kept on throwing.

Wait i remember something, i checked the right hand side BO (to BO) to which value needs to be assigned. That particular BO was null. Why this ? :-(

There is a file named map.config.properties which is located in
runtimes/properties/ folder of your WID/WPS installation location. That file has an important property set which is

createChildBOsbyDefault=false




if this is set to false if there is custom mapping where the value needs to set to a particular field of the BO, at first we need to create the BO otherwise there should be move option to that particular. unless the above two occurs the BO will be always null. If you try to assign a value to field in the BO. It will throw null pointer exception (check the above screenshot)

In order to overcome the issue, before doing a custom assign to variable to the BO, first create that BO or make a move. The move should be always before the custom assign (exceution order) check the below screen shot

Thursday, February 05, 2009

using promoted properties websphere enterprise service bus aka ESB

The concept of the promoted property is dynamic change without restarting or reinstalling the application again. ESB is used mostly in integeration space. Each and every down time of app change counts. This is very good feature. The implemenatation example goes like this.

For example there is two type of implementations which will be used in the mediation flow, only one of the implementation will be used which one to use will can be configured using the promoted property.


Use "MessageFilter" primitive. In the details select the distribution as "First" . And in the filters tab using xpath create two terminals "match1" and "match2".Click on the promoted properties you can see the filter property is promoted field. select the two field and give alias name different.

Wire the "match1" terminal to one application and "match2" to other application.


Deploy the application. Log in to the admin console. Go the sca modules. This will display all the applications deployed in the server.Select the application and then select mdoule properties there you can see your two properties



Give the value such that it passes one condition (it will use one application at a time). If you gave both the conditions as true. since you have given distribution as first. The first condtion matched terminal will be fired.

If you want all the terminals to be fired then set the distribution property as "All". It will the check all the conditions and fires which ever matching

Tuesday, January 27, 2009

Calling Stand alone reference from an EJB

It is as simple as mentioned, calling stand alone reference from an EJB. Create an EJB project let us use stateless session bean here as an example. In the EJB bean add the method which you want to call and use the piece of below code.

ServiceManager serviceManager = new ServiceManager();
(interface) service= (interface)serviceManager.locateService("");

After the lookup, with the help of service call the interface
and the operation with the parameters

service.operationname(parameters);

Add the newly created EJB project to your BEPL/Mediation Module App or project.
While creating the EJB project itself you will see option for
specifying App project,At the place use the ModuleApp Project Name.

For testing the EJB, use universalTestClient http://localhost:9080/UTC/

Thursday, January 08, 2009

CWWBV0003E: Validated process model ''{0}'' with findings: {1} errors, {2} warnings, {3} information: {4}

Now this is error added to my favorite error list, i have rarely seen this when working in 6.0.2. But after migrating to 6.1.2 this has become a regular, I have added it in my checklist.

SystemErr R com.ibm.bpe.plugins.BPELValidationException: CWWBV0003E: Validated process model 'SampleComponent' with findings: 1 errors, 0 warnings, 0 information:
CWWBV3011E: The XSD type definition 'Sample' was not found (process variable 'sample').
at com.ibm.bpe.validation.BPELValidation.writeProblemsToSystemOutWithException(BPELValidation.java:1378)
at com.ibm.bpe.validation.BPELValidation.validateExecutableBPELExtensionsProcess(BPELValidation.java:842)
at com.ibm.bpe.validation.BPELValidation.validateExecutableBPELExtensionsProcess(BPELValidation.java:674)
at com.ibm.bpe.management.application.process.ProcessSCAArchive.loadBPELResource(ProcessSCAArchive.java:795)
at com.ibm.bpe.management.application.process.ProcessSCAArchive.createBPELContext(ProcessSCAArchive.java:273)
at com.ibm.bpe.management.application.process.ProcessSCAArchive.initBPELProcessContexts(ProcessSCAArchive.java:222)
at com.ibm.bpe.management.application.process.ProcessSCAArchive.(ProcessSCAArchive.java:134)
at com.ibm.bpe.management.application.process.ProcessSCAArchive.(ProcessSCAArchive.java:169)
at com.ibm.bpe.management.application.process.ProcessSCAArchive.(ProcessSCAArchive.java:145)
at com.ibm.bpe.processarchive.SCDLProcessComponentConfigureTask.performTask(SCDLProcessComponentConfigureTask.java:129)
at com.ibm.ws.management.application.SchedulerImpl.run(SchedulerImpl.java:262)
at java.lang.Thread.run(Thread.java:810)

As per our initial analysis we figured that the library files which specified in the dependencies are not getting bundled while deploying. we confirmed that by extracting the EAR file of the module. The solution to the problem if the dependencies are not getting correctly bundled then follow these steps

  • remove everything under .settings folder and recompile so that these files will be regenerated from scratch
  • Check the MANIFEST.MF file under META-INF, if any dependency are missing add it manually
  • Do a clean build
  • Export the ear file and check the ear file for the dependency projects
  • If everything looks ok now deploy the application
Note : This may be not 100% solution, the error may be due to some other issue. The solution works only if dependency not getting bundled with the EAR

Tuesday, December 30, 2008

Business Process not deploying (com.ibm.bpe.util.VersionInfo.(VersionInfo.java:52))

I was trying to publish the application (Business process) module in WID to the server. The server was kept on throwing the error
000000c1 SystemErr R java.lang.NullPointerException
000000c1 SystemErr R at java.util.StringTokenizer.(StringTokenizer.java:197)
000000c1 SystemErr R at java.util.StringTokenizer.(StringTokenizer.java:219)

000000c1 SystemErr R at com.ibm.bpe.util.VersionInfo.(VersionInfo.java:52)

00000c1 SystemErr R at com.ibm.bpe.util.VersionInfo.(VersionInfo.java:47)
000000c1 SystemErr R at com.ibm.bpe.management.application.DeploymentTargetContext.initNodeVersionMap(DeploymentTargetContext.java:565)
000000c1 SystemErr R at com.ibm.bpe.management.application.DeploymentTargetContext.(DeploymentTargetContext.java:98)
000000c1 SystemErr R at com.ibm.bpe.management.application.AbstractDeploymentTask.getDeploymentTargetContexts(AbstractDeploymentTask.java:260) 000000c1 SystemErr R at com.ibm.bpe.processarchive.SCDLProcessComponentConfigureTask.performTask(SCDLProcessComponentConfigureTask.java:301) 000000c1 SystemErr R at com.ibm.ws.management.application.SchedulerImpl.run(SchedulerImpl.java:262)
SystemErr R at java.lang.Thread.run(Thread.java:810)


Then i found that i was trying to publish a module to ESB server. I started the websphere process server and published the project. It was successfully published and started. BPEL modules cannot be published on ESB. If you are getting this error first check this and add it to your checklist

Friday, December 12, 2008

WID+ClearCase (Killer Combination)

Yes exactly its a Killer Combination WID+Clearcase (WebSphere Integeration Developer+ClearCase). It can easily take away all of your development time by making some wild assumptions !!!!. I think when these guys get togther they have AI (Artifical Inteligence) or the Seventh Sense. My God ... no even god can't save you. We have been using this combination WID+Clearcase for the past two years.In a way its good b'coz its good CM(Configuration Management) tool.


For us it started with one fine day, when i started my machine and opened my WID did a clean Build (Alt+p+n). I see hell lot of errors. I got scared b'coz we were in middle of our testing cycle. I started checking am i the culprit. All the error was leading to XSD file. when i opened the file it had .............. I am not adding etc.. dots here guys. Its the dot(.) character i see at the end of the file. Hurray i can find who did this checked in clearcase about the history no one has edited the file from the creation date. I got confused and deleting the unwanted character did Alt+p+n.

Everything was normal. Couple of days gone, the monster returns back this time not only in machine space, couple of other machines too faced but with different files. S...t i had this bug did the same thing and cleaned it. From that day still we are getting this issue. Earlier it was only on XSD file It has grown and it managed to spread to .java, .mon , .bpel, .import, .sca module ...... yes all the project files.

One improvement with the issue, it started adding some other characters other than dot to the file. But it has been consistent it adds only at the last

The only solution for this is to checkout the file delete the character and check in again. we have raised a PMR a longgggggggg back. IBM as usual started asking all the log files and their list of documents. We have provided them but they say they are not able reproduce this.

Hope they never. So the only solution is the above one.

Its weekend guys enjoy.... take a break from work ....

Tuesday, October 21, 2008

Clean Logs from WID

Since we were in development mode we are used to make lot of mistakes like killing server in between killing BPEL process without completing, enabling security and disabling and lotsss of other things. Due to this activity you see lot of errors in the SystemOut.log file while starting your server. The most important thing to look in the SystemOut.log file. "Server1 is open for e-business". The rest of error most of them you can ignore (i am not 100% on this). In order to clean log file delete the tranlog and partner log file from the tranlog folder under your profile folder. Restart the server you will find (60%) a clean log file. But do not do this activity on your production server. This method is intend for easing the pain of looking to large log file during the development phase of the project

Friday, August 08, 2008

Human Task Escaltion Settings

While using human task in BPEL, if particular task is not actioned with in a configured time period. we can configure to escalate that through E-mail, Work Item or Event. In event we can customize how we want to handle the escalation. The human tasks which are claimed, ready and subtask started can be configured to escalate.



We have done with event. I will explain how to escalate human task using event. Select any one of the escalation type and create a escalation. In the details tab configure the values you need

Excepted Task State, Escalate After (Time), Notification Type and others.


Escalate After is the time configurable when escalation is to triggered after creation of task, It can be mentioned or it can be dynamic. For dynamic configuration you should pass the time as input to the Human task and you can access like this

%htm.input.<interfacename>HTParamaters\<inputBO Variable
Name>\<Variable holding value>





For example the time values can be like

10 Seconds, 10 hours, 10 minutes


In the Notification Type select Event

Select any where in the Human Task Editor go to the properties tab in details section there will be input place holder for Event handler name, give the class name of the eventHandler.


Now create the class with the name given in the event Handler input box that class should implement NotificationEventHandlerPlugin. This class has a method named escalationNotification with parameters taskID and escalation. with taskid you can get the input values of HT and do the what ever your escalation implementation as designed

TKIID tkiid = task.getID();
String HT_EJB="local:ejb/com/ibm/task/api/HumanTaskManagerHome"
context = new javax.naming.InitialContext();
LocalHumanTaskManagerHome localTaskHome =
(LocalHumanTaskManagerHome)context.lookup();
LocalHumanTaskManager taskManager = localTaskHome.create(HT_EJB);
ClientObjectWrapper clientObjectWrapper =taskManager.getInputMessage(tkiid);
DataObject inputDO = (DataObject) clientObjectWrapper.getObject();




Afer completeion of coding of go the project resources view create a folder name services inside META-INF folder, create a file inside the folder with the name of com.ibm.task.spi.<EventHandlerClassName>NotificationEventHandlerPlugin. Inside the file in the first line type the fully classified name of the event handler.

Upto this is WID. Now from WPS perpective. After installing the application. Go the TaskContainer application, browse through the link Map RunAs roles to users. Here you will see a user can be configured to run the escalation. If there is mismatch between the user which you have configured in Human Task the escalation task will fail.

The better approach is to use groups while configuring Human Task, create a user assign that user to the particular group and use that user as the run as user.

Thursday, July 10, 2008

Sharing your DataPool values across workspace WID

During development we are forced to use different workspace because of n number of issues. If we do changing the workspace we will lose that data which we added in our datapool while using TestComponent facility in WID. To over come this we found shortcut go to your old workspace folder open .metdata folder under that look
folder named com.ibm.wbit.comptest.ui copy that folder.

Paste the folder in your new workspace .metedata folder. Bravo !!!! you got all your old datapool values no need of entering again.

Thanks to keshav who gave this tip to us.


Tuesday, July 08, 2008

uninstall applications which has process instace running or hanging WPS/WID

Most of us face this problem in development some times (sry most of the times :-) ) we are not able to uninstall application which has process instance running. you will not be able to terminate the process or stop. To overcome this, there is a solution which i found in WID forums thought of sharing good one. use the below command to do the uninstall of application

Go to u r bin directory and run this command

wsadmin -lang jacl -f ../ProcessChoreographer/admin/bpcTemplates.jacl -uninstall MyModuleApp
-force

In the place of MyModuleApp give your application name. This commands connects to the server and unistall the application.

Click here to the solution page at WID Forum

Wednesday, June 25, 2008

Quick publishing your application to Process server (using WID)

While doing development you will be changing lot of things in your code. To test those changes usually we used to restart the project.But WID(WebSphere Integeration Developer) has smart option, After completing your changes build the application.Go to problem tab you can see a message stating that your project has changed need to be reinstalled in server. Select the particular row, and right click there you will see a option called Quick Fix. This option will replace the files which has got modified. Your publishing process became faster now :-)

Wednesday, June 04, 2008

Accessing private methods using JUNIT

If you want to test private method of class which has object's as arguments here is the example to how do it.

First SampleObject



package com.sathish;
public class Sample {
public String example;
public String example1;
/**
* @return Returns the example.
*/
public String getExample() {
return example;
}
/**
* @param example The example to set.
*/
public void setExample(String example) {
this.example = example;
}
/**
* @return Returns the example1.
*/
public String getExample1() {
return example1;
}
/**
* @param example1 The example1 to set.
*/
public void setExample1(String example1) {
this.example1 = example1;
}
}



 


Second the Class with private method

package com.sathish;
public class SampleMain {

private Sample getSampleValues(Sample sample)
{
System.
out.println(" Sample Values Setting in SampleMain"+sample.getExample());
return sample;
}
}


 



Third JUNIT Class File



package com.sathish;

import java.lang.reflect.Method;
import junit.framework.TestCase;

public class SampleTest extends TestCase {
/*
* @see TestCase#setUp()
*/
private Sample sample;
private SampleMain sampleMain;
protected void setUp() throws Exception {

sample=
new Sample();
sampleMain=
new SampleMain();
}
public final void testGetSampleValues()
{
try
{
sample.setExample(
" setting Example 1");
final Method[] methods = SampleMain.
class.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("getSampleValues")) {
final Object
params[] = {sample};
methods[i].setAccessible(
true);
sample = (Sample)methods[i].invoke(sampleMain,
params);
}
}
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


 


 

If you check in the JUNIT class, we will be using reflections to find the method and invoke .getDeclaredMethods() method will give array of methods declared in the SampleMain class looping through the methods we are getting the method which has declared private here getSampleValues.

Then we are preparing arguments, setting that particular method accessible and then invoking method with arguments



finally this the output after running the JUNIT file

Sample Values Setting in SampleMain setting Example 1

Tuesday, July 24, 2007

Filters for Authentication & Security


In developing web application security is the most important one,for example a web application is running on port number 8080 (default for tomcat) the application name be Sample.For connecting the application we will
the type the following address in the url http://localhost:8080/Sample and then logging inside the application the url changes as you click the pages and navigate inside the app.Try to collect any of the url from the app that your r navigating and and paste in different browser if that particular page is opened then your app needs as security checks.In Java there is cool concept called Filters.

Filters are are application-level Java code components within a J2EE Web application.They can act as gatekeeper's to your web-app checking the logging in credentials, validating from which page request came and the other very useful things

In the web.xml you have to define the filters



<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>com.filter.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>



In the above mapping whatever request goes to your web-app it is first intercepted by Filter

Filter has ServletRequest and ServletResponse you need it to type cast to HttpServletRequest and HttpServletResponse for getting the username from the request and session. The Logic of the below program is simple.

we are checking whether the request comes from the loginpage if yes the user has entered username in the loginpage so the parameter we are getting using request and checking whether that value is null if it is not null then setting that value to session and leaving the process to application.

If the request is not from the loginpage we are checking whether the username is in session if yes then allow him to go through the app if not throw the user to login page and ask him to enter


Sample Filter Code



public class AuthFilter implements Filter {

private FilterConfig config;

public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
this.config=arg0;
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

/* Type Casting request and response */
HttpSession session = ((HttpServletRequest) request).getSession();
ServletContext context = config.getServletContext();
HttpServletResponse serresponse=(HttpServletResponse)response;
/*
* use the ServletContext.log method to log filter messages
*/
String AUTH_PAGE="/LoginPage.jsp";
String username=null;
String sessusername=null;
String filename=null;
HttpServletRequest serrequest=null;
serrequest=(HttpServletRequest)request;
/* Getting the File Name */
filename=serrequest.getServletPath()+serrequest.getPathInfo();

/* Checking the File Name*/
if(AUTH_PAGE.equals(filename))
{
/* Getting the username from the MainPage */
username=serrequest.getParameter("usernname");
if(username==null)
{
sessusername=(String)session.getAttribute("usernname");
if(sessusername==null&&sessusername.trim().equals(""))
{
serresponse.sendRedirect(serrequest.getContextPath()+AUTH_PAGE);
}
serresponse.sendRedirect(serrequest.getContextPath()+AUTH_PAGE);
}
session.setAttribute("username",username);
chain.doFilter(request, response);
}
else
{ if(session.getAttribute("username")!=null&&!session.getAttribute("username").toString().trim().equals(""))
{
chain.doFilter(request, response);
}
else
{

serresponse.sendRedirect(serrequest.getContextPath()+AUTH_PAGE);
}
}
}

public void destroy() {
}
}

Powered by ScribeFire.

Sunday, July 15, 2007

Reading xml from WEB-INF Directory and Building XML Document

We had a requirement of reading a xml file from the WEB-INF folder of web-app
and to build a xml document from the file, after building the document its very much easy to
parse through the document and get the date.Here are the steps and code-snippets to do it.

Since its a web-app we need to get the ServletContext.


ServletContext context = pageContext.getServletContext();



After getting the context we need get the file as Stream for building xml document


InputStream inputStream=context.getResourceAsStream("/WEB-INF/example.xml");



We have got the inputStream we need a build the xml document.The below DomRead.java
will build the document


Document document = DomReadUtil.parse(inputStream);




public class DomRead
{
public static Document parse(InputStream stream )
{
Document document = null;
// Initiate DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// To get a validating parser
factory.setValidating(false);
// To get one that understands namespaces
factory.setNamespaceAware(true);
try
{
// Get DocumentBuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// Parse and load into memory the Document
document = builder.parse(stream);
return document;
}
catch (SAXParseException spe)
{
// Error generated by the parser
System.out.println("\n** Parsing error , line " + spe.getLineNumber()
+ ", uri " + spe.getSystemId());
System.out.println(" " + spe.getMessage() );
// Use the contained exception, if any
Exception x = spe;
if (spe.getException() != null)
x = spe.getException();
x.printStackTrace();
}
catch (SAXException sxe)
{
// Error generated during parsing
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
}
catch (ParserConfigurationException pce)
{
// Parser with specified options can't be built
pce.printStackTrace();
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
}
return null;
}
}



Now we got the XMLDocument document we can parse the xml document and get the
information we need.

Note :

The inputStream passing to the DomRead.java should be opened or Read, if so it will give
Premature End Of File - SaxParseException.


ServletContext context = pageContext.getServletContext();
InputStream inputStream=context.getResourceAsStream("/WEB-INF/example.xml");
StringBuffer sb=new StringBuffer();
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
while(br.readLine()!=null)
{
sb.append(br.readLine()+"\n");
}
System.out.println("fpath "+sb.toString());
Document document = DomReadUtil.parse(inputStream);



The above code will give you Premature End Of File - SaxParseException.Because we have opened the inputStream and Read the contents.when trying to build the Doc from the stream,its already read.so there is premature end of file