<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-4352584012687120995</id><updated>2024-10-24T12:31:21.255-07:00</updated><category term="PSC"/><category term="java"/><category term="java 8"/><category term="maven"/><category term="Big Decimal"/><category term="Exact numerical methods"/><category term="basics"/><category term="captor"/><category term="default method"/><category term="equals"/><category term="interface"/><category term="introduction"/><category term="j2ee"/><category term="java 1.8"/><category term="jdk"/><category term="jdk 1.8"/><category term="jdk 8"/><category term="jee"/><category term="jsp"/><category term="junit"/><category term="lambda"/><category term="mockito"/><category term="negative dividing"/><category term="overivew"/><category term="remote"/><category term="servlet"/><category term="static method"/><category term="testing"/><category term="verification"/><category term="verify"/><category term="web container"/><title type='text'>Navigating the Mount Everest of Java information</title><subtitle type='html'>Just like a Sherpa guides climbers up Mount Everest, articles here will help you navigate the java and java enterprise environment.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://javasherpa.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://javasherpa.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/03357728230885603222</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>8</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-4352584012687120995.post-9142579404806812267</id><published>2014-10-07T14:03:00.002-07:00</published><updated>2014-10-07T14:15:38.328-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="java 8"/><category scheme="http://www.blogger.com/atom/ns#" term="lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="PSC"/><title type='text'>Java 8 Overview: Lambdas</title><content type='html'>&lt;div&gt;
Probably one of the most requested features and biggest time saver in Java 8 are lambdas. Essentially, a lambda is a short hand way to create an anonymous inner class. Let&#39;s look at how we used to have to do an anonymous comparator for comparing the lower case result of strings in a list:
&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;    Collections.sort(comparison, new Comparator&amp;lt;String&amp;gt;() {
        @Override
        public int compare(String o1, String o2) {
            return o1.toLowerCase().compareTo(o2.toLowerCase());
        }
    });
&lt;/pre&gt;
&lt;div&gt;
Even with this simple example you can see quite a bit of extra code you have to write just to put in the logic of comparing two strings in lower case. Now, in Java 8 with lambdas you can compress the previous statement to the following:
&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Collections.sort(comparison, (o1, o2) -&amp;gt; o1.toLowerCase().compareTo(o2.toLowerCase()));
&lt;/pre&gt;
&lt;div&gt;
Much simpler right?
&lt;/div&gt;
&lt;h2&gt;
Lambda requirements&lt;/h2&gt;
&lt;div&gt;
There is basically a single requirement for an interface to be used as a lambda expression. The interface needs to be annotated with the&amp;nbsp;&lt;a href=&quot;http://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html&quot; target=&quot;_blank&quot;&gt;@FunctionalInterface&lt;/a&gt;&amp;nbsp;annotation. This annotations requires a single non default, non static method in the interface. This way, with only a single method available it&#39;s obvious what method should be called and what the parameters and return type are for the method call. When it comes to creating lambdas there are essentially two types, what I call simple lambdas and standard lambdas.&lt;/div&gt;
&lt;h3&gt;
Simple Lambdas&lt;/h3&gt;
&lt;div&gt;
Simple lambdas consist of a single expression where the result of that expression is returned. They don&#39;t require braces and you can also omit the return keyword as well. The following is an example of what one would look like:&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Collections.sort(comparison, (o1, o2) -&amp;gt; o1.toLowerCase().compareTo(o2.toLowerCase()));
&lt;/pre&gt;
&lt;div&gt;
In these cases even more of the code that is unnecessary is removed to make the result even cleaner.
&lt;/div&gt;
&lt;h3&gt;
Standard Lambdas&lt;/h3&gt;
&lt;div&gt;
You would use a standard lambda when your implementation requires multiple statements. In these cases you would enclose the statements within braces and you need to include the return statement for all return points. If you were to compare a list of users based on their last name then first name then the expression would look something like the following:&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;        Collections.sort(comparison, (User o1, User o2) -&amp;gt; {
            int compare = o1.getLastName().compareTo(o2.getLastName());
            return compare != 0 ? compare : o1.getFirstName().compareTo(o2.getLastName());
        });
&lt;/pre&gt;
&lt;div&gt;
As you can see above, when items become more complex you have to specify the object types (User o1, User o2 instead of just o1, o2 like for the simple setup), you have to use braces and a return statement.
&lt;/div&gt;
&lt;h2&gt;
Extra information&lt;/h2&gt;
&lt;div&gt;
To cut the code necessary for working with lambdas even further Java 8 includes a set of the most common types of operations you&#39;d perform in the&amp;nbsp;&lt;a href=&quot;http://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html&quot; target=&quot;_blank&quot;&gt;java.util.function package&lt;/a&gt;. In there you&#39;ll find operations such as Functions for processing one property and returning a result, predicates that take in an argument and return a boolean result, and a whole host of other standard operations. They&#39;re used heavily by streams (more on that in a future blog post) and can easily be integrated in your code base.&lt;/div&gt;
&lt;h2&gt;
Conclusion&lt;/h2&gt;
&lt;div&gt;
While lambdas don&#39;t introduce a new programming archetype in the language they do greatly simplify the code you need to write (and thus read as well). Like annotations before them they help to make the code more concise and easier for others to work with and understand. Finally, albeit to a lesser extent, it shows that Java can still move with the times and incorporate current programming paradigms to help coders in other languages to relate to the code.&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://javasherpa.blogspot.com/feeds/9142579404806812267/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasherpa.blogspot.com/2014/10/java-8-overview-lambdas.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/9142579404806812267'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/9142579404806812267'/><link rel='alternate' type='text/html' href='http://javasherpa.blogspot.com/2014/10/java-8-overview-lambdas.html' title='Java 8 Overview: Lambdas'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/03357728230885603222</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4352584012687120995.post-7525028615143745887</id><published>2014-08-15T10:01:00.000-07:00</published><updated>2014-08-15T10:01:40.103-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Exact numerical methods"/><category scheme="http://www.blogger.com/atom/ns#" term="java 8"/><category scheme="http://www.blogger.com/atom/ns#" term="negative dividing"/><category scheme="http://www.blogger.com/atom/ns#" term="PSC"/><title type='text'>Java 8 Overview: Exact numerical methods and negative floor/mod methods</title><content type='html'>&lt;div&gt;
&lt;h2&gt;
Exact Numerical Methods&lt;/h2&gt;
One of the lesser known features added to Java 8 is the addition of exact numerical methods to deal with MAX_VALUE/MIN_VALUE situations. Normally when you do arithmetic with integers or longs (floats and doubles work the same but you don&#39;t do much addition with them right? You use BigDecimal right? right?) and you go beyond their max value they just wrap around to MIN_VALUE and increase from there or decrease from MIN_VALUE to MAX_VALUE and decrease from there due to the bit shift of the first bit in a word (which designates a positive number from a negative number). The following code example and output shows how this works for int (long, float, and double work the same).&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
System.out.println(&quot;Max Value: &quot; + Integer.MAX_VALUE);
System.out.println(&quot;Max Value + 1: &quot; + (Integer.MAX_VALUE + 1));

try {
  System.out.println(&quot;This won&#39;t print: &quot; + Math.addExact(Integer.MAX_VALUE, 1));
} catch (ArithmeticException e) {
  System.out.println(&quot;Exception since we overflowed Integer.MAX_VALUE&quot;);
}&lt;/pre&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Max Value: 2147483647
Max Value + 1: -2147483648
Exception since we overflowed Integer.MAX_VALUE
&lt;/pre&gt;
&lt;div&gt;
&lt;h2&gt;
Negative Floor and Mod&lt;/h2&gt;
&lt;/div&gt;
&lt;div&gt;
The other arithmetic &quot;fix&quot; in this release deals with negative division and negative mod values. The way java is supposed to work is when you use the &#39;/&#39; symbol with integers and the result isn&#39;t exact then it&#39;s supposed to give you the first number less than the exact number. So if I were to do (4/3) then I&#39;d get 1 since the actual answer is 1.33. With negative numbers this is off slightly. Instead of the next number down it gives you the next number up (heading for 0), basically the negative version of the positive result. Look at the following example.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
System.out.println(&quot;Divide with negative numerator: &quot; + -4 / 3);
System.out.println(&quot;Math.floorDiv() with negative numerator: &quot; + Math.floorDiv(-4, 3));
&lt;/pre&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
Divide with negative numerator: -1
Math.floorDiv() with negative numerator: -2
&lt;/pre&gt;
&lt;div&gt;
In this example the old value is -1 (the mirror value for the positive result) but that isn&#39;t quite right, it&#39;s the next integer GREATER than the correct answer, not the next integer LESS THAN the answer so now with the new method you get the correct answer of -2.&lt;br /&gt;
Similar to the floor the mod value with negative numbers is also incorrect with the new floorDiv() logic. Now, MOD with negative numbers is already screwy as may languages define it differently but with the new setup you&#39;d get the following:&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
System.out.println(&quot;Mod with negative numerator: &quot; + -4 % 3);
System.out.println(&quot;Math.floorMod() with negative numerator: &quot; + Math.floorMod(-4, 3));
&lt;/pre&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
Mod with negative numerator: -1
Math.floorMod() with negative numerator: 2
&lt;/pre&gt;
&lt;div&gt;
So, what&#39;s happening with the new setup? Well, if you were to do a floorDiv of the same numbers you&#39;d get a -2 and -2 * 3 is -6 so the difference between that result and the original numerator is 2. The floorMod result is always the same sign as the denominator (so if instead of Math.floorMod(-4, 3) we used Math.floorMod(4, -3) then the result would be -2).
&lt;/div&gt;
&lt;h2&gt;
Conclusion&lt;/h2&gt;
&lt;div&gt;
While I would imagine the new mod methods will have limited usefulness, however, the exact numerical methods for int and long I would find very useful. Currently well written programs have to constantly check to see if a summation (it will also work in reverse below MIN_VALUE) exceeds the bounds of the variable type. Now, you can check for ArithmaticException (or not as it&#39;s a runtime exception so it will bubble up nicely) instead and devote your program to what it&#39;s intending to do and leave the bounds checks to the system.&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasherpa.blogspot.com/feeds/7525028615143745887/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasherpa.blogspot.com/2014/08/java-8-overview-exact-numerical-methods.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/7525028615143745887'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/7525028615143745887'/><link rel='alternate' type='text/html' href='http://javasherpa.blogspot.com/2014/08/java-8-overview-exact-numerical-methods.html' title='Java 8 Overview: Exact numerical methods and negative floor/mod methods'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/03357728230885603222</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4352584012687120995.post-248011228619036361</id><published>2014-06-03T08:33:00.001-07:00</published><updated>2014-06-03T10:53:56.652-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="captor"/><category scheme="http://www.blogger.com/atom/ns#" term="junit"/><category scheme="http://www.blogger.com/atom/ns#" term="mockito"/><category scheme="http://www.blogger.com/atom/ns#" term="PSC"/><category scheme="http://www.blogger.com/atom/ns#" term="testing"/><category scheme="http://www.blogger.com/atom/ns#" term="verification"/><category scheme="http://www.blogger.com/atom/ns#" term="verify"/><title type='text'>Mockito Captors and verify(): How to check objects created and verify method calls within a method</title><content type='html'>&lt;div&gt;
Like any good developer I&#39;m sure you write unit tests for each line of your code. Now, you could simply write tests that will execute each line of your code and leave it at that and assume that if the line of code executed then it must be correct but what if you want to actually check that a specific method was called or that a specific method was NOT called because of your setup? What if you want to check the attributes of an object created within the method your testing? Well, with a couple quick calls through Mockito you can easily verify that a method was called and even get objects passed into these method calls.
&lt;br /&gt;
&lt;h2&gt;
Example&lt;/h2&gt;
To keep it simple lets say you have a DAO class that has three methods, a get, an insert, and an update for your domain object.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public interface Dao {
    Domain getDomain(int id);
    void insertDomain(Domain domain);
    void updateDomain(Domain domain);
}
&lt;/pre&gt;
&lt;div&gt;
You also have a service class that takes in a web form, translates it to a domain object and inserts or updates the object depending on if the object is found in the database.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Service {
    private Dao dao;

    public void processWebForm(WebForm webForm) {
        Domain domain = dao.getDomain(webForm.getId());
        if (domain != null) {
            domain.setField1(webForm.getField1());
            dao.updateDomain(domain);
        } else {
            domain = new Domain();
            domain.setId(webForm.getId());
            domain.setField1(webForm.getField1());
            dao.insertDomain(domain);
        }
    }

    public Dao getDao() {
        return dao;
    }

    public void setDao(Dao dao) {
        this.dao = dao;
    }
}
&lt;/pre&gt;
&lt;div&gt;
One quick note, I&#39;m not showing the domain or webform objects here but you can click &lt;a href=&quot;https://github.com/gshyde/mockitoCaptorsExample&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt; to get all the source code for this example. Also, I realize this isn&#39;t the most perfectly written code with all the best programming practices but for the purpose of this example it&#39;s sufficient.
&lt;br /&gt;
Now, for testing I could simply call the processWebForm method to ensure that it doesn&#39;t fail. I could even call it twice with two different WebForm objects where one should be inserted and one should be updated but what if I want to make sure each of the calls do what I expect? Enter Mockito. The following code snippet will test that the submitted WebForm will result in a Domain object being created and inserted into the database.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
    @Test
    public void testInsertWebForm() throws Exception {
        Dao dao = Mockito.mock(Dao.class);
        Domain d = new Domain();
        d.setId(1);
        d.setField1(&quot;field1&quot;);
        Mockito.when(dao.getDomain(Matchers.eq(1))).thenReturn(d);
        Service s = new Service();
        s.setDao(dao);
        WebForm wf = new WebForm();
        wf.setField1(&quot;testValue&quot;);
        s.processWebForm(wf);
        Mockito.verify(dao, Mockito.never()).updateDomain(Matchers.anyObject());
        ArgumentCaptor&lt;domain&gt; domainCaptor = ArgumentCaptor.forClass(Domain.class);
        Mockito.verify(dao, Mockito.times(1)).insertDomain(domainCaptor.capture());
        Domain testDomain = domainCaptor.getValue();
        Assert.assertNotNull(testDomain);
        Assert.assertEquals(0, testDomain.getId());
        Assert.assertEquals(&quot;testValue&quot;, testDomain.getField2());
    }
}
&lt;/domain&gt;&lt;/pre&gt;
&lt;div&gt;
Now, let&#39;s go through the important code sections one by one to explain what each of them do.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;@RunWith(MockitoJUnitRunner.class)&lt;/pre&gt;
&lt;div&gt;
To use any Mockito classes in your JUnit tests you have to use the Mockito JUnit Test Runner&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Dao dao = Mockito.mock(Dao.class);&lt;/pre&gt;
&lt;div&gt;
Verification methods can only be used on Mocked classes.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Mockito.when(dao.getDomain(Matchers.eq(1))).thenReturn(d);&lt;/pre&gt;
&lt;div&gt;
Not strictly necessary since the default setup for a mocked method is to return null but it would be necessary for testing the update method.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Mockito.verify(dao, Mockito.never()).updateDomain(Matchers.anyObject());&lt;/pre&gt;
&lt;div&gt;
This is the first part of the verification that this call does exactly what we want. Since I should be doing an insert then the update method shouldn&#39;t ever be called. This method call ensures that the method wasn&#39;t called.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;ArgumentCaptor&lt;domain&gt; domainCaptor = ArgumentCaptor.forClass(Domain.class);&lt;/domain&gt;&lt;/pre&gt;
&lt;div&gt;
ArgumentCaptors are how you can retrieve objects that were passed into a method call (checking the return value would be silly since you would have set what the return value would be when setting up the mock object to begin with.)&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Mockito.verify(dao, Mockito.times(1)).insertDomain(domainCaptor.capture());&lt;/pre&gt;
&lt;div&gt;
This is the second part of the verification where you do two things:&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Verify that the insert method was called and only called once&lt;/li&gt;
&lt;li&gt;capture the object that was passed into the Dao.insertDomain() method&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Domain testDomain = domainCaptor.getValue();&lt;/pre&gt;
&lt;div&gt;
ArgumentCaptor is type sensitive so the getValue() method will return the appropriate type of object you captured. This is how you retrieve the object to check.&lt;br /&gt;
&lt;h2&gt;
Issues&lt;/h2&gt;
The main thing you need to watch out for when doing verify checks is that the call counts are cumulative from when you create the mock object. If I were to test the update method after my last Assert statement and I tried to do a verify on the insert method with a Mockito.never() for the number of calls it would throw an error saying that it was called once because of the last call. To fix this I generally suggest you test each of the states in separate test methods but if you have to do it in a single test method you&#39;ll have to either re-create the mock object or use the Mockito.reset() method which does the same thing (you&#39;ll have to re-set all the setup either way)&lt;br /&gt;
&lt;h2&gt;
Conclusion&lt;/h2&gt;
&lt;/div&gt;
&lt;div&gt;
Using Mockito to mock out objects you&#39;re not directly testing makes writing unit tests much easier and more suscient. Using the verify() method with captors is a very handy way to tighten the tests to ensure the exact code flow you want to test was the code flow that ran. There are a few issues &amp;nbsp;you have to look out for but it gives you a powerful tool for ensuring tests are complete.&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://javasherpa.blogspot.com/feeds/248011228619036361/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasherpa.blogspot.com/2014/06/mockito-captors-and-verify-how-to-check.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/248011228619036361'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/248011228619036361'/><link rel='alternate' type='text/html' href='http://javasherpa.blogspot.com/2014/06/mockito-captors-and-verify-how-to-check.html' title='Mockito Captors and verify(): How to check objects created and verify method calls within a method'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/03357728230885603222</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4352584012687120995.post-8095471090590067475</id><published>2014-05-15T10:23:00.000-07:00</published><updated>2014-05-15T10:23:14.042-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Big Decimal"/><category scheme="http://www.blogger.com/atom/ns#" term="equals"/><category scheme="http://www.blogger.com/atom/ns#" term="java"/><category scheme="http://www.blogger.com/atom/ns#" term="PSC"/><title type='text'>BigDecimal and equals(); the hidden trap</title><content type='html'>On my last project we were using BigDecimal for calculations (you don&#39;t still use double, or god forbid float, do you?). Like a good programmer I created a helper function for doing the divide to do the checks for things like the numerator or denominator being null and for the denominator equal to 0.&lt;br /&gt;
You can imagine my surprise when we started getting divide by 0 errors in the app. I checked my unit tests (you do have unit tests for all your code, right?) and sure enough there was a test for divide by 0 so what gives?&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
&amp;nbsp; &amp;nbsp; public static BigDecimal divide(BigDecimal numerator, BigDecimal denominator) {&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; if (numerator == null || denominator == null || denominator.equals(BigDecimal.ZERO)) {&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return BigDecimal.ZERO;&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; }&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return numerator.divide(denominator, RoundingMode.HALF_UP);&lt;br /&gt;
&amp;nbsp; &amp;nbsp; }&lt;br /&gt;
&lt;/pre&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
Well, not only does BigDecimal keep more accurate calcs when you do things like divide two floating point numbers but it keeps track of something called precision. Now, for the non-technical out there, precision is used to determine how accurate a number is; let&#39;s look at pi to determine what we&#39;re talking about.&lt;br /&gt;
Since pi is infinite you need to cut it off somewhere for your calculation. For something that doesn&#39;t need to be accurate to a small degree (such as the area of a crop circle down to the square foot) you could just use 3 whereas the area of a machined screw may need to go all the way to 3.1415. In these cases the precision of pi for the crop area is 1 and the precision for the machine screw is 5. I won&#39;t get into the full definition of precision but as a rule the number of digits shown past the decimal point determine what the precision is for that number. So, if you have something like 5.25000 then the precision is 6 (5.25 makes 3 and the 3 0&#39;s make it 6).&lt;br /&gt;
Now, back to my issue above; I determined that I was checking the constant BigDecimal.ZERO (with a precision of 1) to an input value of 0.00 (a precision of 3) and was getting back a value of false for equals() (0 != 0.00). Problem.&lt;br /&gt;
Technically, these numbers aren&#39;t equal but logically I don&#39;t care about the extra precision stored in the second BigDecimal. So, whats a programmer to do? Well, if I were to compare these two numbers the extra precision isn&#39;t taken into account (0 is still 0 no matter how accurate you measure it) so if I were to change my equals to check to a compare to:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
&amp;nbsp; &amp;nbsp; public static BigDecimal divide(BigDecimal numerator, BigDecimal denominator) {&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; if (numerator == null || denominator == null || denominator.compareTo(BigDecimal.ZERO) == 0) {&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return BigDecimal.ZERO;&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; }&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return numerator.divide(denominator, RoundingMode.HALF_UP);&lt;br /&gt;
&amp;nbsp; &amp;nbsp; }&lt;br /&gt;
&lt;/pre&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
you can now check two numbers for logical equality and my issue of divide by 0 goes away. Now, if you&#39;re doing highly scientific calcs this won&#39;t work and equals is the better choice but if you&#39;re just checking to see if two numbers are the same (especially if you&#39;re comparing them to some kind of constant) then precision is more than likely going to get into the way so you compareTo() == 0 instead.</content><link rel='replies' type='application/atom+xml' href='http://javasherpa.blogspot.com/feeds/8095471090590067475/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasherpa.blogspot.com/2014/05/bigdecimal-and-equals-hidden-trap.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/8095471090590067475'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/8095471090590067475'/><link rel='alternate' type='text/html' href='http://javasherpa.blogspot.com/2014/05/bigdecimal-and-equals-hidden-trap.html' title='BigDecimal and equals(); the hidden trap'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/03357728230885603222</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4352584012687120995.post-4885703079532983614</id><published>2014-04-30T06:14:00.000-07:00</published><updated>2014-05-05T12:59:51.798-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="default method"/><category scheme="http://www.blogger.com/atom/ns#" term="interface"/><category scheme="http://www.blogger.com/atom/ns#" term="java"/><category scheme="http://www.blogger.com/atom/ns#" term="java 1.8"/><category scheme="http://www.blogger.com/atom/ns#" term="java 8"/><category scheme="http://www.blogger.com/atom/ns#" term="jdk"/><category scheme="http://www.blogger.com/atom/ns#" term="jdk 1.8"/><category scheme="http://www.blogger.com/atom/ns#" term="jdk 8"/><category scheme="http://www.blogger.com/atom/ns#" term="PSC"/><category scheme="http://www.blogger.com/atom/ns#" term="static method"/><title type='text'>Java 8 Overview: Default and Static Interface Methods</title><content type='html'>&lt;div&gt;
&lt;h2&gt;
Introduction&lt;/h2&gt;
With the release of Java 8 I thought a series of posts on the new features of Java 8 would be appropriate. Probably the simplest of the new concepts is the idea of default and static methods for interfaces. Basically, what you can now do is define a default set of functionality you want for a given interface. Before, you&#39;d have to define an interface and then immediately define an abstract class that implements the interface where you could put the default implementation (Swing event adapter classes anyone?) To use default methods you simply need to put the keyword default before the method signature and implement the method.&lt;br /&gt;
Another inclusion with Java 8 are static methods in interfaces. Like default methods, you can declare any number of static methods inside the interface as well.&lt;br /&gt;
&lt;h2&gt;
Example&lt;/h2&gt;
&lt;h3&gt;
Source&lt;/h3&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Main {
    public interface ContainsDefault {
        String greeting1();
        default String greeting2() {
            return &quot;My Second Greeting&quot;;
        }
        static String greeting3() {
            return &quot;My Third Greeting&quot;;
        }
    }

    public static class Override implements ContainsDefault {
        public String greeting1() {
            return &quot;Alternate Override1&quot;;
        }

        public String greeting2() {
            return &quot;Alternate Override2&quot;;
        }
    }

    public static class NoOverride implements ContainsDefault {
        public String greeting1() {
            return &quot;My First Greeting&quot;;
        }
    }

    public static void main(String[] args) {
        ContainsDefault noOverride = new NoOverride();
        ContainsDefault override = new Override();
        System.out.println(&quot;noOverride,greeting1: &quot; + noOverride.greeting1());
        System.out.println(&quot;noOverride,greeting2: &quot; + noOverride.greeting2());
        System.out.println(&quot;override,greeting1: &quot; + override.greeting1());
        System.out.println(&quot;override,greeting2: &quot; + override.greeting2());
        System.out.println(&quot;containsDefault,greeting3: &quot; + ContainsDefault.greeting3());
    }
}
&lt;/pre&gt;
&lt;h3&gt;
Results&lt;/h3&gt;
&lt;pre&gt;noOverride,greeting1: My First Greeting
noOverride,greeting2: My Second Greeting
override,greeting1: Alternate Override1
override,greeting2: Alternate Override2
containsDefault,greeting3: My Third Greeting
&lt;/pre&gt;
&lt;h2&gt;
Advantages&lt;/h2&gt;
This has a few advantages:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Less classes (you only need the interface, not that plus another abstract class with the default implementations, such as swing event adapter classes)&lt;/li&gt;
&lt;li&gt;Moving the default implementations to the interface allows classes that use it that need the default implementation to still extend from another class.&lt;/li&gt;
&lt;li&gt;You can now add new methods to existing interfaces and if you add a default method you won&#39;t need to go to each implementation to implement the method, where appropriate&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
Concerns&lt;/h2&gt;
&lt;/div&gt;
&lt;div&gt;
There are a few things you need to look out for when using default and static methods:&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;since there is a default implementation, implementing classes aren&#39;t required to implement the method at all so you should be careful with putting in defaults for methods that are central to the operation of your system&lt;/li&gt;
&lt;li&gt;You still cannot define variables, even if they&#39;re public (static and final variables are still OK; but since they&#39;re public the outside world can already access them anyway) so the usefulness of the methods are limited&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
Conclusion&lt;/h2&gt;
&lt;/div&gt;
&lt;div&gt;
While default methods can provide an easier path for setting up interfaces to make them more useful programmers need to be careful not to apply them indiscriminately. They can render default adapters, like the swing event adapters, irrelevant and free up classes to extend others instead of the adapter class; but they can also hide issues when used for core methods that don&#39;t really have a default. At the end of the day they&#39;re just another arrow in a programmer&#39;s quiver that, if used with skill, will make their programs more concise and understandable. &amp;nbsp;&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;/pre&gt;
</content><link rel='replies' type='application/atom+xml' href='http://javasherpa.blogspot.com/feeds/4885703079532983614/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasherpa.blogspot.com/2014/04/java-8-overview-default-and-static.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/4885703079532983614'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/4885703079532983614'/><link rel='alternate' type='text/html' href='http://javasherpa.blogspot.com/2014/04/java-8-overview-default-and-static.html' title='Java 8 Overview: Default and Static Interface Methods'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/03357728230885603222</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4352584012687120995.post-4898060572723415895</id><published>2012-06-05T11:32:00.000-07:00</published><updated>2014-05-05T13:00:11.237-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="java"/><category scheme="http://www.blogger.com/atom/ns#" term="maven"/><category scheme="http://www.blogger.com/atom/ns#" term="PSC"/><category scheme="http://www.blogger.com/atom/ns#" term="remote"/><title type='text'>Setting up and accessing a remote maven repository</title><content type='html'>Now that we&#39;ve reviewed the basics for maven it&#39;s time to explore one of the more common situations in a maven project, setting up and accessing a remote repository. For any team greater than one person (which I&#39;m guessing covers a slim portion of projects out there) and projects with more than a single executable (I&#39;m guessing there is one or two of these types out there) you&#39;ll need a place to build the building blocks for more advanced projects (such as a utility package or a database entity project).&lt;br /&gt;
&lt;h2&gt;
Creating a remote repository&lt;/h2&gt;
&lt;div&gt;
While many people will say finding a place to store your repository would be the first thing you should consider I say that is the second thing you should do, the first thing is decide how you want users to access the repository and how you want contributors to upload content to the repository. Do you want to make it available over http? Will you need to use the SCP protocol to upload content? Are all your machines the same (Windows vs Linux vs Mac) and only internal access is necessary so a file:// protocol would work? These all will make a difference where you put the repository. After these questions are answered you can pick a server that fits these parameters.
&lt;/div&gt;
&lt;h2&gt;
Adding a deployment destination to a project&lt;/h2&gt;
&lt;div&gt;
Now that you&#39;ve decided where to place your project you&#39;ll need a way to add it to your project. Deployment locations are handled in the &lt;span style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;distributionManagement&lt;/span&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&amp;nbsp;section of the pom file. It goes at the end of the file after the dependencies section and a sample distribution section appears below:&lt;/span&gt;&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&amp;lt;distributionManagement&amp;gt;
  &amp;lt;repository&amp;gt;
    &amp;lt;id&amp;gt;serverId&amp;lt;/id&amp;gt;
    &amp;lt;name&amp;gt;Example Upload Location&amp;lt;/name&amp;gt;
    &amp;lt;url&amp;gt;scp://server/srv/maven/repository&amp;lt;/url&amp;gt;
  &amp;lt;/repository&amp;gt;
&amp;lt;/distributionManagement&amp;gt;
&lt;/pre&gt;
&lt;div&gt;
Pretty simple right? &amp;nbsp;There are really two important parts of this snippet, first is the id of the server and second is the URL. The URL&#39;s significance should be obvious so I&#39;ll focus on the id field. The reason the id field is important is because that is the link between the pom file and this server setup and the personal field setup for this server in the settings.xml file. Depending on what type of URL you use, such as scp, you need additional information, like authentication and directory/file permissions, to perform the task so without further ado lets look at:
&lt;/div&gt;
&lt;h2&gt;
Settings.xml&lt;/h2&gt;
&lt;div&gt;
Up until now we haven&#39;t had to worry about maven&#39;s other configuration file as nearly all tasks handled through the pom file don&#39;t need any additional configuration. Technically, if you were to use a file protocol for the deployment you still wouldn&#39;t need to configure a server in settings.xml but I have yet to see a system that could use that effectively. While you can configure many different things, such as a proxy or different profiles, through the settings.xml file the only major one that most people will need to use is the servers section. However, if you want to to learn more about the settings.xml file you can do so &lt;a href=&quot;http://maven.apache.org/settings.html&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. The entire file isn&#39;t all that big so reviewing it is quick. For a final note about the settings.xml file is where to find it; the file is located in each user&#39;s home directory (on linux it would usually be at /home/&amp;lt;userName&amp;gt;/.m2 and in windows usually C:\Users\&amp;lt;userName&amp;gt;\.m2, your mileage may vary).&lt;/div&gt;
&lt;h3&gt;
servers&lt;/h3&gt;
&lt;div&gt;
The important part of the settings file for distribution management is the server section. In this section you can define personal information about connecting to various servers. In the pom file you define the URL (some would ask why this wouldn&#39;t also be here but you can use the same server for multiple functions so the URL needs to be in the pom for different setups) but the rest of the information is here in settings (I&#39;m guessing you may not want your user information broadcast to the rest of the world). A typical server setup looks like the following:&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&amp;lt;servers&amp;gt;
  &amp;lt;server&amp;gt;
    &amp;lt;id&amp;gt;serverId&amp;lt;/id&amp;gt;
    &amp;lt;username&amp;gt;my_login&amp;lt;/username&amp;gt;
    &amp;lt;password&amp;gt;my_password&amp;lt;/password&amp;gt;
    &amp;lt;privateKey&amp;gt;${user.home}/.ssh/id_dsa&amp;lt;/privateKey&amp;gt;
    &amp;lt;passphrase&amp;gt;some_passphrase&amp;lt;/passphrase&amp;gt;
    &amp;lt;filePermissions&amp;gt;664&amp;lt;/filePermissions&amp;gt;
    &amp;lt;directoryPermissions&amp;gt;775&amp;lt;/directoryPermissions&amp;gt;
  &amp;lt;/server&amp;gt;
&amp;lt;/servers&amp;gt;
&lt;/pre&gt;
&lt;div&gt;
First, if you go back up to our distributionManagement example you&#39;ll notice that the id fields match. That would tell maven to use the credential and permissions here when uploading content to the remote repository. You should either enter a password here or is private key/passphrase entry. You should not use both. The permissions are used for the directories and files created on the remote system. If you need an explanation on what the numbers mean you can search for unix file permissions or click &lt;a href=&quot;http://www.december.com/unix/tutor/permissions.html&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/div&gt;
&lt;h4&gt;
A quick bit on security&lt;/h4&gt;
&lt;div&gt;
Starting with Maven 2.1 you can encrypt your password so even if someone managed to get a hold of your settings file (I&#39;m assuming here that you don&#39;t give access to this to anyone other than yourself) they still couldn&#39;t see your password. Plus, administrators always get nervous when passwords are available in plane sight. If you want/need to encrypt your password I would just follow the instructions on the maven site to set it up &lt;a href=&quot;http://maven.apache.org/guides/mini/guide-encryption.html&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/div&gt;
&lt;h2&gt;
Adding a remote repository to a project&lt;/h2&gt;
&lt;div&gt;
There are a plethora of reasons you may need to add a repository to your project.&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Your company has a policy that prohibits downloading software packages directly from the web so you need to connect to a mirrored main repository inside the company&lt;/li&gt;
&lt;li&gt;You need to connect to a third party vendor for additional software packages&lt;/li&gt;
&lt;li&gt;You need to connect to an internal repository to use internal software APIs&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
Whatever the reason, there is a simple way to connect a maven project to one of these repositories. First, you need to add a repository to the &lt;span style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;repositories&lt;/span&gt; section of the pom (just before the dependencies section. The entry would look like the following:&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&amp;lt;repositories&amp;gt;
  &amp;lt;repository&amp;gt;
    &amp;lt;id&amp;gt;java.net.maven1&amp;lt;/id&amp;gt;
    &amp;lt;name&amp;gt;java.net&amp;lt;/name&amp;gt;
    &amp;lt;url&amp;gt;http://download.java.net/maven/2&amp;lt;/url&amp;gt;
   &amp;lt;/repository&amp;gt;
&amp;lt;/repositories&amp;gt;
&lt;/pre&gt;
Like the distribution management element above the name is just a name you want to see. For the id, it only matters if you need additional authentication information for the server you&#39;re connecting to. Since most access is over http and unauthenticated it usually doesn&#39;t matter. However, if you needed to lock down even the pull and ended up using something like scp then you&#39;d want to make sure the id matches a server defined in settings.xml (see above).</content><link rel='replies' type='application/atom+xml' href='http://javasherpa.blogspot.com/feeds/4898060572723415895/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasherpa.blogspot.com/2012/06/setting-up-and-accessing-remote-maven.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/4898060572723415895'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/4898060572723415895'/><link rel='alternate' type='text/html' href='http://javasherpa.blogspot.com/2012/06/setting-up-and-accessing-remote-maven.html' title='Setting up and accessing a remote maven repository'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/03357728230885603222</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4352584012687120995.post-672691856013498401</id><published>2012-05-10T07:24:00.001-07:00</published><updated>2014-05-05T13:00:26.308-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="basics"/><category scheme="http://www.blogger.com/atom/ns#" term="introduction"/><category scheme="http://www.blogger.com/atom/ns#" term="java"/><category scheme="http://www.blogger.com/atom/ns#" term="maven"/><category scheme="http://www.blogger.com/atom/ns#" term="PSC"/><title type='text'>Getting started with Maven</title><content type='html'>&lt;h2&gt;
What is Maven&lt;/h2&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
&lt;a href=&quot;http://maven.apache.org/&quot; target=&quot;_blank&quot;&gt;Maven&lt;/a&gt; is quickly becoming, if it isn&#39;t already, the most popular build tool for java projects. With plugins you can do pretty much anything but at its heart Maven is a project management tool that handles dependency management, building and testing a java project. By default it can handle all the default java project types, jar, war, ejb-jar and ear.
&lt;/div&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
The purpose of this article is to get familiar with the Maven setup so items like plugins and site development won&#39;t be covered here. There will be other articles that will cover those topics.&lt;/div&gt;
&lt;h2&gt;
Application Setup&lt;/h2&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
&quot;Installing&quot; Maven consists of &lt;a href=&quot;http://maven.apache.org/download.html&quot; target=&quot;_blank&quot;&gt;downloading&lt;/a&gt; the package from the Maven site and unzipping the contents into a directory. If you&#39;re using an IDE such as Netbeans, Intellij or Eclipse you can usually skip this step as they already have an install built into the IDE. The important file for command line execution is the mvn.bat (windows) or mvn (linux) file in the bin/ directory. This file starts the maven process. Additional instructions and specialty builds of Maven are available on the Maven download page.&lt;/div&gt;
&lt;h2&gt;
pom.xml&lt;/h2&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
Aside from the application install the only other required file for maven is the &lt;a href=&quot;http://maven.apache.org/pom.html&quot; target=&quot;_blank&quot;&gt;pom.xml&lt;/a&gt; file. The pom file is the basis for a specific Maven project (such as a jar or a war). The pom file also contains information about other projects this project depends on (dependencies) the version to be built and deployment information.&lt;/div&gt;
&lt;h3&gt;
Build information&lt;/h3&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
At the start of the pom file is information about the name, version and type of the artifact to build. This information is summed up in four elements:&lt;/div&gt;
&lt;ol style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
&lt;li&gt;groupId--this is like a package for your project, usually in the form com.&amp;lt;company name&amp;gt;.&amp;lt;group area&amp;gt; such as com.tigereye.examples&lt;/li&gt;
&lt;li&gt;artifactId--This is usually the name of the project&lt;/li&gt;
&lt;li&gt;version&lt;/li&gt;
&lt;li&gt;packaging--this tells Maven what type of artifact the project is. (Such as jar or war, it also tells maven how to package the artifact and any additional steps necessary for the specific project type)&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
Dependencies&lt;/h3&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
While not strictly required for a project only the most basic projects don&#39;t depend on external sources. Whether it&#39;s hibernate for database access, the JEE API files for building an enterprise applications or an internal utility package pretty much all but the most basic applications require some kind of external resource to function.&lt;/div&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
Personally, this is where I believe Maven proves its worth. When setting up your project you only need to define programs your program directly depends on. Maven handles pulling in all the dependencies that project depends on that you don&#39;t so you don&#39;t have to worry about it. Let&#39;s say that you need to use hibernate but you don&#39;t specifically need to use antlr, you just have to add the dependency for hibernate and Maven will pick up antlr when you need to use hibernate (such as building a war or an ear). This way, you can focus on what your project needs and not worry about the rest of the jars necessary to actually run, Maven will ensure you have everything you need when it comes time to use them.&lt;/div&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
The dependency section starts with a dependencies element with one or more dependency elements. The content of each of the dependency element is as follows:&lt;/div&gt;
&lt;ol style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
&lt;li&gt;groupId -- analogous to the groupId at the top of the file except this is the group id of the artifact you want to import&lt;/li&gt;
&lt;li&gt;artifactId -- like groupId, this is the artifact id of the artifact you want to use&lt;/li&gt;
&lt;li&gt;version -- the version of the artifact you want to use&lt;/li&gt;
&lt;li&gt;scope -- an optional attribute (defaults to compile) that has one of four values:&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;compile -- this package is necessary for compiling your code and all other steps&lt;/li&gt;
&lt;li&gt;runtime -- this package isn&#39;t directly referenced in the code but needed to properly run&lt;/li&gt;
&lt;li&gt;test -- this package is necessary for the testing tree but not necessary for running the main project (useful for packages like junit or testng)&lt;/li&gt;
&lt;li&gt;provided -- this package is necessary to compile the project but will be provided for running the application later (such as servlet-api when writing a web app since it&#39;s provided by the web container)&lt;/li&gt;
&lt;/ul&gt;
&lt;/ol&gt;
&lt;h3&gt;
Sample File&lt;/h3&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
Below is a sample of a very basic pom file.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&amp;lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&amp;gt;
  &amp;lt;modelVersion&amp;gt;4.0.0&amp;lt;/modelVersion&amp;gt;
  &amp;lt;groupId&amp;gt;com.psc.example&amp;lt;/groupId&amp;gt;
  &amp;lt;artifactId&amp;gt;jax-ws&amp;lt;/artifactId&amp;gt;
  &amp;lt;packaging&amp;gt;war&amp;lt;/packaging&amp;gt;
  &amp;lt;version&amp;gt;1.0-SNAPSHOT&amp;lt;/version&amp;gt;
  &amp;lt;name&amp;gt;jax-ws Maven Webapp&amp;lt;/name&amp;gt;
  &amp;lt;dependencies&amp;gt;
    &amp;lt;dependency&amp;gt;
      &amp;lt;groupId&amp;gt;javax.persistence&amp;lt;/groupId&amp;gt;
      &amp;lt;artifactId&amp;gt;jpa-api&amp;lt;/artifactId&amp;gt;
      &amp;lt;version&amp;gt;2.1&amp;lt;/version&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
      &amp;lt;groupId&amp;gt;org.hibernate&amp;lt;/groupId&amp;gt;
      &amp;lt;artifactId&amp;gt;hibernate-core&amp;lt;/artifactId&amp;gt;
      &amp;lt;version&amp;gt;3.6.7.Final&amp;lt;/version&amp;gt;
      &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
      &amp;lt;groupId&amp;gt;junit&amp;lt;/groupId&amp;gt;
      &amp;lt;artifactId&amp;gt;junit&amp;lt;/artifactId&amp;gt;
      &amp;lt;version&amp;gt;3.8.1&amp;lt;/version&amp;gt;
      &amp;lt;scope&amp;gt;test&amp;lt;/scope&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
      &amp;lt;groupId&amp;gt;com.sun.faces&amp;lt;/groupId&amp;gt;
      &amp;lt;artifactId&amp;gt;jsf-api&amp;lt;/artifactId&amp;gt;
      &amp;lt;version&amp;gt;2.1.1-b02&amp;lt;/version&amp;gt;
      &amp;lt;scope&amp;gt;provided&amp;lt;/scope&amp;gt;
    &amp;lt;/dependency&amp;gt;
  &amp;lt;/dependencies&amp;gt;
&amp;lt;/project&amp;gt;
&lt;/pre&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
The above sample is a basic web project. It uses JPA for its persistence which requires a compile time dependency with hibernate as the implementing persistence framework. Since we&#39;re using JPA in our code the hibernate dependency is specified as runtime (it won&#39;t appear on the compile classpath but it will be included in the WAR. We also have the JSF api package that is necessary for the presentation pages but that package is already a part of the container so we mark it as provided (it&#39;s used for compiling but won&#39;t be included in the WAR). Finally, for testing we need junit but we don&#39;t want it on the compile classpath or in the WAR so we mark it as test.&lt;/div&gt;
&lt;h2&gt;
Project Structure&lt;/h2&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
While you can override the folders for things like source if you want, unless there&#39;s a good reason it just makes good sense, not to mention a smaller pom file, to use the default directory layout for your project.&amp;nbsp;The &lt;a href=&quot;http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html&quot; target=&quot;_blank&quot;&gt;standard &lt;/a&gt;setup for files is as follows:&lt;/div&gt;
&lt;blockquote class=&quot;tr_bq&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;
&amp;lt;project directory&amp;gt;&lt;br /&gt;
&amp;nbsp; &amp;nbsp; src&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; main&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; java&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; resources&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; webapp (if your app is a web-app)&lt;br /&gt;
&amp;nbsp; &amp;nbsp; test&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; java&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; resources&lt;br /&gt;
&amp;nbsp; &amp;nbsp; pom.xml
&lt;/blockquote&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
If you aren&#39;t using your IDE to generate the project structure and you don&#39;t want to hand code the directory names you can execute the following maven script in the directory ABOVE the project directory:&lt;/div&gt;
&lt;blockquote class=&quot;tr_bq&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;
mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false&lt;/blockquote&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
Substitute groupId and artifactId with appropriate names for your project. After it finishes executing a directory matching your artifactId.&lt;/div&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
Once you start compiling classes and running tests one more directory will be created by maven for storing the compiled classes called target. This directory is at the same level as src and will have sub directories under it for the compiled classes, web content and test resources, just like src has.&lt;/div&gt;
&lt;h2&gt;
Execution&lt;/h2&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
Once you have the rest of the maven setup complete you&#39;ll need to be able to perform actions on your project. In maven speak an action is called a phase. Maven has a very rich set of &lt;a href=&quot;http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html&quot; target=&quot;_blank&quot;&gt;phases&lt;/a&gt; you can perform. In keeping with the theme of this article I&#39;m only going to go over the basic ones here to get you up and running but the linked site has all of them and examples of what they do and how to use them correctly.&lt;/div&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
The main phases you&#39;ll be needed for day-to-day use are:&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;compile -- This compiles all source java files and copies any resources to the target directory&lt;/li&gt;
&lt;li&gt;test -- runs all tests found in the system (if you add -DskipTests it will compile the tests but not run them or -Dmaven.test.skip=true to not even compile them. I&#39;m sure I don&#39;t need to tell you how dangerous this can be)&lt;/li&gt;
&lt;li&gt;package -- builds the output file (jar for standard projects, war, ear, ejb jars, etc. for other project types)&lt;/li&gt;
&lt;li&gt;install -- copies the package to your local maven repository.&lt;/li&gt;
&lt;/ul&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
One thing to note, each phase builds on the previous one so if you execute the package phase it will execute compile, test and any other defined phase before the package phase. This becomes important as you move down the phase chain since a failure in a previous phase will halt the execution.&amp;nbsp;&lt;/div&gt;
&lt;h2&gt;
Local Repository&lt;/h2&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
Finally, while not something&amp;nbsp;neophytes&amp;nbsp;to maven will care about knowing about your local repository will help understand some features of maven. The idea of your local repository is a place on your machine where dependent packages (both for your projects and for maven itself) can be stored so yo don&#39;t have to go out to the internet each time you need to check something. In fact, the first time you run maven and, in general, the first time you use a new package you&#39;ll most likely notice a slowdown in the&amp;nbsp;initial&amp;nbsp;phases as maven downloads updated or new dependencies. Under your home directory (Windows: C:\Users\&amp;lt;username&amp;gt; or linux: /home/&amp;lt;username&amp;gt;) is a .m2 directory. Under there is the repository. It&#39;s essentially a network of first group ids, then artifact ids and finally version number directories where jars, poms and additional information for maven &amp;nbsp;are stored for use by both maven and you projects. As a general rule (even for more advanced things) you shouldn&#39;t need to mess with this much other than occasionally removing entries.&lt;/div&gt;
&lt;h2&gt;
Conclusion&lt;/h2&gt;
&lt;div style=&quot;font-size: medium; font-weight: normal;&quot;&gt;
I can hear you now, &quot;but what about the settings.xml file?&quot;, &quot;what about plugins?&quot;, &quot;what about deployments?&quot; and any number of other things that maven can do. While I do agree that they&#39;re all important they really aren&#39;t necessary for getting started with maven and setting up an initial maven project. I&#39;m sure I&#39;ll be covering them in additional posts but if you don&#39;t have a good foundation then the rest will fall apart.&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://javasherpa.blogspot.com/feeds/672691856013498401/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasherpa.blogspot.com/2012/05/getting-started-with-maven.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/672691856013498401'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/672691856013498401'/><link rel='alternate' type='text/html' href='http://javasherpa.blogspot.com/2012/05/getting-started-with-maven.html' title='Getting started with Maven'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/03357728230885603222</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4352584012687120995.post-8876202860487399670</id><published>2012-03-26T08:35:00.000-07:00</published><updated>2014-05-05T13:00:51.007-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="j2ee"/><category scheme="http://www.blogger.com/atom/ns#" term="java"/><category scheme="http://www.blogger.com/atom/ns#" term="jee"/><category scheme="http://www.blogger.com/atom/ns#" term="jsp"/><category scheme="http://www.blogger.com/atom/ns#" term="overivew"/><category scheme="http://www.blogger.com/atom/ns#" term="PSC"/><category scheme="http://www.blogger.com/atom/ns#" term="servlet"/><category scheme="http://www.blogger.com/atom/ns#" term="web container"/><title type='text'>The Web Container in a nutshell</title><content type='html'>&lt;br /&gt;
&lt;h2&gt;

General Overview&lt;/h2&gt;
This topic is a discussion of the general JEE web container
components. While useful, this isn&#39;t a discussion of any of the
frameworks built upon the JEE web container such as struts, JSF,
Spring MVC or others. Each of these frameworks have their own sites
with a plethora of examples and other information. Each of the
following sections contain a component or piece of the web container
setup. This paper also does not get into other Enterprise components
such as JMS or EJB, although there are ways for the web container to
use these components and those places will be mentioned.&lt;br /&gt;
&lt;h2 class=&quot;western&quot;&gt;

Web Contexts&lt;/h2&gt;
There are 4 different contexts in the web container, in
parentheses would be their object variable equivelant:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Application (static)&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;Session (class)&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;Request (method) 
 &lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;Page (Only applicable on the JSP) (sub-method)&lt;/li&gt;
&lt;/ul&gt;
Application scoped variables are available to every web piece.
They&#39;re available within a given servlet/jsp request, they&#39;re
available to the session and any setup for a servlet, listener,
filter or any other web component, just like static properties are
available to any method in a class and all instances all can see the
same static parameter. Just like static variables, any change to an
application scoped variable will be seen by the rest of the
application.&lt;br /&gt;
Session scoped variables are tied to a specific user that span
multiple requests. This would be like creating a configuration object
in a general project to store information about a specific process
for the length of the process. Any sub process that originates from
this process will get the same data in this configuration object.
Once the process is done the object is discarded, just like a session
when a user leaves the system (or a timeout occurs before the nest
request from a specific user).&lt;br /&gt;
Request scoped variables are tied to a specific request on the
server. The parameters only live for the length of the request and
are reset with the next request. In object speak these would be just
like parameters created within a request. Variables within request
don&#39;t require a visibility modifier (such as public) because once the
method is done the variables are cleaned up and rest for the next
request.&lt;br /&gt;
Page scope is a special case of the request scope used only for
JSPs. Many custom tags will create properties and, in most cases,
store them in the page scope for use on that specific page. If you
were to be redirected to another page (an extremely unlikely thing
but still possible) these variables are wiped clean which makes this
scope a perfect place to store this temporary information.&lt;br /&gt;
&lt;h2 class=&quot;western&quot;&gt;

Servlets&lt;/h2&gt;
Servlets are the primary way to execute logic in a web
application. While you do have direct access to the output stream
that is returned to the client it is generally considered proper form
for the servlet to execute the logic (such as accessing a database,
interacting with a web service or an EJB), set parameters in one of
the web contexts and then forward to a JSP to implement the actual
rendering logic. One usual deviation from this would be if you have
to return some kind of non-viewable content (such as an excel, PDF or
other file) for the user to save outside the HTML viewing process.&lt;br /&gt;
You can chain servlets together using the
HttpServletRequest.forward() and the
HttpServletResponse.sendRedirect() to chain logic (or, generally
using the former) to use a JSP to render the result back to the user.
One thing to note on the sendRedirect() method, it sends a response
back to the browser and tells the browser to go to the page so any
request variables that were set will be reset when accessing the
redirected resource. Usually, instead of directly chaining servlets,
filters would be used. These components are covered in a later
section.&lt;br /&gt;
&lt;h2 class=&quot;western&quot;&gt;

JSP&lt;/h2&gt;
JSPs are actually special servlets that are intended to just
render content for the user. The web server will actually compile the
JSP on the back-end into a servlet for quicker access. They&#39;re
intended to be very light weight and just take properties set in a
servlet and render them to the user. 
&lt;br /&gt;
&lt;h3 class=&quot;western&quot;&gt;

Scriptlets&lt;/h3&gt;
Scriptlets are defined as anything between &amp;lt;% and %&amp;gt;.
Everything between the braces must be valid java. A special cased
where the output is rendered directly to the screen is the &amp;lt;%= %&amp;gt;.
Whatever is between the braces is evaluated and the result is
rendered to the screen, you shouldn&#39;t put a semi-colon at the end of
this expression.  In general a mature project should not use these as
they&#39;re generally reserved for lightweight projects that don&#39;t use
servlets at all. If you find yourself using scriptlets you most
likely should be doing more work in the servlet or creating a custom
tag to keep from cluttering the page.&lt;br /&gt;
&lt;h3 class=&quot;western&quot;&gt;

Expression Language&lt;/h3&gt;
JSPs have their own expression language for quick and easy access
to scoped variables. The format of the expression is ${..} where the
first word inside the braces is a variable name in a scope. After the
variable name you can access properties based on dot notation. So, if
you had an expression like the following ${foo.bar} the jsp would
look in the all the contexts (more on the order in a minute) for a
property called &#39;foo&#39;, and once it finds the object it will try to
access the property getBar() (or isBar() if the property is a&amp;nbsp;Boolean). You can chain this down to
any level you wish, as long as the chain is valid. You can also
access indexed or mapped properties using brackets so an expression
like the following: ${foo[0].bar} would try to find a list in a
context called foo, retrieve the first element and access the bar
property of that object. As a convenience for a map property you can
use the dot notation to access a entry of the map so ${foo.bar} would
be the same as ${foo[&#39;bar&#39;]} if &#39;foo&#39; is a map.&lt;br /&gt;
&lt;h3 class=&quot;western&quot;&gt;

Tag Libraries&lt;/h3&gt;
Tag libraries are self contained pieces of rendering logic that
an be accessed just like any other tag. There are standard tag
libraries (generally called JSTL) and nearly every framework has a
set of tag libraries for use with the framework. You define them at
the top of the JSP file using the format &amp;lt;%@ taglib uri=”uri”
prefix=”x”&amp;gt;. With the preceding tag declaration to use the
taglib you&#39;d start your tags with &amp;lt;x:....&amp;gt; where the colon is
followed by the tag definition. Think of a definition as a method
call to render some kind of element. Now, there are standard tag
libraries for things like database connections but most mature
projects won&#39;t use them as they&#39;re targeted at stand alone JSPs. The
most common tag libraries used are core as &amp;lt;%@ taglib prefix=&quot;c&quot;
uri=&quot;http://java.sun.com/jstl/core&quot; %&amp;gt; and format as &amp;lt;%@
taglib prefix=&quot;f&quot; uri=&quot;http://java.sun.com/jstl/fmt&quot;
%&amp;gt;. There are additional tag libraries like sql and xml but most
of these are covered by a framework.&lt;br /&gt;
&lt;h3 class=&quot;western&quot;&gt;

Custom Tag libraries&lt;/h3&gt;
If the standard tag libraries and your framework&#39;s tag libraries
aren&#39;t sufficient for your needs you can roll your own tag library.
To do this you create an XML file called &amp;lt;name&amp;gt;.tld and place
it in your WEB-INF/tld directory. The XML file has to implement the
&lt;a href=&quot;http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd&quot;&gt;http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd&lt;/a&gt;
schema. You can view a tutorial on Oracle&#39;s site for exactly how to
write a TLD but essentially there are two types of tags:&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Static function calls you want to expose in your application
 to the JSPs. These are defined using the &amp;lt;function&amp;gt; tag with
 the function-class and function-signature elements&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;The &amp;lt;tag&amp;gt; class to define the traditional tag setup
 where you define the tag class with tag-class and body-content to
 define how to handle sub tags or sub html elements.&lt;br /&gt;

&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 class=&quot;western&quot;&gt;

Filters&lt;/h2&gt;
Filters are a command pattern for usage with Servlets. Filters
can operate before the servlet call on the request and after the
servlet call on the response. For the request side they can be useful
for things like verifying a user has logged in (assuming you aren&#39;t
using container managed security defined below) and forwarding to a
login page before secured sections of the app. You can also perform
actions like retrieving necessary information or instantiating
objects needed by the servlet (such as data access objects or common
lookups) since filters can be shared across multiple servlets. On the
outbound side they&#39;re useful for things like encrypting output when
necessary any other cleanup tasks necessary after a servlet is done
executing its tasks.&lt;br /&gt;
&lt;h2 class=&quot;western&quot;&gt;

Listeners&lt;/h2&gt;
There are two different kind of listeners in a standard web
application:&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;SessionListeners&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;ApplicationContextListeners&lt;/li&gt;
&lt;/ol&gt;
Both listeners are essentially the same thing but targeted at
different levels of the web container. They both have two methods to
implement, one for when an object is created and one for when that
object is destroyed.&lt;br /&gt;
For the Session listener it&#39;s targeted (not surprisingly) at when
each session is created or destroyed. While not extreemly useful, it
can be used to track when a particular user has logged in (which can
also be done through a filter for each request) or useage statistics.
When sessions are destroyed you could go through the session and
serialize items for retrieval upon re-creation or closing resources
that were stored in the session but these are generally fringe cases.&lt;br /&gt;
The application context listener is called twice during the life
of a web app, once when the application starts up and once when it
shuts down. In it, you can run anything that you need to manually set
up or tear down. 
&lt;br /&gt;
One thing to note about both these listeners, tread lightly on
the closing of resources when things stop. While you&#39;re guaranteed to
see things start up the app could crash and the shutdown methods may
not be called (a general problem anyway but something to remember)&lt;br /&gt;
&lt;h2 class=&quot;western&quot;&gt;

WAR packaging and web.xml&lt;/h2&gt;
The WAR file is a standard JAR file with a .war extension that
can be decompressed and used by an application server.&lt;br /&gt;
The web.xml file is the configuation file for a web application.
In this file you define all listeners, servlets, servlet mappings and
all other less common web application components. As you&#39;ll see
below, it&#39;s located under the WEB-INF directory and is required to
deploy a web application.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0ScQweazAn6l_3FMtRxiD2BCazr_yxTrfpRxusSHzpjjk6nnvjsSb37TxtorQs63vs4FJHzqsOegKOcEk2ftkwNbYB9c1dM8eOoJ64ASBieznlE8tqf5i1TVyPfE4ZDOlFnyYA8wJIQAT/s1600/WAR+Directory+Structure.PNG&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0ScQweazAn6l_3FMtRxiD2BCazr_yxTrfpRxusSHzpjjk6nnvjsSb37TxtorQs63vs4FJHzqsOegKOcEk2ftkwNbYB9c1dM8eOoJ64ASBieznlE8tqf5i1TVyPfE4ZDOlFnyYA8wJIQAT/s1600/WAR+Directory+Structure.PNG&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
Directory layout&lt;br /&gt;
/ (all jsps go at this level for standard access through the
browser)&lt;br /&gt;
/WEB-INF (in here you put any other configuration file (other
than classes and jars) 
&lt;br /&gt;
/web.xml&lt;br /&gt;
/classes (all classes for the web app go here)&lt;br /&gt;
/lib (any dependent libraries for your web ap)&lt;br /&gt;
/scripts (standard but configurable location for javascript
files)&lt;br /&gt;
/images (standard but configurable location for images)&lt;br /&gt;
&lt;h2 class=&quot;western&quot;&gt;

Security&lt;/h2&gt;
While there is no standard way for an application server to set
up security there are standard ways to interact and set up restricted
access in the web app. There are two prominent ways to deal with
security. Neither way is definitively better than the other and they
can easily be used together.&lt;br /&gt;
The first way is declarative through the web.xml config file
using the &amp;lt;security-constraint&amp;gt; tag. Inside this tag you define
what url patterns you want to secure (they can be hard paths
referenced by a jsp or virtual paths defined in a servlet mapping)
and the roles necessary to access these resources. When a request is
made the server will check if the request has an authenticated user
and if not then redirect them to a login page for authentication.
Once authenticated, it will check the roles assigned to that user to
see if one matches what is necessary to access the page. Both the
page and the user can have multiple roles and only one matching role
is necessary. If no roles match then a forbidden page (403) is
returned to the user.&lt;br /&gt;
The other authentication mechanism is progromatic security (which
relies on the user being authenticated on the system). There are two
methods on the HttpServletRequest object that deal with
authentication:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;getUserPrinciple()&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;isUserInRole(String)&lt;br /&gt;

&lt;/li&gt;
&lt;/ul&gt;
getUserPrinciple() returns a UserPrinciple object if the user is
logged in with information about the logged in user, otherwise it&#39;s
null. The isUserInRole takes in a role as a string and returns true
if the user has that role. These are available in both the servlet
and on jsp pages to conditionally render JSP elements or conditional
business logic on the server.&lt;br /&gt;
&lt;h2 class=&quot;western&quot;&gt;

Resources&lt;/h2&gt;
&lt;h3 class=&quot;western&quot;&gt;

Resource-ref&lt;/h3&gt;
Resource-ref is used to define connection factories for
enterprise components. Some of the standard enterprise factories are:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;DataSource&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;QueueConnectionFactory&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;TopicConnectionFactory&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;Session (for JavaMail)&lt;br /&gt;

&lt;/li&gt;
&lt;/ul&gt;
The declaration includes a JNDI location where to find the
resource.&lt;br /&gt;
&lt;h3 class=&quot;western&quot;&gt;

Env-entry&lt;/h3&gt;
The env-entry tag is used to define a property (similar to a jvm
property) for use by the web application. The following types are
possible:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;java.lang.Boolean&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;java.lang.Byte&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;java.lang.Character&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;java.lang.Double&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;java.lang.Float&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;java.lang.Integer&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;java.lang.Long&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;java.lang.Short&lt;br /&gt;

 &lt;/li&gt;
&lt;li&gt;java.lang.String&lt;br /&gt;

&lt;/li&gt;
&lt;/ul&gt;
These properties are useful for values that change based on the
environment. One example would be if you have to store report files
you can make the directory where they&#39;re stored an environment
property so you can put the same WAR file in each environment and
update the environment value on the server.</content><link rel='replies' type='application/atom+xml' href='http://javasherpa.blogspot.com/feeds/8876202860487399670/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javasherpa.blogspot.com/2012/03/web-container-in-nutshell.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/8876202860487399670'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4352584012687120995/posts/default/8876202860487399670'/><link rel='alternate' type='text/html' href='http://javasherpa.blogspot.com/2012/03/web-container-in-nutshell.html' title='The Web Container in a nutshell'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/03357728230885603222</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0ScQweazAn6l_3FMtRxiD2BCazr_yxTrfpRxusSHzpjjk6nnvjsSb37TxtorQs63vs4FJHzqsOegKOcEk2ftkwNbYB9c1dM8eOoJ64ASBieznlE8tqf5i1TVyPfE4ZDOlFnyYA8wJIQAT/s72-c/WAR+Directory+Structure.PNG" height="72" width="72"/><thr:total>0</thr:total></entry></feed>