My First Month in the Java Training Business – Learning Which End Is Up

As of today it’s been 28 days, a lunar month, working part time on my Java training business.

Preview of Professional Java Level One - The Basics

Preview of Professional Java Level One – The Basics

I realize that as a business I’m probably not supposed to admit that this is my first month, but maybe sometime in 2018 you can look at this post and check the date and say to yourself, oh heck, he’s been doing this for three years now — maybe he knows something by this point.

So far it’s been a steady but slow start, with some good newcomer mistakes that I will look back and laugh at if I myself should read this post three years from now, things like talking into the wrong end of the microphone.

Doh!  Who knew that microphones had “ends”?

So I managed to get lousy audio quality out of my first few videos, until I discovered that the high-quality AT-2020 that I bought a couple of years ago and forgot about is a “side-address” microphone, meaning you shouldn’t talk into the top of it as though you’re making a karaoke commercial — you look for the side that has the audio-technica logo on it, that is to say, the side that is the front.  So you see, the side is of the microphone is actually the front, but only one side is, not the other side.  Now you understand my confusion.

Of course audio-technica wants everyone to write about their brand, and you can’t blame them for that, but a better stamp on the front in terms of usability would have been something like “talk here, dummy”, or the more friendly version, “talk here”.

Anyway, for all that I still have the first 25:31 (twenty-five minutes, thirty-one seconds) of video put together on Udemy — and this is 25:31 speaking into the right side of the microphone, too.  This is thanks to the good folks at Udemy who ask you to submit a test video, and then revealed to me the echo that has since disappeared. “Talk here”.

The image shows how the content so far looks on their site — it’s not published yet but coming soon.

And as for 25:31, I’m hoping to increase that velocity substantially next month.  That should be easy to do now that I which side of the microphone is the front.

Posted in Java Training Online

Getting Started with Git and Github (Video)

As a software developer who taught himself to program many years ago and as a Java trainer, I’m very interested in the path that newcomers to Java — or to any language — take to get into the industry. When I was new and learning C++ and Windows, Github didn’t exist, and the Internet itself was in its infancy. Without a software engineering degree and with only my 25,000 lines of C and C++ code to show for my skills, there was not much to do except to reference those 25,000 lines and whatever else I thought I knew on a resume and even to carry around yellow floppy drives with my code on them to interviews with me.

It took me 3 years of learning and lugging around my little “Sneakernet portfolio”, but eventually this paid off into some real software development jobs, and nowadays my skills and job history are such that I no longer have to beg the industry to do business with me.  Nowadays, of course, the equivalent of my yellow floppies would be a Github account. There’s even an interesting debate going on about whether your Github account is really your resume.   Of course, for for those of you who’ve been too heads down learning your language of choice to get such a thing set up yet, you’re probably more concerned about getting some sort of demo of your code set up, much as I was when I was lugging my floppy disks around.

So here’s a short video that shows you the fastest way to get a Github account set up on Windows.  Just add your own coding practice to a repository on Git, add the link to your resume, and happy job hunting!  And let us never speak of those yellow floppies again.

Posted in Miscellaneous

Java Career Training

When I began putting together Java training courses, I thought about what training opportunities were out there in the market already, and naturally I began to reflect on how I began my own programming career some twenty-four years ago, and some of the successes I’ve had since then. I also thought about programmers I’d interviewed through the years and the things my colleagues and I talked about after the programming interview to decide if the candidate was a good fit or not.

One of the things that I realized almost immediately is that the benefits the schools were trying to sell (such as being a “Certified Programmer”) were not bad things in their own right, but they might not be the quickest way for you to reach your goal. A certificate is not a bad thing to get. Depending on the provider it means you learned something, or sat through a course, or passed a test, and that person certifies (states that it’s true) that you’re a programmer. But in all the interviews I’ve ever been in, on both sides of the table, being certified was far less important than having some kind of experience.

The Road to Experience

Now at this point you may be thinking, “Well, that’s great for you to say because you’ve been doing this for twenty-four years, but look, I don’t have any experience
as a programmer.”

So if experience is the most important thing you can bring to the interview, and you don’t have experience, what do you need to do? You need to give yourself the experience. How do you do that? Well, you do it by programming. You learned to walk by crawling and pulling yourself up on the edge of a couch and falling down, and before you know it your poor tired mom was chasing you all over the place and complaining to her friends that you had too much energy.

Did the fastest professional athlete you can think of learn to walk the same way you did? Sure they did. Now, did they get to be professionals athletes by becoming “Certified Athletes?” Of course not, in athletics the very idea sounds ridiculous. Professional athletes get to be professional athletes by first becoming great amateur athletes, and they get to be great amateur athletes by practicing a lot. They want it, and they have coaches who help and push and encourage them, and above all they practice a lot.

My first few programming resume had a line on it that went something like this:

“Undertook a course of self study in C and C++ consisting of 25,000 lines of sample applications.”

Was I a professional programmer at that point? Not yet. But I could bring code samples to an interview. It took me three years of self study, while holding down a full time job and starting a family. But every day I practiced a bit, reading books like “C: Step by Step” during lunch and writing a few more sample applications in the morning or evening to add to my “line count”.

Flattening the Learning Curve

As a professional programmer with twenty-four years of experience, I wanted to share what I’d learned over the years. Most of all, I wanted to help professionals begin (or upgrade) their programming career in the fastest, most time-effective way possible. This is why I began working on a course of study that was focused on building practical skills and techniques that would help you become a better programmer — faster. In addition to core Java skills, I also wanted to teach you how to use many of the related tools that:

  1. Show up all the time on job descriptions (because they’re what real Java programmers use every day on the job).
  2. You can use to build and deploy a portfolio that point to in order to help you actually land a job.

Above all I wanted my students to graduate from my courses with a portfolio of relevant work, not a certificate. There are enough people out there who’ll sell you a Java certificate, and it’s not that you won’t learn something along the way, but I wanted the focus of my company to be on using professional tools in a professional context.

I know how important career development is — for me it meant being able to finally pay off those student loans, get myself out of debt, and lead a comfortable existence. While other students are saying “Here’s my certificate”, I want the students who trust me to be a part of that process to be able to sit across from their interviewer and say: “Here, click on this URL, it’ll bring you to the web site I developed using Java and Spring. This is running on Amazon EC2. It’s still a work in progress but it shows some basic principles. And here’s a link to the code on Github and some other code I’ve been working on.”

I’ve been on those interviews, on the side worrying about whether I’d get the job as well as on the side making the decision about someone else.

It’s always the one with the code who gets hired.

Posted in Java Training Online

Java Beginner Tutorial – Downloading and Installing Tools for Java Development

This video tutorial for beginners in Java shows you how to install and configure the tools you’ll need to get started in Java development. You’ll download a Java Development Kit, JDK, version 7, and the free community edition of IntelliJ Idea. The total time for this tutorial is 15 minutes.

Posted in Java Beginners Tagged with: , , ,

Using TestNG with Spring


Moving to TestNG From JUnit

A few weeks ago I published a Simple Introduction to Spring Unit testing using JUnit. We’ve been using JUnit quite a bit in our examples so far, but as some of you may already know, JUnit is not the only unit test framework for Java. Another framework, TestNG, offers a lot of features that JUnit lacks, such as the ability to run parameterized tests in which a given test is run against an array of different values, and the ability to break tests down into categories coupled with fine-grained configuration control over what tests to run. Indeed, the author of TestNG (“Next Generation”) very much had the limitations of JUnit in mind in writing the new framework. You can read about some of the problems with JUnit that TestNG was designed to solve on it the TestNG web site.

Of course, the choice of which technology to use is often a matter not of what’s best, but what’s most popular (especially if you’re early in your career and need to get certain key technologies added to your resume). So for my wife, who’s just beginning her technical career as a tester, I’d be inclined to recommend JUnit, whereas for myself, old fart programmer that I am, I have the luxury of picking the technology I consider better in many cases. For example, compared to IntelliJ Idea, for me Eclipse is just too painful — free or not, big market share or not. So I use IntelliJ. So if you’re playing “Dice Keyword Bingo”, stick with JUnit, otherwise do yourself a favor and take a look at TestNG. </My two cents>

Setting up the Maven Dependency for TestNG

Rather than repeat all the sample bean code from our original JUnit article, let’s focus here on the tests. The original sample code is, after all, not very interesting — it only gave us something to test. To migrate the JUnit sample, the first thing I needed to do was change the dependency section in our POM file slightly. Remove the JUnit dependency:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.8.2</version>
  <scope>test</scope>
</dependency>

Now add the dependency for TestNG:

<dependency>
  <groupId>org.testng</groupId>
  <artifactId>testng</artifactId>
  <version>6.1.1</version>
  <scope>test</scope>
</dependency>

For the benefit of those of you starting from scratch, the here is the full POM file.

Simple AbstractTestNGSpringContextTests Test Examples

Next, let’s see what we need to do to use Spring’s basic TestNG testing support class, AbstractTestNGSpringContextTests. Don’t let the “Abstract” in the name scare you off here, there’s really nothing much to implement. All you need to do is add a ContextConfiguration annotation to your class and it just works. Here’s the Hello-World-simple example, which only uses the ContextConfiguration annotation to get it to compile and run.

package com.codesolid.tutorials.tests;

import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.Test;

import static org.testng.Assert.assertTrue;

@ContextConfiguration("file:src/main/resources/spring-config.xml")
public class SimpleTest extends AbstractTestNGSpringContextTests {

    @Test
    public void SomeTest() {
        assertTrue(true);
    }
}

Modifying our JUnit tests to work with TestNG was just as easy. The @RunWith annotation was no longer needed, being replaced by the fact that we’re extending AbstractTestNGSpringContextTexts. So pretty much the only migration we did involved changing JUnit imports to TestNG ones. We removed:

import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

We replaced it with:

import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

Here for example is a little bit longer example, that exercises some of the test beans we’ve wired up in our application context:

package com.codesolid.tutorials.tests;

// Generally needed:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

// Application specific
import com.codesolid.tutorials.UserStory;
import com.codesolid.tutorials.User;

@ContextConfiguration("file:src/main/resources/spring-config.xml")
public class ContextTests extends AbstractTestNGSpringContextTests {

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    protected ApplicationContext ac;

    // Using ApplicationContext
    // The getBean method is the workhorse of the Spring ApplicationContext.
    // The user field in the UserStory object was set up (dependency injected)
    // by Spring:
    @Test
    public void testUserNotNull() {
        UserStory story = (UserStory) ac.getBean("userStory");
        assertNotNull(story.getUser());
    }

    // Not using ApplicationContext
    // Regular non-Spring instantiation
    // Instantiating our own UserStory, you can see that the user
    // is null.
    @Test
    public void testUserStoryNotFromContext() {
        UserStory story = new UserStory();
        assertNull(story.getUser());
    }

    // Not using ApplicationContext
    // Regular non-Spring instantiation
    // The default role if you just call the constructor
    // is "User".
    @Test
    public void testNonSpringUserDefaultRole()
    {
        User u = new User();
        assertEquals(u.getRole(), "User");
    }

    // Using ApplicationContext
    // Since Spring instantiated this according to the property
    // from spring-config.xml, it overrode the default "user"
    // role with "SuperGenius User".  (This presumably
    // is Wile E. Coyote.)
    @Test
    public void testUserRoleIsAsExpected() {
        UserStory story = (UserStory) ac.getBean("userStory");
        assertEquals(story.getUser().getRole(), "SuperGenius User");
    }
}

Getting started using the Spring TestNG support turned out to be really easy. Check our our IntelliJ project and the full source on GitHub.

Posted in Testing, JUnit, TestNG Tutorials Tagged with: , , , ,

Spring Security – Part I: Spring Authentication and Authorization Basics


My Scandalous Confession

Before we begin with the tutorial, I am going to lay bare my soul to you. I know, most tutorials are dry and boring, and don’t include such titillating and scandalous gossip as you are about to hear. You’re welcome.

Whenever I write an article that has Part 1 in the title, I generally am doing so without even a remote business plan for a clue about how many parts I’m going to end up with. There, I’ve made my confession. Eat your heart out, St. Augustine.

In this tutorial we’re going to start digging into Spring Security in the easiest way I know how. First, spend $199 on a great Java IDE, or download it free for thirty days so you can get through however many parts this article ends up having. We’re using IntelliJ 12 Ultimate Edition to generate a starter project for this article in the next section. The cool thing is, though, once you have the starter project, you can likely follow along with the rest of the article using either the IntelliJ Idea 11 or 12 Community Edition, which is free. I’ve had good luck doing that. You can even import the POM file into Eclipse and run the project that way.

Generating a Spring Security Project

With Idea Ultimate Edition Version 12 and later, to create a Spring Security Project you simply select create a new project from the Welcome Screen:

IntelliJCreateNewProject

Next, select Spring Security and give your project a name:

SpringSecurityCreateProject


The Security Configuration Files

In the Spring security starter project, IntelliJ adds the security-related configuration to the two required places, web.xml, and the main Spring configuration file, both of which are in src\webapp\WEB-INF\.

In web.xml, we first set up a security filter name, then use that name to defining a mapping to ensure that all application URLs go through the security filter first:

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Next we turn to the main Spring configuration file, spring-config.xml, which is shown in abbreviated form below:

    <security:global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled" secured-annotations="enabled" />

    <security:http use-expressions="true">
        <security:intercept-url pattern="/**" access="permitAll" />
        <security:form-login />
        <security:logout logout-success-url="/" delete-cookies="JSESSIONID"/>
        <security:remember-me />
        <security:session-management invalid-session-url="/">
            <security:concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
        </security:session-management>
    </security:http>

    <bean id="encoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder"/>

    <security:authentication-manager>
        <security:authentication-provider>
            <security:password-encoder ref="encoder"/>
            <security:user-service>
                <!-- Password: "koala" for both -->
                <security:user name="user"
                      password="4efe081594ce25ee4efd9f7067f7f678a347bccf2de201f3adf2a3eb544850b465b4e51cdc3fcdde"
                      authorities="user"/>
                <security:user name="admin"
                      password="4efe081594ce25ee4efd9f7067f7f678a347bccf2de201f3adf2a3eb544850b465b4e51cdc3fcdde"
                      authorities="admin"/>
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>

First, we see a line enabling JSR-250 annotations, such as @RolesAllowed, @PermitAll, @DenyAll, which allows fine-grained, method level access control. Furthermore, the ‘use-expressions=”true”‘ clause allows us to use Spring Expression Language style security expressions in our view layer. We’ll be looking at what that allows us to do a bit further on when we discuss the view layer.

Next, the attributes ‘pre-post-annotations=”enabled”‘ and ‘secured-annotations=”enabled”‘ will be used by our controllers. These configuration elements enable a feature that is new as of Spring 3.0. Spring 3.0 introduced several new, method-level annotations beginning with @Pre and @Post. We see one of these, @PreAuthorize, used in both the UserService class and the ApplicationController classes:

    // In UserService.java:
    @PreAuthorize("hasRole('admin')")
    public Collection<? extends GrantedAuthority> getAuthorities(UserDetails userDetails) {
        return userDetails.getAuthorities();
    }

    // In ApplicationController.java:
    @PreAuthorize("hasRole('admin')")
    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    public String admin(ModelMap map) {
        UserDetails userDetails =
                (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Collection<? extends GrantedAuthority> securedMessage = userService.getAuthorities(userDetails);
        map.addAttribute("userDetails", userDetails);
        map.addAttribute("userAuthorities", securedMessage);
        return "admin";
    }

In the next section of the configuration, we see a setting that is probably worth giving some thought to before you move an application into production:

  <security:http use-expressions="true">
        <security:intercept-url pattern="/**" access="permitAll" />
        ...
   </security:http>

The demo app takes the unusual approach of allowing access by default, and allowing it for certain roles. Generally it’s considered a best practice for secure applications to deny access by default, then turn it on selectively — that way when you forget a setting somewhere, you err on the side of more security, not less.

Spring’s StandardPasswordEncoder

In the next two sections of spring-config.xml, we set the password encoder our application will use to the StandardPasswordEncoder, then we configure two users with passwords generated by that encoder:

...
<security:user-service>
    <!-- Password: "koala" for both -->
    <security:user name="user"
         password="4efe081594ce25ee4efd9f7067f7f678a347bccf2de201f3adf2a3eb544850b465b4e51cdc3fcdde"
         authorities="user"/>
    <security:user name="admin"
         password="4efe081594ce25ee4efd9f7067f7f678a347bccf2de201f3adf2a3eb544850b465b4e51cdc3fcdde"
         authorities="admin"/>
</security:user-service>
...

The StandardPasswordEncoder is a small and quite nicely designed class that bundles everything you want a password encoder to do into a very small interface. It uses an SHA-256 hasing together with an eight byte random salt to generate a password hash that is unique each time. Although the starter application does not show this, for additional security you can add an extra secret value for your application, in which case the hash will be based on the password, the random salt, and the secret value. This is configured using basic constructor injection:

<bean id="encoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder">
  <constructor-arg value="x9ajDR$#Qkr91">
</bean>

Getting back to the application configuration, we see that the application is configured with two users, “user” and “admin”, both with the password “koala”, which is hashed to: 4efe081594ce25ee4efd9f7067f7f678a347bccf2de201f3adf2a3eb544850b465b4e51cdc3fcdde.

To show you a little more about how the StandardPasswordController works, I’ve added a unit test to the code that IntelliJ Idea provides. As you can guess from the code, each time the tests are run the output for each encoded string will be different, even though we are encoding the same password over and over again. Moreover, though we can verify the encoded string against the password, the password is virtually impossible to reverse engineer.

import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.security.crypto.password.StandardPasswordEncoder;

public class StandardPasswordEncoderDemo {
    @Test
    public void testCannotReproduceHashFromConfigFile() {
        StandardPasswordEncoder encoder = new StandardPasswordEncoder();
        String password = "koala";
        String encoded = encoder.encode(password);
        String encodedFromXML = "4efe081594ce25ee4efd9f7067f7f678a347bccf2de201f3adf2a3eb544850b465b4e51cdc3fcdde";

        // What we generated is not what's in the XML
        assertTrue(encodedFromXML != encoded);

        // But both what's in the XML and what we generated match the password.
        assertTrue(encoder.matches(password, encoded));
        assertTrue(encoder.matches(password, encodedFromXML));

        System.out.println(encoded);
   }

    @Test
    public void testAnotherRunWillAlsoYieldDifferentHashes() {
        StandardPasswordEncoder encoder = new StandardPasswordEncoder();
        String password = "koala";
        String encoded = encoder.encode(password);
        String encoded2 = encoder.encode(password);
        assertTrue(encoded2 != encoded);

        System.out.println(encoded);
        System.out.println(encoded2);
    }
}


Using Security in the View Layer – The Spring Security Tag Libraries

If we look in ApplicationController.java, we find the following method mapping:

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(ModelMap map) {
        // Additional code...
        return "index";
    }

No surprises here, the root mapping is to the traditional index page. Examining the source in src/webapp/WEB-INF/pages/index.jsp we find a good demonstration of the use of the Spring Security Tag Library. First, we import the tag library:

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

We now have access to the Spring Security Expressions that we saw enabled earlier when we discussed the configuration. For example, we first check to see if the User has logged in or not, and if not, we prompt for a sign-in:

<sec:authorize access="isAnonymous()">
    <p>
        <a href="/spring_security_login">Sign In</a>
    </p>
</sec:authorize>

Using the inverse of the isAnonymousCheck, if the user is authenticated we display a welcome message and a sign-out link:

<sec:authorize access="isAuthenticated()">
    <p>Hello, ${userDetails.username}! <a href="/j_spring_security_logout">Sign Out</a></p>
</sec:authorize>

Note that for production use, there’s a bit of a bug in this code, since there’s a the user could be a user who asked to be remembered (“Remember Me”), in which case isAuthenticated would still return true even if the user were not logged in. To eliminate this possibility, use “isFullyAuthenticated” instead.

Finally, we do a check for the admin role and conditionally display a link if the signed in user has that role assigned.

<sec:authorize access="hasRole('admin')">
    <p>
        <a href="/admin">Admin page</a>
    </p>
</sec:authorize>

With that, we’ve seen a basic Spring Security starter project that illustrates how to set up a very basic authentication based on pre-configured user names and passwords. In Spring Security Part II, we’ll dig into how to handle the much more common use case of storing user authentication information in a database. We’ll also dig into customizing the log-in forms. This will serve as a starting point for a much more full featured authorization system suitable for a business to consumer or business to business web site. Later on in another tutorial we’re planning to tie this database-based authentication system with Spring OAuth, allowing users with (for example) a Google account to sign in using that account.

Posted in Spring, Tutorials Tagged with: , , ,

Java Courses

Sign up for news and exclusive offers on new courses.