Featured FREE Whitepapers

What's New Here?

jcg-logo

Java Code Geeks are giving away FREE copies of their Java Concurrency Essentials eBook!

Want to boost your knowledge on Java Concurrency ? Then we have something especially for you! Enter the contest now to win your very own copy of our Java Concurrency Essentials eBook. Concurrency is always a challenge for developers and writing concurrent programs can be extremely hard. There is a number of things that could potentially blow up and the complexity of systems rises considerably when concurrency is introduced. However, the ability to write robust concurrent programs is a great tool in a developer’s belt and can help build sophisticated, enterprise level applications. With this eBook, you will dive into the magic of concurrency. You will be introduced to the fundamentals of concurrency and concurrent code and you will learn about concepts like atomicity, synchronization and thread safety. Enter the contest now to win your very own FREE copy of the book. In addition, we will send you free tips and the latest news from the Java community to master your technical knowledge (you can unsubscribe at any time). In order to win, you only have to refer at least 2 of your friends to join the contest, and you will ALL win a copy of the book! No draw performed! Make sure to use your lucky URL to spread the word! You can share it on your social media channels, or even mention it on a blog post if you are a blogger! Good luck and may the force be with you! Note: You know we are geeks. You know we can easily find whether you are trying to game the contest. So using your own accounts, like ilias.tsagklis@gmail.com, ilias.tsagklis@javacodegeeks.com etc., will get you disqualified. :-)   Join the Contest!   ...
android-logo

Android Tips: On/Off Toggle

When we need to give to users of our apps the ability to switch on/off a given feature, we automatically think of check boxes, toggle buttons or switches:These widgets are available to us out-of-the-box, but then we are constrained to a particular look & feel, which may or may not be what we want in our app. We could customize the switches, but if we’re looking for something entirely different, there are other ways to give users a visual feedback on whether a given feature is enabled or not, for example with plain text and a couple of icons:We could switch from one state to the other by simply touching the text field directly, instead of using buttons, switches or check boxes, with a consistent look & feel across all Android versions. But how? 1. Choose the on/off Icons If we don’t have the icons already, creating those using Android Asset Studio‘s icon generator is fast & easy. 2. Choose the on/off Colors In our Android project’s res/values/colors.xml file:#FFFFFF #FFFFE03. Create the Layout It will be just a clickable TextView with its associated Drawable:Here, the onClick event handler toggleWifi is declared in the XML and will be implemented in the corresponding Activity. 4. Edit the associated Activity //inside Activity //... // field private TextView tvWifi; // flag saved in prefs or db private boolean checkWifi; // colors private static final int COLOR_OFF = R.color.white; private static final int COLOR_ON = R.color.lightyellow; // icons private static final int IC_WIFI_OFF = R.drawable.ic_wifi_off; private static final int IC_WIFI_ON = R.drawable.ic_wifi_on; //... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //... tvWifi = (TextView) findViewById(R.id.wifi_onoff); // get saved wifi status from db checkWifi = ... setWifi(checkWifi); }//.../** onclick handler */ public void toggleWifi(View view) {//toggle setWifi( ! checkWifi); }/** Sets Wi-fi status + visual feedback */ private void setWifi(boolean onoff){tvWifi.setCompoundDrawablesWithIntrinsicBounds( onoff ? IC_WIFI_ON : IC_WIFI_OFF, 0, 0, 0 );tvWifi.setTextColor( onoff ? getResources().getColor(COLOR_ON) : getResources().getColor(COLOR_OFF));// process.. enable or not WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(onoff); }//... @Override protected void onPause() { super.onPause(); // save checkWifi flag in db //... }//... We can do something similar for as many fields as we wish:Notice that we used a View.onClickListener while defining the onClick() in the XML layout. We could have used a View.OnTouchListener instead: // Activity now implements View.OnTouchListener @Override public void onCreate(Bundle savedInstanceState) { //... tvWifi.setOnTouchListener(this); } //... @Override public boolean onTouch(View v, MotionEvent event) { // handle event here ... return true; } What’s the difference between onClick and onTouch? Not much in this particular use case, since we do not need the extra fancy stuff we could do with onTouch and MotionEvents. This technique is just an alternative way for on/off toggle. We could also easily enhance it with some type of animation. Whether it is “better” or not than regular switches, is mostly a question of taste. It is kind of “non-standard” (whatever that means), but, on the other hand, it might give designers more freedom and abilities to create their own original UIs. Happy Coding !Reference: Android Tips: On/Off Toggle from our JCG partner Tony Sicilian at the Tony’s Blog blog....
javafx-logo

How to get rid of focus highlighting in JavaFX

Today I was asked if I know a way to get rid of the focus-highlighting of JavaFX controls (respectively buttons):                  Most posts and tips regarding this issue suggest to add: .button:focused { -fx-focus-color: transparent; } But with this style, a glow like this is still left:To get rid of this glow also often suggested to play around with -fx-background-insets additionally: .button:focused { -fx-focus-color: transparent; -fx-background-insets: -1.4, 0, 1, 2; } But this results in a button rendered with out an outer border:Compared to the default button style:this is still a kind of “highlighting”. Why is that? (And why are there actually 4 inset values ?) Having a look at the JavaFX default style as defined by modena.css bares some more information:/* A bright blue for the focus indicator of objects. Typically used as the * first color in -fx-background-color for the "focused" pseudo-class. Also * typically used with insets of -1.4 to provide a glowing effect. */ -fx-focus-color: #f25f29; -fx-faint-focus-color: #f25f2933;Obviously there is not only one focus color -fx-focus-color but also -fx-faint-focus-color which is meant to create this glow-effect (that remains when setting -fx-focus-color:transparent;). A closer look at the .button:focused pseudo class (in modena.css): .button:focused { -fx-background-color: -fx-faint-focus-color, -fx-focus-color, -fx-inner-border, -fx-body-color; -fx-background-insets: -2, -0.3, 1, 2; -fx-background-radius: 7, 6, 4, 3; } Playing around with some extreme colouring reveals the arrangement: .button:focused { -fx-focus-color: red; -fx-faint-focus-color: green; -fx-inner-border: blue; -fx-body-color: orange;-fx-background-color: -fx-faint-focus-color, -fx-focus-color, -fx-inner-border, -fx-body-color; -fx-background-insets: -2, -0.3, 1, 2; -fx-background-radius: 7, 6, 4, 3; }  Getting back to the topic maybe a clever way to remove the focus highlight is to use the default button styles also for .button:focus (same approach for other controls): .button:focused { -fx-background-color: -fx-outer-border, -fx-inner-border, -fx-body-color; -fx-background-insets: 0, 1, 2; -fx-background-radius: 5, 4, 3; }Reference: How to get rid of focus highlighting in JavaFX from our JCG partner Jens Deters at the JavaFX Delight blog....
software-development-2-logo

Continuous Delivery: Code Coverage

This article is part of the Continuous Integration, Delivery and Deployment series. In the previous article we explored unit tests as the first and fastest set of tests we should run. Now it’s time to see whether our unit tests provide enough code coverage. Code Coverage Unit tests by themselves do not provide enough confidence unless we know that they cover significant code coverage. Having all tests successful while, for example, covering only 15% of the code cannot provide enough trust. Mature teams might not need to measure code coverage. They might know from experience that their unit tests are covering as much code as the project they’re working on needs. Teams like that tend to have years of practice with Test-driven development (TDD). However, for the majority of us, tools that measure the coverage are very indeed useful addition to our tool-belt. What is code coverage? Code coverage is a measure we’re using to check how much of our source code was tested. The higher the code coverage, the bigger the percentage of our code has been tested. Important thing to understand is that the code coverage is not directly related with code quality. High code coverage does not guarantee high quality of those tests. For example, even with 100% of code coverage there is no guarantee that certain functionality was developed correctly nor that it was developed at all. While code coverage can be used with any type of testing, it is most common and useful to tie it to unit tests. Integration and functional tests can be measured as well but the expectations from results must be different. For more information please consult Code and Test Coverage. Let’s see how we can implement code coverage in our CI/CD tools. Jenkins For those of you who did not follow the previous articles in detail or those who failed to reproduce all exercises, please install Vagrant and clone the code from the repository TechnologyConversationsCD. To create a virtual machine with Jenkins and myFirstJob job that performs static analysis, please go to the directory servers/jenkinsWithTests inside the cloned repository and execute the following: vagrant up If this is not the first time you’re starting this vagrant VM (“vagrant up” is configured to run the Docker container only the first time) or for some reason Docker container is not running, it can be run with the following shortcut script. /opt/start_docker_with_jenkins.sh We can check which containers are running by executing: docker ps When finished, virtual machine with Jenkins and myFirstJob job will be up and running. Results can be seen by opening http://localhost:8080 in browser. We’ll continue using Gradle as our build tool. In the last article we were executing the Gradle task check to run static analysis (CheckStyle, FindBugs and PMD) and tests. Now we’ll add Code Coverage with JaCoCo. To add JaCoCo code coverage all that should be done is add the plugin to the build.gradle file. apply plugin: 'jacoco'Good news is that if JaCoCo plugin is used, it adds itself to Gradle tasks check and test. Since we already have Jenkins job that runs Gradle check task, there’s nothing to be done to tell JaCoCo to collect statistics of our tests. However, JaCoCo needs two executions. One is to start collecting data from our tests (already covered within the Gradle check task). The second one is to generate HTML report from collected data. In order to do that, we should change our Gradle invocation from the Jenkins job myFirstJob by adding jacocoTestReport to the list of Gradle tasks. Now it should look like:   clean check jacocoTestReportTo publish JaCoCo coverage reports, we’ll need to install the JaCoCo plugin (Jenkins > Manage Jenkins > Manage Plugins > Available). Once the plugin is installed, we can add the post-build action called “Record JaCoCo coverage report”. As “Path to exec files” put “/.exec” (JaCoCo saves coverage data to an .exec file). “Path to class directories” should be set to “/classes” so that all those previously compiled with Gradle are included. Finally, we should set “Path to source directories” to “/src/main/java”. The rest of parameters are related to coverage health and depends on team preferences. I tend to consider code coverage of 90% acceptable. More than 95% is often counter productive.That’s it. We’re ready to build the myFirstJob with JaCoCo code coverage included. Press “Build Now” button1 from the left-hand menu. Once job execution is finished, enter the build and click the “Coverage Report”. It will show the report with coverage of instructions, branches, complexity, lines, methods and classes. Integrating JaCoCo inside Jenkins is fairly easy. Hard part is to get to the point where code coverage through tests is reasonably high. Having a firm grasp of TDD and functional and integration testing (my preference is BDD) is the key.     Travis Travis does not play well with JaCoCo. Sure, it’s easy to run it through Gradle in the same way as we did with Jenkins. However, there is no easy way to obtain and publish results. In case of test results, inability to publish is not a problem since we are interested only whether there is some failed test and can easily see from logs which one failed. Since failed tests should be fixed as soon as possible, there is no real reason for reports. Code coverage is different. Since in most cases code coverage obtained through tests is not 100%, ability to see and review the results in important. CircleCI As with Travis, CircleCI does not require anything special to be done to run code coverage since it is part of the Gradle task check (assuming that we added JaCoCo Gradle plugin). We already saw in the previous article that Circle is very similar to Travis in its approach to CI. Major difference was in the stability and speed (it is several times faster than Travis). With code coverage we can explore another difference. Circle has the option to store build artifacts. With them we can accomplish the similar effect as what we did with Jenkins. We’ll allow users to see the Gradle code coverage together with other types of reports. All we need to do is to modify our circle.yml file by adding jacocoTestReport and making sure that all reports are added to CircleCI artifacts. [circle.yml] test: override: - gradle check jacocoTestReport post: - cp -R build/reports/* $CIRCLE_ARTIFACTS Full source code can be found in the circle.yml. Once this change is pushed to the repository CircleCI will store all our reports and make them available through the “Artifacts” option available in each build. By opening jacoco/test/html/index.html we can see the nice report JaCoCo generated for us. Summary It was fairly easy to set up code coverage and publish results in both Jenkins and CircleCI. The only thing we had to do was to tell them to run Gradle task jacocoTestReport and where to find the results. Travis, on the other hand, does not have an option to publish reports. Without them code coverage is next to useless. Jenkins continues to shine with its plugin system. Circle’s “Build Artifacts” was a pleasant surprise and another handy addition to its speed. The more I’m using it, the more I can see the advantages when compared to Travis. Travis’ price was unbeatable (public repositories are free). However, since recently CircleCI is free as well while providing faster builds and several nice additions (like storing artifacts). In the next article we’ll explore the final stage of the continuous delivery and deployment. The goal is to continuously deploy (or at least deliver) software. Continous in this case means often, fast and with zero downtime. Stay tuned.  Word of caution: make sure to wipe the workspace ([JOB] > Workspace > Wipe Out Current Workspace) if running the same build multiple times without actually making any changes to the code. Gradle will detect that there are no changes and do nothing. This is a good thing since that way a lot of time can be saved but it can cause a bit of confusion when testing Jenkins job configuration. Reference: Continuous Delivery: Code Coverage from our JCG partner Viktor Farcic at the Technology conversations blog....
software-development-2-logo

It’s All About Tests – Part 3

In the previous two posts I discussed mostly about the philosophy and attitude of developing with testing. In this post I give some tips and tools examples for testing. Tools JUnit http://junit.org/ There’s also TestNG, which is great tool. But I have much more experience with JUnit so I will describe this framework.  Use the latest version. Know your testing tool!@RunWith This is class annotation. It tells JUnit to run with different Runner (mockito and Spring runners are the most common runners I use) import org.mockito.runners.MockitoJUnitRunner; ... @RunWith(MockitoJUnitRunner.class) public class MyClassTest { ... } @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/META-INF/app-context.xml","classpath:anotherContext.xml" }) public class MyClassTest { ... } // You can inherit AbstractJUnit4SpringContextTests instead of using runner@Rule kind of AOP. The most common out-of-the-box rule, is the TemporaryFolder Rule. It lets you use the file system without worrying about opening and closing files. An example of Rules can be found here. Parameterized runner Really cool tool. It lets you run the same test with different input and different expected output. It might be abused and make a atest unreadable. Test Data Preparation and Maintenance Tipshamcrest http://hamcrest.org/JavaHamcrest/ This library is “extension” of JUnit. I can’t work without it! Hamcrest library gives us out-of-the-box matchers. Matchers are used with the assertThat(...,Matcher) flavor. I almost always use this flavor. (In the previous post, someone suggested that I shouldn’t use assertTrue(…), but instead use assertThat). There are plenty type of matchers: You can verify existing objects in collection ignoring order. You can check greater than. The test is more readable using the assertThat + matcher. assertThat(mapAsCache.containsKey(new CacheKey("valA", "valB")), is(true)); assertThat(cachPairs.size(), is(2)); assertThat(enity.getSomething(), nullValue(Double.class)); assertThat(event.getType(), equalTo(Type.SHOWN)); assertThat(bits, containsInAnyOrder(longsFromUsIndexOne, longsFromUsIndexZero)); You can create your own Matcher. It’s very easy. Here’s an example of matchers that verify Regular Expressions. https://github.com/eyalgo/junit-additions mockito https://code.google.com/p/mockito/ This is the second library I can’t work without. It lets you mock dependencies of the class under test. Using mockito you mock dependency. Then you “tell” the mock object how to behave in certain inputs. You tell it what to return if some input entered. You can verify input arguments to a called method. You can verify that a certain method was called (once, never, 3 times, etc.). You can check the order of method / mocks calls. Check this out: package eyalgo; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; //The RunWith automatically instantiate fields with @Mock annotation //and injects to the tested class @InjectMocks @RunWith(MockitoJUnitRunner.class) public class NameConnectorTest { @Mock private NameConvention nameConventionAsMockField; @InjectMocks private NameConnector connector; private NameConvention nameConventionAsMockOther; @Before public void setup() { //This is another way to inject mocks (instead of the annotations above) MockitoAnnotations.initMocks(this); nameConventionAsMockOther = mock(NameConvention.class); NameConnector otherConnector = new NameConnector(nameConventionAsMockOther); } @Test public void showSomeMockitoExamples() { NameConvention nameConventionAsMock = mock(NameConvention.class, "Name for this mock"); // Stub and tell your mock to do something when(nameConventionAsMock.bigBangConvention("INPUT")).thenReturn("Some output"); // Throw exception for some input when(nameConventionAsMock.bigBangConvention("Other INPUT")).thenThrow(new RuntimeException("oops")); // Do more complicated stuff in the "when" Answer answer = new Answer() { @Override public String answer(InvocationOnMock invocation) throws Throwable { //do something really complicated return "some output"; } }; //Show also hamcrest matchers when(nameConventionAsMock.bigBangConvention(argThat(equalTo("my name is Inigo Montoya")))).then(answer); // Run the test.. //Verify some calls verify(nameConventionAsMock).bigBangConvention("INPUT"); verify(nameConventionAsMock, times(10)).bigBangConvention("wow"); // Verify that the method was never called. With any input verify(nameConventionAsMock, never()).bigBangConvention(anyString()); verifyNoMoreInteractions(nameConventionAsMock); verifyZeroInteractions(nameConventionAsMockField); //Check order of calls InOrder order = inOrder(nameConventionAsMock, nameConventionAsMockOther); order.verify(nameConventionAsMock).bigBangConvention("INPUT"); order.verify(nameConventionAsMock).bigBangConvention("other INPUT"); } } Other Mocking ToolsPowerMock and EasyMock These two are very useful when working with legacy code. They allow you to test private methods, static methods and more things that you normally can’t. I think that if you need them, then something is wrong with the design. However, sometimes you use external libraries with singletons and/or static methods. Sometimes you work on legacy code, which is not well suited for testing. On these types of scenarios, then those mocking libraries can help https://code.google.com/p/powermock/ http://easymock.org/ JMockit http://jmockit.github.io/ jMock http://jmock.org/JBehave http://jbehave.org/ JUnit, mockito, hamcrest are used for unit tests. JBehave is not exactly the same. It is a tool for Behavior-Driven-Development (BDD) You write stories which are backed up by code (Java) and then you run them. JBehave can be used for higher level tests, like functional tests. Using JBehave, it’s easier to test a flow in the system. It follows the Given, When, Then sequence. If you take it to the next step, it can be a great tool for communication. The product owner can write the scenarios, and if all is green, by the end of the iteration, then we passed the definition of done. cucumber is another BDD tool. Dependency Injection In order to have testable code, among other things, you need to practice DI (dependency injection). The reason is simple: If you instantiate a dependency in a constructor (or method) of a class under test, then how can you mock it? If you can’t mock the dependency, then you are bound to it. And you can’t simulate different cases. Many application have Spring as the DI container, but less developers take the advantage of using the injection for testing. Metrics Use SONAR in your CI environment. Check code coverage using cobertura or other tools. Use Jenkins / Hudson / Other CI tool for automation. IDE Your IDE can help you writing tests. For eclipse, I have two recommendations:MoreUnit is cool plugin that helps writing tests faster. In eclipse, CTRL+Space can give you hints and fill imports. But not static imports. Most (all?) libraries use static imports. So you can add the testing libraries as favorites and then eclipse will fill them for you.  POM Here’s part of POM for testing libraries. <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <addMavenDescriptor>false</addMavenDescriptor> </archive> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>com.startapp.CouchRunner.GetUserProfile</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> </plugins> </build> You can check the order of method / mocks calls. You can use profiles to separate unit testing with integration tests.Reference: It’s All About Tests – Part 3 from our JCG partner Eyal Golan at the Learning and Improving as a Craftsman Developer blog....
mockito-logo

Unit Testing exercise with FizzBuzz and Mockito

I sometimes use FizzBuzz to demonstrate the basics of unit testing to newbies. Although FizzBuzz is really simple problem, it can also be used to demonstrate more advanced unit testing techniques like mocking. The FizzBuzz Kata: “Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”“.The possible solution to FizzBuzz algorithm: public class FizzBuzz {private static final int FIVE = 5; private static final int THREE = 3;public String calculate(int number) {if (isDivisibleBy(number, THREE) && isDivisibleBy(number, FIVE)) { return "FizzBuzz"; }if (isDivisibleBy(number, THREE)) { return "Fizz"; }if (isDivisibleBy(number, FIVE)) { return "Buzz"; }return "" + number; }private boolean isDivisibleBy(int dividend, int divisor) { return dividend % divisor == 0; } } As the above code solves the FizzBuzz algorithm it does not solve the FizzBuzz problem. To finish it we need code to print the numbers from 1 to 100 using the algorithm. And this part of the code can be used to show the idea of mocking in JUnit with Mockito. As the result of this exercise I ended up with a NumberPrinter that takes two arguments: Printer and NumberCalculator and has one public method to print numbers: public class NumberPrinter {private NumberCalculator numberCalculator; private Printer printer;public NumberPrinter(NumberCalculator numberCalculator, Printer printer) { this.numberCalculator = numberCalculator; this.printer = printer; }public void printNumbers(int limit) { if (limit < 1) { throw new RuntimeException("limit must be >= 1"); } for (int i = 1; i <= limit; i++) { try { printer.print(numberCalculator.calculate(i)); } catch (Exception e) { // noop } } } }public interface NumberCalculator { String calculate(int number); }public interface Printer { void print(String s); } With the interfaces introduced I have not only testable but more robust code. To test NumberPrinter I simply mock dependencies with the power and simplicity of Mockito. With Mockito annotations the configuration test code reads better. Mockito features demonstrated:creating and injecting mocks stubbing methods also with setting different behavior for consecutive method calls. stubbing the void method with an exception verificationsAnnotations used:@RunWith(MockitoJUnitRunner.class) – initializes @Mocks before each test method @Mock – marks a field as mock @InjectMocks – marks a field on which injection should be performed@RunWith(MockitoJUnitRunner.class) public class NumberPrinterTest {@Mock private Printer printer;@Mock private NumberCalculator numberCalculator;@InjectMocks private NumberPrinter numberPrinter;@Test public void printsCalculatorResultsHundredTimes() { // arrange int limit = 100; when(numberCalculator.calculate(anyInt())) .thenReturn("0") // first invocation returns "0" .thenReturn("1"); // other invocations return "1" // act numberPrinter.printNumbers(limit); // assert verify(numberCalculator, times(limit)).calculate(anyInt()); verify(printer, times(1)).print("0"); verify(printer, times(limit - 1)).print("1"); verifyNoMoreInteractions(numberCalculator, printer); }@Test public void continuesOnCalculatorOrPrinterError() { // arrange when(numberCalculator.calculate(anyInt())) .thenReturn("1") .thenThrow(new RuntimeException()) .thenReturn("3"); // stub the void method with an exception doThrow(new RuntimeException()).when(printer).print("3"); // act numberPrinter.printNumbers(3); // assert verify(numberCalculator, times(3)).calculate(anyInt()); verify(printer).print("1"); verify(printer).print("3");verifyNoMoreInteractions(numberCalculator, printer); } } Enjoy Mockito!Want to learn more about Mockito annotations? Have a look at Eugen Paraschiv’s “Mockito – @Mock, @Spy, @Captor and @InjectMocks”: http://www.baeldung.com/mockito-annotationsLooking for code samples? Have a look at unit-testing-demo project presenting different aspects of unit testing, including mocking: https://github.com/kolorobot/unit-testing-demoReference: Unit Testing exercise with FizzBuzz and Mockito from our JCG partner Rafal Borowiec at the Codeleak.pl blog....
spring-interview-questions-answers

Externalizing session state for a Spring-boot application using spring-session

Spring-session is a very cool new project that aims to provide a simpler way of managing sessions in Java based web applications. One of the features that I explored with spring-session recently was the way it supports externalizing session state without needing to fiddle with the internals of specific web containers like Tomcat or Jetty. To test spring-session I have used a shopping cart type application (available here) which makes heavy use of session by keeping the items added to the cart as a session attribute, as can be seen from these screenshots:    Consider first a scenario without Spring session. So this is how I have exposed my application:I am using nginx to load balance across two instances of this application. This set-up is very easy to run using Spring boot, I brought up two instances of the app up using two different server ports, this way: mvn spring-boot:run -Dserver.port=8080 mvn spring-boot:run -Dserver.port=8082 and this is my nginx.conf to load balance across these two instances: events { worker_connections 1024; } http { upstream sessionApp { server localhost:8080; server localhost:8082; }server { listen 80;location / { proxy_pass http://sessionApp; } } } I display the port number of the application in the footer just to show which instance is handling the request. If I were to do nothing to move the state of the session out the application then the behavior of the application would be erratic as the session established on one instance of the application would not be recognized by the other instance – specifically if Tomcat receives a session id it does not recognize then the behavior is to create a new session. Introducing Spring session into the application There are container specific ways to introduce a external session stores – One example is here, where Redis is configured as a store for Tomcat. Pivotal Gemfire provides a module to externalize Tomcat’s session state. The advantage of using Spring-session is that there is no dependence on the container at all – maintaining session state becomes an application concern. The instructions on configuring an application to use Spring session is detailed very well at the Spring-session site, just to quickly summarize how I have configured my Spring Boot application, these are first the dependencies that I have pulled in: <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session</artifactId> <version>1.0.0.BUILD-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>1.0.0.BUILD-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.4.1.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.4.1</version> </dependency> and my configuration to use Spring-session for session support, note the Spring Boot specific FilterRegistrationBean which is used to register the session repository filter: mport org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.session.web.http.SessionRepositoryFilter; import org.springframework.web.filter.DelegatingFilterProxy;import java.util.Arrays;@Configuration @EnableRedisHttpSession public class SessionRepositoryConfig {@Bean @Order(value = 0) public FilterRegistrationBean sessionRepositoryFilterRegistration(SessionRepositoryFilter springSessionRepositoryFilter) { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new DelegatingFilterProxy(springSessionRepositoryFilter)); filterRegistrationBean.setUrlPatterns(Arrays.asList("/*")); return filterRegistrationBean; }@Bean public JedisConnectionFactory connectionFactory() { return new JedisConnectionFactory(); } } And that is it! magically now all session is handled by Spring-session, and neatly externalized to Redis. If I were to retry my previous configuration of using nginx to load balance two different Spring-Boot applications using the common Redis store, the application just works irrespective of the instance handling the request. I look forward to further enhancements to this excellent new project.The sample application which makes use of Spring-session is available here: https://github.com/bijukunjummen/shopping-cart-cf-app.gitReference: Externalizing session state for a Spring-boot application using spring-session from our JCG partner Biju Kunjummen at the all and sundry blog....
java-interview-questions-answers

A common CXF Request Interceptor for all OSGi Bundles

I have been working on Apache CXF, Karaf, Felix from path few months and i find all these bundled technologies very interesting to work with. While working on some use cases i have been got into a situation where i need only One Interceptor that should be executed on each HTTP request sent to any of bundles deployed under application in Karaf. Basically i want to Authorize every request, change some headers and to do some security checks whatever request has been sent to the system and most importantly i want to do it at a single class. I found many ways to add interceptor in every bundle but i want to do that at some centralized location/bundle so that all the requests can be handled from that bundle. It can simply reject any request after doing some authorization or pass it to relevant bundle(cxf does that internally). While doing this i came to know that CXF always creating a separate BUS for every RestServer that is being initialized in bundle’s Blueprint. But to achieve my goal we have to register all the bundles on same bus and apply the interceptor to that bus. With that we can control all the requests flowing on the bus. Common Interceptor public class CommonInterceptor extends AbstractPhaseInterceptor {public CommonInterceptor() { super(Phase.PRE_PROTOCOL); }public void handleMessage(Message message) throws Fault { /** * Here write whatever logic you want to implement on each HTTP call sent to your project. * * This interceptor will be called on every request that is being recieved by container and then will be sent * to the relevant bundle/class for handling. */String url = ( String ) message.get( URL_KEY_ ); String method = ( String ) message.get( Message.HTTP_REQUEST_METHOD );LOGGER.debug( "################### Authentication Interceptor Validating Request : " + url + "####################" );Map< String, List< String >> headers = Headers.getSetProtocolHeaders( message ); if ( headers.containsKey( X_AUTH_TOKEN ) ) { return; }else{ message.getInterceptorChain().abort(); } } } Above is the common interceptor code where you can do anything with the request that is being sent to your server. In constructor i am assigning the Phase to which that interceptor will be hooked up. There are several Phases in CXF. You can get information about Phases link: Phases in CXF. Extending AbstractFeature: public class InterceptorManager extends AbstractFeature {private static final String COMMON_BUS_NAME = "javapitshop_bus"; private static final Logger LOGGER = LoggerFactory.getLogger(InterceptorManager.class); private static final Interceptor< Message > COMMON_INTERCEPTOR = new CommonInterceptor();protected void initializeProvider(InterceptorProvider provider, Bus bus) { if ( COMMON_BUS_NAME.equals( bus.getId() ) ) { LOGGER.debug( " ############## Registering Common Interceptor on BUS ##############" ); bus.getInInterceptors().add( COMMON_INTERCEPTOR ); } else { LOGGER.error( " ############## Bus Id: '" + bus.getId() + "' doesn't matched with system bus id ##############" ); } } } In above code i am extending AbstractFeature class and hooking up initilizeProvider method. Then i have given a name to our common bus. Basically whenever any OSGi Bundle gets installed it registered itself with the bus. In that case we are checking if the bundle has the desired bus Id. That bus ID will be unique system wide and all the bundles having this bus id will be registered to same bus and each and every request that will be related to those bundles will be sent to CommonInterceptor first. Bus Registration In Bundles: <cxf:bus id="javapitshop_bus"> <cxf:features> <cxf:logging /> </cxf:features> </cxf:bus> To register the bundles with same bus you have to give an Id to that bus and register it in bundle’s blueprint.xml file. Do this in all relevant bundles and all those bundles will be assigned the same bus and CommonInterceptor will automatically be implemented to all the bundles.You can downlaod the complete source code from my Github.Reference: A common CXF Request Interceptor for all OSGi Bundles from our JCG partner Ch Shan Arshad at the Java My G.Friend blog....
software-development-2-logo

Making Side Projects With New Technologies

(Captain Obvious mantle on) You are a software engineer and maybe you have a side project – something that you do at home in your spare time. If you don’t, go ahead and have one – no life outside is better than a few more hours of programming. Unwitty jokes aside, having a side project is indeed a very useful practice (read on). A side-project is sometimes thought of as “the thing that would make you rich and you won’t have to program ever again”. It very rarely is, so we’d better view it as “the thing that would sound cool when I speak about it”. But apart from the motivational/coolness aspect, side-projects have a very important practical consequence – they make you a better programmer. Of course, every extra hour of doing something makes you better at it, but a side-project is even better, because you are the one that makes all the decisions – what to do, how to do it, when to do it, what technologies to use. I’ll focus a bit more on the last point. Not only you can choose the technologies to use, but you can choose technologies that you don’t know yet (imagine going to your manager in the beginning of a project and and asking him to build it with a language or framework that nobody on the team has ever used). And that’s what I’m doing – for most of my side-project I choose technologies that I haven’t used before. I get to learn new frameworks, tools and languages (a.k.a. “technology”), and get relatively good with them. That’s the way I learned JSF, Android, Scala, AWS and more. Learning a technology by itself is not the most motivating endeavor, but learning it as part of a project; as part of building something meaningful, is a different thing – it comes naturally. The obvious practical bonus of all this is that you become more “hireable”. Having a technology in your skillset makes you more eligible for certain positions than other people – knowing a bit of scala and AWS makes you way more qualified for a “scala full-stack engineer” than someone with just Java and Linux knowledge. Another scenario is when a new project starts and you get to pick the technologies, you can now say “I have experience with JSF, let’s build the front-end with that” (and that’s exactly what has happened to me). Now, a clarification is due about the “new” word in the title. I don’t intend it to mean “untested, overhyped crap”, I mostly mean “new to you”, something that you haven’t used. It might be an already stable technology, or something that is gaining traction but your conservative company is never going to try. Of course, trying something “fresh” is also good, as being an early-adopter is sometimes rewarding. Should you make side-projects with technologies you are familiar with? Of course, and I’ve done so as well. If the subject of the project is way more interesting than the technologies themselves (e.g. an algorithmic composer). But it is way better to use at least one new thing. By the way, that’s not relevant only for “youngsters”. The “big, fat architect” also needs a bit of the side project experience too, otherwise he risks being irrelevant pretty soon. In a way I think side projects are the way for developers to enrich their skillset and to be up to date. Learning only the technologies you need at work can make you forget how to learn; forget what programmers’ curiosity is – and that’s just bad. And constantly exploring the programming world not only gives you particular skills with a given technology, but also broadens your general engineering mindset.Reference: Making Side Projects With New Technologies from our JCG partner Bozhidar Bozhanov at the Bozho’s tech blog blog....
software-development-2-logo

A Tech Lead Paradox: Delivering vs Learning

Agile Manifesto signatory Jim Highsmith talks about riding paradoxes in his approach to Adaptive Leadership. A leader will find themselves choosing between two solutions or two situations that compete against each other. A leader successfully “rides the paradox” when they adopt an “AND” mindset, instead of an “OR” mindset. Instead of choosing one solution over another, they find a way to satisfy both situations, even though they contradict one another. A common Tech Lead paradox is the case of Delivering versus Learning.   The case for delivering In the commercial of software development, there will always be pressure to deliver software that satisfy user needs. Without paying customers, companies cannot pay their employees. The more software meets user needs, the more a company earns, and the more the company can invest in itself. Business people will always be asking for more software changes as there is no way of knowing if certain features really do meet user needs. Business people do not understand (and cannot be expected to fully understand) what technical infrastructure is needed to deliver features faster or more effectively. As such, they will always put pressure on to deliver software faster. From a purely money-making point of view, it is easy to interpret delivering software as the way of generating more earnings. The case for learning Software is inherently complex. Technology constantly changes. The problem domain shifts as competitors release new offerings and customer needs change in response and evolve through constant usage. People, who have certain skills, leave a company and new people, who have different skills, join. Finding the right balance of skills to match the current set of problems is a constant challenge. From a technologist’s point of view, learning about different technologies can help solve problems better. Learning about completely different technologies opens up new opportunities that may lead to new product offerings. But learning takes time. The conflict For developers to do their job most effectively, they need time to learn new technologies, and to improve their own skills. At the same time, if they spend too much time learning, they cannot deliver enough to help a company to reach their goals, and the company may not earn enough money to compensate their employees and in turn, developers. Encouraging learning at the cost of delivering also potentially leads to technology for technology’s sake – where developers use technology to deliver something. But what they deliver may not solve user needs, and the whole company suffers as a result. What does a Tech Lead do? A Tech Lead needs to keep a constant balance between finding time to learn, and delivering the right thing effectively. It will often be easier for a Tech Lead to succumb to the pressure of delivering over learning. Below is advice for how you can keep a better balance between the two. Champion for some time to learn Google made famous their 20% time for developers. Although not consistently implemented across the entire organisation, the idea has been adopted by several other companies to give developers some creative freedom. 20% is not the only way. Hack days, like Atlassian’s ShipIt days (renamed from FedEx days) also set aside some explicit, focused time to allow developers to learn and play. Champion learning that addresses user needs Internally run Hack Days encourage developers to unleash their own ideas on user needs, where they get to apply their own creativity, and often learn something in the process. They often get to play with technologies and tools they do not use during their normal week, but the outcome is often focused on a “user need” basis, with more business investment (i.e. time) going towards a solution that makes business sense – and not just technology for the sake of technology. Capture lessons learned In large development teams, the same lesson could be learned by different people at different times. This often means duplicated effort that could have been spent learning different or new things. A Tech Lead can encourage team members to share what they have learned with other team members to spread the lessons. Some possibilities I have experienced include:Running regular learning “show-and-tell” sessions – Where team members run a series of lightning talks or code walkthroughs around problems recently encountered and how they went about solving it. Update a FAQ page on a wiki – Allows team members to share “how to do common tasks” that are applicable in their own environment. Share bookmark lists – Teams create a list of links that interesting reads based on problems they have encountered.Encourage co-teaching and co-learning A Tech Lead can demonstrate their support for a learning environment but encouraging everyone to be a student and a teacher at the same time. Most team members will have different interests and strengths, and a Tech Lead can encourage members to share what they have. Encouraging team members to run brown bag sessions on topics that enthuse them encourage an atmosphere of sharing. Weekly reading list I know of a few Tech Leads who send a weekly email with interesting reading links to a wide variety of technology-related topics. Although they do not expect everyone to read every link, each one is hopeful that one of those links will be read by someone on their team.Reference: A Tech Lead Paradox: Delivering vs Learning from our JCG partner Patrick Kua at the THEKUA.COM@WORK blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close