Thursday, January 9, 2014

Sample on Accessing the Web Service Context

JAX-WS Sample
==============
package temp;

import javax.jws.*;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import javax.servlet.http.HttpServletRequest;
import javax.annotation.Resource;
import javax.xml.ws.BindingType;
import javax.xml.ws.soap.SOAPBinding;

public class MyWS {

@Resource(name="wsContext")
private WebServiceContext wsContext;

public String hello() {
String reqInfo = getRequestInfo();
return reqInfo;
}

private String getRequestInfo() {
return ((HttpServletRequest)(wsContext.getMessageContext().get(MessageContext.SERVLET_REQUEST))).getRemoteAddr();
}
}
JAX-RPC Sample
=================
package test;

import javax.jws.*;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.rpc.server.ServletEndpointContext;
import javax.xml.rpc.ServiceException;
import weblogic.wsee.message.WlMessageContext;
import weblogic.wsee.connection.Connection;
import weblogic.wsee.connection.transport.Transport;
import weblogic.wsee.connection.transport.servlet.HttpServerTransport;
import javax.xml.rpc.server.ServiceLifecycle;

import weblogic.webservice.context.*;
public class ServiceImpl implements ServiceLifecycle{

private WebServiceContext wsContext;
private ServletEndpointContext wsctx = null;

public void init(Object context) throws ServiceException {
System.out.println("ServletEndpointContext inited...");
wsctx = (ServletEndpointContext)context;
}
public String getRemoteAddress() {
WlMessageContext msgCtx = (WlMessageContext)wsctx.getMessageContext();
Connection conn = msgCtx.getDispatcher().getConnection();
Transport transport = conn.getTransport();

if (transport instanceof HttpServerTransport) {
return ((HttpServerTransport)transport).getRequest().getRemoteAddr();
}
else {
return null;
}
}

public void destroy() {}
public String helloWorld(){
String reqInfo = getRemoteAddress();
return "Hi";
}
}

Sample on Accessing the Web Service Context

JAX-WS Sample
==============
package temp;

import javax.jws.*;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import javax.servlet.http.HttpServletRequest;
import javax.annotation.Resource;
import javax.xml.ws.BindingType;
import javax.xml.ws.soap.SOAPBinding;

public class MyWS {

@Resource(name="wsContext")
private WebServiceContext wsContext;

public String hello() {
String reqInfo = getRequestInfo();
return reqInfo;
}

private String getRequestInfo() {
return ((HttpServletRequest)(wsContext.getMessageContext().get(MessageContext.SERVLET_REQUEST))).getRemoteAddr();
}
}
JAX-RPC Sample
=================
package test;

import javax.jws.*;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.rpc.server.ServletEndpointContext;
import javax.xml.rpc.ServiceException;
import weblogic.wsee.message.WlMessageContext;
import weblogic.wsee.connection.Connection;
import weblogic.wsee.connection.transport.Transport;
import weblogic.wsee.connection.transport.servlet.HttpServerTransport;
import javax.xml.rpc.server.ServiceLifecycle;

import weblogic.webservice.context.*;
public class ServiceImpl implements ServiceLifecycle{

private WebServiceContext wsContext;
private ServletEndpointContext wsctx = null;

public void init(Object context) throws ServiceException {
System.out.println("ServletEndpointContext inited...");
wsctx = (ServletEndpointContext)context;
}
public String getRemoteAddress() {
WlMessageContext msgCtx = (WlMessageContext)wsctx.getMessageContext();
Connection conn = msgCtx.getDispatcher().getConnection();
Transport transport = conn.getTransport();

if (transport instanceof HttpServerTransport) {
return ((HttpServerTransport)transport).getRequest().getRemoteAddr();
}
else {
return null;
}
}

public void destroy() {}
public String helloWorld(){
String reqInfo = getRemoteAddress();
return "Hi";
}
}

Weblogic Web service Debug flags

For advance debug logging in webservice, you can enable debugs on Weblgic webservice by adding the following -D flags to your server startup script, then restart Weblogic server: 
  • Security related:
    -Dweblogic.wsee.security.verbose=true
    -Dweblogic.wsee.security.debug=true
    -Dweblogic.debug.DebugSecurityCredMap=true
  • Crypto related:

    -Dweblogic.xml.crypto.encrypt.verbose=true
    -Dweblogic.xml.crypto.dsig.debug=true
    -Dweblogic.xml.crypto.dsig.verbose=true
    -Dweblogic.xml.crypto.wss.debug=true
    -Dweblogic.xml.crypto.wss.verbose=true
    -Dweblogic.xml.crypto.keyinfo.debug=true
    -Dweblogic.xml.crypto.keyinfo.verbose=true
    -Dweblogic.xml.crypto.dsig.debug=true
    -Dweblogic.xml.crypto.dsig.verbose=true
    -Dweblogic.xml.crypto.encrypt.debug=true
    -Dweblogic.xml.crypto.encrypt.verbose=true
  • SAML related:

    -Dweblogic.debug.DebugSecuritySAMLService=true
    -Dweblogic.debug.DebugSecuritySAMLCredMap=true
    -Dweblogic.debug.DebugSecuritySAMLAtn=true
    -Dweblogic.debug.DebugSecuritySAMLLib=true
    -Dweblogic.debug.DebugSecuritySAML2Service=true
    -Dweblogic.debug.DebugSecuritySAML2CredMap=true
    -Dweblogic.debug.DebugSecuritySAML2Atn=true
    -Dweblogic.debug.DebugSecuritySAML2Lib=true
  • General:

    -Dweblogic.log.StdoutSeverity=Debug
    -Dweblogic.wsee.verbose=weblogic.wsee.conversation.*, weblogic.wsee.callback.*
    -Dweblogic.webservice.verbose=true
    -Dweblogic.wsee.debug=*
    -Dweblogic.wsee.verbose.timestamp=true
For logging of http request and response with Metro webservice, add the following to your server startup script, and restart Weblogic Server:
  • General:
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true
You can selectively enable the relevant debug flags, as needed.  By default, all logging goes to the WLS server log.
Note:  You can add more verbose debugging from individual subsystem in webservice using -Dweblogic.wsee.verbose by listing the subsystems in comma-separated list, as shown above. Alternatively, you can use use -Dweblogic.wsee.verbose=* to output all the debug logging.

Weblogic Classloader Debug Flags

Here's the list of Weblogic Server Classloader Debug flags that can be set in the start up scripts of weblogic server. 
-Dweblogic.utils.classloaders.GenericClassLoader.Verbose=true
-Dweblogic.utils.classloaders.ChangeAwareClassLoader.Verbose=true
-Dweblogic.utils.classloaders.ClasspathClassFinder=true
-Dweblogic.utils.classloaders.DefaultFilteringClassLoader.Verbose=true
-Dweblogic.utils.classloaders.FilteringClassLoader.Verbose=true
-Dweblogic.utils.classloaders.FilteringClassLoader.ResourceDump=true
-Dweblogic.utils.classloaders.URLClassFinder.Verbose=true

Different ways to take thread dumps in WebLogic Server

Different ways to take thread dumps in WebLogic Server

WebLogic Server (WLS) and Java offer several ways to generate thread dumps, they are detailed below.  It is always recommended to obtain the thread dumps by using operating system (OS) commands rather than by using Java classes or the Administration Console, because if the console is hanging, users won't be able to connect to it to issue thread dumps.
  1. Use operating system commands to get the thread dumps when WLS starts up from a command-line script:
    • On Windows OSes, thread dumps can be created by
      + -- the thread dumps are generated in the server stdout
    • On POSIX-compliant platforms (e.g. Solaris and Linux), first identify the process ID (pid) usingps -ef | grep java, then run
      kill -3 2>&1
      Signal 3 is equivalent to SIGQUIT. Note that in Solaris, the thread dump is generated in the current shell, but in Linux, the thread dump is generated in the shell which started the java process specified by the pid.
  2. Using beasvc (up to WLS 10.3.5 included):
    beasvc -dump -svcname:
    • service_name is the Windows service that is running the server instance (e.g. mydomain_myserver)
  3. Using wlsve (from 10.3.6/12.1.1):
    wlsve -dump -svcname:
  4. Using weblogic.WLST:
    setDomain.cmd or setDomain.sh depending on the OS
    java weblogic.WLST
    connect("","","t3://:")
    threadDump()
    The thread dump will be generated in Thread_Dump_AdminServer.txt.  Note 1274713.1 addresses WLST thread dump in more details with examples on how to define sleep time between each dump and number of dumps to take.
  5. From a command line or shell, a thread dump can be generated via the following command (deprecated from WLS 9.0):
    setDomain.cmd or setDomain.sh depending on the OS
    java weblogic.Admin : -username -password THREAD_DUMP
    The thread dump will be generated in the defined server stdout.
  6. From the WLS Administration Console, a thread dump can be created by navigating to Server -> -> Monitoring -> Dump threads stack. This method could lead to truncated or incomplete thread dumps.
  7. From the Services Administration Tools when WLS runs as a Windows Service, see Note 1348645.1
  8. Java VisualVM can also be used to take thread dumps while applications are running, see http://docs.oracle.com/javase/6/docs/technotes/guides/visualvm/applications_local.html for more details
  9. With jstack
    jstack or jstack -l to print additional information about locks
  10. From the JRockit command line:
    jrcmd print_threads

Saturday, April 13, 2013

Filetype(MIME type) check Using JMimeMagic

Checking the file extension is not a very strong way to determine the file type. A more robust solution is possible with theJMimeMagic library. JMimeMagic is a Java library (LGLP licence) that retrieves file and stream mime types by checking magic headers.


See the below implementation of JMimeMagic to check the file MIME type


        private String VIRUS_FILE_MIME_TYPE = "???";
private String RTF_FILE_MIME_TYPE = "rtf";
private String MSWORD_FILE_MIME_TYPE = "msword";
private String MIME_TYPE_NOTAVAILABLE = "text/plain";



//file extension check
byte[] buf = new byte[1024];

  if(multipartFile.getBytes().length > 100){
        fileIS.read(buf, 0, 100);
 }else{
     fileIS.read(buf, 0, multipartFile.getBytes().length);
}
 MagicMatch match = null;
String mimeType = null;

try{
match = Magic.getMagicMatch(buf, false);
} catch (MagicParseException mpe){
logger.error("MagicParseException-->"+mpe);
} catch (MagicMatchNotFoundException mmf){
logger.error("MagicMatchNotFoundException-->"+mmf);
} catch (MagicException me){
logger.error("MagicException-->"+me);
}catch (Exception e){
logger.error("Magic Exception-->"+e);
}

if(match != null) {
 mimeType = match.getMimeType();
}

logger.debug("MagicMatch mimeType(contenttype):"+mimeType);

String mimeTypeFirstSubStr="";
String mimeTypeSecondSubStr="";

if(mimeType != null && mimeType.length() >0){
int index = mimeType.indexOf("/");

if(index >0){
// In File MIMETYPE first part (ex. in application/rtf first part application and rtf is second part)
mimeTypeFirstSubStr = mimeType.substring(0, index);
// In File MIMETYPE second part
mimeTypeSecondSubStr = mimeType.substring(index+1, mimeType.length());
}
}

String contentType = multipartFile.getContentType();

logger.debug("File extension content type:"+contentType);

String contentTypeFirstSubStr="";
String contentTypeSecondSubStr="";

if(contentType != null && contentType.length() >0){
int index = contentType.indexOf("/");

if(index >0){
// In File CONTENTTYPE first part (ex. in application/rtf first part application and rtf is second part)
contentTypeFirstSubStr = contentType.substring(0, index);
// In File CONTENTTYPE second part 
contentTypeSecondSubStr = contentType.substring(index+1, contentType.length());

}

}

logger.info("File original content type "+ mimeType + " extension content type:"+contentType);  
 
//MIME TYPE check logic
if(mimeType != null && !"".equalsIgnoreCase(mimeType) && !MIME_TYPE_NOTAVAILABLE.equalsIgnoreCase(mimeType)){

if(!"".equalsIgnoreCase(mimeTypeFirstSubStr)&&!"".equalsIgnoreCase(contentTypeFirstSubStr)){
     if(!mimeTypeFirstSubStr.equalsIgnoreCase(contentTypeFirstSubStr)){
    if((!"".equalsIgnoreCase(mimeTypeSecondSubStr) && !"".equalsIgnoreCase(contentTypeSecondSubStr)) && (!mimeTypeSecondSubStr.equalsIgnoreCase(contentTypeSecondSubStr))){

//If RTF file is converted to MSWORD or MSWORD file is converted to RTF
    if(!(RTF_FILE_MIME_TYPE.equalsIgnoreCase(mimeTypeSecondSubStr) && MSWORD_FILE_MIME_TYPE.equalsIgnoreCase(contentTypeSecondSubStr)) && 
    !(MSWORD_FILE_MIME_TYPE.equalsIgnoreCase(mimeTypeSecondSubStr) && RTF_FILE_MIME_TYPE.equalsIgnoreCase(contentTypeSecondSubStr))){
    notAllowedFile = true;
  }
     
}
  }
    //For virus files
    }else if(mimeType != null && !"".equalsIgnoreCase(mimeType) && VIRUS_FILE_MIME_TYPE.equalsIgnoreCase(mimeType)){
  notAllowedFile = true;
   }
 }

    if(notAllowedFile){
    String message = String.valueOf(XMLConfigurationManager.getInstance().getConfig().getList("CustomerMessage.Errors.DocNotAllowedFileTypeMsg"));
  message = message.substring(1,message.length()-1);
customerMessageService.setErrorMessage(message);
}

Sorting problem with Displaytag + Webflow

Please modify the display tag implementation like below .

excludedParams="*"
defaultsort="1" defaultorder="ascending" sort="page" requestURI="${myURL}_eventId=redisplay" pagesize="${fileupload_table_pagesize}">
There is -no- problem with this. Sorting links will work fine, paging links will work fine, no javascript, no hassle, just plain elegant code.


It Solves the below errorError 

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'd' cannot be found on object of type 'com.test..model.entity.Application'
                at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:208)
Good evening guys .. from today I will start writing about spring frame work with Weblogic portal

Thanks,
Venkata Sarvabatla

Sunday, April 29, 2012

JSR 168 VS JSR 286


Simple format
The major improvements from JSR 168, (as noted in the JSR 286 document)
  • Events – enabling a portlet to send and receive events and perform state changes or send further events as a result of processing an event.
  • Public render parameters – allowing portlets to share parameters with other portlets.
  • Resource serving – provides the ability for a portlet to serve a resource.
  • Portlet filter – allowing on -the -fly transformations of information in both the request to and the response from a portlet.
Apart for these major differences,there are many minor changes like
  • getNamespace() – this method gives unique value for the portlet window
  • getWindowsID()- this method returns portlet window ID
  • Portlet Cookies- Can beset  on particular phase and retrieved on the subsequest phase
  • Additions to PortletRequestDispatcher
  • Portlet container runtime options
  • New CSS classess

JSR168 vs JSR 286

JSR-168 – What is missing? 
• inter-portlet communication 
• serving non-html resources (pdf, doc, images etc.) 
• contributing javascript or css to , using cookies 
• proper support for common web frameworks 
• portlet filters 
Inter-portlet communication 
• only supported within the same portlet application 
using session attributes 
• target portlets will only “see” messages during next 
render request 
• portlets cannot (should not) update their state during a 
render request: “event” handling not really possible 
Serving non-html resources 
• A portlet can only render html fragments 
• Have to fallback/delegate to the servlet container 
• Requires coordination between portlet and servlet 
Contributing to , setting cookies 
• javascript or css can only be embedded withing the 
content markup; no body onLoad handling hooks 
• API forbids adding cookies: only client side setting of 
cookies using javascript is possible 
Proper support for common web frameworks 
• Most web frameworks are Servlet API only 
• Servlet dispatching not supported from processAction 
• Needs Portals Bridges or similar solutions 
• JSTL support very limited: 
ut value=”<%= ((FooBean)renderRequest.getSession() 
.getAttribute("fooBean",PortletSession.PORTLET_SCOPE)) 
.getBeanValue() %>"/> 


JSR-286 - Coming up 

• Portlet Specification 2.0 
• Expert Group started January 2006 
• 1st Early Public Draft released August 2006 
covering most, but not yet all, planned features 
• 2nd Early Public Draft November 2006 
covering all features 
• 1st Public Draft December 2006 
• Final Release May 2007 
• RI will be done under Apache Pluto umbrella with help 
from a group at University of Jena 
• Binary compatible with JSR-168 
• Alignment with J2EE 1.4, WSRP 2.0 
• Portlet coordination 
• Public render parameters 
• Shared session state across applications (maybe) 
• Portlet events 
• Resource serving 
• AJAX support 
• Portlet filters 
• Extended cache support 
• Improved support for common web frameworks 
• ... and more