<?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/"
	>

<channel>
	<title>Wazi &#187; Tutorials</title>
	<atom:link href="http://olex.openlogic.com/wazi/category/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://olex.openlogic.com/wazi</link>
	<description>Thinking OPEN</description>
	<lastBuildDate>Fri, 19 Mar 2010 03:29:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Creating Intelligent Projects with Maven</title>
		<link>http://olex.openlogic.com/wazi/2010/creating-intelligent-projects-with-maven/</link>
		<comments>http://olex.openlogic.com/wazi/2010/creating-intelligent-projects-with-maven/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 16:53:32 +0000</pubDate>
		<dc:creator>Mert</dc:creator>
				<category><![CDATA[Highlight]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Maven]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=52694</guid>
		<description><![CDATA[This tutorial covers the core concepts of Apache Maven and discusses how you can begin using Maven in your own development projects. Concepts covered include the Project Object Model (POM), Build Lifecycle, Dependency Management, Repositories, and Plugins. It also gives some hints on the IDE support you can find for popular Java IDEs.]]></description>
			<content:encoded><![CDATA[<p>This article covers core concepts of Apache Maven like the Project Object Model (POM), Build Lifecycle, Dependency Management, Repositories, and Plugins. It also gives some hints on the IDE support that you can find for popular Java IDEs.</p>
<p><a href="https://olex.openlogic.com/packages/maven">Maven</a> is a project management framework hosted by the Apache Software Foundation (ASF) at <a title="Maven Site" href="http://maven.apache.org" target="_blank">http://maven.apache.org</a>. The Maven project started as the result of build process needs inside ASF projects. Before Maven each Apache project had its own methods of compilation, distribution, web site generation, and etc. As a developer, one had to deal with each project&#8217;s build separately. In addition, people weren’t contributing enough to Apache projects since it was a hassle to get each one running on their locals.  So, there was a need for a uniform build system, and with the Apache Turbine project Maven took the scene.</p>
<p>Maven tries to make builds as easy as possible in a uniform way &#8212; if you know how to build one Maven project, you can build all of them. As Maven becomes more widely used, we believe that this will be the first thing that comes to mind any time someone mentions Maven.</p>
<h2>Before You Start</h2>
<p>You need to install Maven on your computer. You can either use the Maven that ships with IDEs / plugins, or you can download it from<a title="Maven Download" href="http://maven.apache.org/download.html" target="_blank"> http://maven.apache.org/download.html</a>.  Follow the installation instructions that are available for <a title="Maven Installation Instructions" href="http://www.sonatype.com/books/mvnref-book/reference/installation-sect-maven-install.html" target="_blank">MacOs</a>, <a title="Maven Installation Instructions" href="http://www.sonatype.com/books/mvnref-book/reference/installation-sect-windows.html" target="_blank">Windows</a> and <a title="Maven Installation Instructions" href="http://www.sonatype.com/books/mvnref-book/reference/installation-sect-maven-linux.html" target="_blank">Linux</a>.</p>
<h2>Meat &amp; Potatoes</h2>
<p>Probably the most important key concept of Maven is that it favors convention over configuration. With six lines of XML you can create a Maven project and build a jar file out of it. Maven offers common interfaces for building projects. You don&#8217;t need to deal with all the necessary libraries, the tasks to run to build the project, and etc.  There&#8217;s a good saying for this: before Maven, it was the era of build engineers.  Maven stops you from building the build, instead letting you focus on development to produce high quality code.  Maven has a detailed dependency management mechanism, so to get a project running on your local you don’t need to deal with jar files or the files that those jar files depend on &#8212; a la transitive dependency. Maven uses third-party public repositories for fetching all those artifacts, and there&#8217;s a good deal of them around.</p>
<p>Maven has a pluggable architecture, and the Maven core is actually very lightweight. It doesn&#8217;t even know about compiling code. It is just a matter of adding a compiler plugin. For Maven, a plugin is just another artifact to be fetched from a repository. Since the architecture is very pluggable, you can implement your own plugin and hook it into the build system easily.</p>
<p>In the sections below we&#8217;ll cover the core concepts of Maven in detail and discuss how you can begin using Maven in your own development projects.</p>
<h3>The POM</h3>
<p>POM stands for Project Object Model, and it&#8217;s what makes your project a Maven project. POM is an XML file that has the same declarative approach as in build.xml of Ant, or web.xml in Java web applications. POM describes the project with metadata for build processes, but it also contains data besides that which is needed for building, such as:</p>
<ul>
<li>the project’s relationship between Maven projects</li>
<li>the list of team members, contributors, and developers</li>
<li>source control management information</li>
<li> the license of the project</li>
<li> site generation information</li>
</ul>
<p>So, it is a conceptual model that tries to cover nearly all the definitions of a software project. POM has a seamless integration with Java, but it is not just for Java projects. For instance, you can build FLEX distributable artifacts with <a title="Israfil Maven Plugin" href="http://code.google.com/p/israfil-mojo" target="_blank">israfil</a> plugins, or you can create Microsoft binaries from C# codes, so it&#8217;s just a matter of plugins as we stated before. The best way to learn about the details of an XML file is to examine its XSD. Since XSD files are not human-readable, you can check out the XSD document of a Maven POM file that we shared at <a title="Maven POM XSD Documentation" href="http://www.tinyurl.com/maven-xsddoc" target="_blank">http://www.tinyurl.com/maven-xsddoc</a> so you can easily see the tags that can be used inside POM.</p>
<p>Here is a sample skeleton for Project Object Model.</p>
<blockquote>
<pre>&lt;project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    http://maven.apache.org/maven-v4_0_0.xsd"&gt;
   &lt;parent /&gt;
   &lt;groupId /&gt;
   &lt;artifactId /&gt;
   &lt;version /&gt;
   &lt;packaging /&gt;
   &lt;developers /&gt; &lt;contributors /&gt;
   &lt;scm&gt;...&lt;/scm&gt;
   &lt;build&gt;
      &lt;plugins&gt;...&lt;/plugins&gt;
   &lt;/build&gt;
   &lt;dependencies&gt;...&lt;/dependencies&gt;
   &lt;repositories&gt;...&lt;/repositories&gt;
   &lt;pluginRepositories&gt;...&lt;/pluginRepositories&gt;
   &lt;profiles&gt;...&lt;/profiles&gt;
&lt;/project&gt;</pre>
</blockquote>
<p>As you can see, all tags reside inside the project tag of POM.  Let&#8217;s go through the tags briefly. With the parent tag you can create parent-child relationships between your Maven projects.  The groupId,  artifactId and the version tags uniquely define a project coordinate.  With the packaging tag, project-specific packaging can be determined such as jar, war, and ear bundling.  The list of developers and contributors can be found inside the developers and contributors tags.  The source control definitions can be provided with the SCM tag, and the build tag allows you can hook in plugins needed for execution and configure them according to your needs.  With the repositories and pluginRepositories definitions you can tell Maven where to look to download the needed dependencies and plugins.  And finally, the profile tag allows you to generate different builds of a project like development, staging or production.</p>
<p>Here is the simplest POM. It&#8217;s just six lines of XML to define a Maven project.</p>
<blockquote>
<pre>&lt;project&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;groupId&gt;com.openlogic.wazi&lt;/groupId&gt;
    &lt;artifactId&gt;myapp&lt;/artifactId&gt;
    &lt;version&gt;1.0.0&lt;/version&gt;
&lt;/project&gt;</pre>
</blockquote>
<p>When we run the <em>mvn install</em> command on this project Maven will try to compile the code, run the tests against that code, package the project as a jar file, and deploy it to the local repository. You may ask how that&#8217;s possible with just six lines of XML &#8212; after all, we haven&#8217;t defined any source folders, test folders, or the target folder that will contain the compiled classes.  Well, those are all coming from the convention.  And they are all defined in the <em>Super POM</em>.</p>
<p>Super POM has the same analogy with Java as in java.lang.Object.  Every Maven project extends this super POM.  It resides under the Maven uber jar.  Super POM defines the standard directory layout.  With Maven 2.0.9, super POM also locks the versions of common plugins to have stable builds.  So it&#8217;s best to use the latest Maven in order to have stable and better builds.  Super POM also contains the central Maven repository definition, <a title="Maven Central Repository" href="http://repo1.maven.org/maven2" target="_blank">http://repo1.maven.org/maven2</a>. Note that there could be more than one POM through your project hierarchy.  Your project can have a parent project, and that parent project will extend the super POM.  Inside the child project, the elements of parent POM are inherited.  So, if you want to see the merged version of the POM, just run the command <strong><em>mvn help:effective-pom</em></strong> goal.</p>
<h3>Build LifeCycle</h3>
<p>We declared the project with the model, but we need a process for building the project out of this metadata.  To achieve this, Maven introduces the concept of lifecycles.  A lifecycle is a process for building and distributing an artifact, and it is clearly defined.  There are three built-in lifecycles of Maven: the <strong>default</strong>, which handles project deployment; the <strong>clean</strong>, which handles the cleaning of all project files generated by a previous build; and the <strong>site</strong>, which generates the project’s site documentation.  Each lifecycle contains phases in a specific order, and zero or more goals are attached to each phase.  So the atomic part here is the goal, and when we gather goals together we have the phases, and when phases are registered in specific order we have the lifecycle.  The illustration below shows the list of phases for the default lifecycle.</p>
<p style="text-align: center"><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/default-lifecycle-phases.png"><img class="aligncenter" src="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/default-lifecycle-phases.png" alt="" width="527" height="360" /></a></p>
<p>The default lifecycle of Maven first validates the project, like checking the consistency of pom.xml file, and then it tries to compile the code. If the compile is successful, it then tries to run the test against the compiled code, package the project in the specified format, run the integration tests against that package, verify the package by checking for the validity, install the verified package to the local repository, and finally deploy the package in the specified environment.</p>
<p>To execute phases/goals we can follow the notation below in the command line:</p>
<blockquote>
<pre>mvn <em>phase</em>
mvn <em>phase:goal</em></pre>
</blockquote>
<p>We can also invoke multiple phases/goals within one command line, like:</p>
<blockquote>
<pre>mvn <em>phase</em> <em>phase:goal</em>
mvn <em>phase:goal </em><em>phase:goal</em></pre>
</blockquote>
<p>When we invoke the <em>mvn integration-test</em> command, Maven executes all the phases that are registered before that phase.  So the validate, compile, and package phases get executed before the integration-test phase.</p>
<h3>Dependency Management</h3>
<p>Maven is very capable of handling dependencies as the build tool.  If you&#8217;re still using the old-fashioned method of copying the necessary artifacts by hand to your lib folder,  believe us &#8212; it’s the beginning of the end for your project. You will find yourself in jar hell very soon.  So how can you avoid this?  The answer is Maven and its dependency mechanism.</p>
<p>If you specify a dependency by giving the coordinates of some third party project, which is the group identifier, artifact identifier, and the version, Maven will look for that artifact inside the defined repositories and fetch to the local repository.  Since everything is a plugin to Maven in the ecosystem, Maven-dependency-plugin is responsible for those actions.</p>
<p>Here is a sample dependency declaration for the project <a href="https://olex.openlogic.com/packages/junit">JUnit</a>.  The dependency is defined by its coordinates, groupId, artifactId, and version.</p>
<blockquote>
<pre>&lt;dependency&gt;
     &lt;groupId&gt;junit&lt;/groupId&gt;
     &lt;artifactId&gt;junit&lt;/artifactId&gt;
     &lt;version&gt;4.8.1&lt;/version&gt;
     &lt;scope&gt;compile&lt;/scope&gt;
&lt;/dependency&gt;</pre>
</blockquote>
<p>Scopes can also be provided while defining the dependency. There are six kinds of scopes.  The default scope is the compile.  All dependencies scoped as compile are in the project&#8217;s compile, test, and runtime classpaths by default.  Provided is a similar scope to compile, but it is expected that the dependency should be provided by JDK or the container at runtime.  For instance, servlet.jar is one of the dependencies that is usually scoped like this.  Because it will be provided by the web container, provided scope affects the compile and test classpaths.  Runtime scope means that the dependency is not needed for compilation, but it is needed at test execution and runtime so it affects the test and runtime classpaths.  For instance we might need a JDBC driver implementation only at runtime, so artifact will be scoped as provided.  Test scope means that dependency is only needed for test compilation and execution and not for the application itself.  It affects the test classpath.  System scope is the same as provided, but the dependency should be explicitly specified since it won’t be looked up in the repository.  It affects the compile and test classpaths. To declare the path of the dependency there is the &lt;systemPath&gt; tag that you can use.  Actually, we don&#8217;t recommend using this, because in our opinion every dependency should be &#8220;Mavenized&#8221; and go into the repository.  The last scope is import, which is introduced with Maven 2.0.9.  With import scope it is stated that the specified POM should be replaced with the dependencies in that POM&#8217;s <tt>&lt;dependencyManagement&gt;</tt> section.</p>
<h3>Versions and Ranges on Dependencies</h3>
<p>Maven follows this notation for versioning artifacts:</p>
<blockquote>
<pre>&lt;major&gt;.&lt;minor&gt;.&lt;incremental&gt; - &lt;qualifier&gt;</pre>
</blockquote>
<p>It starts with a major version and follows up with a minor one, and then an incremental version comes up.  At the end you can also add a qualifier in free-text format.  For example, both of these examples are valid artifact versions:</p>
<blockquote>
<pre>1.2.3
1.2.3-alpha-01</pre>
</blockquote>
<p>Be careful about qualifier notation since Maven uses string comparison while comparing two artifacts.  For example, 1.2.3-alpha-2 would be a later version than 1.2.3-alpha-10.  Zero left padding is needed on the alpha-2 qualifier to make it the earlier version.  You can also define ranges on versions while adding dependencies to your project, and you can define exclusion or inclusion on the range with the bracket notation like this:</p>
<blockquote>
<pre>&lt;dependency&gt;
     &lt;groupId&gt;junit&lt;/groupId&gt;
     &lt;artifactId&gt;junit&lt;/artifactId&gt;
     &lt;version&gt;[3.8,4.0)&lt;/version&gt;
&lt;/dependency&gt;</pre>
</blockquote>
<p>The version tag here states that it should be <span style="text-decoration: underline">3.8</span> at least, and it should be below <span style="text-decoration: underline">4.0</span>.</p>
<h3>Snapshot Qualifier</h3>
<p>Maven also has a special qualifier, the SNAPSHOT, which indicates the artifact is created while the project is under active development.  When you install/release an artifact or fetch one from a remote repository, Maven expands this SNAPSHOT suffix with a date (UTC format)-time-buildnumber pattern.  So for an artifact such as myjar-1.0.0-SNAPSHOT.jar the result would be something like myjar-1.0.0-20100219.141012-1.jar.  And if you install a SNAPSHOT artifact to your local repository, it will not get converted to the date-time format in order to avoid filling your hard disk with snapshot versions.</p>
<p>By default Maven will periodically (on a daily basis) attempt to download the latest version of the snapshot.  You can change it to &#8220;always&#8221; or an &#8220;interval&#8221; specified in minutes by adjusting the setting in your repository configuration.</p>
<blockquote>
<pre>&lt;releases&gt;
      &lt;updatePolicy&gt;interval:30&lt;/updatePolicy&gt;
&lt;/releases&gt;</pre>
</blockquote>
<h3>Managing Projects and Dependencies</h3>
<p>Maven supports parent-child relationships between projects.  To declare a project as a parent, add the parent tag in your project’s pom.xml like this:</p>
<blockquote>
<pre>&lt;project&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;parent&gt;
        &lt;groupId&gt;com.openglogic.wazi&lt;/groupId&gt;
        &lt;artifactId&gt;parentapp&lt;/artifactId&gt;
        &lt;version&gt;1.0.0&lt;/version&gt;
    &lt;/parent&gt;
    &lt;artifactId&gt;sampleapp&lt;/artifactId&gt;
&lt;/project&gt;</pre>
</blockquote>
<p>Just add the groupId, artifactId, and version of your parent project.  Maven will look into the parent folder and the local repository to locate that parent project.  It&#8217;s not mandatory to define groupId and version in your subproject, as Maven could inherit those fields from the parent.  Your project will also inherit dependencies that are declared in the parent project&#8217;s POM.  To see the merged version of the child project&#8217;s POM we can use <em>mvn help:effective-pom </em>command.  Actually, the most likely problem that you might encounter here is this: if you have a good number of child projects extending one parent POM, changing one dependency in the parent causes all child projects to face the consequences of that change.  Thus, it might be better to use the <em>dependencyManagement</em> feature.  Here&#8217;s the parent POM of a project that defines <a href="https://olex.openlogic.com/packages/commons-logging">Commons-Logging</a> with dependencyManagement at version 1.1.1:</p>
<blockquote>
<pre>&lt;project&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;groupId&gt;com.openlogic.wazi&lt;/groupId&gt;
    &lt;artifactId&gt;parentapp&lt;/artifactId&gt;
    &lt;packaging&gt;pom&lt;/packaging&gt;
    &lt;version&gt;1.0&lt;/version&gt;
    &lt;dependencyManagement&gt;
       &lt;dependencies&gt;
           &lt;dependency&gt;
               &lt;groupId&gt;commongs-logging&lt;/groupId&gt;
               &lt;artifactId&gt;commongs-logging&lt;/artifactId&gt;
               &lt;version&gt;1.1.1&lt;/version&gt;
           &lt;/dependency&gt;
       &lt;/dependencies&gt;
    &lt;/dependencyManagement&gt;
&lt;/project&gt;</pre>
</blockquote>
<p>And here&#8217;s the POM of a child application.  As you can see, we didn&#8217;t define the version of Commons-Logging.  Instead, the version that we declared in the parent POM will be used.  And if we don&#8217;t define the Commons-Logging dependency in the child, it won&#8217;t be inherited from parent as in the previous case.</p>
<blockquote>
<pre>&lt;project&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;parent&gt;
        &lt;groupId&gt;com.openlogic.wazi&lt;/groupId&gt;
        &lt;artifactId&gt;parentapp&lt;/artifactId&gt;
        &lt;version&gt;1.0&lt;/version&gt;
    &lt;/parent&gt;
    &lt;artifactId&gt;sampleapp&lt;/artifactId&gt;
    &lt;dependencies&gt;
       &lt;dependency&gt;
           &lt;groupId&gt;commongs-logging&lt;/groupId&gt;
           &lt;artifactId&gt;commongs-logging&lt;/artifactId&gt;
       &lt;/dependency&gt;
    &lt;/dependencies&gt;
&lt;/project&gt;</pre>
</blockquote>
<p>You may also have a project dependency hierarchy like this:</p>
<p style="text-align: center"><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/project-dependency-hierarchy.png"><img class="aligncenter" src="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/project-dependency-hierarchy.png" alt="" width="474" height="61" /></a></p>
<p>Here projectA depends on projectB and projectB depends on projectC.  So to compile projectA we need to compile projectB, but in order to compile projectB we need to compile projectC.  And that results to eight lines of Maven commands for just compiling projectA.</p>
<p style="text-align: center"><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/8-lines.png"><img class="aligncenter" src="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/8-lines.png" alt="" width="350" height="223" /></a></p>
<p>To overcome this, Maven supports a project modules approach.  We can create a modules project and have that project to point to the submodules. Here is the POM of modulesapp:</p>
<blockquote>
<pre>&lt;project&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;groupId&gt;com.openlogic.wazi&lt;/groupId&gt;
    &lt;artifactId&gt;modulesapp&lt;/artifactId&gt;
    &lt;packaging&gt;pom&lt;/packaging&gt;
    &lt;version&gt;1.0&lt;/version&gt;
    &lt;name&gt;modulesapp&lt;/name&gt;
    &lt;modules&gt;
        &lt;module&gt;projectA&lt;/module&gt;
        &lt;module&gt;projectB&lt;/module&gt;
        &lt;module&gt;projectC&lt;/module&gt;
    &lt;/modules&gt;
&lt;/project&gt;</pre>
</blockquote>
<p>By just compiling the modulesapp, we&#8217;ll have three submodules compiled automatically since they&#8217;re declared as modules inside the project. Maven-reactor-plugin will take the stage here and analyze the dependency hierarchy to define the order of compile.</p>
<h3>Repositories</h3>
<p>At some point each Java project that we’ve been developing heavily depends on other artifacts. For instance, a simple web application using the stack JSF, PrimeFaces, Seam, JPA, and Hibernate will have 40 dependencies like:</p>
<blockquote>
<pre>REPO/javax/activation/activation/1.1/activation-1.1.jar
REPO/antlr/antlr/2.7.6/antlr-2.7.6.jar
REPO/asm/asm/3.1/asm-3.1.jar
REPO/cglib/cglib/2.2/cglib-2.2.jar
REPO/commons-beanutils/commons-beanutils/1.7.0/commons-beanutils-1.7.0.jar
REPO/commons-codec/commons-codec/1.3/commons-codec-1.3.jar
REPO/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar
REPO/commons-lang/commons-lang/2.4/commons-lang-2.4.jar
REPO/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar
REPO/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar
REPO/javax/el/el-api/1.0/el-api-1.0.jar
REPO/org/hibernate/hibernate-annotations/3.5.0-Beta-2/hibernate-annotations-3.5.0-Beta-2.jar
REPO/org/hibernate/hibernate-commons-annotations/3.2.0.Beta1/hibernate-commons-annotations-3.2.0.Beta1.jar
REPO/org/hibernate/hibernate-core/3.5.0-Beta-2/hibernate-core-3.5.0-Beta-2.jar
REPO/org/hibernate/hibernate-entitymanager/3.5.0-Beta-2/hibernate-entitymanager-3.5.0-Beta-2.jar
REPO/org/hibernate/hibernate-validator-legacy/4.0.2.GA/hibernate-validator-legacy-4.0.2.GA.jar
REPO/hsqldb/hsqldb/1.8.0.2/hsqldb-1.8.0.2.jar
REPO/javassist/javassist/3.10.0.GA/javassist-3.10.0.GA.jar
REPO/org/jboss/el/jboss-el/1.0_02.CR4/jboss-el-1.0_02.CR4.jar
REPO/org/jboss/seam/jboss-seam/2.2.0.GA/jboss-seam-2.2.0.GA.jar
REPO/org/jboss/seam/jboss-seam-jul/2.2.0.GA/jboss-seam-jul-2.2.0.GA.jar
REPO/org/jboss/seam/jboss-seam-mail/2.2.0.GA/jboss-seam-mail-2.2.0.GA.jar
REPO/org/jboss/seam/jboss-seam-ui/2.2.0.GA/jboss-seam-ui-2.2.0.GA.jar
REPO/org/hibernate/java-persistence/jpa-api/2.0-cr-1/jpa-api-2.0-cr-1.jar
REPO/javax/faces/jsf-api/1.2_13/jsf-api-1.2_13.jar
REPO/com/sun/facelets/jsf-facelets/1.1.14/jsf-facelets-1.1.14.jar
REPO/javax/faces/jsf-impl/1.2_13/jsf-impl-1.2_13.jar
REPO/jstl/jstl/1.2/jstl-1.2.jar
REPO/javax/transaction/jta/1.1/jta-1.1.jar
REPO/junit/junit/3.8.1/junit-3.8.1.jar
REPO/javax/mail/mail/1.4.1/mail-1.4.1.jar
REPO/postgresql/postgresql/8.4-701.jdbc3/postgresql-8.4-701.jdbc3.jar
REPO/org/primefaces/primefaces/1.0.0/primefaces-1.0.0.jar
REPO/quartz/quartz/1.6.0/quartz-1.6.0.jar
REPO/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar
REPO/org/slf4j/slf4j-api/1.5.8/slf4j-api-1.5.8.jar
REPO/org/slf4j/slf4j-nop/1.5.6/slf4j-nop-1.5.6.jar
REPO/org/testng/testng/5.9/testng-5.9.jar
REPO/xpp3/xpp3_min/1.1.3.4.O/xpp3_min-1.1.3.4.O.jar
REPO/xstream/xstream/1.1.3/xstream-1.1.3.jar</pre>
</blockquote>
<p>Of course, we can store those jars in source control, but it will:</p>
<ul>
<li>increase the storage</li>
<li> make it dreadful to checkout the  project</li>
<li>force us to version our jars, and we certainly don&#8217;t need that</li>
</ul>
<p>To manage your project&#8217;s artifacts and dependencies Maven offers the repository mechanism. There are two types of repositories: a local one that caches the remote downloads your projects depends on and stores the build artifacts that you haven’t yet released; and the remote one that&#8217;s mostly hosted by a third party provider and is accessible with a variety of protocols like http. You can store artifacts with extensions like jars, wars, ears, ejbs, zips, and rar and resolve them through the Maven dependency management in your project. If there&#8217;s no external repository specified in the project’s POM, Maven looks for a local repository and the central Maven repository defined in the super POM. There are two types of repositories for hosting snapshot and release artifacts.  Here&#8217;s a sample declaration for each. The first declaration is for a JBoss release repository. The id is uniquely identifying the repository, and it&#8217;s pointing to the given URL.</p>
<blockquote>
<pre>&lt;repository&gt;
    &lt;id&gt;jboss-repo&lt;/id&gt;
    &lt;name&gt;The Release JBoss maven repo&lt;/name&gt;
    &lt;url&gt;http://repository.jboss.org/maven2&lt;/url&gt;
    &lt;releases&gt;
        &lt;enabled&gt;true&lt;/enabled&gt;
    &lt;/releases&gt;
&lt;/repository&gt;</pre>
</blockquote>
<p>The second declaration is for snapshot artifacts. By default, Maven will not look into repositories for snapshot artifacts if the repository declaration is not tagged as snapshots with the enabled tag.</p>
<blockquote>
<pre>&lt;repository&gt;
    &lt;id&gt;jboss-snapshot-repo&lt;/id&gt;
    &lt;name&gt;The Snapshot JBoss maven repo&lt;/name&gt;
    &lt;url&gt;http://snapshots.jboss.org/maven2&lt;/url&gt;
    &lt;snapshots&gt;
        &lt;enabled&gt;true&lt;/enabled&gt;
    &lt;/snapshots&gt;
&lt;/repository&gt;</pre>
</blockquote>
<h3>Searching for Artifacts Online</h3>
<p>Searching for artifacts to add as dependencies to your projects can be a problem from time to time. You know that you need a specific jar, such as the Apache Jackrabbit core jar file, but you don&#8217;t know about its groupId, artifactId, or the latest version that is available. With the sites listed below, you can easily search for your artifacts online.</p>
<p><a href="http://repository.apache.org" target="_blank">http://repository.apache.org</a><br />
<a href="http://www.jarvana.com"> http://www.jarvana.com</a><br />
<a href="http://mvnrepository.com"> http://mvnrepository.com</a><br />
<a href="http://www.artifact-repository.org"> http://www.artifact-repository.org</a><br />
<a href="http://www.mvnbrowser.com"> http://www.mvnbrowser.com</a><br />
<a href="http://mavensearch.net"> http://mavensearch.net</a></p>
<p>Apache runs a Nexus at repository.apache.org. You can find all the Apache-related stuff in there. Another one of the sites above, Jarvana, is actually one of our favorites. It gives you the ability to search for an artifact based on the project name or even a class file name. Suppose you&#8217;re developing a web application and you came across a class not found problem that occurred at runtime. With Jarvana you can search for those classes and find the related Maven artifact. It also lists the Javadocs and other cool stuff if applicable.</p>
<h3>IDE Support</h3>
<p>For popular JAVA IDEs like NetBeans Eclipse or IDEA, you can find first-class support for Maven inside the IDEs. NetBeans and Intellij IDEA support Maven out of the box and ship with the latest version, Maven 3. For Eclipse there are two incubation projects at the moment. One of them is Eclipse Integration for Apache Maven, Eclipse IAM, which is also formerly known as the Q4E project. The other one is the m2eclipse plugin and it&#8217;s being maintained by <a title="Sonatype Home" href="http://www.sonatype.com" target="_blank">Sonatype</a>. m2eclipse is a must-have plugin if you&#8217;re developing on Eclipse. With m2eclipse you can check out Maven projects directly from source control as Maven projects. It supports source controls like Subversion, CVS, Git and many others. You can also create new projects by selecting archetypes.  It&#8217;ll take 30 seconds to get you started, for instance, with web applications. There&#8217;s also a nice POM editor bundled with the plugin so you don&#8217;t need to deal with the XML directly. We&#8217;ve includes some screenshots of the plugin below.</p>
<p style="text-align: center"><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/m2eclipse-new.png"><img class="aligncenter" src="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/m2eclipse-new.png" alt="" width="600" height="575" /></a></p>
<p>To checkout projects from source control:</p>
<p style="text-align: center"><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/m2eclipse-checkout.png"><img class="aligncenter" src="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/m2eclipse-checkout.png" alt="" width="600" height="570" /></a></p>
<p>To create a project with archetypes:</p>
<p style="text-align: center"><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/m2eclipse-create.png"><img class="aligncenter" src="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/m2eclipse-create.png" alt="" width="600" height="491" /></a></p>
<p>The pom.xml editor &#8211; the dependencies:</p>
<p style="text-align: center"><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/pom-xml-editor.png"><img class="aligncenter" src="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/pom-xml-editor.png" alt="" width="600" height="315" /></a></p>
<p>The Dependency Graph:</p>
<p style="text-align: center"><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/dependency-graph.png"><img class="aligncenter" src="http://olex.openlogic.com/wazi/wp-content/uploads/2010/03/dependency-graph.png" alt="" width="600" height="312" /></a></p>
<h2>Finishing up</h2>
<p>There&#8217;s no better way to learn the benefits of Maven than to give it a try.  If you&#8217;re starting from scratch or have a greenfield project, now is the perfect time to get started with Maven!  Maven will ease the build process of your project, and it will be much simpler to manage the project with well-defined metadata. If you&#8217;re part of a group of developers working on the same project, you could also use Maven to create your own repository manager. (<a href="http://nexus.sonatype.org" target="_blank">Nexus</a>, <a href="http://archiva.apache.org" target="_blank">Arcihva</a> and <a href="http://www.jfrog.org/products.php" target="_blank">Artifactory</a> are other open source alternatives you can use for that.) Another way to get started with Maven is to create a company or project-specific POM to easily manage dependencies across your sub-projects.</p>
<p>Regardless of how you get started with Maven, here are a few tips to keep in mind:</p>
<ul>
<li>Keep your POM simple and readable.</li>
<li>Use property references to avoid any hard coding.</li>
<li>Use profiles to create different builds out of your project. Make it so that you can release early and release often &#8212; it&#8217;s a MUST in the land of agile/extreme programming.</li>
<li>Follow the rule for Seperation of Concerns, or SoC. Arrange your Maven projects so that you have one artifact per project.</li>
<li>Use IDE integrations for Maven &#8212; there&#8217;s a good deal of first class support for popular Java IDEs. Move yourself from stone age to iron age on that matter.</li>
<li>And finally, do not use parameters for ignoring your tests, they&#8217;re evil! <img src='http://olex.openlogic.com/wazi/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
</ul>
<p>Should you need additional resources on Maven, try the following books that you can find online for free:</p>
<p><a href="http://www.sonatype.com/book" target="_blank">http://www.sonatype.com/book</a></p>
<ul>
<li>Maven:The Complete Reference</li>
<li>Maven By Example</li>
<li>m2eclipse Book</li>
<li>Nexus Book</li>
</ul>
<p><a href="http://www.maestrodev.com/better-build-maven" target="_blank">http://www.maestrodev.com/better-build-maven</a></p>
<ul>
<li>Better Builds with Maven</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2010/creating-intelligent-projects-with-maven/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Started with Java EE 6</title>
		<link>http://olex.openlogic.com/wazi/2010/get-started-with-jee6/</link>
		<comments>http://olex.openlogic.com/wazi/2010/get-started-with-jee6/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 20:04:54 +0000</pubDate>
		<dc:creator>Mert</dc:creator>
				<category><![CDATA[Features]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[glassfish]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jsf]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[YUI]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=49634</guid>
		<description><![CDATA[Java EE 6 is hot, new, and pretty darn cool. In this tutorial we’ll update you on the world of Java EE 6 with the help of a Twitter-like demo application that contains JSF 2.0, PrimeFaces, CDI and Weld as well as Hibernate Validator frameworks.]]></description>
			<content:encoded><![CDATA[<p>In this tutorial we&#8217;ll update you on the world of Java EE 6 with the help of a Twitter-like demo application we&#8217;ve code-named <a title="wallfriend code.google" href="http://code.google.com/p/wallfriend/" target="_blank">wallfriend</a>. The demo application contains <a href="https://olex.openlogic.com/packages/jsf" target="_blank">JSF</a> 2.0, PrimeFaces, CDI and Weld as well as Hibernate Validator frameworks.</p>
<h3>Before You Start</h3>
<p>Our tutorial assumes that you&#8217;re familiar with the following technologies:</p>
<ul>
<li>JavaServer Faces (JSF) and Facelets</li>
<li>Dependency Injection Mechanism</li>
<li>Bean Validation</li>
</ul>
<p>You&#8217;ll also need to install the following applications in order to build the demo application from scratch, or to run it on your local machine:</p>
<ul>
<li>Java 6 (Java SDK 1.6) or greater</li>
<li><a href="https://olex.openlogic.com/packages/netbeans" target="_blank">NetBeans</a> 6.8 bundled with <a href="https://olex.openlogic.com/packages/glassfish" target="_blank">GlassFish</a> 3</li>
<li><a href="https://olex.openlogic.com/packages/maven" target="_blank">Maven</a>, preferably the latest version 2.2.1 (Netbeans ships with Maven 3.0-SNAPSHOT, so that can also be used)</li>
</ul>
<h3>Meat &amp; Potatoes</h3>
<h4>What&#8217;s New with Java EE 6?</h4>
<p><a title="JSR-316" href="http://jcp.org/en/jsr/detail?id=316" target="_blank">Java EE 6</a> specification was finalized in December of 2009, bringing new and updated features to the world of enterprise application development. It introduces the <em>profile approach</em>, meant to focus both developers and applications on particular parts of the Java EE 6 platform. The first profile defined by the expert group is the Java EE 6 web profile, which attempts to specify the minimal configuration targeted for the development of typical web applications. Here are the elements of the web profile, with a few that we&#8217;ve chosen to explain in detail.</p>
<ol>
<li>Servlet 3.0<br />
In web frameworks, servlets are used as an entry point to handle all incoming requests, so it could be said that they are the core elements of web-based applications. The new 3.0 version (specification <a title="JSR 315" href="http://jcp.org/en/jsr/detail?id=315" target="_blank">JSR-315</a>) offers innovative features like ease of development with annotations (@Servlet, @ServletFilter, @ServletContextListener) and annotations for restful services like @GET, @POST and more. It also offers pluggability and extensibility. The main aim here is to attain zero-configuration when working with other frameworks and libraries. Toward this end, a  new xml tag definition called &lt;web-fragment&gt; can be used to apply this feature. The web fragments, which are to be stored inside the jars of their respective libraries, will be merged by the container &#8212; so there&#8217;s no need for the developer to set up any configurations on the web descriptor file. Speaking of pluggability and extensibility, Servlet 3.0 also has a new application programming interface (API) which can be used to add servlets and filters with coding.</li>
<li>JavaServer Pages (JSP) 2.2</li>
<li>ExpressionLanguage (EL) 2.2</li>
<li>Debugging Support for Other Languages (JSR-45) 1.0</li>
<li>Standard Tag Library for JavaServer Pages (JSTL) 1.2</li>
<li>JavaServer Faces (JSF) 2.0<br />
Ever since  the release of JSF&#8217;s 1.X version, its aim was to be <em>the</em> go-to framework for building user interfaces and web applications. As it gained popularity with many application developers around the world, there was a growing awareness of terrific features like componenting, validation, navigation, i18n and others. However, as with so many wonderful things, flaws and disadvantages became more evident over time &#8212; like how complicated it could be to accomplish even a simple task such as creating your own custom JSF component. JSF version 2.0 aims to remedy these flaws by simplifying and easing development and introducing new features, like built-in Ajax support, which will make standard some of what have until now been third party solutions. Here&#8217;s a quick summary of the improvements that are part of JSF 2.0.</p>
<ul>
<li>Composite components<br />
Implementing custom JSF components in 1.x is a real burden. You have to implement a UI component and Tag class, with the option of a Renderer for the markup, and then configure all these within faces-config and tld files. JSF 2.0 simplifies the procedure with the composite component approach introduced in Facelets.</li>
<li>Native Ajax Support<br />
JSF 2.0 provides built-in support for Ajax with its API and infrastructure.  A good example of the useful new components is f:ajax.</li>
<li>State Saving<br />
Since JSF 2.0 aims to handle requests partially with classes like PartialViewContext and PartialStateHolder (among others), it also attempts to make use of a partial mechanism to handle state saving. This has been implemented before, by Apache Trinidad, but PartialStateHolder and StateHelper classes provide a more elegant solution. The goal is to have a lightweight version of the saved state going back and forth in response to requests.</li>
<li>Scopes<br />
In addition to the request, session and application scopes, 2.0 also introduces view and flash scopes. View-scoped beans have a life span that is longer than a request, but shorter than session-scoped beans. Flash scopes are like the view scopes that will live on a specified view, including the redirects, and will be removed if you’re moving another view.</li>
<li>Navigation<br />
In JSF 1.x every navigation rule should be added to faces-config.xml. With version 2.0 implicit navigation can also be used, as in whether or not an outcome corresponds to a view I.D. It&#8217;s also possible to perform conditional navigations on a navigation-case. The new tag &lt;if&gt; can be used in faces-config, with an el snippet for conditional navigation. Version 2.0 also makes it easy to retrieve view parameters and assign them to a given property, which in turn makes handling the parameters for GET requests easy. Two new components (h:link and h:button) also support the integration of view parameters. The key benefit of using these components will be bookmarkable URLs.</li>
<li>Configuration with Annotations<br />
With JSF 2.0 you can annotate your managed beans with the new @ManagedBean annotation, and you can specify the scope for your beans with @RequestScoped, @SessionScoped, @ViewScoped, @NoneScoped and more. Instead of those, we&#8217;ve chosen to use  CDI and Weld annotations.</li>
</ul>
</li>
<li>Common Annotations for Java Platform (JSR-250) 1.1</li>
<li>Enterprise JavaBeans (EJB) 3.1 Lite</li>
<li>Java Transaction API (JTA) 1.1</li>
<li>Java Persistence API (JPA) 2.0<br />
In our opinion, the  main highlights of this release are the API for criteria queries and the support for validation. There are also some fancy new features like extended map support and ordered list mappings.</li>
</ol>
<h4>Java EE 6 Containers</h4>
<p>There are currently two application servers that are compatible with the implementation of Java EE 6: <a title="GlassFish v3 Java EE 6 Certified App Server" href="http://www.sun.com/software/products/glassfishv3" target="_blank">GlassFish Enterprise Server v3</a> and <a title="TMAX JEUS 7 Java EE 6 Certified App Server" href="http://www.tmax.co.kr/tmax_en/jeus" target="_blank">TMAX JEUS 7</a>. We’ve chosen to stick with GlassFish v3.</p>
<h4>So &#8211; What&#8217;s Up with PrimeFaces?</h4>
<p>PrimeFaces is an open source JSF component suite that bundles over 70 components with built-in Ajax support. It’s based on the <a href="https://olex.openlogic.com/packages/yui" target="_blank">YUI</a> and <a href="https://olex.openlogic.com/packages/jquery" target="_blank">jQuery</a> javascripting libraries. It has a simple, lightweight design that is fully compatible with other JSF component libraries. PrimeFaces also supports Ajax Push with a Comet framework, and it has a mobile UI kit known as TouchFaces. Currently, PrimeFaces supports JSF 2.0 with its 2.0.0.RC and 2.0.0-SNAPSHOT releases.</p>
<p>The ability of Java EE 6 to merge web.xml fragments that originate from third-party frameworks makes it unnecessary (in the context of Java EE 6) to do servlet and mapping configurations for PrimeFaces. Primefaces ships with its own web-fragment.xml.</p>
<p>For more information, visit <a title="PrimeFaces - JSF Component Library" href="http://www.primefaces.org" target="_blank">www.primefaces.org</a>.</p>
<h4>Contexts and Dependency Injection (CDI)</h4>
<p>As stated in Java Specification Request <a title="JSR 299" href="//jcp.org/en/jsr/summary?id=299" target="_blank">JSR-299</a>, the purpose of this specification is to unify the JSF-managed bean component model with the EJB component model, resulting in a significantly simplified programming model for web-based applications. CDI also makes it possible for JEE elements to interact with each other using the observer pattern, making it a lot easier to work with enterprise beans and transactional support, among other things.</p>
<h4>Dependency Injection For Java</h4>
<p><a title="JSR-330" href="http://jcp.org/en/jsr/summary?id=330" target="_blank">JSR 330</a> is also a part of Java EE 6, offering a set of standard annotations that can be used for dependency injection. In our demo application we&#8217;ll use some of these annotations, such as @Named, @Inject, @Qualifier and others.</p>
<h4>WELD</h4>
<p>Weld is the reference implementation of JSR-299, which is abbreviated as CDI.  Weld provides a complete SPI, allowing Java EE containers to use Weld as their built-in CDI implementation. GlassFish 3 (which  we’ll use in our demo) ships with Weld.</p>
<h4>Bean Validation and Hibernate Validator</h4>
<p>The Bean Validation, <a title="JSR-303" href="http://jcp.org/en/jsr/detail?id=303" target="_blank">JSR 303</a>, defines a metadata model and an API for JavaBean validation. The Hibernate Validator is the reference implementation for this specification request. Hibernate Validator&#8217;s latest version adds some nice features &#8212; things like validation grouping, native integration with JPA v.2 and JSF v.2, an extended annotation set and more.</p>
<h4>WallFriend, The Demo APP</h4>
<p>Let’s start by creating the project. We’ll do it using the Maven archetype command. It has an interactive mode, so see below for the user input data (in bold).</p>
<blockquote>
<pre><strong>mvn archetype:generate -DarchetypeCatalog=http://anonsvn.jboss.org
   /repos/weld/archetypes/tags/1.0.0-BETA1</strong></pre>
</blockquote>
<blockquote>
<pre>DEV$ mvn archetype:generate -DarchetypeCatalog=http://anonsvn.jboss.org
   /repos/weld/archetypes/tags/1.0.0-BETA1
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] ------------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO]    task-segment: [archetype:generate] (aggregator-style)
[INFO] ------------------------------------------------------------------
[INFO] Preparing archetype:generate
[INFO] No goals needed for project - skipping
[INFO] Setting property: classpath.resource.loader.class =&gt;
'org.codehaus.plexus.velocity.ContextClassLoaderResourceLoader'.
[INFO] Setting property: velocimacro.messages.on =&gt; 'false'.
[INFO] Setting property: resource.loader =&gt; 'classpath'.
[INFO] Setting property: resource.manager.logwhenfound =&gt; 'false'.
[INFO] [archetype:generate]
[INFO] Generating project in Interactive mode
[INFO] No archetype defined. Using maven-archetype-quickstart
(org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
Choose archetype:
1: remote -&gt; weld-jsf-servlet-minimal (Weld archetype for creating an
application using JSF 2.0 and CDI 1.0 for Servlet Containers
(Tomcat 6 / Jetty 6))
2: remote -&gt; weld-jsf-jee-minimal (Weld archetype for creating a minimal
Java EE 6 application using JSF 2.0, CDI 1.0 and EJB 3.1 (persistence unit
not included))
3: remote -&gt; weld-jsf-jee (Weld archetype for creating a Java EE 6
application using JSF 2.0, CDI 1.0, EJB 3.1 and JPA 2.0 (persistence
unit included))
Choose a number:  (1/2/3): 2

Here enter 2, for weld-jsf-jee-minimal. And then specify the
groupId-artifactId-packaging for the project.

Define value for groupId: : <strong>com.openlogic.wazi</strong>
Define value for artifactId: : <strong>wallfriend</strong>
Define value for package: : <strong>war</strong>
Confirm properties configuration:
version: 1.0.0-SNAPSHOT
groupId: com.openlogic.wazi
artifactId: wallfriend
package: war
 Y: : <strong>Y</strong>
[INFO] -------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -------------------------------------------------------------------
[INFO] Total time: 19 seconds
[INFO] Finished at: Tue Jan 12 21:58:35 EET 2010 [INFO]
Final Memory: 12M/79M [INFO]
-------------------------------------------------------------------</pre>
</blockquote>
<p>Since this is an archetype project, we can immediately run it from the command line with Maven on an embedded GlassFish:</p>
<blockquote>
<pre>DEV$ <strong>mvn package embedded-glassfish:run</strong>
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'embedded-glassfish'.
[INFO] org.apache.maven.plugins: checking for updates from glassfish
[INFO] org.codehaus.mojo: checking for updates from glassfish
[INFO] -------------------------------------------------------------------
[INFO] Building wallfriend
[INFO]    task-segment: [package, embedded-glassfish:run]
[INFO] -------------------------------------------------------------------
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Compiling 1 source file to /DEV/wallfriend/target/classes
[INFO] [resources:testResources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:testCompile]
[INFO] Compiling 1 source file to /DEV/wallfriend/target/test-classes
[INFO] [surefire:test]
[INFO] Surefire report directory: /DEV/wallfriend/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running TestSuite
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.369 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] [war:war]
[INFO] Packaging webapp
[INFO] Assembling webapp[wallfriend] in [/DEV/wallfriend/target/wallfriend]
[INFO] Processing war project
[INFO] Webapp assembled in[162 msecs]
[INFO] Building war: /DEV/wallfriend/target/wallfriend.war
[INFO] [embedded-glassfish:run]
[WARNING] Attempting to build MavenProject instance for Artifact
(org.codehaus.mojo:jboss-maven-plugin:3.0) of type: maven-plugin;
constructing POM artifact instead.
Downloading: http://repository.jboss.org/maven2/org/codehaus/mojo
/jboss-maven-plugin/3.0/jboss-maven-plugin-3.0.pom
Downloading: http://repo1.maven.org/maven2/org/codehaus/mojo
/jboss-maven-plugin/3.0/jboss-maven-plugin-3.0.pom
[WARNING] Attempting to build MavenProject instance for Artifact
(org.apache.maven.plugins:maven-eclipse-plugin:3.0)  of type:
maven-plugin; constructing POM artifact instead.
Downloading: http://repository.jboss.org/maven2/org/apache/maven
/plugins/maven-eclipse-plugin/3.0/maven-eclipse-plugin-3.0.pom
Downloading: http://repo1.maven.org/maven2/org/apache/maven
/plugins/maven-eclipse-plugin/3.0/maven-eclipse-plugin-3.0.pom
Jan 13, 2010 10:36:39 PM com.sun.enterprise.v3.server.AppServerStartup run
INFO: GlassFish v3 (74.2) startup time : Embedded(1228ms)
startup services(1317ms) total(2545ms)
Jan 13, 2010 10:36:39 PM com.sun.enterprise.transaction
.JavaEETransactionManagerSimplified initDelegates
INFO: Using com.sun.enterprise.transaction.jts
.JavaEETransactionManagerJTSDelegate as the delegate
Jan 13, 2010 10:36:40 PM org.glassfish.admin.mbeanserver
.JMXStartupService$JMXConnectorsStarterThread run
INFO: JMXStartupService: JMXConnector system is disabled, skipping.
Jan 13, 2010 10:36:40 PM AppServerStartup run
INFO: [Thread[GlassFish Kernel Main Thread,5,main]] started
Jan 13, 2010 10:36:40 PM org.hibernate.validator.util.Version
INFO: Hibernate Validator null
Jan 13, 2010 10:36:40 PM org.hibernate.validator.engine.resolver
.DefaultTraversableResolver detectJPA
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver
.JPATraversableResolver.
Jan 13, 2010 10:36:41 PM com.sun.enterprise.v3.services.impl
.GrizzlyProxy$2$1 onReady
INFO: Grizzly Framework 1.9.18-k started in: 434ms listening on port 7070
Jan 13, 2010 10:36:58 PM com.sun.common.util.logging
.LoggingConfigImpl openPropFile
INFO: Cannot read logging.properties file.
Jan 13, 2010 10:36:58 PM com.sun.enterprise.web.WebContainer
createHttpListener
INFO: Created HTTP listener embedded-listener on port 7070
Jan 13, 2010 10:36:58 PM com.sun.enterprise.web.WebContainer
configureHttpServiceProperties
WARNING: pewebcontainer.invalid_http_service_property
Jan 13, 2010 10:36:59 PM com.sun.enterprise.web.WebContainer createHosts
INFO: Created virtual server server
Jan 13, 2010 10:36:59 PM com.sun.enterprise.web.WebContainer
loadSystemDefaultWebModules
INFO: Virtual server server loaded system default web module
^[[BJan 13, 2010 10:37:08 PM com.sun.enterprise.security.SecurityLifecycle
INFO: security.secmgroff
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.ssl.SSLUtils
checkCertificateDates
SEVERE: java_security.expired_certificate
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.SecurityLifecycle
onInitialization
INFO: Security startup service called
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.PolicyLoader
loadPolicy
INFO: policy.loading
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.auth.realm.Realm
doInstantiate
INFO: Realm admin-realm of classtype com.sun.enterprise.security.auth
.realm.file.FileRealm successfully created.
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.auth.realm.Realm
doInstantiate
INFO: Realm file of classtype com.sun.enterprise.security.auth.realm.file
.FileRealm successfully created.
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.auth.realm.Realm
doInstantiate
INFO: Realm certificate of classtype com.sun.enterprise.security.auth
.realm.certificate.CertificateRealm successfully created.
Jan 13, 2010 10:37:09 PM com.sun.enterprise.security.SecurityLifecycle
onInitialization
INFO: Security service(s) started successfully....
classLoader = WebappClassLoader (delegate=true; repositories=WEB-INF/classes/)
SharedSecrets.getJavaNetAccess()=java.net.URLClassLoader$7@2d205042
Jan 13, 2010 10:37:09 PM org.jboss.weld.bootstrap.WeldBootstrap
INFO: WELD-000900 SNAPSHOT
Jan 13, 2010 10:37:09 PM org.hibernate.validator.engine.resolver
.DefaultTraversableResolver detectJPA
INFO: Instantiated an instance of org.hibernate.validator.engine
.resolver.JPATraversableResolver.
nullID: /DEV/wallfriend/gfembed6764346819525137279tmp/applications
/wallfriend/ CLASSES: [class war.HelloWorld]

Jan 13, 2010 10:37:10 PM com.sun.faces.config.ConfigureListener
contextInitialized
INFO: Initializing Mojarra 2.0.2 (FCS b10) for context '/wallfriend'
Jan 13, 2010 10:37:14 PM com.sun.enterprise.web.WebApplication start
INFO: Loading application wallfriend at /wallfriend
Hit ENTER to redeploy, X to exit</pre>
</blockquote>
<p>Once you see the line <em>Hit ENTER to redeploy, X to exit, </em>make a request for <a title="wallfriend" href="http://localhost:7070/wallfriend" target="_blank">http://localhost:7070/wallfriend</a> on your browser. You should get a first look at the archetype application like the one below:</p>
<p><img src="http://wallfriend.googlecode.com/svn/trunk/images/wallfriend_firstlook.jpg" alt="WallFriend - FirstLook" width="600" height="400" /></p>
<p>Now, let’s open the project inside NetBeans 6.8. Open NetBeans and click <em>File</em> &gt;<em> New Project</em> and then select <em>Maven</em> / <em>Maven Project with Existing POM</em> from the resulting wizard. This should put the Open Project menu on your screen. Select wallfriend from here and you should see the project in the projects tab:</p>
<p><img src="http://wallfriend.googlecode.com/svn/trunk/images/wallfriend_netbeans.jpg" alt="WallFriend - NetBeans" /></p>
<p>To run wallfriend inside NetBeans 6.8, you need to make sure that you have Java 1.6 defined as a Java platform, and be sure that wallfriend is also using it. Also, from the Tools &gt; Servers menu, you need to define the Java 1.6 executable for your GlassFish. Netbeans also comes with a Maven 3.0-SNAPSHOT version. So, if you want to use your own external Maven, you must declare it to the IDE from <em>Preferences</em> &gt; <em>Miscellaneous</em> &gt; <em>Maven</em>. After configuring it all, just make a request for <a title="wallfriend" href="http://localhost:8080/wallfriend" target="_blank">http://localhost:8080/wallfriend</a> on your browser. You should see the very same page as you did when you ran the project with the embedded GlassFish.</p>
<h4>Adding PrimeFaces to the Project</h4>
<p>In order to use the JSF components of PrimeFaces, we first have to add the repo and dependency definitions to the pom.xml of the project. Go ahead and open Project Files &gt; pom.xml in NetBeans and add the following snippets, respectively:</p>
<blockquote>
<pre>&lt;repository&gt;
    &lt;id&gt;prime-repo&lt;/id&gt;
    &lt;name&gt;Prime Technology Maven Repository&lt;/name&gt;
    &lt;url&gt;http://repository.prime.com.tr&lt;/url&gt;
    &lt;layout&gt;default&lt;/layout&gt;
&lt;/repository&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.primefaces&lt;/groupId&gt;
    &lt;artifactId&gt;primefaces&lt;/artifactId&gt;
    &lt;version&gt;2.0.0-SNAPSHOT&lt;/version&gt;
&lt;/dependency&gt;</pre>
</blockquote>
<p>Now namespace can be added inside the xhtml’s files for PrimeFaces, xmlns:p=&#8221;http://primefaces.prime.com.tr/ui&#8221;. As mentioned above, there is no configuration needed in web.xml since PrimeFaces ships with its own web fragment.</p>
<p><strong>Wallfriend – The Implementation</strong></p>
<p>As we said before, <a title="wallfriend code.google" href="http://code.google.com/p/wallfriend/" target="_blank">wallfriend</a> is a simple write-to-wall application with a basic domain, managed beans, and some xhtml pages. You can check out the source from the Google Code project at <a title="wallfriend source" href="http://wallfriend.googlecode.com/svn/trunk/wallfriend" target="_blank">http://wallfriend.googlecode.com/svn/trunk/wallfriend</a>. A <em>follow the wall</em> mechanism as well as a <em>restful expose of the wall</em> will be added to the project in the near future.</p>
<p>Since the application was not created from scratch, we have some clean-up to do on the archetype-created application. Go ahead and delete the following folders, because they won’t be used:</p>
<ul>
<li>Web Pages/WEB-INF/templates</li>
<li>Web Pages/resources</li>
<li>Source Packages / war</li>
<li>Test packages / war</li>
</ul>
<p>Now let’s go through the parts of the project: <strong>The Model</strong>, <strong>The Managed Beans</strong>, and <strong>The Views</strong>.</p>
<p><strong>The Model</strong></p>
<p>For the domain, we have 3 classes: Wall, Brick and WallFriendContext. Wall and Brick are for defining a master-detail relationship between the posts and the wall. WallFriendContext is the application-scoped bean for storing created walls. It&#8217;s marked with the javax.enterprise.context.ApplicationScoped bean.</p>
<p><span style="text-decoration: underline">Wall.java</span></p>
<blockquote>
<pre>package com.openlogic.wazi.beans;

import java.util.LinkedList;
import java.util.List;

public class Wall {

    String wallName;

    List bricks = new LinkedList();

    public Wall(String wallName) {
        this.wallName = wallName;
    }

    public void addBrick(String graffiti) {
        bricks.add(0, new Brick(graffiti));
    }

    public String getWallName() {
        return wallName;
    }

    public List getBricks() {
        return bricks;
    }
}</pre>
</blockquote>
<p><span style="text-decoration: underline">Brick.java</span></p>
<blockquote>
<pre>package com.openlogic.wazi.beans;

import java.util.Date;

public class Brick {

    private String graffiti;
    private Date publishDate;

    public Brick(String graffiti) {
        this.graffiti = graffiti;
        this.publishDate = new Date();
    }

    public void init() {
    }

    public String getGraffiti() {
        return graffiti;
    }

    public void setGraffiti(String graffiti) {
        this.graffiti = graffiti;
    }

    public Date getPublishDate() {
        return publishDate;
    }

    public void setPublishDate(Date publishDate) {
        this.publishDate = publishDate;
    }
}</pre>
</blockquote>
<p><span style="text-decoration: underline">WallFriendContext.java</span></p>
<blockquote>
<pre>package com.openlogic.wazi.beans;

import java.util.HashMap;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class WallFriendContext {

    private Map walls = new HashMap();

    public void addWall(Wall wall) {
        walls.put(wall.getWallName(), wall);
    }

    public Map getWalls() {
        return walls;
    }
}</pre>
</blockquote>
<p><strong>The Managed Beans (a.k.a. Contextual Beans)</strong></p>
<p>The managed bean classes are defined by the CDI and implemented by Weld, which ships with the GlassFish server. CDI also needs an empty beans.xml file under the WEB-INF folder, since we’re going to use annotations to define our beans. That&#8217;s right &#8212; that means they can also be configured with good old fashioned XML.</p>
<p><em>LoginView</em> is the managed bean of choice for handling wall management and creation/accessing. The annotation javax.enterprise.inject.Model identifies the LoginView as a bean of the model layer, as stated in the MVC  pattern. We use javax.inject.Inject to identify injectable constructors, while methods and fields. org.hibernate.validator.constraints.NotEmpty is a validator annotation that specifies that the field wallName cannot be empty.</p>
<blockquote>
<pre>package com.openlogic.wazi.view;

import com.openlogic.wazi.beans.Wall;
import com.openlogic.wazi.beans.WallFriendContext;
import javax.enterprise.inject.Model;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import org.hibernate.validator.constraints.NotEmpty;

@Model
public class LoginView {

    @Inject
    private WallFriendContext wallFriendContext;

    @NotEmpty(message="Wall Name cannot be empty")
    private String wallName;

    public String doLogin() {
        Wall wall;
        if (wallFriendContext.getWalls().containsKey(wallName)) {
            wall = wallFriendContext.getWalls().get(wallName);
        }
        else {
            wall = new Wall(wallName);
            wallFriendContext.addWall(wall);
        }
        FacesContext.getCurrentInstance().getExternalContext()
.getRequestMap().put("wall", wall);

        return "myWall";
    }

    public String getWallName() {
        return wallName;
    }

    public void setWallName(String wallName) {
        this.wallName = wallName;
    }
}</pre>
</blockquote>
<p>MyWallView is the managed bean for handling the paint-a-graffiti on the wall action. The annotation javax.inject.Named, used here, allows you to access the bean using the bean name, with the first letter in lowercase. We use javax.annotation.PostConstruct to mark a method to be invoked after the Dependency Injection is done.</p>
<blockquote>
<pre>package com.openlogic.wazi.view;

import com.openlogic.wazi.beans.Wall;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.hibernate.validator.constraints.NotEmpty;

@Named
@SessionScoped
public class MyWallView implements Serializable {

    private Wall wall;

    @PostConstruct
    public void init() {
        wall = (Wall) FacesContext.getCurrentInstance()
                  .getExternalContext().getRequestMap().get("wall");
    }

    @NotEmpty(message="Graffiti cannot be empty")
    private String graffiti;

    public String paint() {
        wall.addBrick(graffiti);
        graffiti = "";

        return null;
    }

    public Wall getWall() {
        return wall;
    }

    public void setWall(Wall wall) {
        this.wall = wall;
    }

    public String getGraffiti() {
        return graffiti;
    }

    public void setGraffiti(String graffiti) {
        this.graffiti = graffiti;
    }
}</pre>
</blockquote>
<p><strong>The Pages</strong></p>
<p>Facelets, JSF 2.0, and PrimeFaces projects are used for the development of views. JSF tags are also commonly used. One different component could be p:growl, which is for viewing the FacesMessages in a Mac-like growl. Also, there is no defined navigation-rule in the faces-config.xml file for navigating from login.xhtml to myWall.xhtml. This is with the implicit navigation mechanism that comes  with JSF 2.0. The return string of LoginView#doLogin() method matches the name of the myWall.xhtml view.</p>
<blockquote>
<pre>&lt;html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
     xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.prime.com.tr/ui"&gt;
      &lt;h:head&gt;
          &lt;title&gt;WallFriend - Java EE 6 Starter Application&lt;/title&gt;
      &lt;/h:head&gt;
      &lt;h:body&gt;
          &lt;h:form&gt;
              &lt;p:growl showDetail="true" /&gt;
              &lt;p:panel header="Access to your wall" style="width:400px"&gt;
                  &lt;h:outputLabel value="Wall Name : " for="wallname" /&gt;
                  &lt;h:inputText id="wallname" value="#{loginView.wallName}" /&gt;
                  &lt;h:commandButton value="Paint it Now, Paint it Black"
                      action="#{loginView.doLogin}" /&gt;
              &lt;/p:panel&gt;
          &lt;/h:form&gt;
      &lt;/h:body&gt;
&lt;/html&gt;</pre>
</blockquote>
<p>myWall.xhtml page renders the wall posts for a wall, and the user can also write up to the wall.</p>
<blockquote>
<pre> &lt;html xmlns="http://www.w3.org/1999/xhtml"
       xmlns:h="http://java.sun.com/jsf/html"
       xmlns:f="http://java.sun.com/jsf/core"
       xmlns:ui="http://java.sun.com/jsf/facelets"
       xmlns:p="http://primefaces.prime.com.tr/ui"&gt;
       &lt;h:head&gt;
          &lt;title&gt;WallFriend - Java EE 6 Starter Application&lt;/title&gt;
       &lt;/h:head&gt;
       &lt;h:body&gt;
          &lt;h:form&gt;
             &lt;p:growl showDetail="true" /&gt;
                &lt;p:panel header="#{myWallView.wall.wallName}'s WALL"
                    style="width:600px"&gt;
                   &lt;h:panelGrid columns="1"&gt;
                   &lt;h:panelGroup&gt;
                      &lt;h:inputTextarea value="#{myWallView.graffiti}"
                             cols="50" rows="3" /&gt;
                      &lt;h:commandButton value="Paint"
                             action="#{myWallView.paint}" /&gt;
                   &lt;/h:panelGroup&gt;
                   &lt;p:dataTable value="#{myWallView.wall.bricks}"
                            var="brick"&gt;
                      &lt;p:column&gt;
                        #{brick.graffiti}
                        &lt;br/&gt;
                        &lt;h:outputText value="#{brick.publishDate}"&gt;
                           &lt;f:convertDateTime dateStyle="default"
                              type="both" pattern="dd.MM.yyyy HH:mm:ss" /&gt;
                        &lt;/h:outputText&gt;
                     &lt;/p:column&gt;
                  &lt;/p:dataTable&gt;
               &lt;/h:panelGrid&gt;
            &lt;/p:panel&gt;
         &lt;/h:form&gt;
      &lt;/h:body&gt;
&lt;/html&gt;</pre>
</blockquote>
<h3>Finishing Up</h3>
<p>Java EE 6 is hot, new, and pretty darn cool. In our opinion, as users begin to employ it for upcoming projects, the number of blogposts, samples, and other resources will eventually increase. And with its adoption by the Java Community, we&#8217;ll for sure see more Java EE 6-compliant application servers around. Java EE 6 really eases development with its “standardized” features, and the zero-configuration approach apparent in every part of the implementation is really nice, lending an out-of-the-box feeling that&#8217;s similar to the .NET environment.  It&#8217;s not just another java framework!</p>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2010/get-started-with-jee6/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Escaping Microsoft Exchange via Davmail + Fetchmail + Postfix + Courier IMAP</title>
		<link>http://olex.openlogic.com/wazi/2009/escaping-microsoft-exchange-via-davmail-fetchmail-postfix-courier-imap/</link>
		<comments>http://olex.openlogic.com/wazi/2009/escaping-microsoft-exchange-via-davmail-fetchmail-postfix-courier-imap/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 20:32:24 +0000</pubDate>
		<dc:creator>Andrew Back</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[courier-imap]]></category>
		<category><![CDATA[Davmail]]></category>
		<category><![CDATA[fetchmail]]></category>
		<category><![CDATA[postfix]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=47663</guid>
		<description><![CDATA[This tutorial explains how to use a recipe of Davmail, Fetchmail, Postfix, and Courier IMAP to interface standards-based e-mail clients with Exchange's Outlook Web Access, and to integrate corporate and non-corporate e-mail accounts into a single inbox that's not buried inside the store of the mail user agent.]]></description>
			<content:encoded><![CDATA[<p>Many enterprises use Microsoft Exchange for corporate e-mail, and there is frequently no avoiding its use regardless of where you might sit in the organization or the freedom afforded to you in terms of desktop configuration. Whilst Exchange has the capability to provide an IMAP and/or POP service these are frequently disabled, leaving Outlook Web Access (OWA) as the only remaining hope for users of non-Microsoft mail user agents (MUAs). This tutorial explains how to use a recipe of <a href="https://olex.openlogic.com/packages/Davmail" target="_blank">Davmail</a> + <a href="https://olex.openlogic.com/packages/fetchmail" target="_blank">Fetchmail</a> + <a href="https://olex.openlogic.com/packages/postfix" target="_blank">Postfix</a> + <a href="https://olex.openlogic.com/packages/courier-imap" target="_blank">Courier IMAP</a> to interface standards-based e-mail clients with Exchange&#8217;s OWA, and to integrate corporate and non-corporate e-mail accounts into a single inbox and one that is not buried inside the store of the MUA.</p>
<h2>Before You Start</h2>
<p>This particular configuration is perhaps best suited to a more advanced desktop configuration, else as the basis for a server-based resource where you may have multiple desktops and want to synchronize mail across devices.</p>
<p>If you want the quickest and simplest route to getting mail from OWA into your MUA of choice, and are fine with it being pulled down into the local folders of a MUA, you might be better off using Davmail in its desktop configuration and without the complexity of Postfix + Fetchmail + Courier IMAP.</p>
<p>This tutorial assumes that:</p>
<ul>
<li>You have the OWA service configured on your Exchange server, e.g. https://mail.acme.com/exchange/</li>
<li>You have a Gmail account with POP enabled (this tutorial could be easily adapted to other service providers)</li>
<li>You are running Ubuntu GNU/Linux. However, there should be few differences if you are running Debian, and it should be easy enough to adapt this configuration to accommodate RPM-based distributions</li>
<li>You are capable of appropriately securing services, e.g. managing firewall configuration</li>
</ul>
<h2>Meat &amp; Potatoes</h2>
<p>Note: this tutorial uses acme.com as the example corporate mail domain (OWA) and Gmail as the non-corporate mail service. You could just as easily have multiple Exchange accounts and/or standards-based e-mail accounts.</p>
<h3>Install Packages</h3>
<p><a href="http://fetchmail.berlios.de/" target="_blank">Fetchmail</a>, <a href="http://www.postfix.org/" target="_blank">Postfix</a> and <a href="http://www.courier-mta.org/imap/" target="_blank">Courier IMAP</a> and dependencies can all be installed via the package management system:</p>
<blockquote>
<pre>$sudo apt-get install postfix fetchmail courier-imap sun-java6-jdk tomcat6
tomcat6-admin ant</pre>
</blockquote>
<h3>Configure Certificates</h3>
<p>To be sure that we are actually connecting to Gmail and to encrypt e-mail to and from the service we need to set up a few certificates.</p>
<p>Create a local certificate store:</p>
<blockquote>
<pre>$mkdir -p /etc/ssl/local/certs/</pre>
</blockquote>
<p>Install the Thawte root CA certificate (required for Gmail SMTPS):</p>
<ul>
<li>Go to <a href="http://www.thawte.com/roots/" target="_blank">Thawte</a> and download their root CA certificates</li>
<li>Unzip the ZIP archive and locate the file: <em>Thawte Premium Server CA.cer</em></li>
<li>Convert the CA certificate to PEM format and install:</li>
</ul>
<blockquote>
<pre>$sudo openssl x509 -inform der -in 'Thawte Premium Server CA.cer' -out
/etc/ssl/local/certs/thawte.pem</pre>
</blockquote>
<p>Install the Equifax root CA certificate (required for Gmail POP3S):</p>
<blockquote>
<pre>$sudo wget -O /etc/ssl/local/certs/equifax.pem

https://www.geotrust.com/resources/root_certificates/certificates/

Equifax_Secure_Certificate_Authority.cer</pre>
</blockquote>
<p>Install the Gmail POP3S certificate:</p>
<blockquote>
<pre>$openssl s_client -connect pop.gmail.com:995 -showcerts</pre>
</blockquote>
<p>From the output of the command select the pop.gmail.com certificate (the first block to appear between and including lines &#8220;&#8212;&#8211;BEGIN CERTIFICATE&#8212;&#8211;&#8221; and &#8220;&#8212;&#8211;END CERTIFICATE&#8212;&#8211;&#8221;) and copy and paste this into a new file:</p>
<blockquote>
<pre>/etc/ssl/local/certs/googlepop.pem</pre>
</blockquote>
<p>Hash the certificates:</p>
<blockquote>
<pre>$sudo c_rehash /etc/ssl/local/certs</pre>
</blockquote>
<h3>Build and Configure Davmail</h3>
<p>Grab the latest Davmail code from SVN. For checkout details see <a href="http://sourceforge.net/projects/davmail/develop" target="_blank">the Sourceforge page</a>. Then to build:</p>
<blockquote>
<pre>$cd davmail/trunk
$ant</pre>
</blockquote>
<p>If the build is successful proceed to configure the web application archive (WAR file) version of Davmail:</p>
<blockquote>
<pre>$cd dist
$jar xvf davmail-N.N.N-NNN.war</pre>
</blockquote>
<p>(replacing &#8216;N.N.N-NNN&#8217; with the version number)</p>
<p>Edit the file <em>WEB-INF/classes/davmail.properties</em> as appropriate, for example:</p>
<blockquote>
<pre>davmail.url=https\://mail.acme.com/exchange/
davmail.popPort=1110
davmail.smtpPort=1025
davmail.ldapPort=1389
davmail.caldavPort=1080
davmail.keepDelay=60
davmail.sentKeepDelay=180
davmail.caldavPastDelay=60</code>

davmail.enableProxy=false
davmail.proxyHost=
davmail.proxyPort=
davmail.proxyUser=
davmail.proxyPassword=

davmail.allowRemote=true
davmail.bindAddress=
davmail.server=true
davmail.disableUpdateCheck=false

log4j.logger.davmail=DEBUG
log4j.rootLogger=WARN
log4j.logger.httpclient.wire=WARN
log4j.logger.org.apache.commons.httpclient=WARN</pre>
</blockquote>
<p>You should really only need to update <em>davmail.url</em> with the URL of your OWA service, but you may also choose to adjust the <em>davmail.*Delay</em> settings which control things such as for how many days messages that have been retrieved should be left on the Exchange server. However, note that the Postfix and Fetchmail configuration that follows assumes that you have set the POP3 and SMTP port numbers as detailed above.</p>
<p>Re-package the web application archive:</p>
<blockquote>
<pre>$jar cvf davmail.war WEB-INF META-INF</pre>
</blockquote>
<h3>Configure Tomcat and deploy Davmail</h3>
<p>Grant all Java security permissions to Davmail by editing the file <em>/etc/tomcat6/policy.d/50local.policy</em> and adding to the bottom:</p>
<blockquote><pre>// Davmail
//grant codeBase "file:${catalina.base}/webapps/davmail/-" {
//        permission java.security.AllPermission;
//};</pre>
</blockquote>
<p>Create a user for the Tomcat admin application by editing the file <em>/etc/tomcat6/tomcat-users.xml</em> and adding to the bottom:</p>
<blockquote><pre>&lt;tomcat-users&gt;
&lt;role rolename="tomcat"/&gt;
&lt;role rolename="manager"/&gt;
&lt;user username="yourusername" password="yourpassword" roles="manager"/&gt;
&lt;/tomcat-users&gt;</pre>
</blockquote>
<p>Substitute &#8220;yourusername&#8221; and &#8220;yourpassword&#8221; for the username and password you want to use for administering Tomcat.</p>
<p>Restart Tomcat:</p>
<blockquote><pre>$sudo /etc/init.d/tomcat6 restart</pre>
</blockquote>
<p>Deploy Davmail:</p>
<ul>
<li>Log in to the Tomcat admin application at http://yoursystem:8080/manager/html</li>
<li>From the <em>WAR file to deploy</em> section browse to the davmail.war archive we created earlier, and then select <em>Deploy</em>.</li>
<li>Davmail should now be listed in the <em>Applications</em> section. If Davmail is not showing as running select <em>Start</em> from the <em>Commands</em> column.</li>
</ul>
<h3>Configure Postfix</h3>
<p>For security reasons it makes sense to keep mail on-system whenever possible. Or to put it another way: if I send mail from my Acme Inc account to another Acme Inc user why route it via a 3rd party mail system? So, we&#8217;ll be explicit when it comes to mail routing.</p>
<p>Edit the file <em>/etc/postfix/main.cf</em> and set the following options:</p>
<blockquote><pre>home_mailbox = Maildir/

smtp_tls_loglevel = 1
smtp_tls_per_site = hash:/etc/postfix/tls_per_site
smtp_tls_CAfile = /etc/ssl/local/certs/thawte.pem
smtp_tls_session_cache_database = btree:/var/run/smtp_tls_session_cache
smtp_use_tls = yes

smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_sasl_tls_security_options = noanonymous

relayhost = [smtp.gmail.com]:587

disable_dns_lookups = yes

smtp_generic_maps = hash:/etc/postfix/generic

sender_dependent_relayhost_maps = hash:/etc/postfix/bysender</pre>
</blockquote>
<p>Configure Postfix to route mail sent from the corporate account(s) to OWA via Davmail, by editing the file <em>/etc/postfix/bysender</em> and adding:</p>
<blockquote><pre>@acme.com         [localhost]:1025</pre>
</blockquote>
<p>Map any local users to routable mail addresses by editing the file <em>/etc/postfix/generic</em> and adding:</p>
<blockquote><pre>ausername@yoursystem		someuser@acme.com</pre>
</blockquote>
<p>Note: &#8216;yoursystem&#8217; is the system we are configuring, &#8216;ausername&#8217; is a Linux account on this system and the right hand address could be an Exchange or Google account. This configuration is optional and is only used where a MUA defaults to setting the originator address of a message to $LOGNAME@$HOSTNAME.</p>
<p>Store the authentication credentials for remote SMTP (and sending via OWA) by editing the file <em>/etc/postfix/sasl_passwd</em> and adding:</p>
<blockquote><pre>[smtp.gmail.com]:587    auser@gmail.com:gmailpassword
[localhost]:1025        DOMAIN\USER:domainpassword</pre>
</blockquote>
<p>Note: the 2nd line is specifying credentials that will be passed to OWA via Davmail, therefore &#8220;DOMAIN\USER&#8221; is the username half of Windows domain credentials. Ensure that this file is mode 640 and ownership root:postfix.</p>
<p>For security reasons force connections to Google&#8217;s SMTP service to use TLS by editing the file <em>/etc/postfix/tls_per_site</em> and adding:</p>
<blockquote><pre>smtp.gmail.com         MUST</pre>
</blockquote>
<p>Create the Postfix lookup tables:</p>
<blockquote><pre>$cd /etc/postfix
$sudo postmap bysender
$sudo postmap generic
$sudo postmap sasl_passwd
$sudo postmap tls_per_site</pre>
</blockquote>
<p>Restart Postfix:</p>
<blockquote><pre>$sudo /etc/init.d/postfix restart</pre>
</blockquote>
<p>Note: If you plan to use this configuration on a server you will likely want to configure Postfix to accept SMTP connections from remote MUAs over SSL. However, this is out of the scope of this tutorial.</p>
<h3>Configuring Courier IMAP</h3>
<p>Edit the file <em>/etc/courier/imapd</em> and ensure that the following variables are set (they should be found toward the bottom of the file):</p>
<blockquote><pre>IMAPDSTART=YES

MAILDIRPATH=Maildir</pre>
</blockquote>
<p>Edit the file <em>/etc/courier/authdaemonrc</em> and ensure that the following variable is set:</p>
<blockquote><pre>authmodulelist="authpam"</pre>
</blockquote>
<p>Note: If you plan to use this configuration on a server you will likely want to configure the Courier IMAP service to work over SSL. However, this is out of the scope of this tutorial.</p>
<h3>Configure the Local User Environment</h3>
<p>Create an initial maildir format mailbox:</p>
<blockquote><pre>$maildirmake ~/Maildir</pre>
</blockquote>
<p>Create a new file <em>~/.fetchmailrc</em> to hold the Fetchmail configuration:</p>
<blockquote><pre>#
# ~/.fetchmailrc
#
# Check mail every 120 seconds
#
set daemon 120
set postmaster ausername
#
# Gmail
#
poll pop.gmail.com with proto POP3 and options no dns
        user 'auser@gmail.com' with pass "gmailpassword" is 'ausername'
        here options ssl sslcertck
sslcertpath '/etc/ssl/local/certs/'
        smtphost localhost
#
# ACME Inc
#
poll localhost with proto POP3 and options port 1110 no dns
        user "someuser@ACME" with pass "domainpassword" is 'ausername' here
        smtphost localhost
#</pre>
</blockquote>
<p>Note: &#8220;ausername&#8221; is the local Linux account. SSL is not needed when retrieving mail from Exchange as the fetchmail -&gt; Davmail connection will be over localhost, and Davmail -&gt; OWA over https (unless your Exchange administrators have configured the OWA service to run over http).</p>
<p>Manually start Fetchmail in verbose mode and check for errors:</p>
<blockquote><pre>$fetchmail -v</pre>
</blockquote>
<p>Fetchmail can be configured to automatically start via a number of different mechanisms. For example, with Gnome desktop you could create a new &#8216;Startup Application&#8217; from System -&gt; Preferences, and have &#8216;/usr/bin/fetchmail&#8217; be executed on login. Or you could add fetchmail to your personal crontab, e.g.:</p>
<blockquote><pre>*/2 * * * * /usr/bin/fetchmail -s</pre>
</blockquote>
<p>When using cron you would remove the line starting <em>set daemon</em> from file <em>.fetchmailrc</em>.</p>
<h2>Finishing Up</h2>
<h3>Mail Client Settings</h3>
<p>If you are running a local MUA that supports the maildir mailbox format there should be nothing to configure other than the sending identities and application preferences. If you are using a local MUA that does not support maildir you should use IMAP and enter localhost for the server and use your Linux account credentials for authentication. If you are using this configuration on a server: for the MUA on the client you would use the server FQDN for the IMAP server and your Linux account credentials for authentication, and SMTP settings would depend on how you had configured SMTP authentication (incoming to the server).</p>
<p>Davmail also provides proxies for LDAP and <a href="http://en.wikipedia.org/wiki/CalDAV" target="_blank">CalDAV</a> to OWA:</p>
<ul>
<li>LDAP: server: <em>localhost:1389</em>; bind dn: <em>USER@DOMAIN</em>; password: <em>domainpassword</em>; search base: <em>ou=people</em>; search field: <em>sn</em/li>
<li>CalDAV: URL: <em>http://localhost:1080/users/someuser@acme.com/calendar/</em>; password: <em>domainpassword</em></li>
</ul>
<p>USER@DOMAIN and domainpassword are the credentials associated with your Windows domain account.</p>
<p>Note: Whenever your Windows domain password or Gmail password changes you will need to update this in <em>~/.fetchmailrc</em> and <em>/etc/postfix/sasl_passwd</em>, and execute <em>$sudo postmap /etc/postfix/sasl_passwd</em>.</p>
<h3>Conclusion</h3>
<p>The configuration detailed here is rather more complicated than ought to be and has wrinkles such as having to store user credentials in both Fetchmail and Postfix configuration. As such its appeal is likely limited to use with more complex mail requirements involving OWA and where there are few, if any, alternative options. Davmail could be used on its own for simple OWA access; however, the addition of Fetchmail and Postfix also means that e-mail is always stored in a standard format, maildir, and that where possible outbound e-mail is always kept on-system. The addition of Courier IMAP allows a greater number of local MUAs to be used (i.e. those that do not support maildir), and the configuration could be deployed to a server and the unified inbox synchronised across multiple desktops.</p>
<p>Finally, there is much room for improvement, and it would be great to see this configuration further developed such that user credentials were better handled and a practical, secure multi-user proxy server could be easily set up, thereby providing a shared service for Exchange OWA &lt;&#8212;&gt; standards-based (IMAP, SMTP, LDAP and CalDAV) MUA integration.</p>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2009/escaping-microsoft-exchange-via-davmail-fetchmail-postfix-courier-imap/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Creating a Continuous Integration Server for Java Projects Using Hudson</title>
		<link>http://olex.openlogic.com/wazi/2009/creating-a-continuous-integration-server-for-java-projects-using-hudson/</link>
		<comments>http://olex.openlogic.com/wazi/2009/creating-a-continuous-integration-server-for-java-projects-using-hudson/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 17:56:16 +0000</pubDate>
		<dc:creator>Grant Smith</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Continuum]]></category>
		<category><![CDATA[CruiseControl]]></category>
		<category><![CDATA[Hudson]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Subversion]]></category>
		<category><![CDATA[wget]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=44227</guid>
		<description><![CDATA[A continuous integration (CI) engine is an automated build system that checks out the most current code from a source code repository, builds it, and makes the resulting artifacts available for download and review. This tutorial covers the setup of a continuous integration server for Java projects with Hudson, one of the top open source CI engines.]]></description>
			<content:encoded><![CDATA[<p>In a previous article we demonstrated <a href="http://olex.openlogic.com/wazi/2009/creating-a-maven-based-development-environment-on-linux/" target="_blank">how to setup a Linux server to use Maven</a>, the primary Java build tool. Now we&#8217;ll look at how to use <a href="https://olex.openlogic.com/packages/hudson" target="_blank">Hudson</a> to provide continuous integration to your build environment. Just what is continuous integration? Think of it this way: you have a team of developers who are all busily committing code to your source code repository. Each developer is focused on his or her role, or area of functionality, for the system being developed. A continuous integration (CI) engine is an automated build system that checks out the most current code from the source code repository, builds it, and makes the resulting artifacts available for download and/or review. It&#8217;s also a great way to see if the entire system is, in fact, compilable. More often than we&#8217;d like to admit, developers check in their code without checking for compile errors – creating a problem for others in the team who update their local sources to the trunk, only to find the system no longer compiles! The Continuous Integration Engine can be linked to a mailing list to notify developers that the build has failed. Additionally, it can show a &#8220;diff&#8221; of what has changed since the previous build, so users can see exactly who the culprit is – and follow up with merciless ridicule.</p>
<p>So why use Hudson to create a continuous integration server?  There are certainly other CI engines out there, such as the primary open source rivals to Hudson: <a href="https://olex.openlogic.com/packages/continuum" target="_blank">Apache Continuum</a> and <a href="https://olex.openlogic.com/packages/cruisecontrol" target="_blank">CruiseControl</a>.  Some good commercial CI engines are also available, but those are beyond the scope of this article.</p>
<p>We&#8217;ve worked with both Continuum and CruiseControl in the past, and consider them to be functional – in an adequate sort of way. Continuum&#8217;s web-based front-end isn&#8217;t bad, and for the most part it does what it&#8217;s designed to do. We&#8217;ve found CruiseControl to be more competent than Continuum when it comes to stability, although we must admit that we have not tried any of Continuum&#8217;s newer builds. But when it comes to ease of configuration Hudson wins, hands down. If, like us, you&#8217;re visually-oriented, and if you find it painful to edit an XML file to configure CI (as is the case with CruiseControl), Hudson&#8217;s graphical user interface just makes perfect sense.</p>
<p>Interested readers should be able to find more detailed comparisons of CI engines (like <a href="http://globalgateway.wordpress.com/2007/12/17/cruisecontrol-vs-hudson/" target="_blank">this one</a>) with a quick search, but our conclusion – based on a combination of first-hand experience and other people&#8217;s opinions – is that Hudson is the current front-runner among open source CI engines.</p>
<h2>Before You Start</h2>
<p>You&#8217;ll need to be proficient in  <a href="https://olex.openlogic.com/packages/maven" target="_blank">Maven</a> and <a href="https://olex.openlogic.com/packages/subversion" target="_blank">Subversion</a> before you continue. The principle here is to have a mock application hosted in a Subversion repository. We&#8217;ll then download and configure Hudson to access the Subversion repository, and perform continuous integration builds from there. We&#8217;ll assume you already have Maven configured. If not, have a look at the tutorial titled <a href="http://olex.openlogic.com/wazi/2009/creating-a-maven-based-development-environment-on-linux/" target="_blank">Creating a Maven-Based Development Environment on Linux</a>. You&#8217;ll also need to have an accessible Subversion server set up somewhere.  If you don&#8217;t, a good place to get started is at <a href="http://subversion.tigris.org/faq.html#repository" target="_blank">http://subversion.tigris.org/faq.html#repository</a>.</p>
<h2>Meat &amp; Potatoes</h2>
<h3>Creating a Test Project</h3>
<p>Let&#8217;s start with a software project for illustration purposes. For this, we&#8217;ll use Maven to generate a project with one simple command:</p>
<pre>mvn archetype:generate</pre>
<p>You&#8217;ll be asked to select an application type to generate. Let&#8217;s go with a simple web application. Choose option 18. Then enter the following information into the prompts:</p>
<pre>Define value for groupId: : com.example
Define value for artifactId: : testWebApp
Define value for version:  1.0-SNAPSHOT: : [Press Enter]
Define value for package:  com.example: : [Press Enter]
Define value for package:  com.example: :
Confirm properties configuration:
groupId: com.example
artifactId: testWebApp
version: 1.0-SNAPSHOT
package: com.example
 Y: : [Press Enter]</pre>
<p>Good job. You now have a fully functional web application that does very, very little indeed. You can compile and execute it for test purposes like this:</p>
<pre>cd testWebApp/</pre>
<pre>mvn -Djetty.port=9999 org.mortbay.jetty:maven-jetty-plugin:6.1.18:run</pre>
<p>The reason we use port 9999 is because we have other web applications already running on our machine. Point your favorite web browser to http://localhost:9999/testWebApp and you&#8217;ll be greeted by the now famous &#8220;Hello World!&#8221; greeting. Excited yet?</p>
<h3>Importing the Test Project into Subversion</h3>
<p>Next we need to import our new project into Subversion. We don&#8217;t want to import any generated artifacts so we first perform an <em>mvn clean</em> operation.</p>
<pre>mvn clean</pre>
<pre>cd ..</pre>
<pre>su</pre>
<pre># svnadmin create /var/lib/svn/repositories/testWebApp</pre>
<pre># cd ..</pre>
<pre># svn import testWebApp file:///var/lib/svn/repositories/testWebApp -m "initial import"</pre>
<p>Now remove your existing <em>webapp</em> directory, and check it out from Subversion.</p>
<pre>rm -rf testWebApp</pre>
<pre>svn checkout svn://armor.osdcorp.com/testWebApp</pre>
<p>Your Subversion repository will obviously be different. Substitute the <em>svn://armor.osdcorp.com</em> part with your configuration.</p>
<p>In a normal team development environment, your team would now joyfully check out the source from Subversion, make changes, and check them back in. Let&#8217;s shift our focus to the role of Hudson, our continuous integration engine of choice.</p>
<h3>Downloading and Installing Hudson</h3>
<p>To download Hudson:</p>
<pre>wget http://hudson-ci.org/latest/hudson.war</pre>
<p>Simple as that. Now, to execute it you have two options. You can either drop it into a Servlet container like Tomcat, or you can simply start it up like this:</p>
<pre>java -jar hudson.war --httpPort=8075</pre>
<p>Again, due to our system already running certain web applications, we can specify an alternate port. Point your browser to <em>http://localhost:8075</em> and you should be rewarded with the following:</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/10/hudson1.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/10/hudson1.png" alt="hudson1" width="600" height="281" /></a></p>
<p>We&#8217;ll need to do some basic configuration first. Essentially, we need to tell Hudson where the JDK and Maven reside. Click on &#8220;Manage Hudson&#8221;, then &#8220;Configure System&#8221;. In the resulting screen, configure the locations respectively. This is what it looks like on our server:</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/10/hudson3.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/10/hudson3.png" alt="hudson3" width="600" height="255" /></a></p>
<p>Next, make sure you have configured the &#8220;Hudson URL&#8221; at the bottom of this configuration screen. You need to change it from &#8220;localhost&#8221; to the actual hostname of your server. Something like this:</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/10/hudson4.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/10/hudson4.png" alt="hudson4" width="600" height="38" /></a></p>
<p>Excellent. Now click &#8220;Save&#8221;, and then click on the &#8220;New Job&#8221; link in top left corner of the page and fill out the resulting form as we have below:</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/10/hudson2.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/10/hudson2.png" alt="hudson2" width="600" height="281" /></a></p>
<p>Continuing from here, a more detailed page of your project is available:</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/10/hudson5.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/10/hudson5.png" alt="hudson5" width="600" height="311" /></a></p>
<p>Continued&#8230;</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/10/hudson6.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/10/hudson6.png" alt="hudson6" width="600" height="283" /></a></p>
<p>Some explanation is required here. Hudson has various methods of deciding when to perform a build. These are called <em>build triggers</em>. The method we have chosen here is to poll Subversion every minute. If anything has changed, we perform a build. Other trigger mechanisms exist internally to Hudson. We say <em>internally</em> because there is one other important method to trigger a build. An HTTP GET on http://localhost:8075/job/testWebApp/build will trigger a build from an external source. How is that useful? You could use the <a href="https://olex.openlogic.com/packages/wget" target="_blank">Wget</a> utility to trigger that URL from the command line or a shell. It&#8217;s particularly handy if you use the <em>Wget</em> command on the URL from within a Subversion post-commit hook. So: every time someone commits a change to your source code repository, a build will be performed automatically. In this way we eliminate the wasteful polling of the Subversion repository by Hudson itself.</p>
<p>Let&#8217;s go ahead and set up the post-commit hook now. But first, go back into the testWebapp Hudson job configuration and uncheck the &#8220;Poll SCM&#8221; checkbox. Then click &#8220;Save&#8221;.  Now we&#8217;re ready to configure the post commit hook. Our repository resides in /var/lib/svn/repositories/testWebApp (see above):</p>
<pre>cd /var/lib/svn/repositories/testWebApp/hooks
cp post-commit.tmpl post-commit
chmod 755 post-commit</pre>
<p>Now edit post-commit and ensure that the last three lines look like this:</p>
<pre>REPOS="$1"
REV="$2"

wget http://localhost:8075/job/testWebApp/build</pre>
<p>That&#8217;s it! From now on, every time someone commits code, the build is triggered.</p>
<h2>Finishing Up</h2>
<p>There&#8217;s a lot more you can do with Hudson. It supports multiple other source code control repositories, build triggers, build notifiers&#8230; even Twitter and IRC interfaces! It uses plugins to perform much of this functionality. Take a look <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins" target="_blank">here</a> for the current list of plugins available. We hope this has been a useful introduction to Hudson. If you&#8217;re keen for more, there&#8217;s detailed information at the <a href="http://hudson-ci.org/" target="_blank">Hudson Website</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2009/creating-a-continuous-integration-server-for-java-projects-using-hudson/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Maven-Based Development Environment on Linux</title>
		<link>http://olex.openlogic.com/wazi/2009/creating-a-maven-based-development-environment-on-linux/</link>
		<comments>http://olex.openlogic.com/wazi/2009/creating-a-maven-based-development-environment-on-linux/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 19:12:32 +0000</pubDate>
		<dc:creator>Grant Smith</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Ant]]></category>
		<category><![CDATA[jdk]]></category>
		<category><![CDATA[jetty]]></category>
		<category><![CDATA[Lucene]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Nexus]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=42167</guid>
		<description><![CDATA[Maven is quickly becoming the de facto standard for Java project builds, but its reliance on a remote central repository somewhere on the Internet can be troublesome.  This tutorial covers the setup of a local Maven proxy, including installation and configuration of Maven and the Nexus repository manager on a Linux server.]]></description>
			<content:encoded><![CDATA[<p><a href="https://olex.openlogic.com/packages/maven" target="_blank">Maven</a> is quickly becoming the <em>de facto</em> standard for Java project builds, as more developers realize its benefits and choose to migrate from <a href="https://olex.openlogic.com/packages/ant" target="_blank">Ant</a>. Gone are the days when external project dependencies clogged up valuable space in source code control repositories. Once programmers become familiar with Maven, discovering all its advantages along the way, development proceeds as if they couldn&#8217;t get the job done without it. But there is one aspect of Maven-based development that&#8217;s potentially troublesome: the reliance on a remote central repository somewhere on the Internet. When a new developer joins a team, every single dependency is copied from the remote repository to his or her local repository cache. On Linux, this resides in the <em>$HOME/.m2/repository</em> and is usually a substantially large directory — especially if the developer has multiple projects under Maven control. This places an unnecessarily large load on the company&#8217;s or individual&#8217;s Internet link for the duration of the dependency download. Even worse, should the Internet link go down, the developer is unable to work.</p>
<p>So what&#8217;s the answer to all that wasted Internet bandwidth? A local Maven proxy. The first time a developer requests a dependency, it is copied from the central repository to the local repository, which resides on the machine running the proxy. Subsequent requests by developers in the team are then fed the copy from the local repository, typically on the same local area network (LAN). That translates to quicker builds and — as long as no new dependencies are needed — no reliance on the corporate Internet link for builds.</p>
<h2>Before You Start</h2>
<p>This tutorial covers the setup of Maven on a Linux server, as well as the best free local proxy available today, <a href="https://olex.openlogic.com/packages/nexus" target="_blank">Nexus</a>. Nexus is available in both a GPL-licensed version (Nexus Community) and a commercially-licensed version (Nexus Pro) that provides additional functionality. We will, of course, focus on the open source version as it is sufficient for most requirements. Well, OK&#8230; also because we dig open source and free stuff!</p>
<h2>Meat &amp; Potatoes</h2>
<h3>Maven Setup</h3>
<p>Let&#8217;s start off with Maven. Maven runs as a Java process, so we&#8217;ll need to make sure we have Java installed first. Download the latest <a href="https://olex.openlogic.com/packages/jdk" target="_blank">JDK</a> from <a href="https://olex.openlogic.com/" target="_blank">OpenLogic Exchange (OLEX)</a> or http://java.sun.com/javase/downloads/index.jsp.</p>
<p>You&#8217;ll be asked to select the platform and type of installation. We always download the .bin self-extracting archive, and extract it to /usr/local on the Linux host:</p>
<pre># cp &lt;download_location&gt;/jdk-6u16-linux-x64.bin /usr/local
# cd /usr/local
# sh ./jdk-6u16-linux-x64.bin</pre>
<p>Follow the prompts and install the Java SDK. You&#8217;ll see that at the time of writing, the version of the SDK was 6u16, which will obviously change. Once everything has extracted, a browser window will open and nag you to register. This is optional — the SDK will function just fine, even if you choose not to register. Close the browser and look at the new directory under /usr/local. The JDK will be installed in a directory containing the name of the version of the software, in this instance /usr/local/jdk1.6.0_16. A good trick is to make a symbolic link for this directory to /usr/local/java. That way you can keep your $JAVA_HOME environment variable set to the symbolic link. Every time you upgrade Java, simply remove the old symlink and then relink to the new location:</p>
<pre># rm -f /usr/local/java</pre>
<pre># ln -fs /usr/local/jdk1.6.0_16 /usr/local/java</pre>
<p>If you don&#8217;t already have $JAVA_HOME set up, let&#8217;s do it now. Use your favorite editor to open /etc/profile, and add the following line near the top:</p>
<pre>export JAVA_HOME=/usr/local/java</pre>
<p>While we&#8217;re here, let&#8217;s also add a needed variable for Maven:</p>
<pre>export MAVEN_HOME=/usr/local/maven</pre>
<p>Now look a little further down in the file. You should see a line configuring the $PATH variable. We need to add to the $PATH to include the ./bin directories of both Java and Maven. It should end up looking something like this:</p>
<pre>export PATH="$JAVA_HOME/bin:$PATH\
$MAVEN_HOME/bin:\
$SOME_OTHER_STUFF/bin"</pre>
<p>Save /etc/profile and exit the editor. Now it&#8217;s time to install Maven. Download it from OpenLogic Exchange (OLEX) or http://maven.apache.org/download.html.</p>
<p>Get the latest .tar.gz distribution. In our case it was apache-maven-2.2.1-bin.tar.gz:</p>
<pre># cp &lt;download_location&gt;/apache-maven-2.2.1-bin.tar.gz /usr/local
# cd /usr/local
# tar xvzf ./apache-maven-2.2.1-bin.tar.gz</pre>
<p>Now log out and back in again for the contents of /etc/profile to be read and for the environment variables and PATH to be updated. Verify both installations:</p>
<pre># java -version</pre>
<pre>java version "1.6.0_16"
Java(TM) SE Runtime Environment (build 1.6.0_16-b01)
Java HotSpot(TM) 64-Bit Server VM (build 14.2-b01, mixed mode)</pre>
<pre>#mvn -version
Apache Maven 2.2.1 (r801777; 2009-08-06 12:16:01-0700)
Java version: 1.6.0_16
Java home: /usr/local/jdk1.6.0_16/jre
Default locale: en_US, platform encoding: ISO-8859-1
OS name: "linux" version: "2.6.27.2" arch: "amd64" Family: "unix"</pre>
<p>Good Job! Now on to the final part of our puzzle, the Nexus repository manager.</p>
<h3>Nexus Setup</h3>
<p>Nexus is deployed as a standard J2EE web archive or <em>.war</em>, as it is affectionately known. There are two download options: one as a .war, which you can install into a J2EE compliant server; or a standalone version which contains an embedded <a href="https://olex.openlogic.com/packages/jetty" target="_blank">Jetty</a> server. We&#8217;re going to focus on the standalone deployment.</p>
<p>Let&#8217;s start off by downloading and installing Nexus:</p>
<pre># cd /usr/local</pre>
<pre># wget http://nexus.sonatype.org/downloads/nexus-webapp-1.3.6-bundle.tar.gz</pre>
<pre># tar xvzf nexus-webapp-1.3.6-bundle.tar.gz</pre>
<pre># ln -fs nexus-webapp-1.3.6 nexus</pre>
<pre># cd nexus</pre>
<pre># ls ./bin/jsw/</pre>
<p>This will show you a list of directories for the supported architectures. In this case we&#8217;re running Linux x86-64, so to start the server we type:</p>
<pre>#  ./bin/jsw/linux-x86-64/nexus start</pre>
<p>You can install Nexus as a Linux service, too. Look for the link to the official documentation at the end of this article for details. To follow the log of the starting up server:</p>
<pre># tail -f logs/wrapper.log</pre>
<p>If all runs correctly and you see no ominous-looking error messages, you should now have the proxy up and running. But we still have to tell Maven to look at the repository, instead of at the default central Maven servers. We do this by editing <em>settings.xml</em>, which resides in the <em>.m2</em> directory under your home directory.</p>
<pre>&lt;settings&gt;
  &lt;mirrors&gt;
    &lt;mirror&gt;
      &lt;id&gt;nexus&lt;/id&gt;
      &lt;mirrorOf&gt;*&lt;/mirrorOf&gt;
      &lt;url&gt;http://localhost:8081/nexus/content/groups/public&lt;/url&gt;
    &lt;/mirror&gt;
  &lt;/mirrors&gt;
  &lt;profiles&gt;
    &lt;profile&gt;
      &lt;id&gt;nexus&lt;/id&gt;
      &lt;!--Enable snapshots for the built in central repo to direct --&gt;
      &lt;!--all requests to nexus via the mirror --&gt;
      &lt;repositories&gt;
        &lt;repository&gt;
          &lt;id&gt;central&lt;/id&gt;
          &lt;url&gt;http://central&lt;/url&gt;
          &lt;releases&gt;&lt;enabled&gt;true&lt;/enabled&gt;&lt;/releases&gt;
          &lt;snapshots&gt;&lt;enabled&gt;true&lt;/enabled&gt;&lt;/snapshots&gt;
        &lt;/repository&gt;
      &lt;/repositories&gt;
      &lt;pluginRepositories&gt;
        &lt;pluginRepository&gt;
          &lt;id&gt;central&lt;/id&gt;
          &lt;url&gt;http://central&lt;/url&gt;
          &lt;releases&gt;&lt;enabled&gt;true&lt;/enabled&gt;&lt;/releases&gt;
          &lt;snapshots&gt;&lt;enabled&gt;true&lt;/enabled&gt;&lt;/snapshots&gt;
        &lt;/pluginRepository&gt;
      &lt;/pluginRepositories&gt;
    &lt;/profile&gt;
  &lt;/profiles&gt;
  &lt;activeProfiles&gt;
    &lt;!--make the profile active all the time --&gt;
    &lt;activeProfile&gt;nexus&lt;/activeProfile&gt;
  &lt;/activeProfiles&gt;
&lt;/settings&gt;</pre>
<p>Remember that each of the developers in your organization will have to do this on their local machines, but replace localhost in <span style="text-decoration: underline;">http://localhost:8081/nexus/content/groups/public</span> with the name or IP address of your repository server.</p>
<p>We&#8217;re almost there. We still have to tell the repository proxy exactly what it has to proxy! For this task, Nexus has a really cool web-based interface for us to use. Fire up a browser on the machine and point it to <span style="text-decoration: underline;">http://localhost:8081/nexus</span>.</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/nexus1.jpeg"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/nexus1.jpeg" alt="The Nexus Welcome Screen" width="600" height="129" /></a></p>
<p style="text-align: center">Above: The Nexus <em>Welcome</em> Screen</p>
<p>Click on the <em>Log In</em> link at the top right hand side, and log in as admin with the password you configured during the setup process.</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/nexus2.jpg"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/nexus2.jpg" alt="The Repository View" width="600" height="236" /></a></p>
<p style="text-align: center">Above: The <em>Repository</em> View</p>
<p>Your screen may look slightly different. The <em>Repository Path</em> column will reflect either localhost, or the name of your server if you are administering from a remote machine. The next step is to download the <a href="https://olex.openlogic.com/packages/lucene" target="_blank">Lucene</a> indexes for all of the &#8220;proxy&#8221; pre-configured repositories. For example, click on the &#8220;Maven Central&#8221; proxy and select the <em>Configuration</em> tab below. Change &#8220;Download Remote Indexes&#8221; to <em>True</em>, and then click <em>Save</em>.</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/nexus3.jpg"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/nexus3.jpg" alt="Enabling Download of Remote Indexes" width="600" height="365" /></a></p>
<p style="text-align: center">Above: Enabling Download of Remote Indexes</p>
<p>Then right-click on the same proxy, and select <em>Re-Index</em>. Repeat the process for each of the proxies.</p>
<h2>Finishing Up</h2>
<p>Well done! You now have a functioning proxy that will start building a repository as you use it from your Maven project builds. If something doesn&#8217;t work, or you&#8217;re confused about some of the Nexus functionality, Sonatype has extremely good online documentation at <a href="http://www.sonatype.com/books/nexus-book/reference/index.html" target="_blank">http://www.sonatype.com/books/nexus-book/reference/index.html</a>, including instructions on how to install Nexus as a service. This is definitely worth doing. You can also add periodic tasks to download and re-index the proxies.</p>
<p>At this point, you should aim to become more familiar with the administration interface and understand all of its functionality. Reference the documentation and examine the system logs for any potential problems.</p>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2009/creating-a-maven-based-development-environment-on-linux/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Checking Basic Life Signs of Applications Running In JBoss</title>
		<link>http://olex.openlogic.com/wazi/2009/checking-basic-life-signs-of-applications-running-in-jboss/</link>
		<comments>http://olex.openlogic.com/wazi/2009/checking-basic-life-signs-of-applications-running-in-jboss/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 19:12:33 +0000</pubDate>
		<dc:creator>Veljko Krunic</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[tomcat]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=42775</guid>
		<description><![CDATA[What should you do if your application just slipped into unconsciousness, requests just hang, and your logs don't show anything useful? This tutorial will guide you through basic JBoss paramedic techniques you can use to check your application's vital signs.]]></description>
			<content:encoded><![CDATA[<p>Your application just slipped into unconsciousness, and now any request you make just hangs. To make matters worse, your logs don’t show anything useful. So how can you check your application&#8217;s vital signs when it drops on you like this?</p>
<p>All your production applications should be under critical care with monitoring systems that continually look at key statistics and life signs. Thus, if an application becomes unresponsive, you just need to glance at the monitor on your office wall to see the statistics for your environment.</p>
<p>But what if somehow you find yourself in a position where you have a critical problem with an application but don’t have any monitoring infrastructure? How can you quickly check the following vital signs?</p>
<ol>
<li>Pulse and respiration (data source usage, how many threads are used by HTTP, and AJP connector)</li>
<li>ID information (check server information like JVM, OS, and JBoss versions)</li>
<li>Signs of shock (high CPU usage, which threads took the most time on the server, and what threads are currently doing)</li>
</ol>
<h2>Before You Start</h2>
<p>Ideally, you should never be in this position with production systems.  There should always be some type of monitoring infrastructure in place to help you respond to these types of problems. Only development—and sometimes functional testing QA environments—should be routinely setup without monitoring in place.  Monitoring is an essential part of production environments as well as very useful feature to have in load testing environments.</p>
<p>Having said that, if you&#8217;re experiencing application problems and don’t have monitoring in place, you’d undoubtedly prefer solutions to lectures about best practices that haven’t been followed.  So, let&#8217;s cut to the chase and show one possible solution.</p>
<h2>Meat &amp; Potatoes</h2>
<p>In most situations you should have a monitoring system setup to look at all the information covered below. This article is written for the rare situation in which you do not having a monitoring system.</p>
<p>If your <a href="https://olex.openlogic.com/packages/jboss" target="_blank">JBoss</a> installation is mostly unaltered from its defaults, it is likely you still have the JMX Console, <a href="https://olex.openlogic.com/packages/tomcat" target="_blank">Tomcat</a> status and Admin Console enabled, and you can use them to get answers to key questions that will help you check your application’s vital signs. If you have them enabled, good for you.  But if you leave them on in a production system, don&#8217;t forget to at least secure them—the mechanisms presented here should be at least secured if not disabled in production systems.</p>
<p>Note that there are many reasons why an application might hang, and also that there are many other things you can check (e.g. EJB pools) that are not covered here. This article is not intended to be a detailed course in JBoss and application brain surgery, but rather just a brief paramedic’s manual covering the  most common signs and causes of unresponsive behavior. In other words, this article is intended to help you determine what’s wrong, not how to cure it &#8211; that might be a topic for subsequent articles.</p>
<h3>Where Are Consoles Located?</h3>
<p>To access the JMX Console go to <span style="text-decoration: underline;">http://localhost:8080/jmx-console</span>, where localhost is your server&#8217;s name. Tomcat status is available at <span style="text-decoration: underline;">http://localhost:8080/status?full=true</span>. And (if you&#8217;re using a JBoss version that includes it) the admin console is at <span style="text-decoration: underline;">http://localhost:8080/admin-console</span>.</p>
<p>Note that there are differences between JBoss 4 and JBoss 5.1. We will first talk about methods that work in both JBoss 4 and JBoss 5, and then present a somewhat easier method that works only in JBoss 5.1.</p>
<h3>Checking  DataSource Usage</h3>
<p>Investigating data source usage is useful when you’re unsure if you have enough data sources available for application. If you ran out of the available data source connections, your system is unresponsive because your queries are stuck.</p>
<p>To find statistics about data source usage, you need first to find the name of your data source. Let’s suppose that it’s named MyDataSource.</p>
<p>Go to the JMX console, and find the section called <strong>jboss.jca</strong>. You should see MBean there with the object name:</p>
<p>name=MyDataSource,service=ManagedConnectionPool</p>
<p><strong>Note:</strong> There are multiple similarly named entries in the JMX console, so make sure that you use right one in the right section for the right data source!</p>
<p>Click on that link, and the following arguments are especially useful:</p>
<ul>
<li><strong>MaxConnectionsInUseCount</strong> – displays the maximum number of connections that have ever been used since the server started or the data source was deployed.</li>
<li><strong>InUseConnectionCount</strong> – displays the number of connections currently used.</li>
<li><strong>MaxSize</strong> – displays the maximum number of connections available in the pool.</li>
</ul>
<p>Another interesting operation here is listStatistics(). The example below shows the listing for one data source:</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/JBoss-Operation-Results.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/JBoss-Operation-Results.png" alt="JBoss-Operation-Results" width="500" height="233" /></a></p>
<h3>Checking Connector Thread Usage</h3>
<p>Checking connector thread usage is useful when you want to find out how many of the available request threads are used. If all connector threads are blocked, your incoming requests are waiting on the current requests to proceed before their processing can be started.</p>
<p>To find statistics about connector usage, the best way is to look at <span style="text-decoration: underline;">http://localhost:8080/status?full=true</span>.  This will give you the following statistics:</p>
<ul>
<li><strong>Max threads</strong> – displays the max number of threads the connector can spawn.</li>
<li><strong>Current thread busy</strong> – indicates how many threads are currently used by application users.</li>
</ul>
<p>There are many other useful things available here, including a list of all currently-deployed applications and per-servlet statistics.</p>
<p>Be sure that you are looking at the statistics for the right connector for your setup &#8211; AJP connector if you are using AJP (e.g. setup with Apache HTTPD, mod_jk, and JBoss) or HTTP connector if your HTTP requests go directly to JBoss. The default configuration has AJP connector listening on port 8009 and HTTP connector on port 8080.</p>
<p>The picture below shows statistics for the HTTP connector on a recently-started server with only one user:</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/Tomcat-Status.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/Tomcat-Status.png" alt="JBoss-Operation-Results" width="500" height="51" /></a></p>
<h3>Obtaining Server Information</h3>
<p>Server information is useful when your questions are:</p>
<ul>
<li>How do I get the thread dump?</li>
<li>What’s the cumulative time spent in my threads?</li>
<li>Which JVM, OS, and JBoss versions are used?</li>
<li>How was the server configured? Which configuration (e.g., all, default, or minimal) am I working with?</li>
</ul>
<p>This line of questioning is helpful to collect basic version information for the software you are using, as well as data about what is your server is currently doing.</p>
<p>You probably know the versions and configuration if you were the person who installed the system, and this information is always available in the JBoss boot.log file.  You can also double-check this information with only browser access by finding the following three entries in the jboss.system section of the JMX Console.</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/jboss.system-jmx-console.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/jboss.system-jmx-console.png" alt="JBoss-Operation-Results" /></a></p>
<p>These three beans provide answers to all of the questions listed above:</p>
<ul>
<li><strong>Server</strong> &#8211; provides information about the version of JBoss server in use.</li>
<li><strong>ServerConfig</strong> &#8211; provides information about the server configuration in use.</li>
<li><strong>ServerInfo</strong> &#8211; provides information about the JVM and OS version you are using to run the server. Additionally, the listThreadCpuUtilization() method that you can call from this screen provides you with information about the CPU usage of your threads, and listThreadDump() allows you to execute a thread dump.</li>
</ul>
<h3>Is CPU Usage Going Crazy?</h3>
<p>If your CPU usage is stuck at 100% all the time, it might be an indication of multiple problems such as pooling when you shouldn’t, memory leaks, and CPU-intensive code.</p>
<p>A thread dump can help you detect pooling or infinite loop types of problems.  Do multiple thread dumps and compare the results to determine if you’re still stuck in the same place on some threads. If these threads have high CPU usage as well, they’re doubly suspicious. Both of these can be checked in the SystemInfo bean, as discussed in the previous section.</p>
<p>Memory leaks are slightly more complex.  For additional details on fixing memory leaks please see the tutorial, <a href="http://olex.openlogic.com/wazi/2009/how-to-fix-memory-leaks-in-java/">How to Fix Memory Leaks in Java</a>.</p>
<h3>What About JBoss 5?</h3>
<p>All of the techniques covered so far apply to both JBoss 4 and JBoss 5, but the JMX Console is somewhat intimidating and may provide the impression of a &#8220;big, difficult to navigate pile of MBeans.&#8221; JBoss 5.1 comes to the rescue here with an admin console that delivers a more user-friendly way of obtaining important information.</p>
<p>You can access the JBoss 5.1 admin console at <span style="text-decoration: underline;">http://localhost:8080/admin-console</span>.  All of the previously-mentioned information is readily available within the admin console. Look at the tree on the left side.</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/JBoss-AS-Admin-Console-1.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/JBoss-AS-Admin-Console-1.png" alt="JBoss-Operation-Results" width="500" height="300" /></a></p>
<p>At the root of the tree you can get information about the OS version.</p>
<p>To get information about the JBoss version and configuration, click on the server in the left side tree view (e.g., JBoss AS 5, which is the default entry in the tree).</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/JBoss-AS-Admin-Console-2.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/JBoss-AS-Admin-Console-2.png" alt="JBoss-Operation-Results" width="500" height="300" /></a></p>
<p>Information about the data source is located under JBossAS Servers/YourServer/Resources/Datasources in the tree on the left side. Find your data source, and then look at both the Summary and Metrics panels on the right side. The example above shows the DefaultDS data source, but your data source is probably different.  Be sure to look at statistics for your own data source—not, for example, of DefaultDS!</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/JBoss-AS-Admin-Console-3.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/JBoss-AS-Admin-Console-3.png" alt="JBoss-Operation-Results" width="500" height="300" /></a></p>
<p>To find connector statistics, look in the tree on the left side under JBossAS Servers/YourServer/Resources/JBoss Web/Connectors.</p>
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/JBoss-AS-Admin-Console-4.png"><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/09/JBoss-AS-Admin-Console-4.png" alt="JBoss-Operation-Results" width="500" height="300" /></a></p>
<h3>Can I Get This Information From A Command Line?</h3>
<p>If you prefer to work from a command line, you can get the information covered above by using the twiddle.sh command line utility located in the $JBOSS_HOME/bin. The names of the MBeans that you should use in twiddle.sh are the same as the names of the MBeans you are using in JMX Console.</p>
<h3>If Something is Maxed, I Just Increase It, Right?</h3>
<p>Sometimes, but not always. A lot depends on the situation. What to do in each situation involves some degree of “it depends” and may be the subject of future articles.</p>
<h2>Finishing Up</h2>
<p>What if you don&#8217;t have monitoring installed, can&#8217;t get monitoring information from any application, and your consoles and twiddle.sh don&#8217;t work? Or if all of the vital signs covered above look normal but you are still stuck with a comatose application? Well, in this case there&#8217;s very little that JBoss paramedic techniques can do to help, and you might need to perform a little exploratory surgery to get more information.</p>
<p>You have couple of options here:</p>
<ul>
<li>You might try to dig out the information yourself (as a hint, you can change log levels in JBoss for a lot of things without necessarily needing to restart).</li>
<li>You might reproduce the problem with more monitoring in place, and then try to dig out additional information.</li>
<li>You might look at additional places that are outside of the scope of this article (e.g., EJB pools, JMS behavior, etc.).</li>
<li>If all else fails, most JBoss consultants who are worth their salt should be able to do all of the above for you and have at least few more tricks that apply to your specific situation and are not mentioned in article.</li>
</ul>
<h3>References / For More Info</h3>
<p>The JBoss Group: <a href="http://www.amazon.com/s/ref=nb_ss?url=search-alias%3Daps&amp;field-keywords=JBoss+4&amp;x=0&amp;y=0" target="_blank">&#8220;JBoss 4.0 &#8211; The Official Guide&#8221;</a>, Sams Publishing, April 30, 2005, ISBN 978-0672326486</p>
<p>Javid Jamae, Peter Johnson: <a href="http://www.amazon.com/JBoss-Action-Configuring-Application-Server/dp/1933988029/ref=sr_1_6?ie=UTF8&amp;s=books&amp;qid=1251922078&amp;sr=8-6" target="_blank">&#8220;JBoss in Action: Configuring the JBoss Application Server&#8221;</a>, Manning Publications, January 28, 2009, ISBN 978-1933988023</p>
<p><a href="http://www.jboss.org/community/wiki/SecureTheJmxConsole" target="_blank">http://www.jboss.org/community/wiki/SecureTheJmxConsole</a></p>
<p><a href="http://www.jboss.org/community/wiki/AccessControlForJMXConsole" target="_blank">http://www.jboss.org/community/wiki/AccessControlForJMXConsole</a></p>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2009/checking-basic-life-signs-of-applications-running-in-jboss/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing Apache HTTP Server with a Quick-Start Config</title>
		<link>http://olex.openlogic.com/wazi/2009/installing-apache-http-server-with-quick-start-config/</link>
		<comments>http://olex.openlogic.com/wazi/2009/installing-apache-http-server-with-quick-start-config/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 16:04:56 +0000</pubDate>
		<dc:creator>Freddy Andersen</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[gcc]]></category>
		<category><![CDATA[groundwork]]></category>
		<category><![CDATA[hyperic-hq]]></category>
		<category><![CDATA[mod_jk]]></category>
		<category><![CDATA[mongrel]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[tomcat]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=40435</guid>
		<description><![CDATA[The Apache HTTP Server is one of the most widely used open source software packages, so it's no surprise that we get lots of questions about Apache installation procedures.  Fortunately, we have tons of experience with Apache installations, and we've distilled our years of experience into this handy tutorial.]]></description>
			<content:encoded><![CDATA[<p>The <a href="https://olex.openlogic.com/packages/apache">Apache HTTP Server</a> has been the <a href="http://httpd.apache.org/" target="_blank">most popular web server on the Internet since April 1996</a> and is one of the most widely used open source software packages.  In fact, the <a href="http://news.netcraft.com/archives/2009/06/17/june_2009_web_server_survey.html" target="_blank">latest Netcraft Web Server Survey</a> reports that more than half of all active web sites use Apache, making it more widely used than all other Web servers combined.  So it&#8217;s no surprise that we get lots of questions about Apache HTTP Server installation procedures.  Fortunately, we have tons of experience with Apache installations, and we&#8217;ve distilled our years of experience into this handy tutorial.</p>
<h2>Before You Start</h2>
<p>This article assumes that you have Red Hat/CentOS Linux with a proper build environment setup.  If you do not have <a href="https://olex.openlogic.com/packages/gcc" target="_blank">GCC</a> installed you can get this with all the required packages like this:</p>
<p>yum groupinstall &#8220;Development Libraries&#8221;</p>
<p>You should now be ready to install Apache!</p>
<h2>Meat &amp; Potatoes</h2>
<p>When we install Apache HTTP Server either for ourselves a client — small or large — we follow a &#8220;standard&#8221; configuration setup that&#8217;s very easy to build on later.  For the most part we use CentOS or Red Hat Enterprise edition servers, but these steps should work on any Unix system.  This might not be true for AIX, which requires a little more hand-holding to make sure the compiler is installed correctly.</p>
<p>The steps we&#8217;ll cover in this article are:</p>
<ul>
<li>Download the source code for the latest version of Apache (currently 2.2.11) from OpenLogic Exchange (OLEX) or the Apache project website.</li>
<li>Execute the configure, make, and make install installation steps (with a few custom switches).</li>
<li>Setup the httpd.conf and associated files.</li>
<li>Start your newly built Apache server.</li>
<li>Done!</li>
</ul>
<h3>Download Apache</h3>
<p>The first step is to download the Apache source code, not binaries or RPMs.  We believe that using the source code gives the best performing, most flexible installation of Apache.  If you follow a few simple steps the actual &#8220;installation&#8221; procedure is not difficult, and you&#8217;ll have a good foundation to add or remove features later.</p>
<p>To download the source source code, go to <a href="https://olex.openlogic.com/packages/apache">OpenLogic Exchange (OLEX)</a> or the <a href="http://httpd.apache.org/download.cgi" target="_blank">Apache downloads site</a> and look for the latest ZIP, TGZ, or BZ2 file (currently version 2.2.11).</p>
<h3>Compiling/Installing the Source for Apache</h3>
<p>We like to keep our source downloads in ~/Software/ so it&#8217;s easy go back and re-compile and re-install the binaries if we need to add a module or two.  With the source saved under ~/Software/httpd-2.2.11, compile Apache HTTP Server with the following configure string:</p>
<blockquote>
<pre>[root@coco ~]# cd ~/Software/httpd-2.2.11
[root@coco httpd-2.2.11]# "./configure"
"--enable-ssl"
"--enable-proxy"
"--enable-proxy-balancer"
"--enable-rewrite"
"--enable-headers"
"--enable-deflate"
"--enable-cache"
"--enable-expires"
"--enable-mem-cache"
"--enable-disk-cache"
"--enable-file-cache"
"--with-mpm=worker"
"--disable-cgi --disable-asis"
"--disable-autoindex"
"--disable-userdir"</pre>
</blockquote>
<p>Here&#8217;s a brief explanation of the configuration options shown above:</p>
<ul>
<li><strong>enable-ssl</strong>: This will allow you to enable a secure port later.</li>
<li><strong>enable-proxy/enable-proxy-balancer</strong>: This will setup a connection to a back-end server like <a href="https://olex.openlogic.com/packages/tomcat">Tomcat</a> or <a href="https://olex.openlogic.com/packages/mongrel">Mongrel</a></li>
<li><strong>enable-rewrite</strong>: We&#8217;re always going to need rewrite rules in the config file.</li>
<li><strong>enable-headers</strong>: We need this to enable monitoring of the server, and for mod_proxy we need to manipulate the header.</li>
<li><strong>enable-deflate</strong>: Enables the old gzip module, which will allow us to setup some content to be compressed with gzip.</li>
<li><strong>enable-cache/expires/mem-cache/disk-cache/file-cache</strong>: These are all included so we can enable the expires module.</li>
<li><strong>with-mpm=worker</strong>: We&#8217;re choosing to use the worker MPM as the default since most servers we work with have more than one CPU.  Use the prefork MPM if you&#8217;re working on a server that has only one CPU.</li>
</ul>
<p>Next, run the following to install Apache HTTP Server:</p>
<blockquote><p>[root@coco httpd-2.2.11]# make &amp;&amp; make install</p></blockquote>
<p>The Apache server should now be installed in <strong>/usr/local/apache2</strong>, which is the default installation directory.  To change the Apache installation directory you&#8217;ll need to add the &#8211;prefix=/my/directory/apache2 switch to the configure string, and then run the make &amp;&amp; make install command as shown above.</p>
<h3>Apache Startup Script</h3>
<p>The easiest and fastest way to start Apache is to copy /usr/local/apache2/bin/apachectl to /etc/init.d/apache. This will allow you to do /etc/init.d/apache start|stop|restart.</p>
<p>If you want a script that has more feedback you can use the following:</p>
<blockquote>
<pre>#!/bin/bash
# httpd        Startup script for the Apache HTTP Server
# chkconfig: 2345 85 15
# description: Apache is a World Wide Web server.  It is used to serve
#              HTML files and CGI.
# processname: httpd
# config: /usr/local/apache2/conf/httpd.conf
# pidfile: /var/run/apache2.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Start httpd in the C locale by default.
HTTPD_LANG=${HTTPD_LANG-"C"}

# This will prevent initlog from swallowing up a pass-phrase prompt if
# mod_ssl needs a pass-phrase from the user.
INITLOG_ARGS=""

# Path to the apachectl script, server binary, and short-form for messages.
apachectl=/usr/local/apache2/bin/apachectl
httpd=${HTTPD-/usr/local/apache2/bin/httpd}
prog=httpd
pidfile=${PIDFILE-/var/run/apache2.pid}
lockfile=${LOCKFILE-/var/lock/subsys/apache2}
RETVAL=0

start() {
 echo -n $"Starting $prog: "
 LANG=$HTTPD_LANG daemon $httpd $OPTIONS
 RETVAL=$?
 echo
 [ $RETVAL = 0 ] &amp;&amp; touch ${lockfile}
 return $RETVAL
}
stop() {
 echo -n $"Stopping $prog: "
 killproc $httpd
 RETVAL=$?
 echo
 [ $RETVAL = 0 ] &amp;&amp; rm -f ${lockfile} ${pidfile}
}
reload() {
 echo -n $"Reloading $prog: "
 if ! LANG=$HTTPD_LANG $httpd $OPTIONS -t &gt;&amp;/dev/null; then
 RETVAL=$?
 echo $"not reloading due to configuration syntax error"
 failure $"not reloading $httpd due to configuration syntax error"
 else
 killproc $httpd -HUP
 RETVAL=$?
 fi
 echo
}

# See how we were called.
case "$1" in
 start)
 start
 ;;
 stop)
 stop
 ;;
 status)
 status $httpd
 RETVAL=$?
 ;;
 restart)
 stop
 start
 ;;
 condrestart)
 if [ -f ${pidfile} ] ; then
 stop
 start
 fi
 ;;
 reload)
 reload
 ;;
 graceful|help|configtest|fullstatus)
 $apachectl $@
 RETVAL=$?
 ;;
 *)
 echo $"Usage: $prog {start|stop|restart|condrestart|reload|status|fullstatus|graceful|help|configtest}"
 exit 1
esac

exit $RETVAL</pre>
</blockquote>
<h3><strong>Apache configuration file</strong></h3>
<p>The main configuration file we use as a template for Apache servers has a few different sections that are important to understand.</p>
<blockquote>
<pre># =================================================
# Basic Settings
# =================================================
ServerName %{SERVER_NAME}
ServerRoot "/usr/local/apache2"
PidFile "/var/run/apache2.pid"
# =================================================
# Performance Settings
# =================================================
Timeout 30
KeepAlive On
MaxKeepAliveRequests 500
KeepAliveTimeout 2
&lt;IfModule mpm_prefork_module&gt;
 StartServers            1
 MinSpareServers         1
 MaxSpareServers         10
 MaxClients              25
 MaxRequestsPerChild     1000
&lt;/IfModule&gt;
&lt;IfModule mpm_worker_module&gt;
 ServerLimit             16
 StartServers             2
 MaxClients              40
 MinSpareThreads          5
 MaxSpareThreads         20
 ThreadsPerChild         20
 MaxRequestsPerChild   5000
&lt;/IfModule&gt;</pre>
</blockquote>
<p>The Basic Settings section just defines the root directory of Apache, but the Performance Settings section has a few noteworthy options.  We have a Timeout of 30 seconds, which is enough for most setups (the default of 300 is way too long).  We enable KeepAlive, but the KeepAlive timeout is only 2 seconds.  This allows each user to get their own connection, but the connection will close as soon as they download the page they requested (you can play with this timeout, but you&#8217;ll most likely want to have it set somewhere in the 1-5 sec range). Next, we setup prefork and worker based on the number of CPUs that are installed on the Apache server.</p>
<blockquote>
<pre># =================================================
# General Settings
# =================================================
Listen 80
# Listen 443
User www
Group www
ServerAdmin webmaster@openlogic.com
UseCanonicalName Off
ServerTokens Prod
ServerSignature Off
HostnameLookups Off
ExtendedStatus On
# =================================================
# Modules
# =================================================
#LoadModule dummy_module /usr/lib/apache2/modules/mod_dummy.so</pre>
</blockquote>
<p>In the General Settings section we set Listen to port 80, but we also have port 443 as an option to choose from (we’ll show you how to setup a https/SSL/secure virtual host later).  User and Group are set to the www user, which is a system user (note that on Red Hat you create a system user with the -r switch <em>adduser -r www</em>).  We don&#8217;t want the server to look up hostname or show a signature to our users, so those options are disabled.  The ExtendedStatus option is enabled for monitoring reasons.  And in the Modules section, the dummy module is there in case we want to install <a href="https://olex.openlogic.com/packages/php">PHP</a> later on.</p>
<blockquote>
<pre># =================================================
# Access Control
# =================================================
&lt;Directory /&gt;
 Options FollowSymLinks
 AllowOverride None
 Order deny,allow
 Deny from all
&lt;/Directory&gt;
&lt;DirectoryMatch "^/.*/.svn/"&gt;
 ErrorDocument 403 /404.html
 Order allow,deny
 Deny from all
 Satisfy All
&lt;/DirectoryMatch&gt;
&lt;FilesMatch "^.ht"&gt;
 Order allow,deny
 Deny from all
 Satisfy All
&lt;/FilesMatch&gt;
# =================================================
# MIME Encoding
# =================================================
DefaultType text/plain
TypesConfig conf/mime.types
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl    .crl</pre>
</blockquote>
<p>Needless to say, the Access Control section contains some important options.  Deny from all makes sure we have to allow access to any directory that&#8217;s used in the Apache configuration.  Then, we make sure that users don&#8217;t have access to .svn directories or .ht files.  In the MIME Encoding section we have a minimal mime.type setup for the deflate and SSL modules.</p>
<blockquote>
<pre># =================================================
# Logs
# =================================================
LogLevel warn
LogFormat "%h %l %u %t "%r" %&gt;s %b "%{Referer}i" "%{User-Agent}i"" combined
ErrorLog /usr/local/apache2/logs/error_log
# Mark requests for the robots.txt file
SetEnvIf Request_URI "^/robots.txt$" dontlog
SetEnvIf Request_URI "^/monit/token$" dontlog
# =================================================
# SSL Configuration
# =================================================
SSLPassPhraseDialog  builtin
SSLSessionCache        shmcb:/usr/local/apache2/logs/ssl_scache(512000)
SSLSessionCacheTimeout  300
SSLMutex  file:/usr/local/apache2/logs/ssl_mutex
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin</pre>
</blockquote>
<p>Next, we setup the LogFormat for use in our virtual hosts and the server error log file.  We also have two dontlog Env settings to remove the robot.txt and monit/token hits from the log.  (We&#8217;ll show how this is used when we create the virtual host.)  We also setup a default SSL configuration for the server.</p>
<blockquote>
<pre># =================================================
# Mod Status for Monitoring
# =================================================
&lt;VirtualHost 127.0.0.1:80&gt;
 &lt;Location /server-status&gt;
 SetHandler server-status
 Order Deny,Allow
 Deny from all
 Allow from localhost
 Allow from 127.0.0.1
 &lt;/Location&gt;
&lt;/VirtualHost&gt;
# =================================================
# Include Extra Configs
# =================================================
Include conf/extra/httpd-myblog.com.conf</pre>
</blockquote>
<p>In the Mod Status for Monitoring section we get to the server monitoring setup.  We start by allowing only access from localhost, and we specify that it will only listen to the 127.0.0.1 IP.  This is a good setup for tools like <a href="https://olex.openlogic.com/packages/groundwork">GroundWork</a> and <a href="https://olex.openlogic.com/packages/hyperic-hq">Hyperic</a>.  The last line includes a virtual host configuration file.  Now let&#8217;s have a look at the virtual host.</p>
<h4>Virtual Hosts Using a Name-Based Setup</h4>
<p>We like to configure our httpd.conf with server-wide settings while keeping it free of actual content hosting elements or mod_proxy/mod_jk configurations.  In this example we have a blog that&#8217;s running on a <a href="https://olex.openlogic.com/packages/ruby">Ruby</a> on <a href="https://olex.openlogic.com/packages/ruby">Rails</a> back-end with three Thin servers listening to ports 8000-8002 (Thin an application server that can be used for RoR as an alternative to Tomcat or Mongrel).</p>
<blockquote>
<pre># --------------------------------------------------------
# Always Keep the Host Header
# --------------------------------------------------------
ProxyPreserveHost On
# --------------------------------------------------------
# Rails Cluster
# --------------------------------------------------------
&lt;Proxy balancer://rails-cluster&gt;
  BalancerMember http://127.0.0.1:8000
  BalancerMember http://127.0.0.1:8001
  BalancerMember http://127.0.0.1:8002
&lt;/Proxy&gt;</pre>
</blockquote>
<p>This setup has three servers in a proxy_balancer cluster that you can access using balancer://rails-cluster/ just as though it was one server.</p>
<blockquote>
<pre># --------------------------------------------------------
# Name-Based Virtual Hosting
# --------------------------------------------------------
NameVirtualHost *:80

&lt;VirtualHost *:80&gt;
 DocumentRoot "/var/www/myblog.com/current/public"
 ServerName www.myblog.com
 ServerAlias myblog.com

 # -------------------------------------------------
 # Rewrite Rules
 # -------------------------------------------------
 RewriteEngine on

 # Force www.myblog.com and make sure we use a 301 HTTP code for the
 # redirect. This is a SEO must.
 RewriteCond %{HTTP_HOST}   !^www.myblog.com [NC]
 RewriteCond %{HTTP_HOST}   !^$
 RewriteRule ^/(.*)         http://www.myblog.com/$1 [L,R=301]

 # --------------------------------------------------------
 # List of URLs Not to Proxy
 # --------------------------------------------------------
 ProxyPass /system !
 ProxyPass /images !
 ProxyPass /stylesheets !
 ProxyPass /javascripts !
 ProxyPass /monit/token !
 # Send everything else to the proxy_balancer cluster of rails servers
 ProxyPass / balancer://rails-cluster/
 ProxyPassReverse / balancer://rails-cluster/

 &lt;Directory "/var/www/myblog.com/current/public"&gt;
  Options FollowSymLinks
  AllowOverride None
  Order allow,deny
  Allow from all
 &lt;/Directory&gt;
 # Before you restart the server you need to create the logs/myblog.com
 # directory.
 # We are also adding the dontlog environment variable here to stop
 # logging the set entries. (This is configured in your httpd.conf)
 ErrorLog  "logs/myblog.com/error_log"
 CustomLog "logs/myblog.com/access_log" combined env=!dontlog

 # --------------------------------------------------------
 # Deflate Module Configuration
 # --------------------------------------------------------
 &lt;IfModule deflate_module&gt;
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/atom_xml
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/x-httpd-php
  AddOutputFilterByType DEFLATE application/x-httpd-fastphp
  AddOutputFilterByType DEFLATE application/x-httpd-eruby
  AddOutputFilterByType DEFLATE text/html
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4.0[678] no-gzip
 &lt;/IfModule&gt;
 # =============================================
 # Configure Expires Module
 # =============================================
 &lt;IfModule mod_expires.c&gt;
  ExpiresActive On
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType text/html "access plus 1 seconds"
  ExpiresByType image/gif "access plus 1 week"
  ExpiresByType image/jpeg "access plus 1 week"
  ExpiresByType image/png "access plus 1 week"
  ExpiresByType text/css "access plus 1 week"
  ExpiresByType text/javascript "access plus 1 week"
  ExpiresByType application/x-javascript "access plus 1 week"
  ExpiresByType text/xml "access plus 1 seconds"
 &lt;/IfModule&gt;
&lt;/VirtualHost&gt;</pre>
</blockquote>
<p>There&#8217;s a lot of information here, so lets take it step by step.  First, we setup a server with the name www.myblog.com that also listens to myblog.com, but by using mod_rewrite we force everyone to www.myblog.com with a 301 redirect.  Next, we setup all of the static content that we want Apache to serve from the local file system using ProxyPass with a ! to say &#8220;do not proxypass&#8221; these directories, and then we send everything else to the balancer cluster.  We setup the access rights to the static directory where our content (like images, JavaScript, uploaded files, and CSS) is stored.  Then, we setup the virtualhosts log file in its own directory inside the logs directory.  The mod_deflate and mod_expires configurations work for most setups, but this piece needs to be monitored and tuned to your setup.  We&#8217;ve seen the mod_expires setup cause problems using Rails and authentication.</p>
<p>Now, off to a secure.myblog.com virtual host:</p>
<blockquote>
<pre>&lt;VirtualHost _default_:443&gt;
 DocumentRoot "/var/www/myblog.com/current/public"
 ServerName secure.myblog.com
 ServerAlias www.myblog.com myblog.com
 RewriteCond %{HTTP_HOST}   !^secure.myblog.com [NC]
 RewriteCond %{HTTP_HOST}   !^$
 RewriteRule ^/(.*)         https://secure.myblog.com/$1 [L,R=301]
 # --------------------------------------------------------
 # List of URLs Not to Proxy
 # --------------------------------------------------------
 ProxyPass /system !
 ProxyPass /images !
 ProxyPass /stylesheets !
 ProxyPass /javascripts !
 ProxyPass / balancer://rails-cluster/
 ProxyPassReverse / balancer://rails-cluster/

 ErrorLog  "logs/myblog.com/error_log"
 CustomLog "logs/myblog.com/access_log" combined env=!donlog

 # --------------------------------------------------------
 # SSL Certificates
 # --------------------------------------------------------
 SSLEngine on
 SSLCertificateFile    /usr/local/apache2/ssl/secure.myblog.com.crt
 SSLCertificateKeyFile /usr/local/apache2/ssl/secure.myblog.com.key
 # --------------------------------------------------------
 # Deflate Module Configuration
 # --------------------------------------------------------
 &lt;IfModule deflate_module&gt;
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/atom_xml
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/x-httpd-php
  AddOutputFilterByType DEFLATE application/x-httpd-fastphp
  AddOutputFilterByType DEFLATE application/x-httpd-eruby
  AddOutputFilterByType DEFLATE text/html
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4.0[678] no-gzip
 &lt;/IfModule&gt;
 # =============================================
 # Configure Expires Module
 # =============================================
 &lt;IfModule mod_expires.c&gt;
  ExpiresActive On
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType text/html "access plus 1 seconds"
  ExpiresByType image/gif "access plus 1 week"
  ExpiresByType image/jpeg "access plus 1 week"
  ExpiresByType image/png "access plus 1 week"
  ExpiresByType text/css "access plus 1 week"
  ExpiresByType text/javascript "access plus 1 week"
  ExpiresByType application/x-javascript "access plus 1 week"
  ExpiresByType text/xml "access plus 1 seconds"
 &lt;/IfModule&gt;
 # --------------------------------------------------------
 # Document Root /
 # --------------------------------------------------------
 &lt;Directory "/var/www/myblog.com/current/public"&gt;
  Options FollowSymLinks
  AllowOverride None
  Order allow,deny
  Allow from all
 &lt;/Directory&gt;
 # -------------------------------------------------
 # Fixing Yet Another IE 6 Bug
 # -------------------------------------------------
 BrowserMatch ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
 # -------------------------------------------------
 # Add this to the request header so that
 # Rails puts the correct redirect in place
 # -------------------------------------------------
 RequestHeader set X_FORWARDED_PROTO 'https'
&lt;/VirtualHost&gt;</pre>
</blockquote>
<p>This is very similar to the port 80 virtual host of the same name.  The biggest difference is with the SSL certificates and the bottom SSL/https settings to fix issues with Mongrel/Rails and IE6.  You can&#8217;t configure mod_expires and mod_deflate in the main configuration file and have the virtual host inheret the configuration, so the best solution to be dry is to put these settings in their own mod_deflate.conf and mod_expires.conf and then include the named configuration files in each virtualhosts configuration file like so:</p>
<blockquote><p>Include conf/mod_deflate.conf<br />
Include conf/mod_expires.conf</p></blockquote>
<h2>Finishing Up</h2>
<p>Apache with mod_proxy rocks.  After working through the above steps we have an Apache installation that is ready to be expanded to a high performance web server or proxy server, or both.  We like to start with this setup and then build from here.  If you need to get more concurrent clients and throughput on your Apache server, take a look at your available memory and CPU cycles and consider doing something like this:</p>
<blockquote>
<pre>&lt;IfModule mpm_worker_module&gt;
  ThreadLimit 100
  StartServers 5
  MaxClients 1000
  MinSpareThreads 100
  MaxSpareThreads 1000
  ThreadsPerChild 100
  MaxRequestsPerChild 0
&lt;/IfModule&gt;</pre>
</blockquote>
<p>This is a high threads and low processes setup, and to get the number of processes that Apache will use simply divide MaxClients by ThreadPerChild.  So, this gives us 10 processes each with a maximum of 100 threads, with a maximum of 1000 clients total.  Depending on the server and type of content that you are serving you can load test and increase these settings if you need more than 1000 concurrent users.</p>
<p>We&#8217;re very big fans of mod_proxy, and we use mod_proxy_ajp in place of <a href="https://olex.openlogic.com/packages/mod_jk">mod_jk</a> every chance we get.  We also talk a lot of customers into using mod_proxy over mod_jk if they&#8217;re using Apache 2.2.x.</p>
<p>Using this setup to include the virtual hosts that the server runs, it&#8217;s easy to add and remove new websites.  It also provides a good overview of what&#8217;s running on the server.</p>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2009/installing-apache-http-server-with-quick-start-config/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Installing an SSH/SFTP Server on Windows</title>
		<link>http://olex.openlogic.com/wazi/2009/installing-an-ssh-sftp-server-on-windows/</link>
		<comments>http://olex.openlogic.com/wazi/2009/installing-an-ssh-sftp-server-on-windows/#comments</comments>
		<pubDate>Thu, 14 May 2009 21:53:55 +0000</pubDate>
		<dc:creator>Glen Bettridge</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[cygwin]]></category>
		<category><![CDATA[filezilla]]></category>
		<category><![CDATA[openssh]]></category>
		<category><![CDATA[winscp]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=2942</guid>
		<description><![CDATA[Need to get an OpenSSH Secure Shell and SFTP server running on Windows?  You've come to the right place.  This tutorial will guide you through the basic steps necessary to install and configure OpenSSH, with Cygwin as a compatibility layer on top of Windows.]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s the scenario: you&#8217;ve just started a meeting with your IT security chief and, as you&#8217;re describing how the big client wants you to set up an FTP server so they can upload a bunch of confidential files for your project, you notice that the chief&#8217;s face is turning an interesting shade of red. In the calm, measured voice that lets you know you&#8217;ve just stepped into a minefield, she suggests that you might want to find a file transfer mechanism that is ever-so-slightly more secure than FTP. Or else.</p>
<p>Since you are, of course, a strong advocate of open source solutions, you do some research and discover <a href="https://olex.openlogic.com/packages/openssh" target="_blank">OpenSSH</a> and the SSH File Transfer Protocol (also know as SFTP).  SFTP looks like it&#8217;s just the ticket <em>and</em> puts a smile on the security chief&#8217;s face. The only problem is that your server room runs on Windows and OpenSSH doesn&#8217;t. After a little more research, you find that OpenSSH does run on Windows — it just needs a little help from the <a href="https://olex.openlogic.com/packages/cygwin" target="_blank">Cygwin</a> project. Now if you could just find some instructions on how to get started. This is where we come in.</p>
<h2>Before You Start</h2>
<p>This is a bare bones guide to getting an OpenSSH Secure Shell (SSH) and SFTP (Secure File Transfer Protocol) server running under Windows. You will need a copy of the Cygwin installer, Internet access, and an Administrator account on your Windows server. You can download the Cygwin installer (setup.exe) from <a href="http://cygwin.com">cygwin.com</a>. At the time this tutorial was published, the Cygwin installer was at version 1.5.25-15.</p>
<p>Please note that the basic instructions covered in this tutorial should work on most versions of Windows and have been thoroughly tested on Windows XP and Vista. We have included version-specific notes where the instructions diverged.</p>
<h2>Meat &amp; Potatoes</h2>
<h3>Installation</h3>
<p>Because OpenSSH is available as an optional component of Cygwin, the easiest way to get OpenSSH running under Windows is to employ a custom Cygwin install.</p>
<ol>
<li><span>Login to Windows using an administrator account.</span></li>
<li><span>Copy the Cygwin installer somewhere convenient (like c:\, for example).</span></li>
<li><span>Run setup.exe.
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/cygwin-installation_type.png" target="_blank"><img class="size-medium wp-image-16048" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/cygwin-installation_type.png" border="0" alt="Cygwin installation type" width="385" height="300" /></a><br />
<em>Cygwin installation type</em></p>
<p></span></li>
<li><span>Choose “Install from Internet&#8221;.</span></li>
<li><span>Select a directory for the installed Cygwin files (the “Root Directory”). The default c:\cygwin will work fine. Make sure &#8220;Install For&#8221; is set to &#8220;All Users&#8221; and &#8220;Default Text File Type&#8221; is set to &#8220;Unix/binary&#8221;.
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/cygwin-location.png" target="_blank"><img class="size-medium wp-image-16049" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/cygwin-location.png" border="0" alt="Cygwin install location" width="385" height="300" /></a><br />
<em>Cygwin install location</em></p>
<p></span></li>
<li><span>Select a directory for the downloaded installation files (the “Local Package Directory”). It&#8217;s better if this is not the same as the Root Directory. Something like c:\cygwin_packages works well.
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/cygwin-package-location.png" target="_blank"><img class="size-medium wp-image-16050" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/cygwin-package-location.png" border="0" alt="Cygwin packages location" width="385" height="300" /></a><br />
<em>Cygwin packages location</em></p>
<p></span></li>
<li><span>For the Internet connection, &#8220;Direct Connection&#8221; will probably work. If not, check with your network administrator to see what’s most appropriate.
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/cygwin-connection-type.png" target="_blank"><img class="size-medium wp-image-16047" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/cygwin-connection-type.png" border="0" alt="Cygwin connection type" width="385" height="300" /></a><br />
<em>Cygwin connection type</em></p>
<p></span></li>
<li><span>The download sites are mirrors of the central Cygwin package repository and should have essentially identical content. Choosing a site in your region will likely result in speedier downloads.
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/cygwin-choose-dl-site.png" target="_blank"><img class="size-medium wp-image-16046" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/cygwin-choose-dl-site.png" border="0" alt="Cygwin download site" width="385" height="300" /></a><br />
<em>Cygwin download site</em></p>
<p></span></li>
<li><span>Once the installer has downloaded and displayed the list of packages available on the repository, click on the &#8220;View&#8221; button until the text to the right of the button says &#8220;Full&#8221;. In the list of packages, scroll down until you see a package called &#8220;openssh: The OpenSSH server and client programs&#8221; in the Package column. Under the New column, click on the word &#8220;Skip&#8221;. This should display a version number for the installable OpenSSH package. Note that this may change the status on other packages, from &#8220;Skip&#8221; to a version. Don&#8217;t change those entries! They&#8217;re packages upon which OpenSSH depends.
<p><a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/cygwin-package-selection.png" target="_blank"><img class="size-medium wp-image-16051" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/cygwin-package-selection.png" border="0" alt="Cygwin OpenSSH package selection" width="385" height="245" /></a><br />
<em>Cygwin OpenSSH package selection</em></p>
<p></span></li>
<li><span>The next screen will begin the installation process. Installation will take some time and may be a good opportunity to take a coffee break (or two).</span></li>
<li><span>Once the installation is complete, you can choose whether or not to add Cygwin shortcuts to the Start menu or Desktop.</span></li>
<li><span>Now launch the Cygwin shell (this is similar to a DOS/command window) by clicking on a shortcut (if you created one during the installation), or by running c:\cygwin\Cygwin.bat.</span></li>
<p><span><strong>Vista vs. XP Note:</strong></span><span> on Windows XP you can simply run the Cygwin.bat. On Vista, you’ll need to run Cygwin.bat as an administrator.</span></p>
<li><span><strong>On XP:</strong></span><span> At the prompt, run the following commands:</span><br />
<code>export CYGWIN='ntsec tty'<br />
chmod +rw /etc/group<br />
chmod +rw /etc/passwd<br />
chmod 0755 /var<br />
ssh-host-config -y<br />
net start sshd</code></p>
<p><span><strong>On Vista: </strong></span><span>At the prompt, run the following commands:</span><br />
<code>export CYGWIN='ntsec tty'<br />
chmod +rw /etc/group<br />
chmod +rw /etc/passwd<br />
chmod 0755 /var<br />
ssh-host-config</code><br />
<em>Answer yes to each question except &#8220;Do you want to use a different name?&#8221; and &#8220;Create new privileged user account &#8216;cyg_server&#8217;?&#8221; The answer to both of these is no.</em><br />
<code>net start sshd</code></p>
<p><span>This will configure, install and start the SSH/SFTP server as a Windows service.</span></li>
<li><span>Synchronize Cygwin user information with your Windows users by running:</span><br />
<code>mkpasswd -cl &gt; /etc/password<br />
mkgroup --local &gt; /etc/group</code></li>
<li><span>You can test the server by connecting from another system using an SFTP client such as FileZilla or an SSH client such as PuTTY.</span></li>
</ol>
<p><strong>Note</strong><span>: The default configuration we&#8217;ve gone through uses port 22 for SSH connections. You will need to open this port in your firewall in order for the SSH server to work.</span></p>
<h3>Configuring A User&#8217;s Home Directory</h3>
<p>For most Windows users and administrators, a user&#8217;s home directory is c:\Documents and Settings\[user name]. However, under Cygwin and OpenSSH, when remote users log in they may be surprised to find their (Cygwin) home is under c:\cygwin\home\[user name]. Fortunately, changing the Cygwin/OpenSSH behavior to match Windows standard behavior more closely is pretty straightforward, provided you understand the differences in the path conventions for Windows and Cygwin.</p>
<h4>Translating Paths From Cygwin to Windows and Back</h4>
<p><span>Since Cygwin is a Linux/Unix emulation that runs on top of Windows, the Cygwin shell does some things quite differently from Windows or a DOS command shell. Most notably, the paths in Cygwin follow a different, Linux-like convention.</span></p>
<p><span>Under Linux (and Cygwin), the file system has a single top level called the root and written &#8220;/&#8221;. The path delimiters are slashes, so, for example, the path to a directory called <em>user</em> inside a directory called <em>home</em> would be &#8220;/home/user&#8221;.</span></p>
<p><span>Windows, of course, supports multiple top levels on the file system: c:\, d:\, e:\ etc. The path delimiters are back-slashes and a similar path on the c drive would be &#8220;c:\home\user&#8221;.</span></p>
<p><span>In order for Cygwin to let Linux applications understand path information, Cygwin paths follow the Linux convention. However, the root directory in Cygwin points to the Windows directory in which Cygwin was installed.</span></p>
<p><span>To shoehorn the Windows path information in under the Linux convention, Cygwin puts the drive letters under a &#8220;cygdrive&#8221; directory. So, the path to the file &#8220;c:\home\user\myfile.txt&#8221; (Windows-speak) in Cygwin is &#8220;/cygdrive/c/home/user/myfile.txt&#8221;. The Cygwin path for something on, say, the g:\ drive, would be &#8220;/cygdrive/g/&#8230;&#8221;</span></p>
<p><span>Some general path examples for Windows:</span></p>
<table class="help_table" border="0">
<tbody>
<tr>
<th><span><strong>Windows Path</strong></span></th>
<th><span><strong>Cygwin Path</strong></span></th>
</tr>
<tr>
<td valign="top"><span>c:\cygwin</span></td>
<td valign="top"><span>/</span></td>
</tr>
<tr>
<td valign="top"><span>c:\</span></td>
<td valign="top"><span>/cygdrive/c</span></td>
</tr>
<tr>
<td valign="top"><span>e:\</span></td>
<td valign="top"><span>/cygdrive/e</span></td>
</tr>
<tr>
<td valign="top"><span>c:\Program Files\MyApp</span></td>
<td valign="top"><span>/cygdrive/c/Program\ Files/MyApp</span></td>
</tr>
<tr>
<td valign="top"><span>c:\cygwin\home\username</span></td>
<td valign="top"><span>/home/username</span></td>
</tr>
</tbody>
</table>
<p><span>Note the escaped space in the Cygwin path for the fourth example.</span></p>
<h4>Default Directory for Users</h4>
<p><span>Here&#8217;s why we need all this path information: when using the mkpasswd command to create Cygwin user accounts from local Windows user accounts, the user’s (Cygwin) home directory will default to “/home/[username]” (Cygwin path). </span></p>
<p><span>When that user logs in remotely through SFTP, he or she will start in that home directory; so in order to change the starting point for an SFTP session, the home directory setting for the user will need to be updated.</span></p>
<p><span>To change this, open the file /etc/passwd in a text editor that understands how to read Unix line endings. </span></p>
<p><span><strong>Warning</strong>: Notepad doesn’t read Unix files correctly. Wordpad does, but if you use Wordpad, be <em>very</em> careful to save the passwd file in a text format. Saving in any non-text format will break the file which will have unfortunate effects on Cygwin.</span></p>
<p><span>Each line in the file corresponds to the Cygwin settings for a particular user. The entries are separated by colons, “:”. There are seven entries for each user:</span></p>
<ol>
<li><em>Username.</em></li>
<li><em>Password</em>: actually a placeholder.</li>
<li><em>User ID (UID)</em>: a unique number assigned to each users.</li>
<li><em>Group ID (GID)</em>: the unique number assigned to the user’s primary group.</li>
<li><em>User ID Information</em>: A comment field, normally used for human readable information about a user.</li>
<li><em>Home Directory</em>: the path of the user’s home directory.</li>
<li><em>User’s Default Shell</em>: the path to the shell executable. In Cygwin, this is almost always /bin/bash.</li>
</ol>
<p><span>Change the 6th field to the path you’d like as the SFTP entry point for each user. Note that this must be a Cygwin-style path, for example: /cygdrive/c/Documents\ and\ Settings/[user name].</span></p>
<p><span>Once the service has been restarted, the new home directories will take effect.</span></p>
<h2>Finishing Up</h2>
<p>Now that the server is set for secure transfers, the users have the right home directories, and all is right with the world, it might be a good time to mention that your big client is going to need some way of connecting with the new SFTP server. Since FTP and SFTP are entirely different under the hood, the client will need a new client. Fortunately, the open source community can help once again. <a href="https://olex.openlogic.com/packages/winscp" target="_blank">WinSCP</a> is an excellent, streamlined Windows SFTP client which also supports FTP and SCP file transfers. If you need a cross-platform client, you might also consider <a href="https://olex.openlogic.com/packages/filezilla" target="_blank">FileZilla</a>, an SFTP, FTP, and FTPS client that runs on Windows, Linux, Mac OS X, the BSDs, and other platforms.</p>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2009/installing-an-ssh-sftp-server-on-windows/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating a Secure Repository with Subversion</title>
		<link>http://olex.openlogic.com/wazi/2009/creating-a-secure-repository-with-subversion/</link>
		<comments>http://olex.openlogic.com/wazi/2009/creating-a-secure-repository-with-subversion/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 22:12:45 +0000</pubDate>
		<dc:creator>Dru Lavigne</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[RapidSVN]]></category>
		<category><![CDATA[Subversion]]></category>
		<category><![CDATA[TortoiseSVN]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=2654</guid>
		<description><![CDATA[Whether you're a software developer, graphic artist, or office manager, odds are you've got important files that are routinely shared and updated. This tutorial will show you how to streamline collaboration by creating a secure Subversion repository for archiving those files and tracking revisions.]]></description>
			<content:encoded><![CDATA[<p><a href="https://olex.openlogic.com/packages/subversion" target="_blank">Subversion</a> is an open source revision control system. It&#8217;s well <a href="http://www.open.collab.net/community/subversion/svnbook/" target="_blank">documented</a>, and commercial support, training, and consulting are available through Collabnet and OpenLogic. The <a href="http://www.open.collab.net/products/cee/" target="_blank">Collabnet Enterprise Edition</a> also provides an integrated suite of software development, lifecycle management and collaboration tools in an extensible web-based platform.</p>
<p>Not only is a revision control system considered an essential tool in software development, it can also be a valuable addition to any department that uses files. A revision control system allows you to archive your electronic files so that you have a copy of every saved version of a file as well as that file&#8217;s history and comments about its changes, which are recorded and can be viewed later. The ability to rollback means that any past version can become the current version. Rollback can come in mighty handy: imagine a system administrator who discovers a configuration error and needs to quickly return to a previously working configuration file, or an employee who discovers a spreadsheet error that was introduced several versions ago. How about a manager who prefers an earlier graphic in a promotional brochure? A revision control system also provides file locks, authentication mechanisms and permissions—all of which make it an ideal environment to manage multiple user edits.</p>
<h2>Before You Start</h2>
<p>There are two methods for providing secure (that is, encrypted) access to a Subversion repository. The first method is quite portable and easy to use, but the set-up process is fairly complex. In contrast, set-up&#8217;s a snap with our second method, but you&#8217;ll find that advantage offset by a steeper learning curve for users—as well as additional time spent installing client software. We suggest that you base your decision about which method best suits your environment on three main criteria: your operating system, the experience level of the administrator available for initial setup, and the experience level of the users who will be accessing the repository.</p>
<h3>Method 1: Through Apache</h3>
<p>This method is the easiest to use as well as the most portable (the <a href="https://olex.openlogic.com/packages/apache" target="_blank">Apache web server</a> can be installed on most operating systems), but it&#8217;s also the most complex to setup. We recommend that you consider using this method if you already have an Apache web server and a system administrator experienced in WebDAV since users will not require any additional utilities or training to use the Subversion repository. They&#8217;ll be able to browse the repository using their web browser, and can use a WebDAV client to commit (upload) files to the repository. A <a href="http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.webdav.clients" target="_blank">list of WebDAV utilities</a> includes Microsoft Office, Adobe Dreamweaver and Photoshop, Mac OSX (which has built-in support), Novell NetDrive, KDE <a href="http://www.konqueror.org/" target="_blank">Konqueror</a>, and Gnome <a href="http://live.gnome.org/Nautilus" target="_blank">Nautilus</a>.</p>
<p>Using this method also scores you some benefits provided by Apache to your Subversion repository.  You&#8217;ll take advantage of all of Apache&#8217;s authentication mechanisms as well as its logging, and you won&#8217;t need to reconfigure any firewall rules since it will use HTTPS and can take advantage of any existing caching, load balancing, or proxying servers. However, you&#8217;ll find that this method is slower than Method 2 because of the nature of the HTTP protocol.</p>
<h3>Method 2: Through SSH</h3>
<p>Compared to Method 1, set-up through SSH is trivial. You&#8217;ll save time, which is great—but that time will in turn be devoted to installing client software, educating your users on how to use a utility to interact with the Subversion repository, and teaching them to authenticate when they access the repository. Method 2  is better suited to BSD and Linux servers, which typically ship with an SSH server installed. Windows systems do not ship with an SSH server, which means that additional configuration will be required. Windows SSH servers are available from <a href="http://sshwindows.sourceforge.net/" target="_blank">SSHWindows</a> and <a href="http://www.freesshd.com/" target="_blank">freeSSHd</a>.</p>
<p>Subversion provides a command line client that needs to be installed on each client. It might not be suitable for users familiar with a graphical environment. Fortunately, there are over a dozen <a href="http://subversion.tigris.org/links.html#clients" target="_blank">free and commercial graphical clients</a> available for Windows, Mac OS X, and Linux/BSD systems.</p>
<h3>A Note on Certificates and Keys</h3>
<p>If you&#8217;re using Method 1 and don&#8217;t have a certificate for Apache, instructions for generating the SSL certificate and configuring Apache for SSL can be found in the <a href="http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html" target="_blank">SSL FAQ</a>. Modern browsers require user interaction to access a web server whose certificate authority is not recognized. You&#8217;ll lessen the confusion of your users by having the certificate signed by an authority from the browser&#8217;s certificate authorities list. Different browsers support different authorities, so be sure to choose a certificate authority supported by all the browsers that are in use.</p>
<p>If you&#8217;re using Method 2, the key pair used by the SSH server should have been generated during installation of the server. If you wish to use certificates for client authentication, you&#8217;ll find instructions for generating and distributing client keys <a href="http://sial.org/howto/openssh/publickey-auth/" target="_blank">here</a>. This reference also describes agent forwarding, which will reduce the number of times the user has to enter their pass phrase when interacting with the Subversion repository.</p>
<h2>Meat &amp; Potatoes</h2>
<h3>Method 1: Configuring Subversion through Apache and WebDAV</h3>
<p>We mentioned before that while this method is the most user-friendly, it is very complex to setup. Before beginning, it&#8217;s important that the administrator read, with attention,  the <a href="http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.serverconfig.httpd" target="_blank">Apache configuration</a> and <a href="http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.webdav" target="_blank">WebDAV</a> sections of the online Subversion book. The administrator will also need to be familiar with configuring Apache modules and <a href="http://httpd.apache.org/docs/2.0/mod/directives.html" target="_blank">directives</a>.</p>
<p>Since the necessary steps, considerations, and gotchas are well covered in the online Subversion book, we will instead provide a checklist of the steps needed:</p>
<ol>
<li>Make sure the system has Apache 2.x and Subversion installed. If installing Subversion <a href="http://svn.collab.net/repos/svn/trunk/INSTALL" target="_blank">from source</a>, make sure Apache is already installed and include &#8211;enable-dav in the configure command.</li>
<li>Configure Apache for SSL.</li>
<li>Create the Subversion repository using svnadmin and svn import.</li>
<li>Modify httpd.conf to load the mod_dav_svn module.</li>
<li>Add a Location section to httpd.conf that points to the Subversion repository.</li>
<li>Configure the desired method of authentication.</li>
<li>Configure the desired access control.</li>
<li>Make sure Apache and Subversion permissions match up.</li>
<li>Configure MIME types for the types of files that will be saved in the repository.</li>
<li>Add a CustomLog directive.</li>
</ol>
<p>Once Apache is configured, the administrator will want to spend time testing to ensure that authentication and access control work as expected. Testing should be performed from each operating system used by clients, as well as from each WebDAV application to be employed by end-users.</p>
<p>The Subversion book also explains how to configure <a href="http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.serverconfig.httpd.extra.writethruproxy" target="_blank">write-through proxying</a>, which allows one repository to be hosted on multiple Apache servers in a master/slave replication scenario. This allows several offices or geographically separated departments to use the same Subversion repository.</p>
<h3>Method 2: Configuring Subversion through SSH</h3>
<p>For this method, it&#8217;s best that the administrator be familiar with Unix permissions and the creation of users/groups, as well as the basic SSH concepts involved in configuring a Subversion repository to use SSH. When using Subversion through an SSH connection, access control is limited to Unix-style permissions and the umask, which sets the default permissions for new files.</p>
<p>You&#8217;ll need to create a user account and group for the Subversion server to employ as well as decide on a umask that is appropriate for the repository, as the default umask for a user account does not typically allow group write access. The default umask can be changed in the Subversion user&#8217;s shell file, as described in this <a href="http://www.onlamp.com/pub/a/bsd/2005/05/12/FreeBSD_Basics.html" target="_blank">how-to</a> (which also explains how to create a wrapper script if you&#8217;re unsure of the umask compiled into your Subversion binary). Finally, every user requiring access to the repository will need a user account on the server so they can login over SSH. Make sure each user is added to the Subversion group so they have write access to the repository.</p>
<p>Once the repository and user accounts have been created, providing access to the repository through SSH is a simple matter of starting svnserve (the Subversion server) in tunnel mode, as seen in this <a href="http://www.onlamp.com/pub/a/bsd/2005/08/11/FreeBSD_Basics.html" target="_blank">how-to</a>. When clients wish to connect, either through the command line or a GUI client, they preface the server address and repository path with &#8220;svn+ssh&#8221; just like in this example:</p>
<pre>svn+ssh://192.168.1.100/home/svn/repository/sharedfiles</pre>
<p>The administrator should test that users can connect and that permissions work as expected.  Users who are comfortable with command line connections can be provided with a cheat sheet of commonly used svn commands. An example cheat sheet includes:</p>
<pre>svn checkout     #use this the first time you connect to download a working copy of
                 #the repository
svn update       #use this command EVERY time you access the repository and before
                 #making changes to ensure you have the latest copies of files and
                 #to avoid conflicts
svn add          #use this after you create a new file to add to the repository
svn commit       #use this whenever you make changes to a file
svn delete       #use this command to delete a file NEVER use rm
svn log          #use this to see the latest changes</pre>
<p>A complete listing of all svn commands and their use is available in the <a href="http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.ref" target="_blank">Subversion Complete Reference</a>.</p>
<p>In environments where users prefer a graphical utility, the administrator should spend some time trying out the various graphical clients in order to become familiar with their features. No graphical client provides access to every svn command, but any client should provide access to the most commonly used commands listed above. Being aware of the available features ahead of time will make educating users much easier and encourage them to actually use the repository.</p>
<p>Two examples of popular graphic clients are seen below:</p>
<p><strong>TortoiseSVN Adds Menu Items to Windows Explorer</strong><br />
<a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/create_repo_tortoisesvn.png" target="_blank"><img class="alignnone size-full wp-image-2692" title="create_repo_tortoisesvn" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/create_repo_tortoisesvn.png" alt="create_repo_tortoisesvn" width="500" height="375" /></a></p>
<p><strong>RapidSVN on Windows</strong><br />
<a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/create_repo_rapidsv.png" target="_blank"><img class="alignnone size-full wp-image-2693" title="create_repo_rapidsv" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/create_repo_rapidsv.png" alt="create_repo_rapidsv" width="500" height="375" /></a></p>
<h2>Finishing Up</h2>
<p>Regardless of the method implemented, education is key. Users will need to invest some time becoming familiar with the <a href="http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.tour.cycle" target="_blank">basic work cycle</a> and selecting a client with which they&#8217;re comfortable accessing the repository and making changes. But soon enough your investment in user education will pay off in increased productivity and ease of collaboration, and users will wonder how they ever lived without a secure repository!</p>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2009/creating-a-secure-repository-with-subversion/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to Fix Memory Leaks in Java</title>
		<link>http://olex.openlogic.com/wazi/2009/how-to-fix-memory-leaks-in-java/</link>
		<comments>http://olex.openlogic.com/wazi/2009/how-to-fix-memory-leaks-in-java/#comments</comments>
		<pubDate>Tue, 10 Mar 2009 21:13:14 +0000</pubDate>
		<dc:creator>Veljko Krunic</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[jmap]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[tomcat]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=2506</guid>
		<description><![CDATA[Got a case of memory leak induced insomnia? Well, we've got a cure for what ails you. This tutorial will teach you everything you need to know to ease your suffering, including what memory leaks are, why they happen, and how to diagnose and fix 'em.]]></description>
			<content:encoded><![CDATA[<p>Your pager hasn&#8217;t been sleeping well. It periodically wakes you up in the middle of the night to tell you that your server is firing off &#8220;OutOfMemoryError&#8221; messages. Worse still, your significant other forcibly relocated you to the couch and told you not to return until your pager stops buzzing.</p>
<p>Sound familiar?  If so, you may have a case of memory leak induced insomnia, but fortunately we&#8217;ve got a cure for what ails you. This tutorial will teach you everything you need to know to ease your suffering, including what memory leaks are, why they happen, and how to diagnose and fix &#8216;em.</p>
<p>In this article we&#8217;ll focus on techniques that will enable you to address memory leaks with any commercial or free/open source memory profiler; we&#8217;re not here to recommend one tool over another.  After all, the most important thing is that you fix the problem and get some rest, not the tool you use to get it done.</p>
<h2>Before You Start</h2>
<p>Ever heard the story about how Java has &#8220;automatic memory management&#8221;—you know, the one that someone in marketing upgraded to an epic tale about how you&#8217;ll never have to worry about memory leaks ever again? As is often the case, the truth is more complex than the marketing department made it out to be. While it&#8217;s true that Java’s garbage collector (GC) helps to eliminate the most common memory leak issues from applications, it is unfortunately still possible to experience memory leaks in Java.  However, they happen a lot less often than they used to in the C or C++ days.</p>
<p>Many people believe that black magic and complex tools are required to fix memory leaks. This undeserved reputation is caused by the lack of good explanations of what they are and what to do when you encounter them. But with the proper tools and knowledge to fix memory leaks, they aren&#8217;t nearly as intimidating.</p>
<h3>Methodology</h3>
<p>In this article we&#8217;ll cover everything from memory leak basics to analyzing heap dumps, so—whether you&#8217;re an experienced Java developer or encountering Java memory leaks for the first time—you&#8217;ll be better prepared to deal with memory leaks by the time you reach the conclusion.  We won&#8217;t outline a series of steps, like &#8220;do ABC with commercial tool XYZ and don&#8217;t ask why,&#8221; as that approach doesn’t work and implies that remedies are more complex then they really are. Instead, we&#8217;ll give you the background information necessary to address memory leaks, with emphasis placed on particular steps you&#8217;ll need to execute. Similarly, we&#8217;ll assume that you can learn on your own how to use the memory profiler of your choice; what&#8217;s missing is an understanding of what the tool is trying to do and why, so that will be the focus of this article.</p>
<p>Java will be used for all examples, so all information in this article directly applies to Java applications running standalone or as a part of J2EE/JEE/<a href="https://olex.openlogic.com/packages/tomcat" target="_blank">Tomcat</a>-based application server. But remember, although our primary focus is on Java, most of the process of diagnosing and fixing memory leaks described herein applies to other languages with garbage collectors. So even if you&#8217;re using <a href="https://olex.openlogic.com/packages/ruby" target="_blank">Ruby</a>, C#, or <a href="https://olex.openlogic.com/packages/python" target="_blank">Python</a>, there should be something for you in this article.</p>
<h3>What Are Memory Leaks?</h3>
<p>Let&#8217;s start by describing how memory leaks happen in Java. Java implements automatic garbage collection (GC), and once you stop using an object you can depend on the garbage collector to collect it. While additional details of the collection process are important when tuning GC performance, for the sole purpose of fixing a memory leak we can safely ignore them.</p>
<p>When is memory eligible for GC? Let&#8217;s take a look at an example:</p>
<p><img class="alignnone size-medium wp-image-2577" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/gc-eligable.jpg" alt="gc-eligable" width="600" height="196" /></p>
<p>We don&#8217;t have to do anything special to make an object eligible for GC—we just eliminate any references to it, and it &#8220;magically&#8221; disappears and stops using memory. That&#8217;s why we say that Java performs &#8220;automatic&#8221; GC.</p>
<p>Why &#8220;eligible&#8221; for GC? Because objects are not collected immediately. GC is not instantaneous and comes with some performance impacts. Consequently, Java doesn&#8217;t immediately collect every object that is eligible for collection; it typically postpones collection until a more convenient time later on. The way to think about GC in Java is that it&#8217;s a &#8220;lazy bachelor&#8221; that hates taking out the trash and typically postpones the process for some period of time. However, if the trash can begins to overflow, Java immediately takes it out. In other words, if memory becomes scarce, Java immediately runs GC to free memory.</p>
<p>Since we don&#8217;t need to do anything special in order to dispose of objects in Java, how do memory leaks happen in Java? Memory leaks occur when a program never stops using an object, thus keeping a permanent reference to it.</p>
<p>Let&#8217;s take a look at an example that helps illustrate this point.  The following code will cause all available memory in the JVM to be exhausted:</p>
<p><img class="alignnone size-full wp-image-2560" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/memory_leaks_figure6.png" alt="memory_leaks_figure6" width="605" height="314" /></p>
<p>When no more memory is remaining, an OutOfMemoryError alert will be thrown and generate an exception like this:</p>
<p><span style="color: #ff0000;">Exception in thread &#8220;main&#8221; java.lang.OutOfMemoryError: Java heap space at<br />
MemoryLeakDemo.main(MemoryLeakDemo.java:14)</span></p>
<p>In the example above, we continue adding new elements to the list <em>memoryLeakArea</em> without ever removing them. In addition, we keep references to the <em>memoryLeakArea</em>, thereby preventing GC from collecting the list itself. So although there is GC available, it cannot help because we are still using memory. The more time passes the more memory we use, which in effect requires an infinite amount memory for this program to continue running.</p>
<p>This is an example of unbounded memory leak—the longer the program runs, the more memory it takes. So even if the memory size is increased, the application will still run out of memory at a later date.</p>
<h2>Meat &amp; Potatoes</h2>
<h3>Fixing Memory Leaks</h3>
<p>As illustrated by the flowchart below, the process of fixing memory leaks is fairly simple:</p>
<p><img class="alignnone size-full wp-image-2554" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/memory_leaks_figure1.png" alt="memory_leaks_figure1" width="430" height="640" /></p>
<p>Memory leaks are misunderstood creatures. Just getting an OutOfMemoryError alert doesn’t necessary mean that you&#8217;re suffering from a memory leak. So, before you dive into &#8220;fixing&#8221; the problem, you must first find out whether or not a memory leak actually exists. If a memory leak does in fact exist, the next step is to determine which objects are leaking and uncover the source of the memory leak. Then, you fix it.</p>
<p>We&#8217;ll skip past the initial steps and dive right into diagnosing whether or not the problem is a memory leak.</p>
<h3>Is My Program Leaking Memory?</h3>
<p>Not every OutOfMemoryError alert indicates that a program is suffering from a memory leak. Some programs simply need more memory to run.  In other words, some OutOfMemoryError alerts are caused by the load, not by the passage of time, and as a result they indicate the need for more memory in a program rather than a memory leak.</p>
<p>To distinguish between a memory leak and an application that simply needs more memory, we need to look at the &#8220;peak load&#8221; concept. When program has just started no users have yet used it, and as a result it typically needs much less memory then when thousands of users are interacting with it. Thus, measuring memory usage immediately after a program starts is not the best way to gauge how much memory it needs! To measure how much memory an application needs, memory size measurements should be taken at the time of peak load—when it is most heavily used.</p>
<p>The graph below shows the memory usage in a healthy Java application that does not suffer from memory leaks, with the peak load occurring around 10 AM and application usage drastically decreasing at 5 PM. Naturally, the peak load on business applications often correlates with normal business hours.</p>
<p><img class="alignnone size-full wp-image-2561" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/memory_leaks_figure7.png" alt="memory_leaks_figure7" width="605" height="396" /></p>
<p>The application illustrated by the chart above reaches its peak load around 10 AM and needs around 900MB of memory to run. This is normal behavior for an application suffering from no memory leaks; the difference in memory requirements throughout the day is caused solely by the user load.</p>
<p>Now, let&#8217;s suppose that we have a memory leak in the application. The primary characteristic of memory leaks is that memory requirements increase <em>as a function of time</em>, not <em>as a function of the load</em>. Let&#8217;s see how the application would look after running for a few days with a memory leak and the same peak user loads reached around 10 AM every day:</p>
<p><img class="alignnone size-full wp-image-2562" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/memory_leaks_figure8.png" alt="memory_leaks_figure8" width="605" height="396" /></p>
<p>Because peak loads on the system are similar every morning but memory usage is growing over a period of a few days, this picture indicates a strong possibility of memory leaks. If the program eventually started suffering from OutOfMemory exceptions, it would be a very strong indication that there&#8217;s a problem with memory leaks. The picture above shows a memory leak of about 100MB per day.</p>
<p>Note that the key to this example is that the only thing changing is the amount of time the system is up—the system peak load doesn&#8217;t change over time. This is not the case for all businesses. For example, the peak load for a tax preparation service is seasonal, as there are likely more users on the system in April than July.</p>
<p>There is one special case that should be noted here: a program that needs to be restarted periodically in order to prevent it from crashing with an OutOfMemoryError alert. Imagine that on the previous graph the max memory size was 1100MB. If the program started with about 900MB of memory used, it would take about 48 hours to crash because it leaks about 100MB of memory per day. Similarly, if the max memory size was set to 1000MB, the program would crash every 24 hours. However, if the program was regularly restarted more often than this interval, it would appear that all is fine.</p>
<p>Regularly scheduled restarts may appear to help, but also might make &#8220;upward sloping memory use&#8221; (as shown in the previous graph) more difficult to notice because the graph is cut short before the pattern emerges. In a case like this, you&#8217;ll need to look more carefully at the memory usage, or try to increase the available memory so that it&#8217;s easier to see the pattern.</p>
<h3>Monitoring Memory in Java</h3>
<p>As you are already aware, you need to measure memory that is free and used inside of the JVM, not memory that the JVM process is using. In other words, the top/Task Manager/Activity Monitor will measure how much memory your Java process is using, but that&#8217;s not what you need.  You need a tool that can look inside the JVM process and tell you how much memory is available for your program running inside the JVM.</p>
<p>In addition, keep in mind that Java GC is not a constant process—it runs in intervals. The memory usage that you see in the JVM is usually higher then what your program needs at the moment, as GC hasn&#8217;t yet run. Remember, lazy bachelors usually have some trash in their apartments waiting to be taken out.</p>
<p>So, what you need to investigate is not current memory usage, but rather the average usage over a long period of time.  For example, if your program is currently using 100MB of memory and five seconds later it&#8217;s using 101MB, that&#8217;s not an indication of a memory leak because GC might free up memory when it eventually runs. But if your program&#8217;s memory usage increases over a long period of time under constant usage, you might have trouble on your hands.</p>
<p>There are a couple of options for measuring the amount of memory a program uses. The simplest one, which does not require any tools and works even with production systems, is the Verbose GC log.</p>
<h4>Verbose GC Log</h4>
<p>The Verbose GC log is defined when the JVM process is started. There are a couple of switches that can be used:</p>
<ol>
<li>-verbose:gc — prints basic information about GC to the standard output</li>
<li>-XX:+PrintGCTimeStamps — prints the times that GC executes</li>
<li>-XX:+PrintGCDetails — prints statistics about different regions of memory in the JVM</li>
<li>-Xloggc:&lt;file&gt; — logs the results of GC in the given file</li>
</ol>
<p>The following is an example of the output generated for Tomcat running in the default configuration with all of the previous switches enabled:</p>
<pre>1.854: [GC 1.854: [DefNew: 570K-&gt;62K(576K), 0.0012355 secs] 2623K-&gt;2175K(3980K), 0.0012922 secs]
1.871: [GC 1.871: [DefNew: 574K-&gt;55K(576K), 0.0009810 secs] 2687K-&gt;2229K(3980K), 0.0010752 secs]
1.881: [GC 1.881: [DefNew: 567K-&gt;30K(576K), 0.0007417 secs] 2741K-&gt;2257K(3980K), 0.0007947 secs]
1.890: [GC 1.890: [DefNew: 542K-&gt;64K(576K), 0.0012155 secs] 2769K-&gt;2295K(3980K), 0.0012808 secs]</pre>
<p>The most important set of numbers is located in the second column after the second -&gt; (e.g., in the top line shown it is 2623K-&gt;2175K(3980K).  These numbers indicate that as a result of GC, we are using around 2200K of memory at the end of each GC cycle.</p>
<p>This trace is not an indication of a memory leak&mdash;it shows a short-term trend with less then a second between samples, and that&#8217;s why we must observe long-term trends. However, if the Verbose GC log showed that the program was using around 2200K of memory after running for two days, and after running for 10 days it was using 2GB of memory (even after GC had just run), we could then conclude that there&#8217;s a memory leak.</p>
<p>All the information that needs to be collected in order to determine if a memory leak exists can be found in the results of the Verbose GC logs. The other memory monitoring tools we&#8217;ll cover in this article simply provide more information in a form that&#8217;s easier to interpret.</p>
<h4>Monitoring the Java Process</h4>
<p>The following approach works for any Java process, including standalone clients as well as application servers like <a href="https://olex.openlogic.com/packages/jboss" target="_blank">JBoss</a> and servlet containers like Tomcat. It is based on starting the Java process with JMX monitoring enabled and attaching with the JMX monitoring tools. We&#8217;ll use Tomcat in the following example.</p>
<p>To start Tomcat or the Java process with JMX monitoring enabled, use the following options when starting JVM:</p>
<ul>
<li>-Dcom.sun.management.jmxremote — enables JMX monitoring</li>
<li>-Dcom.sun.management.jmxremote.port=&lt;port&gt; — controls the port for JMX monitoring</li>
</ul>
<p>Note that if you&#8217;re on a production system, you&#8217;ll most likely want to secure your JVM before running it with these parameters. For that, you can specify these additional options:</p>
<ul>
<li>com.sun.management.jmxremote.ssl</li>
<li>com.sun.management.jmxremote.authenticate</li>
</ul>
<p>Once started, you can use JConsole or <a href="https://visualvm.dev.java.net/" target="_blank">VisualVM</a> to attach to the process.  Note that later JDK 6 versions include VisualVM.</p>
<p>This is an example of the JConsole monitoring Tomcat. As shown in the example below, click on the Memory tab to get memory information:</p>
<p><img class="alignnone size-full wp-image-2563" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/memory_leaks_figure9.png" alt="memory_leaks_figure9" width="605" height="455" /></p>
<p>Again, we&#8217;re interested in the long-term trends of heap memory usage, not trends from just a few minutes of running.</p>
<p>Finally, note that monitoring tools like Hyperic can typically show historical trends over longer periods of time than VisualVM or JConsole. In addition, tools like Hyperic allow for more fine-grained control over operations that are permitted by users. As a result, we recommend using monitoring tools for production systems use, while all the other tools discussed in this section are more appropriate for developers or &#8220;first aid&#8221; in the absence of the real monitoring tools.</p>
<h3>Speed Kills</h3>
<p>We now know how to find out whether or not a memory leak exists, and we can even determine the speed at which we&#8217;re leaking memory (e.g., 100MB per day). But are we better off with a &#8220;slow&#8221; leak (e.g., 1MB per day) or a &#8220;fast&#8221; leak (e.g., 500MB/hour)?</p>
<p>It depends. With a &#8220;slow&#8221; leak, it takes longer for the system to run out of memory. For example, if we have 256MB of free memory remaining at the peak load time, it can take quite a long time to run out of memory with a 1MB/day memory leak. On the other hand, a faster memory leak makes it easier to reproduce and fix the problem.</p>
<p>One of the best ways to quickly determine whether there&#8217;s a fast memory leak or you simply need more memory to run at the peak time is to allot more memory to the program and see what happens. If you increase the available heap in a Java program and the time between crashes increases, you are likely suffering from memory leak.</p>
<p>Let&#8217;s assume that we&#8217;re lucky enough to have a fast memory leak—on the order of 100MB per hour—on our hands, and that the initial memory picture looks like this:</p>
<p><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/memory_leaks_figure10.png" title="memory_leaks_figure10" width="250" height="130" class="alignnone size-full wp-image-2609" /></p>
<p>In this example, we can expect to run out of memory after about five hours of running time.</p>
<h3>How To Find Leaked Objects in a Fast Memory Leak</h3>
<p>Somewhat surprisingly, it is much easier to debug large memory leaks than small memory leaks. The reason is that memory leaks present a sort of &#8220;needle in the haystack&#8221; type problem—you need to find the leaked objects amongst all the other objects in the program.</p>
<p>Suppose that the program we&#8217;re debugging just ran out of memory. If the program initially had 512MB of free memory and now has none, it is obvious that the leaked objects used about 512MB of memory.  The figure below illustrates this example:</p>
<p><img src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/memory_leaks_figure11.png" title="memory_leaks_figure11" width="250" height="130" class="alignnone size-full wp-image-2608" /></p>
<p>In this situation, half of the objects in memory have been leaked! If we randomly select an object, there&#8217;s a 50% chance that it has leaked. And as memory leaks usually consist of objects of a few classes, you can get a really good start on determining which objects are leaking memory by sorting memory usage based on aggregate memory use of all objects of the same class.</p>
<p>What if the ratio is less favorable (e.g., 512MB heap size, initially used memory 480MB, and 32MB of leaked objects at the end)? If you have an easy to reproduce memory leak, you can <em>increase</em> the heap size because an unbounded memory leak will eventually fill any amount of memory allotted to the program. So, you can increase the heap to 1GB, reproduce the memory leak, and get 544MB of leaked objects in a 1GB of heap.</p>
<p>If we had a way to look at the &#8220;complete picture&#8221; of memory, it would be fairly easy to pinpoint leaked objects. Fortunately, there&#8217;s a way to do exactly this: heap dump the process.</p>
<h3>Dump me Gently</h3>
<p>A heap dump is a list of objects in the memory of JVM as well as the content of the memory occupied by those objects. It preserves the value of any attributes of the objects, including references to other objects. In other words, a heap dump gives you a complete picture of the memory.</p>
<p>There are multiple tools that allow you to dump heap in a Java process:</p>
<ul>
<li>If you&#8217;re using JDK 6, you can use tool called <a href="https://olex.openlogic.com/packages/jmap" target="_blank">jmap</a> on any platform.</li>
<li>If you&#8217;re using JDK 5, the situation is slightly more complex:
<ul>
<li>If you&#8217;re running UNIX (Linux, Solaris, OS X) with JDK 5 you can use jmap.</li>
<li>If you&#8217;re using JDK 5 update 14 or later, you can use the -XX:+HeapDumpOnCtrlBreak option when starting JVM, then use the CTRL+BREAK key combination on Windows (or CTRL + \ on UNIX) to dump the heap.</li>
<li>If you&#8217;re running Windows and using JDK 5 pre-update 14, you&#8217;ll soon wish you weren&#8217;t. Trying to reproduce the problem with a more recent JDK is probably the best bet here.</li>
</ul>
</li>
</ul>
<p>Some tools like VisualVM and memory profilers allow you to initiate a heap dump from the GUI, but you don’t need any fancy tools here—jmap will do just fine. As it provides the most general case, we&#8217;ll use jmap in the next example.</p>
<p>Before you dump heap, be sure to keep the following issues in mind:</p>
<ul>
<li>Programs in the JVM should be paused for the duration of the heap dump, which might take anywhere from ten seconds to several minutes. Many enterprise applications—and users of those applications—don’t take kindly to pauses that long, which may cause various timeouts to expire. So don’t try this at home or in production (unless the application is already a goner)!</li>
<li>Heap dumps are saved on disk, and the files might be fairly large. A good rule is to make sure that you have at least twice the size of the physical memory free on the disk before you initiate a memory dump.</li>
</ul>
<p>With those final words of caution out of the way, you should now be ready to run the following command:</p>
<pre>jmap -heap:live,format=b,file=FILENAME PID</pre>
<p>Note that the -F option, which will dump non-responsive programs, might be useful on UNIX systems, but is not available on Windows. Note also that JDK 6 includes the option +XX:+HeapDumpOnOutOfMemoryError that will dump heap whenever the OutOfMemoryError alert is encountered. This can be a useful option, but keep in mind that it has the potential to consume significant amounts of disk space.</p>
<p>You now have a heap dump in the file FILENAME and are ready to analyze it.</p>
<h3>What&#8217;s In &#8220;Leaked&#8221; Memory?</h3>
<p>With the heap dump complete, we can now take a look at the memory and find out what&#8217;s really causing the memory leak.</p>
<p>Suppose that objects are holding references to each other as illustrated by the picture below. For the sake of easy calculation, let&#8217;s assume that each object is 100 bytes, so that all of them together occupy 600 bytes of memory.</p>
<p><img class="alignnone size-full wp-image-2555" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/memory_leaks_figure2.png" alt="memory_leaks_figure2" width="500" height="224" /></p>
<p>Now, suppose that the program holds reference to object A for a prolonged period of time. As a result, objects B, C, D, E, and F are all ineligible for garbage collection, and we have the following amount of memory leaking:</p>
<ul>
<li>100 bytes for object A</li>
<li>500 bytes for objects B, C, D, E and F that are retained due to the retention of object A</li>
</ul>
<p>So, holding reference to object A causes a memory leak of 600 bytes. The <em>shallow heap</em> of object A is 100 bytes (object A itself), and the <em>retained heap</em> of object A is 600 bytes.</p>
<p>Although objects A through F are all leaked, the real cause of the memory leak is the program holding reference to object A. So how can we fix the root cause of this leak? If we first identify that object F is leaked, we can follow the reference chain back through objects D, C and A to find the cause of the memory leak.  However, there are some complications to this &#8220;follow the reference chain&#8221; process:</p>
<ul>
<li>Reference chains can be really long, so manually following them can be time consuming</li>
<li>An object is sometimes retained by more then one object, and there can even be circles involved as shown in the picture below:</li>
</ul>
<p><img class="alignnone size-full wp-image-2556" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/memory_leaks_figure3.png" alt="memory_leaks_figure3" width="500" height="212" /></p>
<p>If we start following inbound references from object F in this example, we have to choose between following object C or object D.  In addition, there&#8217;s the possibility of getting caught in a circle by repeatedly following the path between objects D, E and B.  On this small diagram it&#8217;s easy to see that the root cause is holding object A, but when you&#8217;re dealing with a situation that involves hundreds of thousands of objects (as any self-respecting memory leak does) you quickly realize that manually following the reference chain be very complex and time consuming.</p>
<p>This is where some shortcuts can come in handy:</p>
<ul>
<li>If we had a tool that allowed us to play a &#8220;what would happen if I remove this reference&#8221; type of guessing game, we could run experiments that help locate the cause.  For example, we could see that if we removed reference from &#8220;Cause of Leak&#8221; to A in the diagram above, objects A through F would all be freed. Some tools (like Quest&#8217;s <a href="https://olex.openlogic.com/packages/jprobe" target="_&quot;blank&quot;">JProbe</a>) have this capability.</li>
<li>If the memory leak is large and we have a tool that allows us to sort objects by retained heap, we&#8217;ll get an even greater head start because the objects with the largest retained heap are usually the cause of large memory leaks.</li>
</ul>
<p>Now that we understand what memory leaks are and how they can be corrected, let&#8217;s find out how to fix them by analyzing heap dumps.</p>
<h3>Tools for Dealing with Heap Dumps</h3>
<p>Strictly speaking, you don’t need any tools that are not already part of the JDK. JDK ships with a tool called jhat, which you can use to inspect the heap dump. The process of fixing memory leaks is the same with all tools, and it&#8217;s our opinion that no single tool is &#8220;light years&#8221; ahead of the others when it comes to fixing memory leaks.</p>
<p>Although jhat will get the job done, better tools often provide a few extra helpful features:</p>
<ul>
<li>Present a better summary of heap statistics.</li>
<li>Sort objects by retained heap.  In other words, some tools can tell you the memory usage of an object and all other objects that are referenced by it, as well as list the objects referenced by other objects. This makes it much faster to diagnose the cause of a memory leak.</li>
<li>Function on machines that have less memory then the size of the heap dump.  For example, they&#8217;ll allow you to analyze a 16GB heap dump from your server on a machine with only 1GB of physical memory.</li>
</ul>
<p>There are several free tools that are useful for analyzing heap dumps in Java. One that&#8217;s widely used and is even included with the later versions of the JVM 6 is <a href="https://visualvm.dev.java.net/" target="_blank">VisualVM</a>. VisualVM is nice tool that gives you just enough to resolve memory leaks, and it shows heap dumps and relations between objects in graphical form.</p>
<p>Feature-wise, one step above VisualVM is the <a href="http://www.eclipse.org/mat/" target="_blank">Eclipse Memory Analyzer Tool (MAT)</a>, a free tool that includes a lot of additional options. Although it&#8217;s still in <a href="http://wiki.eclipse.org/Development_Resources/HOWTO/Incubation_Phase" target="_blank">incubation phase</a> as of publication of this article, MAT is free and we&#8217;ve found it to be extremely useful.</p>
<p>Commercial products like JProfiler, YourKit, and JProbe are also excellent tools for debugging memory leaks. These applications include a few options that go above and beyond VisualVM and MAT, but they&#8217;re certainly not necessary to successfully debug memory leaks.  Unless you already have a license for one of these commercial tools, we recommend trying MAT first.</p>
<h4>Analyzing the Heap Dump for Fast Memory Leaks</h4>
<p>It&#8217;s usually easy to find a fast memory leak. A lot of memory is leaked, and you simply need to find the big hog that leaked all that memory.</p>
<p>Analyzing the heap dump is done in order to:</p>
<ul>
<li>Find objects that are &#8220;leaking&#8221;</li>
<li>Find the root cause of the memory leak</li>
</ul>
<p>If you have a fast memory leak and are able to reproduce it in such a way as to make the leaked objects a significant portion of the final memory picture, then determining which objects are leaked is simple because they occupy a significant portion of the memory. To determine which objects are leaked, sort the classes by total memory usage of all instances of each class. The objects near the top of the list are usually the leaked objects. Then, you can follow the reference chain to them until you find the cause of the memory leak.</p>
<p>A useful heuristic here is that if you sort <em>all the objects by retained heap</em>, you can find the objects that are likely the root cause of the memory leak. Again, an example:</p>
<p><img class="alignnone size-full wp-image-2557" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/memory_leaks_figure4.png" alt="memory_leaks_figure4" width="420" height="220" /></p>
<p>If we assume that each instance of object C is 100 bytes, then holding object A resulted in a memory leak of almost 1GB! In other words, the retained heap of object A in this example is about 1GB.  So, if we were investigating this memory leak, it would be fairly obvious that we should start there.  Remember, the Eclipse Memory Analyzer Tool (MAT) allows you to sort the heap dump by the retained heap usage of the objects, so it would have been easy to use MAT to determine the retained heap of object A.</p>
<h4>Slow and Small Memory Leaks</h4>
<p>It always helps if you can easily reproduce the problem, but what if the memory leak is really small and slow? What should you do if after a few days you can reproduce only a 10MB leak in a heap that contains 2GB of objects? In situations like this, looking for the cause of the problem can feel like finding a needle in the haystack.</p>
<p>One solution in this case is the brute force approach—simply devote enough time looking at the objects to find the problem. While that will ultimately work, there&#8217;s another way to address the problem if you have an idea of which operations are leaking memory.  If you know or suspect which operations leak memory, you can find even relatively slow memory leaks.</p>
<p>The secret here is to compare heap dumps, as this highlights objects that are present in one heap dump but not in another. For example, suppose that objects A, B, and C are present in the first heap dump, while objects A, B, C, D, and E are present in the second heap dump. In this case, objects D and E are the difference.</p>
<p>Comparing heap dumps makes it easier to find memory leaks because it effectively reduces the size of the &#8220;haystack&#8221; containing your needle. Comparing heap dumps can easily reduce the size of the objects for which you need to examine heaps from 2GBs to a few KB.</p>
<p>Many commercial profilers as well as Eclipse MAT can be used to compare heaps. Once you&#8217;ve selected a tool that can compare heaps, simply follow the process explained in the following diagram:</p>
<p><img class="alignnone size-full wp-image-2553" src="http://olex.openlogic.com/wazi/wp-content/uploads/2009/03/memory_leaks_figure5.png" alt="memory_leaks_figure5" width="395" height="560" /></p>
<p>In effect, what you&#8217;re doing is creating two snapshots, one before and one after executing the use case that you know is leaking memory. That way, you significantly reduce the number of objects that you need to investigate to find leaked objects. After you find the objects that leaked, you can find the cause of the memory leak as described in the previous section.</p>
<p>Why perform garbage collection before taking a snapshot? Because some tools won’t automatically perform GC for you, and consequently the snapshots might include objects that are no longer reachable. Many modern tools will perform GC before taking the snapshot, but if you are unsure whether or not your tool performs full GC before taking a snapshot it is recommended that you do so yourself. That way you don’t have to worry about objects that are eligible for GC but have not yet been collected.</p>
<p>Among the objects that are created during the use case, some are supposed to be there because they are the result of the use case execution (e.g., we created a new customer, and that customer object should be retained), while other objects are the memory leak. However, since the only objects present in the difference between the snapshots are the ones that were created during the use case, the size of the haystack you need to look through is significantly reduced.</p>
<h3>Practical Problems</h3>
<p>Why do memory leaks sometimes take a long time to fix if the process is this simple? In our opinion, the main reasons are:</p>
<ul>
<li>There isn&#8217;t a sufficient amount of easily available information about fixing Java memory leaks. We hope this article will help improve the situation.</li>
<li>It can be difficult to reliably reproduce an issue, and a lot of time is typically required to reproduce an issue before you can really start addressing it.</li>
<li>People lack the right tools for the job—in particular, memory profilers. With many free profilers available and reasonably low prices for commercial profilers, there&#8217;s no reason you shouldn’t have good tools in your toolbox.</li>
<li>There are a few practical issues with the use of tools and techniques that might be perceived as road blocks the first time someone tries them. We&#8217;ll address some of these issues below.</li>
</ul>
<p>Fortunately, the practical issues most commonly encountered aren&#8217;t very difficult to solve.  The most common problems are:</p>
<ul>
<li><strong>You can&#8217;t load the snapshot because you don&#8217;t have enough memory in your development box.</strong> For example, this can easily happen if you have 64-bit servers with 8GB of memory allocated to the JVM. You might not have physical memory in your development box, or you might be using the 32-bit JVM on your development box, but the tool you&#8217;re using insists on loading most of the snapshot into memory. If you like the idea of having a really powerful development box, use this situation to your advantage and ask your boss for a new machine. Alternatively, try using a tool with less of an appetite for memory, like Eclipse MAT.</li>
<li><strong>You can’t increase your memory on the server to get a bigger set of leaked objects, yet you need a bigger set of leaked objects to speed up the process of finding the memory leak.</strong> This often happens with 32-bit JVMs. One option in this situation is to apply the techniques described above for finding slow memory leaks, although this approach requires a significant amount of time. Alternatively, you can try to reproduce problem on a 64-bit JVM, which will allow you to increase the memory. If the problem causing the memory leak is in your application, changing the JVM is extremely unlikely to &#8220;hide&#8221; the leak.</li>
<li><strong>The memory leak is not in objects of just one class—you&#8217;re leaking objects from thousands of classes, so it&#8217;s difficult to find leaked objects.</strong> Or, your graph of object relations is so complex that you can find the initially-leaked objects but can&#8217;t locate the cause.  In either case, you&#8217;ve got quite a pickle on your hands. The only words of encouragement we can offer are that the situation will eventually improve, as the longer you track object references the better you&#8217;ll get at it. One other piece of advice: you should probably call your significant other and let him or her know that you won&#8217;t be home for dinner.</li>
<li><strong>You&#8217;re getting an OutOfMemoryError alert with a new, different format.</strong> For example, you might be looking at something like this:<br />
<span style="color: #ff0000;">Exception in thread &#8220;pool-2-thread-1&#8243; java.lang.OutOfMemoryError: GC overhead limit exceeded.</span><br />
This message can happen with some GC settings that limit the overhead of the GC. It often indicates a memory leak, although there are some corner cases in which problems with GC performance can cause it. The best way to distinguish the cause of this message (is it a GC misconfiguration or a memory leak?) is to examine the pattern of errors.  If they happen with regularity (in other words, they&#8217;re a function of time the program is running), then it&#8217;s a memory leak. If they happen only occasionally under heavy loads and clear later (in other words, they&#8217;re not a function of running time), they might indicate a need to tweak the GC or increase available memory.</li>
<li><strong>3rd party caching systems</strong> can be setup so that caches are allowed to expand and fill up the available memory the program doesn&#8217;t need. However, if the program no longer needs more memory, the cache automatically releases it. The point here is that in the absence of any OutOfMemoryError alerts, continually increasing memory usage does not necessary indicate a memory leak.  Both &#8220;used memory grows as function of time&#8221; and &#8220;free memory eventually runs out&#8221; conditions are necessary in order to determine the presence of a memory leak.</li>
</ul>
<h2>Finishing Up</h2>
<p>This article described the methodology and techniques necessary to fix memory leaks. These techniques are universal—they apply to any profiler, and some of them even apply to languages other than Java that use garbage collection. The information presented above should give you everything you need in order to use the tools of your choice to investigate and fix memory leaks.</p>
<p>The proper usage of specific tools will be discussed in future articles, which will focus primarily on free tools and problems in Java.  However, if there&#8217;s enough interest we might tackle other languages as well. If you&#8217;re interested in follow-up articles related to memory leak resolution in a different environment or language, please leave a comment or contact us at docs-at-openlogic.com.</p>
<h3>Additional Resources</h3>
<p>The following links provide additional information on the behavior of GC in Java as well as different tools that you may find useful.</p>
<ul>
<li><a href="http://java.sun.com/j2se/1.5.0/docs/guide/management/agent.html" target="_blank">http://java.sun.com/j2se/1.5.0/docs/guide/management/agent.html</a></li>
<li><a href="http://java.sun.com/j2se/1.5.0/docs/guide/management/jconsole.html" target="_blank">http://java.sun.com/j2se/1.5.0/docs/guide/management/jconsole.html</a></li>
<li><a href="http://java.sun.com/j2se/reference/whitepapers/memorymanagement_whitepaper.pdf" target="_blank">http://java.sun.com/j2se/reference/whitepapers/memorymanagement_whitepaper.pdf</a></li>
<li><a href="http://java.sun.com/developer/technicalArticles/Programming/GCPortal/" target="_blank">http://java.sun.com/developer/technicalArticles/Programming/GCPortal/</a></li>
<li><a href="http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html" target="_blank">http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html</a></li>
<li><a href="http://www.eclipse.org/mat/" target="_blank">http://www.eclipse.org/mat/</a></li>
<li><a href="https://visualvm.dev.java.net/" target="_blank">https://visualvm.dev.java.net/</a></li>
<li><a href="http://www.ej-technologies.com/products/jprofiler/overview.html" target="_blank">http://www.ej-technologies.com/products/jprofiler/overview.html</a></li>
<li><a href="http://www.yourkit.com/" target="_blank">http://www.yourkit.com/</a></li>
<li><a href="http://www.quest.com/jprobe/" target="_blank">http://www.quest.com/jprobe/</a></li>
<li><a href="http://java.sun.com/j2se/reference/whitepapers/memorymanagement_whitepaper.pdf" target="_blank">http://java.sun.com/j2se/reference/whitepapers/memorymanagement_whitepaper.pdf</a></li>
<li><a href="http://java.sun.com/javase/6/docs/technotes/tools/share/jhat.html" target="_blank">http://java.sun.com/javase/6/docs/technotes/tools/share/jhat.html</a></li>
<li><a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jmap.html" target="_blank">http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jmap.html</a></li>
<li><a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstat.html" target="_blank">http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstat.html</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2009/how-to-fix-memory-leaks-in-java/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>JRuby and Glassfish on Rails Part II: Setting up a Production Environment on Red Hat Linux</title>
		<link>http://olex.openlogic.com/wazi/2008/jruby-and-glassfish-a-production-ruby-on-rails-environment/</link>
		<comments>http://olex.openlogic.com/wazi/2008/jruby-and-glassfish-a-production-ruby-on-rails-environment/#comments</comments>
		<pubDate>Mon, 01 Dec 2008 19:40:17 +0000</pubDate>
		<dc:creator>Freddy Andersen</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[jruby]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=1409</guid>
		<description><![CDATA[Learn to deploy a Ruby on Rails application into a production-ready JRuby on Rails environment running GlassFish.]]></description>
			<content:encoded><![CDATA[<p>Now we&#8217;ll deploy a <a title="Ruby in OLEX" href="https://olex.openlogic.com/packages/ruby" target="_blank">Ruby</a> on <a title="Rails in OLEX" href="https://olex.openlogic.com/packages/glassfish" target="_blank">Rails</a> application (we&#8217;ll use a ready-to-deploy Rails application, Radiant, that drops into this environment easily) into a production-ready <a title="JRuby in OLEX" href="https://olex.openlogic.com/packages/glassfish" target="_blank">JRuby</a> on Rails environment running GlassFish. This tutorial does not cover tuning any parameters, but focuses rather on getting the server installed and running, and successfully deploying a Rails application into the <a title="GlassFish in OLEX" href="https://olex.openlogic.com/packages/glassfish" target="_blank">GlassFish</a> container.</p>
<h2>Before You Start</h2>
<p>We will use a RedHat ES 5 server for this tutorial. We&#8217;ve chosen the latest stable binary of JRuby 1.1.5 and we will use <a title="GlassFish in OLEX" href="https://olex.openlogic.com/packages/glassfish" target="_blank">GlassFish</a> v2. I think that&#8217;s all we need to know before we jump into the &#8230;</p>
<h2>Meat &amp; Potatoes</h2>
<h3><span style="#993300;"><strong><span style="#800000;"><span style="underline;">Installing JRuby</span></span></strong></span></h3>
<ol>
<li>Download the latest <a title="JRuby in OLEX" href="https://olex.openlogic.com/packages/jruby" target="_self">JRuby release from OLEX</a>.</li>
<li>Unzip and copy the JRuby directory to your /usr/local/ directory. (If you don&#8217;t like the /usr/local/ area but are more of a /opt sort, that&#8217;s fine, too, but this tutorial will reference /usr/local/ as the install location.)</li>
<li>Create a file /etc/profile.d/jruby.sh and add the following content:</li>
<li>Log-out and log-in to your system, this will make sure the environment for JRuby is correctly setup.</li>
<li>Test JRuby with the following command:<br />
<code><em>export JRUBY_HOME=/usr/local/jruby<br />
export PATH=$PATH:$JRUBY_HOME/bin</em></code><br />
<code>[freddy@wazi]# jruby -v<br />
jruby 1.1.5 (ruby 1.8.6 patchlevel 114) (2008-11-03 rev 7996) [amd64-java]</code></li>
</ol>
<p>That&#8217;s working great!</p>
<h3>Install Rails</h3>
<p>The recommended way to run these commands (known as <code>system-level executable commands</code>) in JRuby is to always use <code>jruby -S</code>.</p>
<p style="30px;"><code>[freddy@wazi]# jruby -S gem install <strong>rubygems-update</strong><br />
[freddy@wazi]# jruby -S <strong>update_rubygems</strong><br />
[freddy@wazi]# jruby -S gem install <strong>jruby-openssl</strong><br />
[freddy@wazi]# jruby -S gem install <strong>rails activerecord-jdbcmysql-adapter warbler<br />
</strong></code></p>
<p style="30px;">[freddy@wazi]# jruby -S rails -v Rails 2.2.2</p>
<p>We are going to use Radiant CMS for some simple testing, so let&#8217;s install and setup Radiant&#8230;</p>
<p style="30px;"><code>[freddy@wazi]# jruby -S gem install radiant<br />
[freddy@wazi]# jruby -S radiant --database mysql /usr/local/wazi-radiant<br />
[freddy@wazi]# mysqladmin create wazi-radiant_production</code></p>
<p>We are not going to set up any security for the <a title="MySQL in OLEX" href="https://olex.openlogic.com/packages/mysql" target="_blank">MySQL</a> instance; that&#8217;s a different topic altogether. For this reason, a local MySQL server in conjunction with the root user should work.</p>
<pre style="30px;"><code>=&gt; /usr/local/wazi-radiant/config/database.yml &lt;=</code></pre>
<pre style="30px;">production:
adapter: mysql
database: wazi-radiant_production
username: root
password:
host: localhost</pre>
<p>That should do it for the configuration, now let&#8217;s bootstrap the application:</p>
<p style="30px;"><code>[freddy@wazi /usr/local/wazi-radiant]# jruby -S rake production db:bootstrap</code></p>
<pre style="30px;"><em>This task will destroy any data in the database. Are you sure you want to
continue? [yn] y</em></pre>
<pre style="30px;"><em>
= 1 CreateRadiantTables: migrating ==========================================Create the admin user (press enter for defaults).
Name (Administrator):
Username (admin):</em><em>Password (radiant):
Select a database template:
1. Empty
2. Simple Blog
3. Styled Blog</em><em>[1-3]: 3
Creating Pages....OK
Creating Layouts....OK
Creating Snippets....OK</em><em>Creating Page parts....OK
Finished.</em></pre>
<p>Now, let&#8217;s run a quick test to see if everything is where it should be. We will start WEBrick and open a test page:</p>
<pre style="30px;"><code>jruby -S script/server -e production -p 4444</code></pre>
<pre style="30px;">=&gt; Booting WEBrick...
=&gt; Rails application started on http://0.0.0.0:4444
=&gt; Ctrl-C to shutdown server; call with --help for options
[2008-11-19 16:29:03] INFO  WEBrick 1.3.1
[2008-11-19 16:29:03] INFO  ruby 1.8.6 (2008-11-03) [java]
[2008-11-19 16:29:03] INFO  WEBrick::HTTPServer#start: pid=3359 port=4444</pre>
<p>Pointing the browser to <code>http://localhost:4444/</code> should now result in a nice looking blog interface, with an admin section available at <code>http://localhost:4444/admin</code>.</p>
<p>Now, let&#8217;s install and configure GlassFish so that we can deploy this application in a Java engine.</p>
<h3>Installing <a title="GlassFish in OLEX" href="https://olex.openlogic.com/packages/glassfish" target="_blank">GlassFish</a></h3>
<p>To install and configure GlassFish, you need to have <a title="JDK in OLEX" href="https://olex.openlogic.com/packages/jdk" target="_blank">JDK v5 or JDK v6</a> installed on your system. For this demo we are using JDK1.6.0_02-b05.</p>
<p>You can download the Glassfish v2-ur1-b09d installer from OLEX here https://olex.openlogic.com/packages/glassfish. And here are the instructions for running the installer:</p>
<blockquote><p>Make sure your JAVA_HOME is set to a <strong>JDK</strong>!</p>
<p>[freddy@wazi]# java -Xmx256m -jar filename.jar<br />
[freddy@wazi]# mv glassfish /usr/local/<br />
[freddy@wazi]# cd /usr/local/glassfish<br />
[freddy@wazi]# chmod -R +x lib/ant/bin<br />
[freddy@wazi]# lib/ant/bin/ant -f setup.xml<br />
We are waiting for <strong>BUILD SUCCESSFUL</strong></p></blockquote>
<p>Now you can move the Glassfish directory where you would like your Glassfish installation to live. ( Like /usr/local/glassfish )</p>
<p>Now cd into the glassfish directory and start the server&#8230;</p>
<p><code>[freddy@wazi]# bin/asadmin start-domain</code></p>
<pre style="30px;"><code>...</code></pre>
<pre style="30px;">Domain listens on at least following ports for connections:
[8080 8181 4848 3700 3820 3920 8686 ].
Domain does not support application server clusters and other standalone instances.</pre>
<p>You should now be able to access the GlassFish admin screen at <code>http://localhost:4848</code>, and the GlassFish landing page at <code>http://localhost:8080/<code>. The username/password for the admin console is admin/adminadmin.</code></code></p>
<p>We will now use Warbler to package our application into a war file, but we will need to setup the <code>warble.rb</code> configuration file first. First, we should create a generic configuration file for warbler. Strictly speaking, you don&#8217;t &#8220;need&#8221; a <code>wrble.rb</code> file, BUT it makes the process a lot easier, so we recommend it.</p>
<p style="30px;"><code>[freddy@wazi]# jruby -S warble config</code></p>
<p>The <code>warble.rb</code> file has a few issues with the Radiant <code>gem</code>, so we have to edit the file:</p>
<p style="30px;"><code>=&gt; config/warble.rb &lt;=</code></p>
<pre style="30px;">Warbler::Config.new do |config|
config.staging_dir = "tmp/war"
config.dirs = %w(config log vendor tmp)
config.gems += ["activerecord-jdbcmysql-adapter", "jruby-openssl"]
require "#{RAILS_ROOT}/config/boot"
BUILD_GEMS = %w(warbler rake rcov)
for gem in Gem.loaded_specs.values
next if BUILD_GEMS.include?(gem.name)
config.gems[gem.name] = gem.version.version
end
config.gem_dependencies = true
config.webxml.rails.env = ENV['RAILS_ENV'] || 'production'
end
[freddy@wazi /usr/local/wazi-radiant]# jruby -S warble
[freddy@wazi /usr/local/wazi-radiant]# ls *.war
wazi-radiant.war</pre>
<p>We now have a .war file that is deployable, so let&#8217;s push that to our running GlassFish server:</p>
<p style="30px;"><code>[freddy@wazi /usr/local/wazi-radiant]# ../glassfish/bin/asadmin deploy --contextroot / wazi-radiant.war</code></p>
<pre style="30px;"><code>Command deploy executed successfully.</code></pre>
<h2>Finishing Up</h2>
<p>Now our Radiant application can be accessed via <code>http://localhost:8080/</code>.</p>
<p>This was a very high level tutorial geared to get you up and running fast using Glassfish as your production Ruby on Rails server. We used a ready-to-deploy Rails application, Radiant, that drops into this environment easily and shows something &#8216;real&#8217; when the process is completed.</p>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2008/jruby-and-glassfish-a-production-ruby-on-rails-environment/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JRuby and Glassfish on Rails Part I: Setting Up A Developer Environment (on a Mac)</title>
		<link>http://olex.openlogic.com/wazi/2008/jruby-and-glassfish-as-a-rails-developer-environment/</link>
		<comments>http://olex.openlogic.com/wazi/2008/jruby-and-glassfish-as-a-rails-developer-environment/#comments</comments>
		<pubDate>Fri, 28 Nov 2008 19:39:50 +0000</pubDate>
		<dc:creator>Freddy Andersen</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[glassfish]]></category>
		<category><![CDATA[jruby]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=1452</guid>
		<description><![CDATA[In this tutorial, we cover setting up your Mac environment to use Glassfish as the server to run your Ruby on Rails projects. ]]></description>
			<content:encoded><![CDATA[<p>In this tutorial, we&#8217;ll cover setting up your Mac environment to use <a title="GlassFish in OLEX" href="https://olex.openlogic.com/packages/glassfish" target="_blank">Glassfish</a> as the server to run your <a title="Ruby in OLEX" href="https://olex.openlogic.com/packages/ruby" target="_blank">Ruby</a> on <a title="Rails in OLEX" href="https://olex.openlogic.com/packages/rails" target="_blank">Rails</a> projects. This tutorial should port to a Linux desktop, but we&#8217;ve not tested that scenario.</p>
<h2>Before You Start</h2>
<p>There&#8217;s some stuff you&#8217;ll need on your system:</p>
<ul>
<li>MacPorts installed and at version 1.6. (http://www.macports.org/install.php )</li>
<li>Some diskspace.</li>
<li>About 15min.</li>
</ul>
<h2>Meat &amp; Potatoes</h2>
<h3>Installing <a title="JRuby in OLEX" href="https://olex.openlogic.com/packages/jruby" target="_blank">JRuby</a></h3>
<p>The latest JRuby port is 1.1.3 so that is what we will use today.</p>
<p style="30px;"><code>[freddy@wazi]# port list jruby<br />
jruby           @1.1.3          lang/jruby</code></p>
<p>It&#8217;s as easy as entering:</p>
<p style="30px;"><code>[freddy@wazi]# sudo port install jruby<br />
[freddy@wazi]# ruby -v<br />
jruby 1.1.3 (ruby 1.8.6 patchlevel 114) (2008-11-17 rev 6586) [i386-java]</code></p>
<p><a title="JRuby in OLEX" href="https://olex.openlogic.com/packages/jruby" target="_blank">JRuby</a> uses a separate area to store <code>gems</code> and the Ruby environment, so we will need to install the <code>gems</code> that are needed for our development. This includes the Rails <code>gem</code>.</p>
<h3>Installing Rails and Friends</h3>
<p>Install <a title="Rails in OLEX" href="https://olex.openlogic.com/packages/rails" target="_blank">Rails</a> and create a test application:</p>
<p style="30px;"><code>[freddy@wazi]# sudo jruby -S gem install jruby-openssl<br />
[freddy@wazi]# sudo jruby -S gem install rails activerecord-jdbc-adapter<br />
[freddy@wazi]# sudo jruby -S rails wazi_app</code></p>
<p>Now we need to download the latest MySQL Java (JDBC) driver from https://olex.openlogic.com/packages/mysql-connector. Copy <code>mysql-connector-java-x.x.x-bin.jar</code> to <code>$JRUBY_HOME/lib</code> (/opt/local/share/java/jruby).</p>
<p>Now let&#8217;s update the <code>database.yml</code> file to use the JDBC driver:</p>
<pre style="30px;"><code>development:
adapter: jdbc
driver: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost/testapp_development
username: root
password:</code></pre>
<p>We should also make sure the JDBC driver will load. To do this, we edit the <code>environment.rb</code> file with these changes:</p>
<p style="30px;"><code><em><span style="italic;"># Bootstrap the Rails environment, frameworks, and default configuration</span><br />
<span style="italic;">require File.join(File.dirname(__FILE__), 'boot')</span></em><br />
<strong>if RUBY_PLATFORM =~ /java/<br />
require 'rubygems'<br />
RAILS_CONNECTION_ADAPTERS = %w(jdbc)<br />
end</strong></code></p>
<p>Now let&#8217;s boot the server in our JRuby environment:</p>
<p style="30px;"><code>[freddy@wazi]# jruby script/server<br />
=&gt; Booting WEBrick...<br />
=&gt; Rails 2.2.2 application started on http://0.0.0.0:4000<br />
=&gt; Ctrl-C to shutdown server; call with --help for options<br />
[2008-11-17 16:40:34] INFO  WEBrick 1.3.1<br />
[2008-11-17 16:40:34] INFO  ruby 1.8.6 (2008-11-17) [java]<br />
[2008-11-17 16:40:34] INFO  WEBrick::HTTPServer#start: pid=13484 port=4000</code></p>
<h3>Installing the Glassfish <code>gem</code></h3>
<p>Having <a title="GlassFish in OLEX" href="https://olex.openlogic.com/packages/glassfish" target="_blank">GlassFish</a> fully installed on your development environment is not always the best thing. If you don&#8217;t need it then you don&#8217;t want either the hogging of memory, or the administration that comes with a running J2EE container, so I&#8217;m going to show you an alternative. Do this:</p>
<p style="30px;"><code>[freddy@wazi]# jruby -S install glassfish</code></p>
<p>Whew, wasn&#8217;t that easy! <img src='http://olex.openlogic.com/wazi/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Now, let&#8217;s start the server using Glassfish rather than WEBrick:</p>
<p style="30px;"><code>[freddy@wazi]# jruby -S glassfish_rails<br />
...<br />
Nov 24, 2008 1:33:55 PM com.sun.enterprise.v3.services.impl.GrizzlyProxy start<br />
INFO: Listening on port 3000<br />
...<br />
Nov 24, 2008 1:34:01 PM com.sun.enterprise.v3.server.AppServerStartup run<br />
INFO: GlassFish v3 Prelude startup time : Felix(1813ms) startup services(6457ms) total(8270ms)</code><strong></strong></p>
<p style="30px;">
<p>Nice job! The application is now available at http://localhost:3000/.</p>
<h2>Finishing Up</h2>
<p>You now have a working environment in which you can develop your Rails application, and test them on your local desktop using a J2EE (<a title="GlassFish in OLEX" href="https://olex.openlogic.com/packages/glassfish" target="_blank">Glassfish</a>) container. We also installed<a title="JRuby in OLEX" href="https://olex.openlogic.com/packages/jruby" target="_blank"> JRuby</a> with all the required <code>gems</code> needed and this gives us the flexibility of either using JRuby or Ruby and/or Mongrel/Glassfish for different projects.</p>
<p style="30px;">As an added bonus, here&#8217;s some more information about the Glassfish gem:<br />
<code><br />
-c, --contextroot PATH: change the context root (default: '/')<br />
-p, --port PORT:        change server port (default: 3000)<br />
-e, --environment ENV:  change rails environment (default: development)<br />
-n --runtimes NUMBER:   Number of JRuby runtimes to crete initially<br />
--runtimes-min NUMBER:  Minimum JRuby runtimes to crete<br />
--runtimes-max NUMBER:  Maximum number of JRuby runtimes to crete<br />
APPLICATION_PATH (optional): Path to the application to be run (default: current)</code></p>
<p style="30px;">
<p style="30px;">
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2008/jruby-and-glassfish-as-a-rails-developer-environment/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Build Apache 2.2.X on AIX 5.3 Platforms Part II: Common Issues</title>
		<link>http://olex.openlogic.com/wazi/2008/how-to-build-apache-22x-on-aix-53-platforms-part-ii-some-common-errors-and-pitfalls/</link>
		<comments>http://olex.openlogic.com/wazi/2008/how-to-build-apache-22x-on-aix-53-platforms-part-ii-some-common-errors-and-pitfalls/#comments</comments>
		<pubDate>Fri, 14 Nov 2008 15:48:14 +0000</pubDate>
		<dc:creator>Brad Reeves</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[openssl]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=1300</guid>
		<description><![CDATA[Building the Apache Web server on AIX is generally a straightforward enterprise in which you:
obtain the code, run a few simple commands (configure, make, and make install)...kidding...read on...]]></description>
			<content:encoded><![CDATA[<h2>Purpose</h2>
<p>Building the Apache Web server on AIX is generally a straightforward enterprise in which you:<br />
obtain the code, run a few simple commands (configure, make, and make install) and then stop by your boss&#8217;s cube to ask if she&#8217;s got anything she&#8217;d like you to take off her plate.</p>
<p>You don&#8217;t know us very well yet, so we&#8217;ll be frank: we say &#8220;straightforward&#8221; with tongue firmly planted in cheek. A quick Google search on the topic will return a plethora of issues users encounter while building the code if they try anything beyond straight vanilla. In other words, if you need an install with any additional modules or capabilities, expect some issues.</p>
<p>We&#8217;ve already covered the vanilla installation, in the first installment of the Building Apache on AIX. This second part of the tutorial takes you beyond those basics. Before attempting any of these work arounds, we recommend that you have met all the requirements for a &#8220;basic&#8221; build.</p>
<h2>Before You Start</h2>
<p>Follow the setup from the first installment of this guide. Building Apache 2.2.X on AIX 5.3 platforms.</p>
<h2>Meat &amp; Potatoes</h2>
<h3>Common Problems</h3>
<p><strong>Neglecting to  clean between failed builds (or builds with numerous, particular errors)</strong><br />
During compilation phase of the build, if any errors are encountered, the subsequent build<br />
must be preceded by a make clean. As Joe Biden would say &#8220;Let me repeat that&#8221;, make clean.<br />
It is important that your build runs from start to finish without errors and that there is<br />
not any artifacts from previous build attempts giving you false positive or false negative results.</p>
<p><strong>Environment Issues</strong><br />
The most frequent issues with a build are ones that are encountered because the build environment<br />
is not set up correctly. Incorrect gcc version, gcc library version, and not adding the<br />
math library (libm.a) are the most common. Setup of these environment elements are covered in<br />
the <a href="http://olex.openlogic.com/wazi/2008/how-to-build-apache-22x-on-aix-53-platforms/">first installment of this guide</a>.</p>
<h3>Configuration options</h3>
<p>The latest versions of Apache Web server have over 160 configuration options and flags, making for millions potential combinations. These options control exactly how the Web server is going to build and, more importantly, how it is going to run. On AIX, there are several options that we have found are either required, or particularly beneficial to complete the build.</p>
<p style="padding-left: 30px;"><code>--prefix=PATH</code><br />
Setting this option is required. PATH is the exact path where the Web server will be installed and run from post compilation.</p>
<p style="padding-left: 30px;"><code>--with-included-apr</code><br />
<code>apr</code> and <code>apr-util </code>are bundled with the Apache Web server source releases, and will be used without any problems in almost all circumstances. However, if <code>apr </code>or <code>apr-util</code> versions 1.0 or 1.1, are installed on your system (as is the case if you are using AIX 5.3), you must either upgrade your <code>apr/apr-util</code> installations to 1.2 and force the use of the bundled libraries, or have <code>httpd</code> use separate builds.</p>
<p style="padding-left: 30px;">To use the bundled <code>apr/apr-util</code> sources, specify the <code>--with-included-apr</code> option added in version 2.2.3 of Apache Web server.</p>
<p style="padding-left: 30px;"><code>--enable-ssl=shared</code><br />
If you choose to add ssl capabilities to your Web server, you must enable this option. This also means that you must have <a href="https://olex.openlogic.com/packages/openssl">OpenSSL</a> installed on your system. On AIX systems a typical install will litter OpenSSL elements across your file system, and this will cause issues as you compile. For instance, we have found complete or portions of OpenSSL installed in the following directories : <code>/usr</code> , <code>/usr/bin</code>, <code>/opt/freeware/bin</code>, <code>/usr/include</code>, <code>/usr/linux</code>. Most often, the correct OpenSSL to use is the libraries found in <code>/usr</code>.  To specify using this one, you must set the following options:</p>
<p style="padding-left: 60px;"><code>--with-ssl=/usr</code> This tells the configuration step to bind to libraries found in and under <code>/usr</code>.</p>
<p style="padding-left: 60px;"><code>--enable-mods-shared=ssl </code>This tells the system to create the <code>ssl</code> module as a shared object.</p>
<p>Other important configuration options include:</p>
<p style="padding-left: 30px;"><code>--enable-so</code>: This configures apache for later installation of shared objects (modules).  Apache httpd can be built either with static, built-in modules, or be built so that modules can be stored outside of the httpd binary file, and may be compiled and added at a later time. Having the ability to add modules after the main build is accomplished using the Apache Extention Tool (apxs).  This dynamic build is enabled by the &#8211;enable-so option. The modules that are built as extentions to the main binary are called Dynamic Shared Objects (DSO).</p>
<p>Finally, here are a few optional modules you may include during your configuration:</p>
<p style="padding-left: 30px;"><strong>Proxy Modules</strong><br />
<code>--enable-proxy</code><br />
<code>--enable-proxy-ajp</code><br />
<code>--enable-proxy-balancer</code></p>
<p style="padding-left: 30px;"><strong>Configuring Proxy</strong></p>
<ul>
<li>Forward Proxy</li>
</ul>
<p><code>ProxyRequests On<br />
ProxyVia On</p>
<p>&lt;Proxy *&gt;<br />
<span class="indent"> Order deny,allow<br />
Deny from all<br />
Allow from internal.example.com<br />
</span> &lt;/Proxy&gt; </code></p>
<ul>
<li>Reverse Proxy</li>
</ul>
<p><code> ProxyRequests Off</p>
<p>&lt;Proxy *&gt;<br />
<span class="indent"> Order deny,allow<br />
Allow from all<br />
</span> &lt;/Proxy&gt;</p>
<p>ProxyPass /path http://domainname.com/thing<br />
ProxyPassReverse /path http://domainname.com/thing</code></p>
<ul>
<li>Proxy Access</li>
</ul>
<p><code> &lt;Proxy *&gt;<br />
<span class="indent"> Order Deny,Allow<br />
Deny from all<br />
Allow from 192.168.0<br />
</span> &lt;/Proxy&gt; </code></p>
<p style="padding-left: 30px;"><strong>Helper Modules</strong><br />
<code>--enable-module=rewrite</code><br />
<code>--enable-module=log_referer</code></p>
<h3>Common Error Messages</h3>
<p><strong>Openssl compilation error. </strong><br />
Sample error: <code>/usr/include/openssl/pq_compat.h:1:3: error: invalid preprocessing directive #IBM_PROLOG_BEGIN_TAG</code></p>
<p>On AIX, it is not uncommon to encounter errors during compilation if ssl is enabled. This is because<br />
IBM&#8217;s OpenSSL package contains a number of include files in <code>/usr/include/openssl</code> where a special &#8220;IBM Prolog&#8221; include line has been added, making the header files incompatible with gcc.<br />
The fix is to edit <code>pq_compat.h</code>, and comment out any lines with <code>IBM_PROLOG_BEGIN_TAG</code>, as well as any associated lines with the Prolog include tag.</p>
<p><strong>Linker errors</strong><br />
Sample error: <code>0711-317 ERROR: Undefined symbol: .BIO_clear_flags</code></p>
<p>On AIX, once you have satisfied the gcc requirements to build Apache two linkers will exist<br />
on your system. Linker errors, like the one seen above, are a result of the pathing to libraries being<br />
different for the compiler and the linker, and can be resolved by setting environment flags.</p>
<p>Now, on all UNIX systems there is a library path that is to be used during link phase, and runtime,<br />
and on all UNIX systems this path is set via the <code>LD_LIBRARY_PATH</code> variable. All Unix systems, that is, except AIX. For this reason, we usually set the path using both the standard and the AIX variable as a safety precaution. The native AIX linker should use <code>LIBPATH</code>, while <code>LD_LIBRARY_PATH</code> will be used by the Gnu linker.</p>
<p>Example library path setup looks like this:</p>
<pre>set LIBPATH=/usr/lib:/lib
set LD_LIBRARY_PATH=/usr/lib:/lib
export LIBPATH LD_LIBRARY_PATH</pre>
<h2>Finishing Up</h2>
<p>Augmenting the basic build with additional modules will add complexity to the build process, but by following this tutorial and properly setting up your environment, most errors can be avoided. Of course, each system can have other libraries and packages installed that can cause additional error messages, or warnings. While we have built Apache on AIX many times, on many different systems, this guide does not claim to, and can&#8217;t possibly, anticipate every situation. Should you encounter other errors, please email them to us, and we&#8217;ll include them in a future revision.</p>
<p>We wish you good luck, and happy compiling.</p>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2008/how-to-build-apache-22x-on-aix-53-platforms-part-ii-some-common-errors-and-pitfalls/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to Customize the Firefox 3 Installer</title>
		<link>http://olex.openlogic.com/wazi/2008/how-to-customize-the-firefox-3-installer-for-the-enterprise/</link>
		<comments>http://olex.openlogic.com/wazi/2008/how-to-customize-the-firefox-3-installer-for-the-enterprise/#comments</comments>
		<pubDate>Tue, 21 Oct 2008 18:45:00 +0000</pubDate>
		<dc:creator>Glen Bettridge</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[firefox]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=1219</guid>
		<description><![CDATA[With the increasing adoption of Firefox, enterprise IT shops face a challenge: providing Firefox to their users while maintaining security. One approach to this challenge is to create a customized Firefox installer pre-configured with IT-approved extensions and settings.]]></description>
			<content:encoded><![CDATA[<p>With adoption of Firefox on the increase, enterprise IT shops face a challenge: how to provide Firefox to their users while keeping a handle on security. To address this, we suggest creating a customized Firefox installer preconfigured with the extensions and settings approved by your IT department. This tutorial takes you through that process.</p>
<h2>Before You Start</h2>
<p>Before customizing Firefox, avoid headaches by looking carefully at which extensions best suit your needs. You, or your IT team, should also thoroughly research the Firefox settings and create a list of those you wish to include.</p>
<h3>Extensions</h3>
<p>One of Firefox&#8217;s greatest strengths is its diverse collection of extensions. Extensions such as NoScript or CookieSafe can be used to secure Firefox, while AdBlock or one of its variants could help reduce unwanted traffic to ad servers. Before building a customized installer, you will need to decide which extensions best meet your needs and the needs of your users. With an eye toward security policies and customer requests, browse the <a href="https://addons.mozilla.org/en-US/firefox/" target="_blank">Firefox Add-on Repository</a> and download the (Firefox 3-compatible) add-ons that best meet your needs.</p>
<h3>Settings</h3>
<p>Firefox offers a large number of settings, many of which aren&#8217;t accessible through the standard preferences/options dialog window. To see the available options, enter &#8220;about:config&#8221; in Firefox&#8217;s location bar. This will display a list of all settings. While the list is intimidating, Mozilla publishes <a href="http://kb.mozillazine.org/About:config_entries" target="_blank">a reference to all of the settings</a>. Review the  options and collect a list of settings for which you&#8217;d either like to set a custom default value or completely lock down to a specific value.</p>
<h3>What You Will Need</h3>
<p>Once you&#8217;ve decided what extensions and settings you&#8217;d like in your spiffy custom installer, there are a few components you&#8217;ll need.</p>
<p>For a custom Windows installer, grab</p>
<ol>
<li>A current, standard <a href="http://www.mozilla.com/products/download.html?product=firefox-3.0.3&amp;os=win&amp;lang=en-US" target="_blank">Firefox 3 installer for Windows.</a></li>
<li>A current app.tag file from Mozilla&#8217;s site (copy the appropriate text from <a href="http://lxr.mozilla.org/mozilla/source/browser/installer/windows/app.tag" target="_blank">http://lxr.mozilla.org/mozilla/source/browser/installer/windows/app.tag</a> into a text file called app.tag).</li>
<li>A 7zSD.sfx file from Mozilla&#8217;s site (download this from <a href="http://lxr.mozilla.org/mozilla/source/other-licenses/7zstub/firefox/7zSD.sfx?raw=1" target="_blank">http://lxr.mozilla.org/mozilla/source/other-licenses/7zstub/firefox/7zSD.sfx?raw=1</a>).</li>
<li>The 7zip command line utility (currently at <a href="http://downloads.sourceforge.net/sevenzip/7za457.zip" target="_blank">http://downloads.sourceforge.net/sevenzip/7za457.zip</a>).</li>
</ol>
<p>For a custom Linux installer,you&#8217;ll need to</p>
<ol>
<li>Grab a current standard <a href="http://www.mozilla.com/products/download.html?product=firefox-3.0.3&amp;os=linux&amp;lang=en-US" target="_blank">Firefox 3 binary for Linux.</a></li>
<li>Have familiarity with tar and gzip.</li>
</ol>
<p>You&#8217;ll also need copies of each extension you wish to include in the installer (the xpi files), and the list of settings and values.</p>
<p><em>Note for Mac users:</em> I&#8217;m working on a version of this article for Firefox 3 on the Mac, but I&#8217;m still sorting out the details of repackaging a dmg file.</p>
<h2>Meat &amp; Potatoes</h2>
<h3>Creating Your Settings File</h3>
<p>The settings file I&#8217;m going to describe is basically just a Javascript file with a set of calls to two Firefox-defined JS functions, <code>defaultPref</code> and <code>lockPref</code>. Unsurprisingly, the <code>defaultPref</code> function can be used to specify a default value for a setting and lockPref sets the value for the setting so that it cannot be changed by the user. Each has similar arguments:</p>
<p style="padding-left: 30px; "><code>function defaultPref(prefName, value)<br />
function lockPref(prefName, value)</code></p>
<p>so, for example, you could set the default home page using</p>
<p style="padding-left: 30px; "><code>defaultPref("browser.startup.homepage","http://www.mycompany.com/portal");</code></p>
<p>or, you could require that the browser always check for updates</p>
<p style="padding-left: 30px; "><code>lockPref("app.update.enabled",true);</code></p>
<p>You can find additional information about these and other preference Javascript functions for Firefox in &#8220;<a href="http://developer.mozilla.org/en/MCD,_Mission_Control_Desktop_AKA_AutoConfig" target="_blank">MCD, Mission Control Desktop AKA AutoConfig</a>&#8221; at the Mozilla Developer Center.</p>
<p>Use the list of settings you prepared to build a settings file. For the rest of the article, I&#8217;ll refer to this file as &#8220;firefox.cfg&#8221;, although you can use any name you prefer.</p>
<p><em>Note:</em> Since the settings file is a Javascript file, there are many sophisticated and clever javascript tricks you can include, but I&#8217;m not going to cover any of them.</p>
<h3>Making Your Extensions Manually Installable</h3>
<p>The next step is to prepare your chosen extensions to be manually installed. For each extension,</p>
<ol>
<li>Unzip the xpi file (using 7zip, WinZip, Zip-Info or your preferred tool). You&#8217;ll end up with a folder probably with the same name as the extension (for example, NoScript)</li>
<li>In the folder, find the file called install.rdf, open it in a text editor and find the &lt;em:id&gt; tag under the &lt;Description&gt; tag. This is the unique ID of the extension ({73a6fe31-595d-460b-a920-fcc0f8843232} for NoScript)</li>
<li>Change the name of the extension folder to the extension&#8217;s ID (e.g. Change the &#8220;NoScript&#8221; folder to &#8220;{73a6fe31-595d-460b-a920-fcc0f8843232}&#8221;)</li>
</ol>
<h3>On to the Installer</h3>
<p>Now we&#8217;re ready to rebuild the installer.</p>
<h4>Windows Installer</h4>
<p>Let&#8217;s walk through the process for the Windows installer and then I&#8217;ll describe the somewhat simpler process on Linux.</p>
<ol>
<li>The Firefox installer is basically a self-extracting 7zip archive. You can open the 3.0.3 installer into a directory called &#8220;firefox-win&#8221; using
<p style="padding-left: 30px; "><code>7za x -ofirefox-win "Firefox Setup 3.0.3.exe"</code></p>
</li>
<li>Copy each of the renamed extension folders into <code>firefox-win\nonlocalized\extensions\</code> (assuming Windows path style). That&#8217;s all that needs to be done for a generic extension installations. If the extensions add new settings, the installer will use the default values for those settings. Those settings could also be added to the firefox.cfg file, if you needed to change them, but I won&#8217;t go into details here.</li>
<li>Create a file called firefox.cfg in firefox-win\nonlocalized\ where the firefox.exe file is located. Here&#8217;s an example <a href="http://olex.openlogic.com/wazi/wp-content/uploads/2009/05/firefox.cfg">firefox.cfg</a> which provides some basic security settings (note that everything in the example config file is commented out so it can be tested without affecting any settings at all; uncomment the settings you&#8217;d like to try).</li>
<li>Open firefox-win\nonlocalized\greprefs\all.js in a text editor and add the following lines</li>
<p><code>pref('general.config.obscure_value', 0);<br />
pref('general.config.filename', 'firefox.cfg');</code></p>
<p>This causes Firefox 3 to load the settings in the firefox.cfg file.</p>
<li>Build a new exe installer from the firefox-win folder: cd into firefox-win and execute the following commands
<ol>
<li><code>7za a -t7z ..\custom.7z</code></li>
<li><code>cd ..</code></li>
<li><code>copy /b  7zSD.sfx+app.tag+custom.7z FirefoxCustomInstall.exe</code></li>
</ol>
</li>
</ol>
<h4>Linux Installer</h4>
<p>When you download Firefox for Linux, instead of an installer, you&#8217;ll just have a tarball. This means you can untar it, walk through steps 2-4 in the Windows process and re-archive the directory.</p>
<h2>Finishing Up</h2>
<p>Distribute your newly created .exe to users and you&#8217;re set!</p>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2008/how-to-customize-the-firefox-3-installer-for-the-enterprise/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Build Apache 2.2.X on AIX 5.3 Platforms Part I: Basics</title>
		<link>http://olex.openlogic.com/wazi/2008/how-to-build-apache-22x-on-aix-53-platforms/</link>
		<comments>http://olex.openlogic.com/wazi/2008/how-to-build-apache-22x-on-aix-53-platforms/#comments</comments>
		<pubDate>Thu, 02 Oct 2008 00:00:36 +0000</pubDate>
		<dc:creator>Brad Reeves</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[apache]]></category>

		<guid isPermaLink="false">http://olex.openlogic.com/wazi/?p=171</guid>
		<description><![CDATA[While there are many binary versions of Apache available for the AIX platform, many people wish to build it themselves, adding modules or custom locations to the Apache web server. Our cookbook will guide you through the system setup and build process for the Apache web server.]]></description>
			<content:encoded><![CDATA[<p>While there are many binary versions of Apache available for the AIX platform, many people wish to build it themselves so they can add modules or custom locations to the Apache Web server. Should you need that flexibility, this tutorial will guide you.</p>
<p>This is not an AIX administration guide, and any administration tasks suggested by this guide will need to be performed as a &#8220;root&#8221; user. If you&#8217;re unsure of whether or not you <em>are</em> a &#8220;root&#8221; user, then you should stop now, and find someone who knows for sure.</p>
<p>This tutorial will also assume that we&#8217;re building Apache with GCC (GNU Compiler Collection). The steps outlined here may work with other compilers, but have only been tested with GCC.</p>
<h2>Before You Start</h2>
<p>In order to properly prepare the system and the Apache build configuration, we need to make a checklist of where you want Apache and what use you wish to make of it.</p>
<ol>
<li>Where will you install Apache? In order to compile Apache you&#8217;ll need ~250MB of free disk space in the following areas:
<ul>
<li><strong>Build Directory</strong> &#8211; this is where you&#8217;ll build the code. It can be anywhere on the file system. Although many people choose to do this in their home directory, we recommend that you create a specific directory.  Something like<code> /build </code>in the root directory, or in a place where you have free space.</li>
<li><strong>Prefix Directory</strong> &#8211; this is where you want Apache to be installed when you&#8217;re done. By default, Apache installs in the <code>/usr</code> partition.</li>
<li><strong>Tmp Directory </strong>- It&#8217;s always a good idea to have some free space in <code>/tmp</code> during builds.</li>
</ul>
</li>
<li>You&#8217;ll need the following tools :
<ul>
<li><strong>Apache Source Code:</strong> Version 2.2.8 can be obtained <a title="Link to Apache #" href="https://olex.openlogic.com/packages/apache#1543">here</a>. Click on the download link.</li>
<li><strong>GCC 4.0</strong>: GNU C compiler version 4 for AIX 5.3. You&#8217;ll find it <a title="Link to " href="http://www.ibm.com/servers/aix/products/aixos/linux/download.html">here</a>.</li>
<li><strong>libgcc 4.0</strong>: the library for GCC for AIX 5.3. Go <a href="http://www.ibm.com/servers/aix/products/aixos/linux/download.html">here</a> to get it.</li>
</ul>
</li>
<li>You&#8217;ll also need to install libm.a from the AIX 5.3 installation disk 1.  We recommend using &#8220;smitty installp&#8221; to accomplish this install.</li>
<li>Uncompress the Apache source code into a temporary location. We usually create a <code>/hold/Apache-2.2.8</code> directory, but any directory where you have space is fine.</li>
<li>Change directory to <code>/hold/Apache-2.2.8</code> ( <code>cd /hold/Apache-2.2.8</code> )</li>
<li>Run the configure command with the prefix option.   ( <code>./configure --prefix=/usr/local/apache</code> ). This command evaluates your system for its readiness to build Apache. You&#8217;ll notice that some things will be found, and others will not be found. As long as the configure completes without errors, you may continue the build process.</li>
</ol>
<p><strong>Note: Installing the RPMs (Red Hat Package Managers) for GCC should be done as the root user.</strong></p>
<h2>Meat &amp; Potatoes</h2>
<h3>Building Apache</h3>
<p>First you&#8217;ll want to uncompress the Apache source code into a temporary location. We usually create a <code>/hold/Apache-2.2.8</code> directory, but any directory where you have space is fine.</p>
<p>This tutorial will assume that directory is <code>/hold/Apache-2.2.8</code> and will assume that the answer to question 1 in the Prerequisites section above is <code>/usr/local/apache</code>.</p>
<ol>
<li>Make the Apache project. ( <code>make</code> ) The make command reads the Makefile that was created in the configuration step. This will run for approximately 15 minutes. You may see some warnings, but again, as with the configuration step, if it completes without errors, it is fine.</li>
<li>Deploy the Apache Project.  (<code> make install</code> )  Once more, this should be accomplished as the &#8216;root&#8217; user.</li>
<li>Test the project. Change directory to<code> /usr/local/apache/bin</code>.  Run the Apache start-up script. (<code>./apachectl start </code>) You may be warned that Apache can&#8217;t determine the server&#8217;s name, but no worries &#8211; that&#8217;s to be expected, as we have not configured Apache. The server will still start up.</li>
<li>In a web browser go to URL http://localhost.</li>
</ol>
<h2>Finishing Up</h2>
<p>You should see the page load, and it will report &#8220;It Works!&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://olex.openlogic.com/wazi/2008/how-to-build-apache-22x-on-aix-53-platforms/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
