<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>F monologue &#187; datasource</title>
	<atom:link href="http://blog.fguy.com/tag/datasource/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.fguy.com</link>
	<description>Taehoon Kang</description>
	<lastBuildDate>Fri, 10 Feb 2012 00:53:34 +0000</lastBuildDate>
	<language>ko</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.fguy.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/302d17afa2133e49879c9121b033814d?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>F monologue &#187; datasource</title>
		<link>http://blog.fguy.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.fguy.com/osd.xml" title="F monologue" />
	<atom:link rel='hub' href='http://blog.fguy.com/?pushpress=hub'/>
		<item>
		<title>JNDI DataSource Loading for TDD</title>
		<link>http://blog.fguy.com/2008/11/04/jndi-datasource-loading-for-tdd/</link>
		<comments>http://blog.fguy.com/2008/11/04/jndi-datasource-loading-for-tdd/#comments</comments>
		<pubDate>Tue, 04 Nov 2008 09:32:17 +0000</pubDate>
		<dc:creator>fguy</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[datasource]]></category>
		<category><![CDATA[fscontrext]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JNDI]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[tomcat]]></category>

		<guid isPermaLink="false">http://fguy.krac.kr/2008/11/04/jndi-datasource-loading-for-tdd/</guid>
		<description><![CDATA[Tomcat 등의 Servlet Container를 사용하여, 웹애플리케이션을 개발할 때, DataSource를 Servlet Container의 Context 에 JNDI Resource로 bind 하여 사용하는 경우가 많다. test case를 실행하기 위해 JNDI remote provider 를 제공하는 application server (glassfish, jboss 등)를 사용할 수도 있으나, 이러한 것은 test의 &#8230; <a href="http://blog.fguy.com/2008/11/04/jndi-datasource-loading-for-tdd/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.fguy.com&amp;blog=13748523&amp;post=42&amp;subd=fguyblog&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Tomcat 등의 Servlet Container를 사용하여, 웹애플리케이션을 개발할 때, DataSource를 Servlet Container의 Context 에 JNDI Resource로 bind 하여 사용하는 경우가 많다. </p>
<p>test case를 실행하기 위해 JNDI remote provider 를 제공하는 application server (glassfish, jboss 등)를 사용할 수도 있으나, 이러한 것은 test의 원자성을 저해하기 때문에 test 환경 자체에서 JNDI resource를 생성할 수 있는 방법을 생각해 보았다.</p>
<p><a href="http://java.sun.com/products/jndi/" target="_blank">Sun에서 제공</a>하는 File System Service Provider를 이용하는 것이다. 사용법은 매우 간단하다. 단순히 naming context의 initail context factory 를 com.sun.jndi.fscontext.RefFSContextFactory 로 지정하기만 하면 된다.</p>
<p>다음은 간단히 만들어 본 class 이다. 이 class는 context xml 파일을 읽어서 JNDI resource를 loading해 주는 역할을 한다. test를 수행하기 전에 JNDILoader.init()을 실행 해주면 다른 작업 없이 test case를 실행시킬 수 있을 것이다.</p>
<pre>package com.fguy.test;

import java.io.File;
import java.io.IOException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class JNDILoader {
	private static final Logger LOG = Logger.getLogger(JNDILoader.class);

	private static final boolean initialized = false;
	private static final String CONTEXT_XML = "WebContent/META-INF/context.xml";

	private JNDILoader() {

	}

	public static final void init() throws ParserConfigurationException,
			SAXException, IOException, DOMException, NamingException {

		if (!initialized) {
			Context context = getNamingContext();

			List resourceNames = new ArrayList();
			Map&gt; references = new HashMap&gt;();

			NodeList contextResourceNodeList = getContextResourceNodeList();
			for (int i = 0; i &lt; contextResourceNodeList.getLength(); i++) {
				Node item = contextResourceNodeList.item(i);
				// print comment;
				if (LOG.isDebugEnabled()
						&amp;&amp; item.getNodeType() == Node.COMMENT_NODE
						&amp;&amp; item != null) {
					LOG.debug(item.getNodeValue());
				}

				// register to JNDI
				if ("resource".equalsIgnoreCase(item.getNodeName())
						&amp;&amp; "javax.sql.DataSource".equals(item.getAttributes()
								.getNamedItem("type").getNodeValue())) {
					NamedNodeMap attributes = item.getAttributes();
					String name = attributes.getNamedItem("name")
							.getNodeValue();
					Map reference = references.get(name);

					if (reference == null) {
						reference = new HashMap();
					}

					for (int j = 0; j &lt; attributes.getLength(); j++) {
						String n = attributes.item(j).getNodeName();
						String v = attributes.item(j).getNodeValue();
						if (!"name".equals(n)) {
							reference.put(n, v);
						}
						LOG.debug(attributes.item(j));
					}

					resourceNames.add(name);
					references.put(name, reference);
				}

				if ("resourceparams".equalsIgnoreCase(item.getNodeName())) {
					NodeList parameters = item.getChildNodes();
					String name = item.getAttributes().getNamedItem("name")
							.getNodeValue();
					Map reference = references.get(name);

					if (reference == null) {
						reference = new HashMap();
					}

					for (int j = 0; j &lt; parameters.getLength(); j++) {
						Node paramItem = parameters.item(j);
						if ("parameter".equalsIgnoreCase(paramItem
								.getNodeName())) {
							NodeList children = paramItem.getChildNodes();
							String n = null;
							String v = null;
							for (int k = 0; k &lt; children.getLength(); k++) {
								Node child = children.item(k);
								if ("name"
										.equalsIgnoreCase(child.getNodeName())) {
									n = child.getNodeValue();
								} else if ("value".equalsIgnoreCase(child
										.getNodeName())) {
									v = child.getNodeValue();
								}
								LOG.debug(child);
							}
							reference.put(n, v);
						}
					}
					references.put(name, reference);
				}
			}
			for (String name : resourceNames) {
				Reference reference = new Reference("javax.sql.DataSource",
						"org.apache.commons.dbcp.BasicDataSourceFactory", null);
				Map referenceMap = references.get(name);

				for (String key : referenceMap.keySet()) {
					reference
							.add(new StringRefAddr(key, referenceMap.get(key)));
				}

				context.rebind("java:comp/env/".concat(name), reference);
			}
		}
	}

	private static final NodeList getContextResourceNodeList()
			throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(new File(CONTEXT_XML));
		return doc.getFirstChild().getChildNodes();
	}

	private static final Context getNamingContext() throws NamingException {
		System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.fscontext.RefFSContextFactory");
		System.setProperty(Context.PROVIDER_URL, "file:///tmp");

		return new InitialContext();
	}
}</pre>
<br /> Tagged: datasource, fscontrext, java, JNDI, TDD, tomcat <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/fguyblog.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/fguyblog.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/fguyblog.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/fguyblog.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/fguyblog.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/fguyblog.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/fguyblog.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/fguyblog.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/fguyblog.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/fguyblog.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/fguyblog.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/fguyblog.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/fguyblog.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/fguyblog.wordpress.com/42/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.fguy.com&amp;blog=13748523&amp;post=42&amp;subd=fguyblog&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.fguy.com/2008/11/04/jndi-datasource-loading-for-tdd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d10c905edc572a61b5206377c1a36c98?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">fguy79</media:title>
		</media:content>
	</item>
	</channel>
</rss>
