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

Thursday, February 09, 2017

Serialize and Deserialize Object in java

Sample Data Class
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package sample.test;

import java.util.Vector;

public class MyXML implements java.io.Serializable {

 String name;
 String value;
 Vector subtree = new Vector();

 public MyXML() {
 }

 public void insert(MyXML x) {
  subtree.addElement(x);
 }

 static final long serialVersionUID = 1L;
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package sample.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeTest {
 public static void main1(String[] args)
 {
  try
  {
      ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("empInfo.ser"));
      MyXML emp = new MyXML();
   emp.name = "test";
   emp.value = "1";
      //Serialize the object
      oos.writeObject(emp);
      oos.close();
  } catch (Exception e)
  {
      System.out.println(e);
  }

 }

 public static void main(String[] args) {
  try {
   ObjectInputStream ooi = new ObjectInputStream(new FileInputStream(
     "empInfo.ser"));
   // Read the object back
   MyXML readEmpInfo = (MyXML) ooi.readObject();
   System.out.println(readEmpInfo.name);
   System.out.println(readEmpInfo.value);
   ooi.close();
  } catch (Exception e) {
   System.out.println(e);
  }

 }
}

Thursday, June 16, 2016

How to get the referred/called url

I want to find the URL from which my page is called or from which my page is redirected. The example is given below.


Example
@InjectObject(value = "service:tapestry.globals.RequestGlobals")
public abstract RequestGlobals getRequestGlobals();

HttpServletRequest httpServletRequest = requestGlobals.getRequest();
String referrer =httpServletRequest.getHeader("referer");

Wednesday, July 22, 2015

Send a file as attachment from webservice to client using Axis2 Axioms

WebService
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public String executeWebServiceXML(OMElement element){
  FileDataSource fileDataSource=null;
  DataHandler fileDataHandler=null;
  MessageContext inMessageContext = MessageContext.getCurrentMessageContext();
  OperationContext operationContext = inMessageContext.getOperationContext();
  MessageContext outMessageContext = null;
  try {
    outMessageContext = operationContext
     .getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
  } catch (org.apache.axis2.AxisFault e) {
  }
  String paramCode = element.getFirstChildWithName(new QName("http://mywebservice.webservices.com","paramCode")).getText();
  String paramDate = element.getFirstChildWithName(new QName("http://mywebservice.webservices.com","paramDate")).getText();
  
   String folderPath="D://test":

  String filePath = folderPath +File.separator+ merchantCode+SplCharsConstants.UNDERSCORE+refundDate+ FileExtenConstants.XML;
  fileDataSource = new FileDataSource(filePath);
  fileDataHandler = new DataHandler(fileDataSource);
  String dataHandlerId = outMessageContext.addAttachment(fileDataHandler);
  createDownloadStatisticsElement(dataHandlerId);
  return dataHandlerId;
 }
  
 private OMElement createDownloadStatisticsElement(String dataHandlerId) {
  OMFactory factory = OMAbstractFactory.getOMFactory();
  OMNamespace omNs = factory.createOMNamespace("http://mywebservice.webservices.com", "swa");
  OMElement wrapperElement = factory.createOMElement("getStatsResponse", omNs);
  OMElement dataElement = factory.createOMElement("getElementResponse", omNs, wrapperElement);
  dataHandlerId = "cid:"+dataHandlerId;
  dataElement.addAttribute("href", dataHandlerId,null);
  return wrapperElement;
 }
 
Client
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public static void main(String[] args) {
  final String ENDPOINT="http://localhost:8080/webservice/services/myWebService.MyWebServiceHttpSoap11Endpoint/";
  EndpointReference targetEPR = new EndpointReference(ENDPOINT);
  Options options = new Options();
  options.setTo(targetEPR);
  options.setAction("urn:executeWebService");
  options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
  ServiceClient sender=null;
  try {
   sender = new ServiceClient();
   sender.setOptions(options);
   OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);
         MessageContext messageContext = new MessageContext();
         SOAPEnvelope env = createEnvelope();
         messageContext.setEnvelope(env);
   mepClient.addMessageContext(messageContext);
   mepClient.execute(true);
   MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
   SOAPBody body = response.getEnvelope().getBody();
   OMElement element1 = body.getFirstElement();
   String dataHandlerId =element1.getFirstElement().getText();
   DataHandler dataHandler= response.getAttachment(dataHandlerId);
         if (dataHandler!=null){
    File xMLFile = new File("c://temp/new.xml");
    FileOutputStream outputStream = new FileOutputStream(xMLFile);
    dataHandler.writeTo(outputStream);
    outputStream.flush();
         }
  } catch (AxisFault e) {
  } catch (FileNotFoundException e) {
  } catch (IOException e) {
  }
 }

 private static SOAPEnvelope createEnvelope() {
  SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
  SOAPEnvelope env = fac.getDefaultEnvelope();
  OMNamespace omNs = fac.createOMNamespace("http://mywebservice.webservices.com","swa");
  OMElement statsElement = fac.createOMElement("executeWebService",omNs);
  OMElement root = fac.createOMElement("root",omNs);
  OMElement nameEle = fac.createOMElement("paramCode", omNs);
  nameEle.setText("test");
  OMElement nameEle1 = fac.createOMElement("paramDate", omNs);
  nameEle1.setText("20150719");
  statsElement.addChild(root);
  root.addChild(nameEle);
  root.addChild(nameEle1);
  env.getBody().addChild(statsElement);
  return env;
 }
}

Send a File from server to client using Axis2 Web Service

Web Service
1
2
3
4
5
6
7
8
9
public DataHandler executeWebService(String param1,String param2){
  DataHandler actualDH=null;
  try {
    actualDH = new DataHandler(new URL("file:///D:\\test\\NEW.xml"));
  } catch (MalformedURLException e) {
  }
  return actualDH;
  
 }
Client
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
 public static void main(String args[]) throws java.lang.Exception {
             RPCServiceClient serviceClient = null;;
         try
         {
             serviceClient = new RPCServiceClient();
         }
         catch (AxisFault e1)
         {
             e1.printStackTrace();
         }

         Options options = serviceClient.getOptions();
         EndpointReference targetEPR = new EndpointReference(
            "http://localhost:8080/webservice/services/myWebService.MyWebServiceHttpSoap11Endpoint/");
         options.setProperty(Constants.Configuration.ENABLE_MTOM,
                 Constants.VALUE_TRUE);
         options.setAction("urn:executeWebService");
         options.setTo(targetEPR);
         QName opName = new QName("http://my.webservices.com", "executeWebService");
         Object[] opSetArgs = new Object[0];
          Class[] returnTypes = new Class[] { DataHandler.class };

          try
          {
              Object[] response = serviceClient.invokeBlocking(opName, opSetArgs,
                      returnTypes);
              DataHandler actualDH;
              actualDH = (DataHandler) response[0];// get the binary data
              System.out.println(actualDH);

              //Received file will be available in this location.
              File graphFile = new File("D://test//NEW1.xml");
              if (!graphFile.exists())
              {
                  try
                  {
                      graphFile.createNewFile();
                  }
                  catch (IOException e)
                  {
                      e.printStackTrace();
                  }
              }
                  FileOutputStream outputStream = null;
                  try
                  {
                      outputStream = new FileOutputStream(graphFile);
                  }
                  catch (FileNotFoundException e)
                  {
                      e.printStackTrace();
                  }
                  try
                  {
                      actualDH.writeTo(outputStream);
                  }
                  catch (IOException e)
                  {
                      e.printStackTrace();
                  }
           
          } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } 
             }

Monday, January 27, 2014

How to write methods of java file to text file

The below example shows you how to write contents of java file to a text file.


Step 1: Open cmd.exe
Step 2: First go to the folder which contains the class file of the java file
Step 3: Execute the line javap filename >test.txt
            where filename is the name of the class file.(Do not enter extension)


Now you will see a text file created in the folder with the given file name;

Friday, September 20, 2013

CAS Client with Java web.xml

We have configured the CAS Server in the previous blog post. Now we will see how to call it from client ie. in Projects where Single Sign On is needed.
 
Download CAS-Client and go to module folder. add all the jar files in the folder to your project library.
 
The following configurations are to be added to your web.xml for adding CAS Single Sign on to your project
  1. AuthenticationFilter
  2. TicketValidationFilter (whichever one is chosen)
  3. HttpServletRequestWrapperFilter
  4. AssertionThreadLocalFilter

Add the below to web.xml file

<filter>
<filter-name>CAS Authentication Filter</filter-name>
<filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>
<init-param>
         <param-name>casServerLoginUrl</param-name>
          <param-value>https://localhost/cas-server-webapp-3.5.2/login</param-value>
</init-param>
<init-param>
          <param-name>serverName</param-name>
          <param-value>http://localhost:8080</param-value>
</init-param>
<init-param>
         <param-name>renew</param-name>
          <param-value>false</param-value>
</init-param>
<init-param>
        <param-name>gateway</param-name>
         <param-value>false</param-value>
</init-param>
</filter>

<filter>
<filter-name>CAS Validation Filter</filter-name>
<filter-class>org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter</filter-class>
<init-param>
       <param-name>casServerUrlPrefix</param-name>
       <param-value>https://localhost/cas-server-webapp-3.5.2</param-value>
</init-param>

<init-param>
         <param-name>serverName</param-name>
         <param-value>http://localhost:8080</param-value>
</init-param>

<init-param>
      <param-name>proxyCallbackUrl</param-name>
      <param-value>http://localhost:8080/webappcas2/proxyCallback</param-value>
</init-param>

<init-param>
       <param-name>proxyReceptorUrl</param-name>
       <param-value>/webappcas2/proxyCallback</param-value>
</init-param>

</filter>
 
<filter>
            <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>
          <filter-class>org.jasig.cas.client.util.HttpServletRequestWrapperFilter</filter-class>
</filter>
 
<filter>
            <filter-name>CAS Assertion Thread Local Filter</filter-name>
            <filter-class>org.jasig.cas.client.util.AssertionThreadLocalFilter</filter-class>
</filter>
 
<filter-mapping>
         <filter-name>CAS Authentication Filter</filter-name>
          <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
         filter-name>CAS Validation Filter</filter-name>
         <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
      <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>
      <url-pattern>/*</url-pattern>
</filter-mapping>
 
<filter-mapping>
       <filter-name>CAS Assertion Thread Local Filter</filter-name>
       <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
        <filter-name>CAS Validation Filter</filter-name>
        <url-pattern>/proxyCallback</url-pattern>
</filter-mapping>

Setting up CAS Server for JDBC Postgres

We are going to see on how to setup CAS Server for Post gres.database. This is for single sign on

Click here to Download CAS Server.

 What you are viewing is the folder structure of the CAS Server you have downloaded.

Go to modules folder.

Take the cas-server-webapp-3.5.2.war and deploy it in your tomcat.

Start the tomcat server. Now the war will be deployed. Now stop the tomcat server and remove the cas-server-webapp-3.5.2.war file from server so that it will not overwrite the folder deployed.

Copy cas-server-support-jdbc-3.5.2.jar from Modules folder and put it inside the webapps\cas-server-webapp-3.5.2\WEB-INF\lib folder

This jar is required for JDBC Connection.

As we are using Postgres we need to download the driver for it. Please Download

We also require 2 more jars. Also download these jars mentioned below.

     commons-dbcp-1.2.2.jar

     commons-pool-1.2.jar

Put all the jars in the same path webapps\cas-server-webapp-3.5.2\WEB-INF\lib


Go to the WEB-INF folder. you will see the folder structure as shown here. Open the deployerConfigContext.xml file and modify the contents as shown below.

Search for the line below

<bean class="org.jasig.cas.authentication.handler.support. SimpleTestUsernamePasswordAuthenticationHandler" />
 </list>
  </property>
 </bean>
Replace it with below code



     <bean class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">
        <property name="dataSource" ref="dataSource" />
        <property name="sql" value="select password from user_list where lower(user_name) = lower(?)" />
      </bean>

        
           </list>
        </property>
    </bean>
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
     <property name="driverClassName">
      <value>org.postgresql.Driver</value>
     </property>
     <property name="url">
      <value>jdbc:postgresql://localhost:5432/testing</value>
     </property>
     <property name="username">
      <value>postgres</value>
     </property>
     <property name="password">
      <value>postgres</value>
     </property>
    </bean>

Now run the apache tomcat and go to url https://localhost/cas-server-webapp-3.5.2/login
If it is working correctly, you should see authentication screen.

Monday, August 05, 2013

Get Absolute Url in Tapestry4 and Tapestry5

In Tapestry 4 for getting the absolute Url we use
IRequestCycle obCycle = (IRequestCycle)event.getRequestCycle();
obCycle.getAbsoluteURL("/app?page=Login&service=page");
In Tapestry5 we can use the below code to get the absolute url.
@Inject
PageRenderLinkSource linkSource;

Link link = linkSource.createPageRenderLinkWithContext(
                "DepartmentMasterPG",
                5);
String s = link.toAbsoluteURI();

Thursday, August 01, 2013

ValidationDelegate in Tapestry4 is recordError in Tapestry5

In Tapestry4 we are using

ValidationDelegate delegate = (ValidationDelegate)getBeans().getBean("delegate");

to validate and show the error. In Tapestry5 it is obsolete. In Tapestry5 we need to create as shown below

Page

 

<form t:type="form" t:id="departmentMasterList">
<t:errors />

@Component
private Form departmentMasterList;

Java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
void onValidateFromDepartmentMasterList() {
 Iterator<DepartmentMasterListVO> iter = deptMasterList.iterator();
 while (iter.hasNext()) {
  DepartmentMasterListVO departmentListVO = iter.next();
  if (!departmentListVO.getCategory().equals("Test")) {
   departmentMasterList.recordError("Category entered is wrong");
   break;
  }
 }
}

In Method onValidateFromDepartmentMasterList DepartmentMasterList is the form Name given in Page.

In the above example I am iterating through a list and checking whether category contains a specific value. This is just for testing only. So now when you press the button, it will go to the above method (OnValidateFrom) if the validation fails, it will display the given message in the location where we have given <t:errors />. If there is any error, the program will not call the OnSuccess