Friday, December 11, 2009

Configuring SSL on Weblogic

http://download.oracle.com/docs/cd/E12839_01/web.1111/e13707
/identity_trust.htm


http://java.sun.com/javase/6/docs/technotes/tools/windows/keytool.html#importCertCmd


http://chrismuir.sys-con.com/node/1075471/mobile

ProfessionalWeblogic



.  /usr/bea/wlserver_10.3/server/bin/setWLSEnv.sh

rm -f *jks *pem *der

# create CA self signed certificate
java utils.CertGen -certfile ServerCACert -keyusage digitalSignature,keyAgreement,keyCertSign,keyEncipherment,dataEncipherment -keyusagecritical false -keyfile ServerCAKey -keyfilepass ServerCAKey -selfsigned -e somebody@dave.com -ou FOR-DEVELOPMENT-ONLY -o XXXX -l PRAGUE -s CZ -c EU

#print certificate
openssl x509 -text -inform der -in ServerCACert.der

# store the private key and the digital certificate in the identity keystore
java utils.ImportPrivateKey -certfile ServerCACert.der -keyfile ServerCAKey.der -keyfilepass ServerCAKey -keystore ServerIdentity.jks -storepass ServerCAKey -alias identity -keypass ServerCAKey

#Store the same digital certificate into the trust keystore
keytool -import -v -trustcacerts -alias identity -file ServerCACert.der -keystore ServerTrust.jks -storepass ServerTrustStorePass

keytool -list -keystore ServerIdentity.jks -storepass ServerCAKey
keytool -list -keystore ServerTrust.jks -storepass ServerTrustStorePass




<Dec 11, 2009 12:17:40 AM CET> <Notice> <Security> <BEA-090171> <Loading the identity certificate and private key stored under the alias identity from the JKS keystore file /home/dave/workspace/cert/ServerIdentity.jks.> 
<Dec 11, 2009 12:17:44 AM CET> <Notice> <Security> <BEA-090169> <Loading trusted certificates from the JKS keystore file /home/dave/workspace/cert/ServerTrust.jks.>
<Dec 11, 2009 12:17:44 AM CET> <Notice> <Server> <BEA-002613> <Channel "DefaultSecure" is now listening on 127.0.0.1:7002 for protocols iiops, t3s, ldaps, https.>



java  -Dssl.debug=true -Dweblogic.StdoutDebugEnabled=true \
-Dweblogic.security.TrustKeyStore=CustomTrust \
-Dweblogic.security.CustomTrustKeyStoreFileName=/home/dave/workspace/cert/ServerTrust.jks \
-Dweblogic.security.CustomTrustKeyStoreType=jks \
-Dweblogic.security.SSL.trustedCAKeyStore=/home/dave/workspace/cert/ServerTrust.jks

weblogic.WLST connectSSL.py






java utils.CertGen -help

Usage: java utils.CertGen
-certfile <cert_file> -keyfile <private_key_file>
-keyfilepass <private_key_password>
[-cacert <ca_cert_file>][-cakey <ca_key_file>]
[-cakeypass <ca_key_password>]
[-selfsigned][-strength <key_strength>]
[-e <email_address>][-cn <common_name>]
[-ou <org_unit>][-o <organization>]
[-l <locality>][-s <state>][-c <country_code>]
[-keyusage [digitalSignature,nonRepudiation,keyEncipherment,
dataEncipherment,keyAgreement,keyCertSign,
cRLSign,encipherOnly,decipherOnly]]
[-keyusagecritical true|false]
[-subjectkeyid <subject_key_identifier>]
[-subjectkeyidformat UTF-8|BASE64]
[-help]

Where:
-cacert, -cakey, -cakeypass
public certificate, private key file names, and private key
password of the CA to be used as an issuer of the generated
certificate. When these options are not specified Demo CA files:
CertGenCA.der, CertGenCAKey.der from the current working directory
or from WebLogic lib directory will be used.

-selfsigned
generate a self-signed certificate. CA options will be ignored
when this option is specified

-certfile, -keyfile
output file names without extensions for the generated public
certificate and private key. Appropriate extensions are appended
when the pem and der files are created.

-keyfilepass
password of the generated private key.

-strength
size of the generated keys. The default is 1024 bits.

-e, -cn, -ou, -o, -l, -s, -c
Subject DN attributes of the generated public certificate.

-keyusage
generate certificate with keyusage extension, and with bits set
according to the comma-separated list of bit names.
Extension will be marked as critical by default.
Use [-keyusagecritical false] to generate certificate with
non-critical extension.

-subjectkeyid
generate certificate with the specified subject key identifier
Use [-subjectkeyidformat UTF-8|BASE64] to indicate the format of
the specified subject key identifier string. The default is UTF-8.



WLSTException: Error occured while performing connect : "Cannot connect to WLST." : The command line trust keystore configuration is incorrect. Either TrustKeyStore is set to an illegal value or TrustKeyStore is set to CustomTrust and CustomTrustKeyStoreFileName is not set.

To use the trusted CAs in the JDK's cacerts, specify:

-Dweblogic.security.TrustKeyStore=JavaStandardTrust
defaults to JavaStandardTrust

-Dweblogic.security.JavaStandardTrustKeyStorePassPhrase=passphrase
defaults to no passphrase which means
read-only access to the JDK's cacerts.

To use the trusted CAs in DemoTrust.jks and in the JDK's cacerts, specify:

-Dweblogic.security.TrustKeyStore=DemoTrust
-Dweblogic.security.JavaStandardTrustKeyStorePassPhrase=passphrase
defaults to no passphrase which means
read-only access to the JDK's cacerts.

To use the trusted CAs from another keystore, specify:

-Dweblogic.security.TrustKeyStore=CustomTrust

-Dweblogic.security.CustomTrustKeyStoreFileName=filename
either an absolute pathname or a pathname relative to the
directory the server was booted in.

-Dweblogic.security.CustomTrustKeyStoreType=type
defaults to the default keystore type specified
in the JDK's java.security file.

-Dweblogic.security.CustomTrustKeyStorePassPhrase=passphrase
defaults to no passphrase. Some keystore types allow this
but only grant read-access (eg. jks). Other keystore types
require a keystore passphrase even for read-access.

Sunday, December 6, 2009

Starting AdminServer with WLST

Use the WLST startServer command to start the Administration Server.

startServer([adminServerName], [domainName], [url], [username],
[password],[domainDir], [block], [timeout], [serverLog],
[systemProperties], [jvmArgs] [spaceAsJvmArgsDelimiter])



import os

adminServerName = "AdminServer"
adminServerUrl = "t3://localhost:7001"
adminUser = "weblogic"
adminPassword = "weblogic123"

domainName = "base_domain"
domainHome = "/app/bea/domains/base_domain"

print "JAVA_HOME %s" % os.getenv("JAVA_HOME")
print "CLASSPATH %s" % os.getenv("CLASSPATH")

try:
print "try connect to WLS %s" % adminServerName
hideDumpStack("true")
connect(adminUser, adminPassword, adminServerUrl)
hideDumpStack("false")
print "Connected to %s" % adminServerName
except WLSTException:
hideDumpStack("false")
print "Server not started, try start %s " % adminServerName
startServer(adminServerName,domainName,
adminServerUrl, adminUser, adminPassword,
domainHome,block="true")
print "started %s" % adminServerName
connect(adminUser, adminPassword, adminServerUrl)

ls()

shutdown(force='true')

exit()




Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

JAVA_HOME /usr/java/jdk160_05
CLASSPATH None
try connect to WLS AdminServer
Connecting to t3://localhost:7001 with userid weblogic ...
Server not started, try start AdminServer
Starting weblogic server ...



Server started successfully.
started AdminServer
Connecting to t3://localhost:7001 with userid weblogic ...
WLST-WLS-1260094522421: <Dec 6, 2009 11:15:45 AM CET> <Warning> <JMX> <BEA-149517> <An attempt was made to unregister an mbean that was already unregistered: weblogic.servlet.internal.ServletRuntimeMBeanImpl@146de01>
Successfully connected to Admin Server 'AdminServer' that belongs to domain 'mydomain'.

Warning: An insecure protocol was used to connect to the
server. To ensure on-the-wire security, the SSL port or
Admin port should be used instead.

Thursday, November 12, 2009

Weblogic 11g (10.3.1) weblogic-application.xml, application.xml documentation

Enterprise Application Deployment Descriptor Elements
http://download.oracle.com/docs/cd/E12839_01/web.1111/e13706/app_xml.htm#i1062940

http://java.sun.com/xml/ns/javaee/

Using run-as-principal in MDB deployment descriptor

ejb-jar.xml
            <security-identity>
<run-as>
<role-name>Admin</role-name>
</run-as>
</security-identity>
</message-driven>


...
<assembly-descriptor>
<security-role>
<role-name>Admin</role-name>
</security-role>
<container-transaction>


weblogic-ejb-jar.xml
<security-role-assignment>
<role-name>
Admin
</role-name>
<principal-name>
weblogic
</principal-name>
</security-role-assignment>
<run-as-role-assignment>
<role-name>
Admin
</role-name>
<run-as-principal-name>
weblogic
</run-as-principal-name>
</run-as-role-assignment>

Wednesday, November 11, 2009

Weblogic 11g (10.3.1) weblogic.xml, web.xml, weblogic-ejb-jar.xml, ejb-jar.xml documentation

Oracle Developer Guides
http://download.oracle.com/docs/cd/E12839_01/dev.htm

Oracle® Fusion Middleware Developing Web Applications, Servlets, and JSPs for Oracle WebLogic Server
11g Release 1 (10.3.1)
http://download.oracle.com/docs/cd/E12839_01/web.1111/e13712/toc.htm

Java EE : XML Schemas for Java EE Deployment Descriptors
http://java.sun.com/xml/ns/javaee/


web.xml Deployment Descriptor Elements
http://download.oracle.com/docs/cd/E12839_01/web.1111/e13712/web_xml.htm#i1039990

Oracle® Fusion Middleware Programming Enterprise JavaBeans for Oracle WebLogic Server
http://download.oracle.com/docs/cd/E12839_01/web.1111/e13719/toc.htm

weblogic-ejb-jar.xml Deployment Descriptor Reference
http://download.oracle.com/docs/cd/E12839_01/web.1111/e13719/ejb_jar_ref.htm#i1432300

ejb-jar.xml schema
http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd


weblogic.xml Deployment Descriptor Elements
http://download.oracle.com/docs/cd/E12839_01/web.1111/e13712/weblogic_xml.htm#i1057398

Tuesday, September 8, 2009

Using Weblogic Clusters

http://download.oracle.com/docs/cd/E13222_01/wls/docs103/cluster/index.html

Cluster configuration
http://download.oracle.com/docs/cd/E13222_01/wls/docs103/cluster/config.html

Setting up WebLogic Clusters
http://download.oracle.com/docs/cd/E13222_01/wls/docs103/cluster/setup.html

Cluster Architectures
http://download.oracle.com/docs/cd/E13222_01/wls/docs103/cluster/planning.html#wp1028504


 <server>
<name>AdminServer</name>
<machine>Machine_1</machine>
<listen-address></listen-address>
</server>
<server>
<name>ManagedServer_1</name>
<machine>Machine_1</machine>
<listen-port>7002</listen-port>
<cluster>Cluster_1</cluster>
<listen-address>localhost</listen-address>
<jta-migratable-target>
<user-preferred-server>ManagedServer_1</user-preferred-server>
<cluster>Cluster_1</cluster>
</jta-migratable-target>
</server>
<server>
<name>ManagedServer_2</name>
<machine>Machine_1</machine>
<listen-port>7003</listen-port>
<cluster>Cluster_1</cluster>
<listen-address>localhost</listen-address>
<jta-migratable-target>
<user-preferred-server>ManagedServer_2</user-preferred-server>
<cluster>Cluster_1</cluster>
</jta-migratable-target>
</server>
<cluster>
<name>Cluster_1</name>
<multicast-address>239.192.0.0</multicast-address>
<multicast-port>7005</multicast-port>
<cluster-messaging-mode>multicast</cluster-messaging-mode>
</cluster>



 <machine>
<name>Machine_1</name>
<node-manager>
<name>Machine_1</name>
<listen-address>localhost</listen-address>
</node-manager>
</machine>
<migratable-target>
<name>ManagedServer_1 (migratable)</name>
<notes>This is a system generated default migratable target for a server. Do not delete manually.</notes>
<user-preferred-server>ManagedServer_1</user-preferred-server>
<cluster>Cluster_1</cluster>
</migratable-target>
<migratable-target>
<name>ManagedServer_2 (migratable)</name>
<notes>This is a system generated default migratable target for a server. Do not delete manually.</notes>
<user-preferred-server>ManagedServer_2</user-preferred-server>
<cluster>Cluster_1</cluster>
</migratable-target>
<admin-server-name>AdminServer</admin-server-name>

Thursday, September 3, 2009

EJB client connecting to Weblogic

Lookup service for EJB

requires wlfullclient.jar or wlthint3client.jar on classpath (must be first)

http://docs.oracle.com/cd/E17904_01/web.1111/e13717/wlthint3client.htm
http://docs.oracle.com/cd/E17904_01/web.1111/e13717/basics.htm#i1068418

    public void lookupService()  {
try {
Properties props = new Properties();
props.put(Context.PROVIDER_URL, "t3://localhost:7001");
props.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
Context ctx = new InitialContext(props);
service = (TestTimer) ctx.lookup("ejb/TestTimer#testEAR.TestTimer");
} catch (NamingException e) {
e.printStackTrace();
}
}

Thursday, August 27, 2009

Using Weblogic Work Managers

Using Work Managers to Optimize Scheduled Work
http://e-docs.bea.com/wls/docs103/config_wls/self_tuned.html#wp1063790

<work-manager>
<name>stuckthread_workmanager</name>
<work-manager-shutdown-trigger>
<max-stuck-thread-time>30</max-stuck-thread-time>
<stuck-thread-count>2</stuck-thread-count>
</work-manager-shutdown-trigger>
</work-manager>


   <weblogic-enterprise-bean>
<ejb-name>ResourceConstraintEJB</ejb-name>
<jndi-name>core_work_ejb_resource_ResourceConstraintEJB</jndi-name>
<dispatch-policy>stuckthread_workmanager</dispatch-policy>
</weblogic-enterprise-bean>

Connecting to Weblogic using WLST

WebLogic Scripting Tool
http://edocs.bea.com/wls/docs103/config_scripting/index.html

java weblogic.WLST

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

wls:/offline> connect('weblogic','weblogic','t3://localhost:7001')


wls:/UserDomain/serverConfig> ls()



Thursday, August 13, 2009

Using Ant XmlTask to read properties from xml file

xmltask provides the facility for automatically editing XML files as part of an Ant build
http://www.oopsconsultancy.com/software/xmltask/

    <path id="externaltask.ant.classpath">
<pathelement location="./xmltask-v1.15.jar"/>
</path>

<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask" classpathref="externaltask.ant.classpath"/>

<xmltask source="config.xml">
<copy path="//deploymentPath/text()" property="deployment"/>
<copy path="//software/beaHome/text()" property="weblogicHome"/>
</xmltask>

Wednesday, August 5, 2009

Using anonymous class in Java

The Java Language Specification, Third Edition
http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html

The Java Tutorials
http://java.sun.com/docs/books/tutorial/index.html

Java in a Nutshell
http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class TestAnonymous {

@SuppressWarnings("serial")
public static void main(String[] args) {

Map<Object, Object> map = new HashMap<Object, Object>() {

@SuppressWarnings("unchecked")
@Override
public Object put(Object key, Object value) {
if (containsKey(key)) {
((List<Object>) get(key)).add(value);
} else {
List<Object> list = new ArrayList<Object>();
list.add(value);
super.put(key, list);
}
return value;
}
};

map.put("k1", 1);
map.put("k1", 2);
map.put("k1", "1");
map.put("k1", "2");

map.put("k2", 1);
map.put("k2", "1");

map.put("k3", 1);

System.out.println(map.toString());


}

}



{k3=[1], k1=[1, 2, 1, 2], k2=[1, 1]}


Anonymous class converted to nested class
private static final class HashMapConvertList extends
HashMap<Object, Object> {
@SuppressWarnings("unchecked")
@Override
public Object put(Object key, Object value) {
if (containsKey(key)) {
((List<Object>) get(key)).add(value);
} else {
List<Object> list = new ArrayList<Object>();
list.add(value);
super.put(key, list);
}
return value;
}
}
...

Map<Object, Object> map = new HashMapConvertList();



Friday, July 31, 2009

EclipseLink JPA

The Eclipse Persistence Services Project (EclipseLink) delivers a comprehensive open-source Java persistence solution.
http://www.eclipse.org/eclipselink/

Developing Applications using EclipseLink JPA
http://wiki.eclipse.org/Category:JPA

Introduction to Java Persistence API (ELUG)
http://wiki.eclipse.org/Introduction_to_Java_Persistence_API_%28ELUG%29

Configuring EclipseLink in Eclipse Galileo


How to use Application Scoped Data Sources in WebLogic with EclipseLink JPA

http://wiki.eclipse.org/EclipseLink/Examples/JPA/WLS_AppScoped_DataSource


persistence.xml using JTA
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="testJPA" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>java:/app/jdbc/SimpleAppScopedDS</jta-data-source>

<class>testEAR.Author</class>
<class>testEAR.Book</class>
<properties>
<property name="eclipselink.target-server" value="WebLogic_10"/>
<property name="javax.persistence.jtaDataSource" value="java:/app/jdbc/SimpleAppScopedDS" />
</properties>
</persistence-unit>
</persistence>



[EL Finest]: 2009-07-31 14:42:43.602--UnitOfWork(4744686)--Thread(Thread[[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--Execute query ReadObjectQuery(referenceClass=Author sql="SELECT AUTHOR_ID, LAST_NAME, EMAIL, FIRST_NAME FROM AUTHOR WHERE (AUTHOR_ID = ?)")
[EL Fine]: 2009-07-31 14:42:43.602--ServerSession(18462140)--Connection(17112484)--Thread(Thread[[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--SELECT AUTHOR_ID, LAST_NAME, EMAIL, FIRST_NAME FROM AUTHOR WHERE (AUTHOR_ID = ?)
bind => [1]
[EL Finest]: 2009-07-31 14:42:43.68--ServerSession(18462140)--Thread(Thread[[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--Execute query ReadAllQuery(name="books" referenceClass=Book sql="SELECT BOOK_ID, TITLE, PUBLISH_DATE, AUTHOR_ID FROM BOOK WHERE (AUTHOR_ID = ?)")
[EL Fine]: 2009-07-31 14:42:43.68--ServerSession(18462140)--Connection(12687286)--Thread(Thread[[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--SELECT BOOK_ID, TITLE, PUBLISH_DATE, AUTHOR_ID FROM BOOK WHERE (AUTHOR_ID = ?)
bind => [1]

Convert existing entity EJB to Entity Bean to EJB 3.0

Learn how to convert an EJB 2.0 entity bean to an EJB 3.0 entity bean, step by step.
http://www.oracle.com/technology/pub/articles/vohra_ejb.html?rssid=rss_otn_articles


Understanding Enterprise JavaBeans 3.0
http://edocs.bea.com/wls/docs103/ejb30/understanding.html
Because the EJB 3.0 programming model is so simple, BEA no longer supports using the EJBGen tags and code-generating tool on EJB 3.0 beans.

Thursday, July 30, 2009

Creating JPA project in Eclipse

Introduction to Oracle Enterprise Pack for Eclipse 11g JPA Workbench


http://www.oracle.com/technetwork/articles/cioroianu-eclipse-jpa-084626.html


Dali JPA Tools
An Eclipse Web Tools Platform Sub-Project
http://eclipse.org/webtools/dali/main.php

Generate custom entities



Custom individual entity




Generated entity class

@Entity()
public class Book implements Serializable {
private static final long serialVersionUID = 1L;

@Id()
@SequenceGenerator(name="BOOK_BOOKID_GENERATOR", sequenceName="BOOK_SEQ")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="BOOK_BOOKID_GENERATOR")
@Column(name="BOOK_ID")
private long bookId;

private String title;

@Temporal( TemporalType.DATE)
@Column(name="PUBLISH_DATE")
private java.util.Date publishDate;

//bi-directional many-to-one association to Author
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="AUTHOR_ID", referencedColumnName="AUTHOR_ID")
private Author author;

public Book() {
}
public long getBookId() {
return this.bookId;
}

public void setBookId(long bookId) {
this.bookId = bookId;
}

public String getTitle() {
return this.title;
}

public void setTitle(String title) {
this.title = title;
}

public java.util.Date getPublishDate() {
return this.publishDate;
}

public void setPublishDate(java.util.Date publishDate) {
this.publishDate = publishDate;
}

public Author getAuthor() {
return this.author;
}

public void setAuthor(Author author) {
this.author = author;
}

}


@Entity()
public class Author implements Serializable {
private static final long serialVersionUID = 1L;

@Id()
@SequenceGenerator(name="AUTHOR_AUTHORID_GENERATOR", sequenceName="BOOK_SEQ")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="AUTHOR_AUTHORID_GENERATOR")
@Column(name="AUTHOR_ID")
private long authorId;

@Column(name="FIRST_NAME")
private String firstName;

@Column(name="LAST_NAME")
private String lastName;

private String email;

//bi-directional many-to-one association to Book
@OneToMany(mappedBy="author", fetch=FetchType.EAGER)
private java.util.Set<Book> books;

public Author() {
}
public long getAuthorId() {
return this.authorId;
}

public void setAuthorId(long authorId) {
this.authorId = authorId;
}

public String getFirstName() {
return this.firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return this.lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return this.email;
}

public void setEmail(String email) {
this.email = email;
}

public java.util.Set<Book> getBooks() {
return this.books;
}

public void setBooks(java.util.Set<Book> books) {
this.books = books;
}

}


JPA Field detail



Add JPA project to EJB project


Add finder call to Session Bean

    @PersistenceContext
private javax.persistence.EntityManager em;

@Override
public Author findAuthor(long authorId) {
return em.find(Author.class, authorId);
}


Add session bean call to servlet
 @EJB
TestSessionBeanRemote remoteBusinessIntf;

Author author = remoteBusinessIntf.findAuthor(Long.parseLong(name));

response.getWriter().write(author.getLastName());

Creating new Java project in Eclipse

Organizing source code in Eclipse project

http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.jdt.doc.user/gettingStarted/qs-OrganizingSources.htm


Java EE applications
http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.jst.j2ee.doc.user/topics/ph-j2eeapp.html

Monday, July 27, 2009

Dependency Injection (DI) and JNDI

EJB3 in action http://www.manning.com/panda/
Chapter 2.1.2 - Introducing dependency injection In a sense, injection is lookup reversed. As you can see, in the manual JNDI lookup model, the bean explicitly retrieves the resources and components it needs. As a result, component and resource names are hard-coded in the bean. With DI, on the other hand, the container reads target bean configuration, figures out what beans and resources the target bean needs, and injects them into the bean at runtime.

Inversion of Control Containers and the Dependency Injection pattern
http://www.martinfowler.com/articles/injection.html

Sunday, July 26, 2009

EJB3 Interceptor class example on Weblogic server

Annotations Used to Configure Interceptors
http://edocs.bea.com/wls/docs103/ejb30/annotations.html#wp1428539


Programming the Annotated EJB 3.0 Class
http:
//edocs.bea.com/wls/docs103/ejb30/program.html#wp1207312


Oracle Weblogic example
@Stateful
@TransactionAttribute(REQUIRES_NEW)
@Remote({sessionbean.Account.class})
@Interceptors({sessionbean.AuditInterceptor.class})
public class AccountBean
implements Account
{

private int balance = 0;

public void deposit(int amount) {
balance += amount;
System.out.println("deposited: "+amount+" balance: "+balance);
}

public void withdraw(int amount) {
balance -= amount;
System.out.println("withdrew: "+amount+" balance: "+balance);
}

public int getBalance(){
int bogus;
return balance + 1;
}

@ExcludeClassInterceptors
public void sayHelloFromAccountBean() {

}


@PreDestroy
public void preDestroy() {
System.out.println("Invoking method: preDestroy()");
}

}


Interceptor class
package sessionbean;



import javax.interceptor.AroundInvoke;

import javax.interceptor.InvocationContext;



import javax.ejb.PostActivate;

import javax.ejb.PrePassivate;



/**

* Interceptor class. The interceptor method is annotated with the

* @AroundInvoke annotation.

*/



public class AuditInterceptor {



public AuditInterceptor() {}



@AroundInvoke

public Object audit(InvocationContext ic) throws Exception {

System.out.println("Invoking method: "+ic.getMethod());

return ic.proceed();

}



@PostActivate

public void postActivate(InvocationContext ic) {

System.out.println("Invoking method: "+ic.getMethod());

}



@PrePassivate

public void prePassivate(InvocationContext ic) {

System.out.println("Invoking method: "+ic.getMethod());

}



}




Inject EJB into servlet
@EJB
Account remoteAccount;




Invoking method: public java.lang.Object sessionbean.AccountBean_2lqacg_Impl.beaInvoke(java.lang.Object[],int)
deposited: 200 balance: 800

Saturday, July 25, 2009

Add FastSwap on Weblogic server using Eclipse

Enterprise Application Deployment Descriptor Elements
http://edocs.bea.com/wls/docs103/programming/app_xml.html

Using FastSwap Deployment to Minimize Redeployment
http://edocs.bea.com/wls/docs103/deployment/deployunits.html#FastSwap

Oracle Enterprise pack detailed tutorial
http://www.oracle.com/technology/products/enterprise-pack-for-eclipse/demos.html

Setting FastSwap in Eclipse


weblogic-application.xml
<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-application xmlns:wls="http://www.bea.com/ns/weblogic/weblogic-application" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/javaee_5.xsd http://www.bea.com/ns/weblogic/weblogic-application http://www.bea.com/ns/weblogic/weblogic-application/1.0/weblogic-application.xsd">
<!-- server-version: 10.3.0 -->
<wls:application-param>
<wls:param-name>webapp.encoding.default</wls:param-name>
<wls:param-value>UTF-8</wls:param-value>
</wls:application-param>
<wls:fast-swap>
<wls:enabled>true</wls:enabled>
</wls:fast-swap>

</wls:weblogic-application>

Create Application Lifecycle Listener using Eclipse

http://help.eclipse.org/ganymede/index.jsp?topic=/org.eclipse.wst.webtools.doc.user/topics/cwebartifact.html

Create listener using wizard



Select listener type



package testEAR;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
* Application Lifecycle Listener implementation class TestApplicationLifecycleListener
*
*/
public class TestApplicationLifecycleListener implements ServletContextListener {

/**
* Default constructor.
*/
public TestApplicationLifecycleListener() {
System.out.println("TestApplicationLifecycleListener constructor");
}

/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("TestApplicationLifecycleListener initialize event" + arg0);
}

/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("TestApplicationLifecycleListener destroy event" + arg0);
}

}



web.xml descriptor
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>testDynamicWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>TestServlet</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>testEAR.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/sayHello</url-pattern>
</servlet-mapping>
<listener>
<listener-class>testEAR.TestApplicationLifecycleListener</listener-class>
</listener>

</web-app>



TestApplicationLifecycleListener constructor
TestApplicationLifecycleListener initialize eventjavax.servlet.ServletContextEvent[source=weblogic.servlet.internal.WebAppServletContext@194737d
- appName: 'testEAR', name: 'testDynamicWeb', context-path: '/testDynamicWeb', spec-version: '2.5']
...
TestApplicationLifecycleListener destroy eventjavax.servlet.ServletContextEvent[source=weblogic.servlet.internal.WebAppServletContext@194737d
- appName: 'testEAR', name: 'testDynamicWeb', context-path: '/testDynamicWeb', spec-version: '2.5']


Friday, July 24, 2009

Create EJBTimer On Weblogic 10.3 using resource injection

Programming the EJB Timer Service
http://edocs.bea.com/wls/docs103/ejb/implementing.html#wp1191405

EJB 3.0 Metadata Annotations Reference
http://edocs.bea.com/wls/docs103/ejb30/annotations.html#wp1425297

Interface TimerService.createTimer
http://java.sun.com/j2ee/1.4/docs/api/javax/ejb/TimerService.html#createTimer%28long,%20long,%20java.io.Serializable%29

@Local
@Remote
@Stateless(mappedName = "ejb/TestTimer")
public class TestTimerEJB implements TestTimer {


// resources that the container will inject
@Resource
private TimerService timerService;

//inject data source
@Resource(mappedName="jdbc/MyDataSource")
private javax.sql.DataSource datasource;


@Timeout
public void execute(Timer timer) {
System.out.println("Hi from TestTimerEJB timer");
}

Thursday, July 2, 2009

Weblogic 10.3 Enterprise Application decriptors generated by Eclipse Ganymede

application.xml
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:application="http://java.sun.com/xml/ns/javaee/application_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd" id="Application_ID" version="5">
<display-name>
testEAR</display-name>
<module>
<ejb>testEJB.jar</ejb>
</module>
<module>
<web>
<web-uri>testDynamicWeb.war</web-uri>
<context-root>testDynamicWeb</context-root>
</web>
</module>
<library-directory>/lib</library-directory>
</application>


weblogic-application.xml
<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-application xmlns:wls="http://www.bea.com/ns/weblogic/weblogic-application" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/javaee_5.xsd http://www.bea.com/ns/weblogic/weblogic-application http://www.bea.com/ns/weblogic/weblogic-application/1.0/weblogic-application.xsd">
<!-- server-version: 10.3.0 -->
<wls:application-param>
<wls:param-name>webapp.encoding.default</wls:param-name>
<wls:param-value>UTF-8</wls:param-value>
</wls:application-param>
</wls:weblogic-application>


weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://www.bea.com/ns/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://www.bea.com/ns/weblogic/weblogic-web-app http://www.bea.com/ns/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd">
<wls:weblogic-version>10.3.0</wls:weblogic-version>
<wls:container-descriptor>
<wls:prefer-web-inf-classes>false</wls:prefer-web-inf-classes>
</wls:container-descriptor>
<wls:context-root>testDynamicWeb</wls:context-root>
</wls:weblogic-web-app>


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>testDynamicWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>TestServlet</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>testEAR.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/sayHello</url-pattern>
</servlet-mapping>
</web-app>


ejb-jar.xml
<?xml version="1.0" encoding="ASCII"?>
<ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:ejb="http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" version="3.0">
<display-name>testEJB</display-name>
</ejb-jar>


weblogic-ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-ejb-jar xmlns:wls="http://www.bea.com/ns/weblogic/weblogic-ejb-jar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd http://www.bea.com/ns/weblogic/weblogic-ejb-jar http://www.bea.com/ns/weblogic/weblogic-ejb-jar/1.0/weblogic-ejb-jar.xsd">
<!-- server-version: 10.3.0 -->
</wls:weblogic-ejb-jar>

Wednesday, July 1, 2009

SWIFT parser using ANTLR

SWIFT definition http://publib.boulder.ibm.com/infocenter/wbihelp/v6rxmx/index.jsp?topic=/com.ibm.wbia_adapters.doc/doc/swift/swift72.htm
ANTLR http://antlr.org/
ANTLRWorks http://antlr.org/works/index.html
ANTLR Cheet sheet http://www.antlr.org/wiki/display/ANTLR3/ANTLR+Cheat+Sheet

grammar SwiftBlock;

message : block+;

block : '{' '1' ':' expr {System.out.println("expr1=" + $expr.text);} '}' |
'{' '2' ':' expr {System.out.println("expr2=" + $expr.text);} '}' |
'{' '3' ':' expr3* '}' |
'{' '4' ':' expr4+ '}' |
'{' '5' ':' expr5+ '}' ;

expr3 : '{' expr ':' expr '}' {System.out.println("expr3=" + $expr3.text);} ;

expr4 : ('\n'|'\r')+ (':' expr ':' expr {System.out.println("expr4=" + $expr4.text);} | '-')+;

expr5 : ('\n'|'\r')+ '{' expr ':' expr '}' {System.out.println("expr5=" + $expr5.text);} ;

expr : FIELDVALUE* {System.out.println("expr=" + $expr.text);} ;


/*------------------------------------------------------------------
* LEXER RULES
*------------------------------------------------------------------*/

FIELDVALUE : (~('-'|':'|'}'|'{'|'\n'|'\r'))+;


Grammar Interpreter
Syntax Diagram



Parse tree detail


java -cp .:/home/app/antlr-3.1.3/lib/antlr-3.1.3.jar org.antlr.Tool SwiftBlock.g 


import java.io.FileInputStream;

import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.CommonTokenStream;

public class AntlrSwiftBlock {
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("/home/dave/workspace/antlrSwift/src/swift.txt");
ANTLRInputStream input = new ANTLRInputStream(fileInputStream);
SwiftBlockLexer lexer = new SwiftBlockLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
SwiftBlockParser parser = new SwiftBlockParser(tokens);
parser.message();
}
}


{1:F01AAAABB99BSMK3513951576}{2:O9400934081223BBBBAA33XXXX03592332770812230834N}{3:{113:xxxx}{108:abcdefgh12345678}}{4:
:20:0112230000000890
:25:SAKG800030155USD
:28C:255/1
:60F:C011223USD175768,92
:61:0112201223CD110,92NDIVNONREF//08 IL053309
/GB/2542049/SHS/312,
:62F:C011021USD175879,84
-}{5:
{CHK:0F4E5614DD28}}


expr=F01AAAABB99BSMK3513951576
expr1=F01AAAABB99BSMK3513951576
expr=O9400934081223BBBBAA33XXXX03592332770812230834N
expr2=O9400934081223BBBBAA33XXXX03592332770812230834N
expr=113
expr=xxxx
expr3={113:xxxx}
expr=108
expr=abcdefgh12345678
expr3={108:abcdefgh12345678}
expr=20
expr=0112230000000890
expr4=
:20:0112230000000890
expr=25
expr=SAKG800030155USD
expr4=
:25:SAKG800030155USD
expr=28C
expr=255/1
expr4=
:28C:255/1
expr=60F
expr=C011223USD175768,92
expr4=
:60F:C011223USD175768,92
expr=61
expr=0112201223CD110,92NDIVNONREF//08 IL053309
expr4=
:61:0112201223CD110,92NDIVNONREF//08 IL053309
line 7:0 required (...)+ loop did not match anything at input '/GB/2542049/SHS/312,'
expr=62F
expr=C011021USD175879,84
expr4=
:62F:C011021USD175879,84
expr=CHK
expr=0F4E5614DD28
expr5=
{CHK:0F4E5614DD28}

MDB 3. 0 on Weblogic 10.3 using Oracle AQ ( Advanced Queue)



package testEAR;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import weblogic.javaee.MessageDestinationConfiguration;

@MessageDestinationConfiguration(connectionFactoryJNDIName = "jms.aq.AQFactory")
@MessageDriven(
activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType",
propertyValue = "javax.jms.Queue") },
mappedName = "jms.aq.MY_QUEUE"
)
public class TestMDB implements MessageListener {

public void onMessage(Message message) {
TextMessage txtMsg = null;

txtMsg = (TextMessage) message;
try {
String stringMessage = txtMsg.getText();

System.out.print("Payload: " + stringMessage + "\n");

} catch (JMSException e) {
e.printStackTrace();
}
}
}

Monday, June 29, 2009

Weblogic Classloading configuration

Weblogic Server classloading manual
http://e-docs.bea.com/wls/docs103/programming/classloading.html

WebLogic Server provides a location within an EAR file where you can store shared utility classes. Place utility JAR files in the APP-INF/lib directory and individual classes in the APP-INF/classes directory.

  • Create test library to print classloader of class
System.out.println(clazz.getSimpleName() + " loaded by " + clazz.getClassLoader().getClass().getSimpleName());
  • Add test library into Web Project



  • Add library into EAR

  • Deploy with prefer-web-inf-classes = true
TestClassloader loaded by ChangeAwareClassLoader
TestServlet loaded by ChangeAwareClassLoader
TestClassloader loaded by GenericClassLoader
TestSessionBean_eb2d8g_Impl loaded by GenericClassLoader

  • Deploy with prefer-web-inf-classes = false ( default)
TestClassloader loaded by GenericClassLoader TestServlet loaded by ChangeAwareClassLoader TestClassloader loaded by GenericClassLoader TestSessionBean_eb2d8g_Impl loaded by GenericClassLoader

Sunday, June 28, 2009

Create JavaEE application using Eclipse Ganymede and Weblogic 10.3




  • Add WLS 10.3 as new server

  • Create new EJB project
  • Create new Dynamic Web Project
  • Run EAR project on WLS server