From the base Tomcat Authentication Sequence (using JAAS you can see the changes made by both JBoss and the IIS Connector. The important bit to note here is on the ISAPI Connector DLL Sequence. Due to the dll injecting a Principal into the request for Tomcat, all of Tomcat's regular authenticator valves fail to authorize the user. This is because, by default, they check to see if a Principal already exists in the session and return if it does.
The Tomcat IIS Authenticator Sequence shows how using the Tomcat IIS Authenticator Valve makes tomcat continue the authentication and authorization. Authentication is 'checked' by verifying that the NTLM provided Principal is not-null. Authorization is performed by passing the Principal to the Security Realm. The security realm can then populate the user's Principal with the Role's the user is granted base on the implementation of the Realm.
JBoss will now be able to use any LoginModule to populate the user's roles since it's security realm (registered in Tomcat) will now be called.
Recently I came across a small problem with setting up Oracle UCM 10gR3 on a MSSQL2005 instance.
Using the net.sourceforge.jtds.jdbc.Driver class.
The DBAs had setup a clustered SQL environment and had given me MSSQLDB0001\ARCHIVETR.
ARCHIVETR being the SQL instance which I needed to install the UCM to.
For future reference all you need to do is append ‘;instance=ARCHIVETR’ to the connection string like the following:
What's the best way to read a large XML document?
Of course you'd use a SAX parser or a pull parser.
What's the best way to write a large XML document?
Building a DOM structure to describe a large XML document
won't work because it won't fit in memory.
Even if it did, it's not a simple API to use.
There hasn't been a solution that is
simple and memory efficient until now.
Writing API for XML (WAX) is a free, open-source, library
for writing XML documents.
I created it because I got an OutOfMemoryError
while trying to output a large XML document
from an application I wrote using JDOM,
another Java-based XML library.
I searched for other libraries
that could write large XML documents
but couldn't find any that were
as simple to use as I thought they should be.
WAX is released under the
LGPL
with the intention of making its use unencumbered.
It is well-tested and ready for production use.
The WAX home page is at
http://www.ociweb.com/wax/.
Java and Ruby versions are available now.
The Java version of WAX can be downloaded from Google Code at
http://code.google.com/p/waxy/.
For information about the Ruby version, click here.
Ports for other programming languages will follow.
WAX has the following characteristics:
focuses on writing XML, not reading it
requires less code than other approaches
uses less memory than other approaches
(because it outputs XML as each method is called rather than
storing it in a DOM-like structure and outputting it later)
doesn't depend on any Java classes
other than standard JDK classes
is a small library (around 16K)
writes all XML node types
always outputs well-formed XML or throws an exception
unless running in "trust me" mode
provides extensive error checking
automatically escapes special characters in
text and attribute values (unless "unescaped" methods are used)
allows most error checking to be turned off for performance
knows how to associate DTDs, XML Schemas and
XSLT stylesheets with the XML it outputs
is well-suited for writing XML request and response messages
for REST-based and SOAP-based services
This section provides many examples of using WAX.
Each code snippet is followed by the output it produces.
When the no-arg WAX constructor is used,
XML is written to standard output.
There are also WAX constructors that take
a java.io.OutputStream
or a java.io.Writer object.
Here's a simple example where only a root element is written:
WAX wax = new WAX();
wax.start("car").close();
<car/>
After a WAX object is closed,
a new one must be created in order to write more XML.
In the examples that follow, assume that has been done.
Let's write a root element with some text inside:
wax.start("car").text("Prius").end().close();
<car>Prius</car>
The default indentation used is two spaces.
The end method terminates the element
that is started by the start method.
In this case it's not necessary to call end
because the close method
terminates all unterminated elements.
Attributes must be specified before
any content for their element is specified.
For example, calling
start, attr and text is valid,
but calling
start, text and attr is not.
If this rule is violated then
an IllegalStateException is thrown.
Let's add an XML declaration:
WAX wax = new WAX(Version.V1_0); // Version is an enum
wax.start("car").attr("year", 2008)
.child("model", "Prius").close();
Like attributes, namespaces must be specified
before any content for their element is specified.
If this rule is violated then
an IllegalStateException is thrown.
<!DOCTYPE car SYSTEM "car.dtd">
<car year="2008">
<model>Prius</model>
</car>
Let's add and use entity definitions:
String url = "http://www.ociweb.com/xml/";
wax.entityDef("oci", "Object Computing, Inc.")
.externalEntityDef("moreData", url + "moreData.xml")
.start("root")
.unescapedText("The author works at &oci; in St. Louis, Missouri.",
true) // avoiding escaping for entity reference
.unescapedText("&moreData;", true)
.close();
<!DOCTYPE root [
<!ENTITY oci "Object Computing, Inc.">
<!ENTITY moreData SYSTEM "http://www.ociweb.com/xml/moreData.xml">
]>
<root>
The author works at &oci; in St. Louis, Missouri.
&moreData;
</root>
A common usage pattern is to pass a
WAX object to a method of model objects
that use it to write their XML representation.
For example, a Car class could have the following method.
Quickly create web services in Spring 2.5 using Apache CXF 2.0, a.k.a. XFire 2.0.
In this tutorial I explain how to get a web service
up and running using Spring 2.5 and Apache CXF 2.0, which is the
combination of Celtix and XFire
and is considered XFire 2.0. (I don't know what the Celtix team would say about that, but
that's what the XFire site says.) Here I just
treat the web service itself; to learn about consuming the web service using Spring and CXF,
please see the article Make Web Services
Transparent with Spring 2.5 and Apache CXF 2.0.
CXF supports both WSDL-first and Java-first web service development. This article takes
the Java-first approach.
Project Setup
The first thing you'll need to do is download
CXF from the Apache CXF site. At the time of this writing the project is in incubator status
and the latest version is 2.0.4. That's the version I'm using.
Also, the docs describe a "Hello, World" web service that just returns a string, and in this
tutorial we want to go a little further than that and actually do a class databinding.
Here are the service-side dependencies you'll need. Inside the distribution there is
a file called WHICH_JARS that describes in a little more detail what the JARs
are for and which ones you'll really need, if you're interested in that. But the following
is essentially the list given in the user docs.
CXF itself
cxf-2.0.4-incubator.jar
CXF dependencies
Note that for CXF 2.0.4 the documented dependencies are almost but not quite
the same as the JARs that are actually included in the distribution, once again,
at the time of this writing (February 2008). Specifically the stax,
neethi and XMLSchema JARs are not the ones listed. Here's
the corrected list for CXF 2.0.4:
In addition to the above, you will need to add jdom-1.0.jar since
Aegis databinding uses it.
Spring dependencies
In this case ignore what's in the CXF documentation, because we're integrating
with Spring 2.5 instead of Spring 2.0. I'm going to assume that you have Spring 2.5
already set up on your web services project, including Hibernate or anything else that
your web services will need on the implementation side.
Just in case you were wondering, you don't need the Spring MVC module's
DispatcherServlet as CXF comes with its own servlet,
org.apache.cxf.transport.servlet.CXFServlet.
OK, that should be good for basic project setup. Let's write a simple service.
You should be able to delete
${catalina.home}/work/Catalina/localhost/appName/SESSION.ser where
appName is your application (or just delete the whole work directory).
In Struts 2, resource bundles can be associated with classes. The
framework will automatically discover and load class-orientated
resource bundles. You can also specify one or more global resource
bundles, which would be available to all classes in the application,
using either the standard properties file, or a custom listener.
Properties file
Global resource bundles can be specified in the struts.properties configuration file.
struts.properties
struts.custom.i18n.resources=global-messages
The framework searches the class heirarchy first, then, as a last resource, checks the global resources.
Multiple resource bundles can be specified by providing a comma-separated list.
Aside from the properties file, a Listener could also be used to load global resource bundles.
ActionGlobalMessagesListener.java
public class ActionGlobalMessagesListener implements ServletContextListener { privatestatic Logger log = Logger.getLogger(ActionGlobalMessagesListener .class); privatestaticfinalString DEFAULT_RESOURCE = "global-messages";
/** * Uses the LocalizedTextUtil to load messages from the global message bundle. * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.Servle tContextEvent) */ public void contextInitialized(ServletContextEvent arg0) { log.info("Loading global messages from " + DEFAULT_RESOURCE); LocalizedTextUtil.addDefaultResourceBundle(DEFAULT_RESOURCE); log.info("Global messages loaded."); }
/** * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) */ public void contextDestroyed(ServletContextEvent arg0) {
private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
public static final String toString(byte[] ba, int offset, int length) { char[] buf = new char[length * 2]; for (int i = 0, j = 0, k; i < length; ) { k = ba[offset + i++]; buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F]; buf[j++] = HEX_DIGITS[ k & 0x0F]; } return new String(buf); }
This Appendix shows an example of a dynamic client application that does not use the WSDL file when it invokes a WebLogic Web Service. In particular, the example invokes a message-style Web service and sends data to WebLogic Server.
Dynamic client applications that do not use the WSDL of the Web service are dynamic in every way, because they can invoke a Web service without knowing either the interface of the Web service, or the JavaBean interface of return values and parameters, or even the number and signatures of the methods that make up the Web service.
The example uses the URL http://www.myHost.com:7001/msg/sendMsg to invoke the Web Service. Because the example shows a dynamic client application that does not use the WSDL of the Web service, the preceding URL is for the Web service itself, rather than the URL for the WSDL of the Web service.
The procedure after the example discusses relevant sections of the example as part of the basic steps you follow to create this client.
String toSend = arg.length == 0 ? "No arg to send" : arg[0];
Object result = method.invoke( new Object[]{ toSend } );
}
}
Follow these steps to create a dynamic Java client that does not use WSDL to invoke a message-style WebLogic Web Service that sends data to WebLogic Server:
Get the Java client JAR file from the WebLogic Server hosting the WebLogic Web Service.
Add the Java client JAR file to your CLASSPATH on your client computer.
Create the client Java program. The following steps describe the Web services-specific Java code:
In the main method of your client application, create a factory of encoding styles and register the two that are supported by WebLogic Server (the SOAP encoding style and Apache's Literal XML encoding style):
CodecFactory factory = CodecFactory.newInstance();
factory.register( new SoapEncodingCodec() );
factory.register( new LiteralCodec() );
Add the following Java code to create the connection to the Web service and set the encoding style factory:
Invoke the send method and send data to the Web service. In the example, the client application simply takes its first argument and sends it as a String; if the user does not specify an argument specified, then the client application sends the string No arg to send:
String toSend = arg.length == 0 ? "No arg to send" : arg[0];
Object result = method.invoke( new Object[]{ toSend } );
Compile and run the client Java program as usual.
The following more complex example shows how to use a send method that accepts a org.w3c.dom.Document, org.w3c.dom.DocumentFragment, or org.w3c.dom.Element data type as its parameter. The example shows how to set literal encoding on this flavor of the send method.
// Print out proxy to make sure method signature looks good
System.out.println("Proxy:"+proxy);
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
//Obtain an instance of a DocumentBuilder from the factory.
DocumentBuilder db = dbf.newDocumentBuilder();
//Parse the document.
Document w3cDoc = db.parse(new File("/test/fdr_nodtd.xml"));
// Print out XML just to make sure the document was read successfully
OutputFormat of = new OutputFormat();
of.setEncoding("UTF-8");
of.setLineWidth(40);
of.setIndent(4);
XMLSerializer xs = new XMLSerializer(System.out,of);
xs.serialize(w3cDoc);
System.out.println("Before Invoke");
Object result = method.invoke( new Object[]{w3cDoc} );
System.out.println("Done");
}
}
Download RandomGUID. -- generates truly random GUIDs in the standard format.
RandomGUID.java
/*
* RandomGUID
* @version 1.2.1 11/05/02
* @author Marc A. Mnich
*
* From www.JavaExchange.com, Open Software licensing
*
* 11/05/02 -- Performance enhancement from Mike Dubman.
* Moved InetAddr.getLocal to static block. Mike has measured
* a 10 fold improvement in run time.
* 01/29/02 -- Bug fix: Improper seeding of nonsecure Random object
* caused duplicate GUIDs to be produced. Random object
* is now only created once per JVM.
* 01/19/02 -- Modified random seeding and added new constructor
* to allow secure random feature.
* 01/14/02 -- Added random function seeding with JVM run time
*
*/
import java.net.*;
import java.util.*;
import java.security.*;
/*
* In the multitude of java GUID generators, I found none that
* guaranteed randomness. GUIDs are guaranteed to be globally unique
* by using ethernet MACs, IP addresses, time elements, and sequential
* numbers. GUIDs are not expected to be random and most often are
* easy/possible to guess given a sample from a given generator.
* SQL Server, for example generates GUID that are unique but
* sequencial within a given instance.
*
* GUIDs can be used as security devices to hide things such as
* files within a filesystem where listings are unavailable (e.g. files
* that are served up from a Web server with indexing turned off).
* This may be desireable in cases where standard authentication is not
* appropriate. In this scenario, the RandomGUIDs are used as directories.
* Another example is the use of GUIDs for primary keys in a database
* where you want to ensure that the keys are secret. Random GUIDs can
* then be used in a URL to prevent hackers (or users) from accessing
* records by guessing or simply by incrementing sequential numbers.
*
* There are many other possiblities of using GUIDs in the realm of
* security and encryption where the element of randomness is important.
* This class was written for these purposes but can also be used as a
* general purpose GUID generator as well.
*
* RandomGUID generates truly random GUIDs by using the system's
* IP address (name/IP), system time in milliseconds (as an integer),
* and a very large random number joined together in a single String
* that is passed through an MD5 hash. The IP address and system time
* make the MD5 seed globally unique and the random number guarantees
* that the generated GUIDs will have no discernable pattern and
* cannot be guessed given any number of previously generated GUIDs.
* It is generally not possible to access the seed information (IP, time,
* random number) from the resulting GUIDs as the MD5 hash algorithm
* provides one way encryption.
*
* ----> Security of RandomGUID: <-----
* RandomGUID can be called one of two ways -- with the basic java Random
* number generator or a cryptographically strong random generator
* (SecureRandom). The choice is offered because the secure random
* generator takes about 3.5 times longer to generate its random numbers
* and this performance hit may not be worth the added security
* especially considering the basic generator is seeded with a
* cryptographically strong random seed.
*
* Seeding the basic generator in this way effectively decouples
* the random numbers from the time component making it virtually impossible
* to predict the random number component even if one had absolute knowledge
* of the System time. Thanks to Ashutosh Narhari for the suggestion
* of using the static method to prime the basic random generator.
*
* Using the secure random option, this class compies with the statistical
* random number generator tests specified in FIPS 140-2, Security
* Requirements for Cryptographic Modules, secition 4.9.1.
*
* I converted all the pieces of the seed to a String before handing
* it over to the MD5 hash so that you could print it out to make
* sure it contains the data you expect to see and to give a nice
* warm fuzzy. If you need better performance, you may want to stick
* to byte[] arrays.
*
* I believe that it is important that the algorithm for
* generating random GUIDs be open for inspection and modification.
* This class is free for all uses.
*
*
* - Marc
*/
public class RandomGUID extends Object {
public String valueBeforeMD5 = "";
public String valueAfterMD5 = "";
private static Random myRand;
private static SecureRandom mySecureRand;
private static String s_id;
/*
* Static block to take care of one time secureRandom seed.
* It takes a few seconds to initialize SecureRandom. You might
* want to consider removing this static block or replacing
* it with a "time since first loaded" seed to reduce this time.
* This block will run only once per JVM instance.
*/
static {
mySecureRand = new SecureRandom();
long secureInitializer = mySecureRand.nextLong();
myRand = new Random(secureInitializer);
try {
s_id = InetAddress.getLocalHost().toString();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
/*
* Default constructor. With no specification of security option,
* this constructor defaults to lower security, high performance.
*/
public RandomGUID() {
getRandomGUID(false);
}
/*
* Constructor with security option. Setting secure true
* enables each random number generated to be cryptographically
* strong. Secure false defaults to the standard Random function seeded
* with a single cryptographically strong random number.
*/
public RandomGUID(boolean secure) {
getRandomGUID(secure);
}
/*
* Method to generate the random GUID
*/
private void getRandomGUID(boolean secure) {
MessageDigest md5 = null;
StringBuffer sbValueBeforeMD5 = new StringBuffer();
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
System.out.println("Error: " + e);
}
try {
long time = System.currentTimeMillis();
long rand = 0;
if (secure) {
rand = mySecureRand.nextLong();
} else {
rand = myRand.nextLong();
}
// This StringBuffer can be a long as you need; the MD5
// hash will always return 128 bits. You can change
// the seed to include anything you want here.
// You could even stream a file through the MD5 making
// the odds of guessing it at least as great as that
// of guessing the contents of the file!
sbValueBeforeMD5.append(s_id);
sbValueBeforeMD5.append(":");
sbValueBeforeMD5.append(Long.toString(time));
sbValueBeforeMD5.append(":");
sbValueBeforeMD5.append(Long.toString(rand));
valueBeforeMD5 = sbValueBeforeMD5.toString();
md5.update(valueBeforeMD5.getBytes());
byte[] array = md5.digest();
StringBuffer sb = new StringBuffer();
for (int j = 0; j < array.length; ++j) {
int b = array[j] & 0xFF;
if (b < 0x10) sb.append('0');
sb.append(Integer.toHexString(b));
}
valueAfterMD5 = sb.toString();
} catch (Exception e) {
System.out.println("Error:" + e);
}
}
/*
* Convert to the standard format for GUID
* (Useful for SQL Server UniqueIdentifiers, etc.)
* Example: C2FEEEAC-CFCD-11D1-8B05-00600806D9B6
*/
public String toString() {
String raw = valueAfterMD5.toUpperCase();
StringBuffer sb = new StringBuffer();
sb.append(raw.substring(0, 8));
sb.append("-");
sb.append(raw.substring(8, 12));
sb.append("-");
sb.append(raw.substring(12, 16));
sb.append("-");
sb.append(raw.substring(16, 20));
sb.append("-");
sb.append(raw.substring(20));
return sb.toString();
}
/*
* Demonstraton and self test of class
*/
public static void main(String args[]) {
for (int i=0; i< 100; i++) {
RandomGUID myGUID = new RandomGUID();
System.out.println("Seeding String=" + myGUID.valueBeforeMD5);
System.out.println("rawGUID=" + myGUID.valueAfterMD5);
System.out.println("RandomGUID=" + myGUID.toString());
}
}
}
Download RandomGUID. -- generates truly random GUIDs in the standard format.