Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Monday, March 24, 2014

EL to avoid cross site scripting

If you have ${dataWhichInputByUser} on your jsp, it potentially has the threaten of cross site scripting. Because if the “dataWhichInputByUser” contains java script, for example <script>alert(‘abc’);</script>, the browser will execute the java script.
There are three ways to avoid it.
#1, always using c:out, the attribute escapeXml is true by default
<c:out value="${user.name}"/>
#2, using fn:escapeXml to escaple the xml tag
${fn:escapeXml(user.name)}
#3, add a listener to escaple xml wherever ${} is used. Add the listener in web.xml
<listener>
  <listener-class>com.github.pukkaone.jsp.EscapeXmlELResolverListener</listener-class>
</listener> 
The listener java class could be found here

 
http://pukkaone.github.io/2011/01/03/jsp-cross-site-scripting-elresolver.html

Thursday, November 28, 2013

java command for web service

contract first, generating wsdl first, to generate java class from wsdl, run wsimport

contract last, generating java class first, to generate wsdl from java class, run wsgen

Wednesday, January 16, 2013

HttpServeltResponse send error message in UTF-8

I used to fix a bug of httpServletResponse sending error message in utf-8. It was the response of an ajax call. If there was error, it need send error with error message back to the client to trigger the method below in client javascript.

error: function( jqXHR xhr, String textStatus, String errorThrown ) 


The previous guy used this code in java



response.sendError(11, errorMessage);


and tried to get the error message with this code in javascript.



xhr.statusText


This did not work if there was French character with accent in message.



The solution is like this, in java code



response.setStatus(11);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(errorMessage);


in javascript, get responseText instead of statusText



xhr.responseText


Before I found this, I also tried this. Although it worked on UI, but I saw error messages in log file from weblogic.



response.setContentType("text/html;charset=UTF-8");
response.sendError(11, errorMessage);


The error message is about the



ProtocolException: Didn't meet stated Content-Length


Here is a similar issue

Wednesday, June 27, 2012

weblogic jar confliction

If the application classpath is conflicting with weblogic classpath, for example, different version of xml parser, the easiest way to solve it is to set <prefer-web-inf-classes>to true in weblogic.xml

<wls:container-descriptor>
    <wls:prefer-web-inf-classes>true</wls:prefer-web-inf-classes>
</wls:container-descriptor>

Tuesday, January 24, 2012

Getting the List size in JSP

${fn:length(list)}


<c:set var="endLoop" value="${offset + maxPageItems}"/>  
    <c:if test="${fn:length(searchResults) < endLoop}"> 
      <c:set var="endLoop" value="${fn:length(searchResults)"/> 
    </c:if> 
    <c:forEach items="${searchResults}" var="searchResult" varStatus="searchIndex" begin="${offset}" end="${endLoop}">  
      <td>${result.city}</td> 
    </c:forEach>

Wednesday, September 7, 2011

difference between JTA and JTS

JTA is the abbreviation for the Java Transaction API.
JTS is the abbreviation for the Jave Transaction Service.

JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation.
The J2EE SDK implements the transaction manager with JTS. But your code doesn’t call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn’t directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.

 

Here is the original post on internet http://www.roseindia.net/answers/viewqa/Servlet-Interview-Questions/13335-JTA-and-JTS.html

Change glassfish default port

I used to work with oracle XE and glassfish together. Oracle listener is listening on 8080 which is the default port of glassfish.

To change the default port of glassfish

Open

GLASSFISH_PATH>\\glassfish\\domains\\domain1\\config\\domain.xml

Just change the following properties:

<network-listeners>

<network-listener port="8093" ... />

<network-listener port="8181" ... />

<network-listener port="4848" ... />

</network-listeners>

Tuesday, December 30, 2008

Using jencks to pool JMS connections

Using Jencks
Jencks is a lightweight JCA container which is easy to deploy inside Spring to provide Message Driven POJOs. In addition Jencks supports inbound and outbound messaging using APIs like JMS, JAX-RPC, JBI and JCA CCI as well as providing an XA based pooling mechanism for JDBC.

Jencks by default reuses the Geronimo JCA connector, WorkManager and TransactionManager - though there are no fixed runtime dependencies on Geronimo so you should be able to use Jencks with JOTM and Jonas too - though we recommend the Geronimo implementations as they are heavily tested and support full XA recovery.

Here is the sample configuration.
<bean id="jmsResourceAdapter" class="org.apache.activemq.ra.ActiveMQResourceAdapter">
<property name="serverUrl" value="tcp://localhost:61616" />
</bean>

<!-- ###### Transaction manager ###### -->
<bean id="transactionManager" class="org.jencks.factory.TransactionManagerFactoryBean" />

<!-- ###### Connection Manager ###### -->
<bean id="connectionManager" class="org.jencks.factory.ConnectionManagerFactoryBean">
<property name="transactionManager" ref="transactionManager" />
<property name="poolMaxSize" value="20" />
</bean>

<!-- ###### JMS Managed Connection Factory ###### -->
<bean id="jmsManagedConnectionFactory" class="org.apache.activemq.ra.ActiveMQManagedConnectionFactory">
<property name="resourceAdapter" ref="jmsResourceAdapter" />
</bean>

<bean id="connectionFactory" class="org.jencks.factory.ConnectionFactoryFactoryBean">
<property name="managedConnectionFactory" ref="jmsManagedConnectionFactory" />
<property name="connectionManager" ref="connectionManager" />
</bean>

<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="mqDestination" />
<property name="messageConverter" ref="jmsMessageConverter" />
</bean>

We also need add dependency in pom.xml
<dependency>
<groupId>org.jencks</groupId>
<artifactId>jencks</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.jencks</groupId>
<artifactId>jencks-amqpool</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-ra</artifactId>
<version>5.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-j2ee-connector_1.5_spec</artifactId>
<version>1.1</version>
</dependency>



You can also use PooledConnectionFactory from activeMQ
Sample: here is the orginal spring configuration without pooling.


<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:61616" />
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="mqDestination" />
<property name="messageConverter" ref="jmsMessageConverter" />
</bean>

We only need replace the "org.apache.activemq.ActiveMQConnectionFactory" with "org.apache.activemq.pool.PooledConnectionFactory"

<bean id="connectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
<constructor-arg value="tcp://localhost:61616" />
<property name="maxConnections" value="20" />
</bean>


The weak point is that it is activemq specific. Once the jms provider is changed, this setting should also be changed.

Tuesday, December 9, 2008

Monitor ActiveMQ started embedded

The activeMQ could be started embedded. But the normal monitor web console (http://localhost:8161/admin) does not work, the web console only works when the activeMQ is started standalone.
In this case, we can use JMX to monitor embedded ActiveMQ.
To make the activeMQ could be monitored by JMX. The configuration file must be set like this
<broker xmlns="http://activemq.apache.org/schema/core" useJmx="true" brokerName="epMQBroker">
......
<!-- This may collide with JBoss/Websphere/Weblogic so need to set the port manually for now-->
<managementContext>
<managementContext connectorPort="1099" jmxDomainName="localhost"/>
</managementContext>
......

After the activeMQ is started embedded, run jconsole in %JAVA_HOME%/bin, click the "Advanced" tab, input the JMX url
service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi

Note the port number must be consistent with the port number in "managementContext" in the configuration file.

Monday, December 8, 2008

Disable ActiveMQ multicast

The Multicast allows to route the same message to a number of endpoints and process them in a different way.

It seems ActiveMQ will look up all the activeMQ server in the intranet for multicast by default.

I found if my co-worker (in the same intranet) started activeMQ, then I would have the problem to start my activeMQ. It was probably caused by "multicast". To disable the multicast, open the file %ACTIVEMQ_HOME%/conf/activemq.xml and comment
<networkConnector name="default-nc" uri="multicast://default"/>

Friday, August 22, 2008

JBoss EAR Classloading

Jboss follows the standard J2EE 1.4 spec that all Jar resources in the EAR must be specified as a
<module>
<java>lib/jarfile.jar</java>
</module>
entry in the META-INF/application.xml. So if its not specified in this file, JBoss is blind to it during runtime.

The other issue is the embedded Tomcat cannot see out to the enclosing ear file to retrieve classes until you change a setting in JBoss. You must set the UseJbossWebLoader property to true in deploy/jbossweb-tomcat5.5/META-INF/jboss-service.xml. Once you do this, all the jars that you've specified in your application.xml are visible to the underlying war file.

We had a properties file that existed in WEB-INF/classes/app.properties Using the JbossWebLoader=true, this file was not visible to the class loader. Moving the file to WEB-INF/classes/resources/app.properties, made the file visible and the calling application, in this case a jsf change was made to

There also exists the possibilty of using JbossWebLoader=false, then creating a META-INF/MANIFEST.MF entry for Class-Path: in the war archive.
Class-Path: jarfile.jar
This entry will explictly tell the web archive exactlly what jars it needs on its classpath from the upper level ear archive.

To study more about jboss classloading, visit http://wiki.jboss.org/wiki/ClassLoading

Sunday, July 20, 2008

JAAS - Java Authentication and Authorization Service

The figure below gives a high-level overview of how JAAS achieves this pluggability. Your application-layer code deals primarily with a LoginContext. Underneath that LoginContext is a set of one or more dynamically configured LoginModules, which handle the actual authentication using the appropriate security infrastructure.


In addition to being pluggable, JAAS is stackable: in the context of a single login, a set of security modules can stack on top of one another, each called in order and each interacting with a different security infrastructure.

Using JAAS authentication from your application typically involves the following steps:
  1. Create a LoginContext
  2. Optionally pass a CallbackHandler to the LoginContext, for gathering or processing authentication data
  3. Perform authentication by calling the LoginContext's login() method
  4. Perform privileged actions using the returned Subject (assuming login succeeds)

The configuration file structure is
      Application {
ModuleClass Flag ModuleOptions;
ModuleClass Flag ModuleOptions;
...
};
Application {
ModuleClass Flag ModuleOptions;
...
};
The options for "Flag" is REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL.
REQUIRED
This option is the default setting for any Authentication Provider. A required Authentication Provider is always invoked, irrespective of the control flag settings on other providers. The overall authentication cannot succeed if any REQUIRED provider fails. Thus, REQUIRED providers are always invoked, and overall authentication fails if any one of them fails.
REQUISITE
This option also requires the Authentication Provider to succeed during the login sequence. However, all of the REQUISITE providers need not be invoked for the overall authentication to succeed. If a REQUISITE provider succeeds, the authentication proceeds as normal to other providers in the sequence. However, if it fails, the overall authentication cannot succeed, and control is immediately passed back to the application once all REQUIRED providers in the login sequence have been invoked.
SUFFICIENT
This option does not require the Authentication Provider to succeed during the login sequence. If a SUFFICIENT provider does succeed, the overall authentication proceeds to ensure that only the remaining REQUIRED providers in the login sequence are executed. However, if it fails, the overall authentication proceeds as normal to the other providers in the login sequence.
OPTIONAL
This option does not require the Authentication Provider to succeed during the login sequence. Regardless of whether an OPTIONAL provider succeeds, the authentication proceeds to other providers that have been configured as part of the login sequence.
* All REQUIRED modules must be invoked, and each must successfully validate the user.
* Any REQUISITE module that gets invoked must successfully validate the user.
* If a SUFFICIENT module successfully validates the user, the overall success depends on the success of all REQUIRED modules, and any REQUISITE modules invoked before the SUFFICIENT module.
* If the login sequence consists only of OPTIONAL modules, at least one module must successfully validate the user.


    LoginContext lc = new LoginContext("JaasSample");
try {
lc.login();
} catch (LoginException) {
// Authentication failed.
}
// Authentication successful, we can now continue.
// We can use the returned Subject if we like.
Subject sub = lc.getSubject();
Subject.doAs(sub, new MyPrivilegedAction());

LoginContext Configuration
When your code instantiates a LoginContext, you pass it the name of one of the application blocks in the configuration file. The LoginContext will use LoginModules based on what you specify in the application entry. These specifications drive which LoginModules are invoked, in which order, and according to which rules.
JaasSample {
com.sun.security.auth.module.Krb5LoginModule required debug=true;
};
For example, the configuration file is saved as jaas.config, then we would specify the location on the command line as follows:
java -Djava.security.auth.login.config=jaas.config JaasTestClassName


Common Subject, Principal, credential (credential is not any specific class, but can be any object)
Authentication LoginContext, LoginModule, CallbackHandler, Callback
Authorization Policy, AuthPermission, PrivateCredentialPermission

The Subject class represents an authenticated entity.
Principals represent Subject identities.A Subject instance contains an array of Principals, it can thus have multiple name, such like a social security number, login ID, email address, and so on
Credentials can include any authentication artifact, such as a ticket, key, or password, that specific security systems might require.

CallbackHandlers and Callbacks let a LoginModule gather necessary authentication information from a user or system.

Sunday, July 13, 2008

JMS

Java Message System is for the software using asynchronous messaging.

JMS has two types

JMS Queue:
peer to peer
One provider, one consumer.

JMS Topic:
subscribe and publishing
One provider, multiple consumers.

JMS is typically used in the following scenarios
1. Enterprise Application Integration: - Where a legacy application is integrated with a new application via messaging.
2. B2B or Business to Business: - Businesses can interact with each other via messaging because JMS allows organizations to cooperate without tightly coupling their business systems.
3. Geographically dispersed units: - JMS can ensure safe exchange of data amongst the geographically dispersed units of an organization.
4. One to many applications: - The applications that need to push data in packet to huge number of clients in a one-to-many fashion are good candidates for the use JMS. Typical such applications are Auction Sites, Stock Quote Services etc.

JMS messages are composed of the following parts:
  • Header - All messages support the same set of header fields.Header fields contain values used by both clients and providers to identify and route messages.
  • Properties - Each message contains a built-in facility for supporting application-defined property values. Properties provide an efficient mechanism for supporting application-defined message filtering.
  • Body - The JMS API defines several types of message body, which cover the majority of messaging styles currently in use.


There are different types of messages available in the JMS API.
  • Message
  • TextMessage
  • BytesMessage
  • StreamMessage
  • ObjectMessage
  • MapMessage

Message is a light weight message having only header and properties and no payload. If the receivers are to be notified about an event, and no data needs to be exchanged then using Message can be very efficient.

TextMessage contains instance of java.lang.String in the message body.This message type can be used to transport plain-text messages, and XML messages.

BytesMessage contains a stream of uninterpreted bytes. This message type is for literally encoding a body to match an existing message format. In many cases, it is possible to use one of the other body types, which are easier to use. Although the JMS API allows the use of message properties with byte messages, they are typically not used, since the inclusion of properties may affect the format.

StreamMessage contains a stream of primitive values in the Java programming language ("Java primitives") in its message body. It is filled and read sequentially.

ObjectMessage contains a Serializable Java object. It allows exchange of Java objects between applications. The consumer of the message must typecast the object received to it's appropriate type. Thus the consumer should before hand know the actual type of the object sent by the sender.

MapMessage carries name-value pair in its message body, where names are String objects, and values are Java primitives.

Q: What is the difference between BytesMessage and StreamMessage??
A:
BytesMessage stores the primitive data types by converting them to their byte representation. Thus the message is one contiguous stream of bytes. While the StreamMessage maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. BytesMessage allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the StreamMessage. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read.