archive-se.com » SE » S » SAWANO.SE

Total: 50

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • sôft'wâr'
    Modeling June 11 2013 MapReduce made simple with Akka As you probably already know Akka can make your life a lot easier when it comes to things like concurrency and scalability A very typical use case for starting to use Akka is when you have a computation or algorithm of some sort that lends itself to parallelizing Implementing that with just core Java is cumbersome error prone and it will feel like you are reinventing the wheel every time you do it Akka will for example enable you to take advantage of all the cores in your CPU or maybe even the CPUs of several machines without having to worry about the evils of things like threads lock semaphores etc and not to mention the hassle of trying to distribute the computations Read more Posted by Daniel Sawano 0 comments Email This BlogThis Share to Twitter Share to Facebook Share to Pinterest Links to this post Labels Akka Concurrency Java February 12 2013 Java based configuration in Spring An introduction If you have not started using Java based configuration in your Spring projects you really should take a look at it since it is a very valuable tool to master Java based configuration has been supported right out of the box since Spring 3 0 so it has become quite complete by now with the stable release being 3 2 x at the time of writing this post Personally I have found that I hardly ever use any XML configuration files in Spring projects that I create nowadays And as a side note if I am also able to use an application server that supports Servlet 3 0 I can even get rid of my web xml file Thus eliminating a big part of the XML based configuration usually needed Ok but why You might ask Well if you think about it there are a lot of benefits of having your configuration in code instead of in XML Read more Posted by Daniel Sawano 0 comments Email This BlogThis Share to Twitter Share to Facebook Share to Pinterest Links to this post Labels Java Spring Spring MVC XML September 6 2012 Not using Spring Data yet Well you should and here s why In pretty much every single project you will ever work in there will be a need to persist data Typically you will use things like JPA Hibernate and similar APIs Using these APIs is a huge step forward compared to the good ol days when we didn t have things like O R mappings and nice transactional APIs but had to fiddle around with JDBC connections rolling back transactions reading from result sets and whatnot 1 But still pretty much all of the work you do every time you create a repository class for your entities is plumbing You are creating nothing but boiler plate code And time spent on boilerplate code is time wasted because you are writing code that adds no real value but still

    Original URL path: http://software.sawano.se/ (2016-05-02)
    Open archived version from archive


  • sôft'wâr': Continuous Delivery and Conway's Law
    they never going to get a second chance to change anything they keep the idea until they have perfected it to be the best product in history before passing it on to the design department Once the designers get it they know that once the developers have gotten their hands on it it will be impossible to even change a single pixel so they end up designing the most beautiful UI ever seen that has every imaginable feature in it Not until a graphical nirvana has been reached do they pass it on to development And so the process continues If any of this feels even remotely familiar then do not be ashamed It is more common than you might think What we just witnessed in our imaginary little story is an organization that will never be capable of performing anything but a non repeating sequential business development process The organizational structure has thus created an inertia in the process that prevents it from rapidly transforming a business idea into working software In other words the structure itself is putting a limit on the cycle time of the delivery process This limit is very much caused by communication barriers within the process and as long as these barriers exist this organization will never be able to reap the full benefits of continuous delivery Conway s Law In 1968 Melvin E Conway published a paper How Do Committees Invent 1 in which he put forward the thesis that organizations which design systems are constrained to produce designs which are copies of the communication structures of these organizations organizations which design systems are constrained to produce designs which are copies of the communication structures of these organizations M Conway 1968 This thesis was later dubbed Conway s Law by Fred Brooks in his book The Mythical Man Month 2 and it is by this name Conway s thesis is generally known as The essence in what Conway is stating is that the communication structures within an organization will put limits on what types of IT designs and architectures that the organization can create Now this is a very interesting observation It means that given a certain organization there are only certain style of architectures that the given organization can produce Once you realize this it becomes apparent that if you are striving towards creating a certain type of software design or architecture then maybe you should adjust your organization to promote that type of architecture As a matter of fact this is exactly what the term Inverse Conway Maneuver is all about The nature of business value Once we start to understand the implications of Conway s Law on IT architecture we can start to use the same reasoning when we are analyzing why an organization might struggle to implement continuous delivery Even though the technical aspects of continuous delivery tends to get a lot focus partly because it is a practice often driven by software centric companies delivering working software is

    Original URL path: http://software.sawano.se/2015/06/continuous-delivery-and-conways-law.html (2016-05-02)
    Open archived version from archive

  • sôft'wâr': Custom accessors with IntelliJ's new code generation features
    setters for them then the generated methods would all follow the JavaBeans naming conventions see example code below Leaving me to either manually have to rename all of the generated methods or simply just write them all by hand Both alternatives are tedious but apart from resorting to compiler based solutions like Lombok there really haven t been any good alternatives public class Person private final String firstName public String getFirstName return firstName New code generation to the rescue No good alternatives up until now that is The 14 1 release of IntelliJ IDEA brings a couple of nice new features One of them being the ability to define you own templates for code generation for getters and setters as well as for equal and hashcode That means that the accessors that IntelliJ generates for you no longer are limited to the JavaBeans naming convention JetBrains has a blog post that explains how to access the templates used when generating code and once you found it you can simply choose to create your own Velocity templates This feature is something that I have been waiting for so I was very pleased to see that it has finally been implemented and of course I immediately went off to define a template that will allow me to generate the type of accessors that I want So now my Person class will end up looking like this with generated accessors public class Person private final String firstName public String firstName return firstName This might seem like a small feature but if you are writing a lot of code then this reduction of manual typing will add up to quite some time savings And below is the template used to achieve this The template is simply a tweak of the standard one supplied by

    Original URL path: http://software.sawano.se/2015/03/custom-accessors-with-intellijs-new.html (2016-05-02)
    Open archived version from archive

  • sôft'wâr': Clean code - why it matters
    an area where you want to make it as easy as possible to spot mistakes and bugs Security related code should ideally have the highest standards when it comes to being readable and explicit in its intent Critical code should be the cleanest code Too many times have I seen security related code that is nothing more than a huge mess and in general it tends to be in the messy code where you will find the most bugs My colleague Dan Bergh Johnsson has some excellent thoughts on how code design can help improve software security Domain Driven Security and I suggest reading it if you are interested in software security A tale from the trenches Making the code readable and being explicit with its intent and purpose can also help you avoid problems that you didn t even think about To give a concrete example I was reviewing some code for a client and it turned out that the code didn t compile when upgrading to a newer JDK version At first it wasn t clear to me why it refused to compile but after sifting through some JDK documentation it turned out that the code stopped working because a bug in the Java compiler had been fixed in the newer version 1 I e the code should never have worked in the first place The code looked something like this turned into a simple example to protect the innocent public class A private static class Inner private int value return 42 public T extends Inner void doStuff T t final int value t value This code will compile in JDK 5 and 6 but not in 7 Can you spot the mistake As a Java developer this code looks legit as it is allowed in Java to access a private member of an inner class The key here is T extends Inner If the method doStuff would have looked like below it would have been valid public void doStuff Inner t final int value t value The reason for why the first example is invalid is that T is a subclass of Inner and as such there is no guarantee that a private member of Inner will be available in T Which makes perfect sense when you think about it Now how does this relate to clean code Well my point here is that if we had been thinking about making the code expressive and to clearly communicate its intent we could have avoided getting into this situation in the first place Let me elaborate Class Inner is an inner class that is only to be used by class A That is a clear intent and it is expressed by declaring Inner as private But even though Java allows A to access private members of Inner by use of synthetic accessors it is better to avoid that and instead design Inner just as if it wasn t an inner class That means that if we intend the

    Original URL path: http://software.sawano.se/2014/04/clean-code-why-it-matters.html (2016-05-02)
    Open archived version from archive

  • sôft'wâr': MapReduce made simple with Akka
    all workers have reported back and then send back the total result to the actor who sent the original request to the parent That in turn also means that the parent actor needs to keep a reference to the sender of the original request in order to report back the total result and doing so without falling in the trap of shared mutable state Using the previously described scenario you would typically send a message to your workers from your parent actor by doing something like this originalCaller getSender Needed to send back the total result worker tell new Begin getSelf and then you would wait for the workers to report back by having this in your onReceive method if Result class isInstance message recordPartialResult message if allWorkersHasReportedBack sendBackTotalResultToOriginalCaller This is not as complicated as it sounds and it can be made to be a decent and workable solution but there is a more simple way of solving this problem by using Akka s Future s and the functional features that Akka provides with it You can read all about these features here but lets look at a hands on example The functional approach Instead of just sending a message to our workers we will ask them for a result Future Object future ask worker new Begin 1000 answers add future This will give us a Future that we can use to get our partial result from So if we ask all our workers we can then use the returned futures to get all the partial results And lastly we can combine the partial results into a total result and then report back to the original caller This is where the method fold comes into the picture If you are familiar with Scala then this functionality will not be anything new to you but this is one handy method that is available in Akka and it can really make your life easier if you learn it Taken from the documentation fold takes a start value a sequence of Future s and a function from the type of the start value a timeout and the type of the futures and returns something with the same type as the start value and then applies the function to all elements in the sequence of futures non blockingly the execution will be started when the last of the Futures is completed Translated to our example this means that the function we will provide to fold will be responsible for combining the partial results into a total result In code this would look like this private Result totalResult List Future Object answers throws Exception final Future Result totalResult fold new Result 0 answers new Function2 Result Object Result Override public Result apply Result previousResult Object workerResponse throws Exception return new Result previousResult result Integer workerResponse getContext dispatcher return Await result totalResult Duration create 2 TimeUnit SECONDS In our example we are just summing up integers but it serves to illustrate the concept of combining partial

    Original URL path: http://software.sawano.se/2013/06/mapreduce-made-simple-with-akka.html (2016-05-02)
    Open archived version from archive

  • sôft'wâr': Java-based configuration in Spring - An introduction
    These two annotations corresponds to the following XML mvc annotation driven context component scan base package com foo bar myapp Assuming that PackageMarker is a marker interface defined in the com foo bar myapp package Personally I am not a big fan of having magic strings sprinkled throughout the code so even if ComponentScan com foo bar myapp is the same as ComponentScan basePackageClasses PackageMarker class I prefer the latter one because it refers to an actual class which helps to avoid typos and the IDE will also provide better support for refactorings etc To tell our web application to use Java based configuration we can make our web xml look something like this servlet servlet name Spring MVC Dispatcher Servlet servlet name servlet class org springframework web servlet DispatcherServlet servlet class init param param name contextClass param name param value org springframework web context support AnnotationConfigWebApplicationContext param value init param init param param name contextConfigLocation param name param value com foo bar SpringConfig param value init param load on startup 1 load on startup servlet Note the use of AnnotationConfigWebApplicationContext and that the contextConfigLocation is pointing to our configuration class rather than an XML file Our SpringConfig class is where we will put all of the methods that we will use to configure Spring Now lets take a look at some typical configuration examples and see how they would look like in Java Defining beans Defining a bean in Java is as simple as annotating a method with Bean The Bean annotation corresponds to the bean XML element so the following is effectively the same XML configuration bean class com foo bar MyBean Java configuration Bean public MyBean myBean return new MyBean By default the bean name will be the same as the name of the method A very common thing to do when building MVC applications is to define view resolvers Lets do just that so we can see how to do a more realistic bean definition than the previous example The standard XML configuration for adding view resolvers would typically look something like this bean class org springframework web servlet view InternalResourceViewResolver property name prefix value WEB INF views property name suffix value jsp bean and the corresponding configuration in Java would be Bean public InternalResourceViewResolver internalResourceViewResolver InternalResourceViewResolver viewResolver new InternalResourceViewResolver viewResolver setPrefix WEB INF views viewResolver setSuffix jsp return viewResolver Custom MVC configuration If you want to start customizing the MVC configuration you can extend the WebMvcConfigurerAdapter class and override the methods that you are interested in Our configuration class would then look like this Configuration EnableWebMvc ComponentScan basePackageClasses PackageMarker class public class SpringConfig extends WebMvcConfigurerAdapter Following are some examples of how you would override methods in WebMvcConfigurerAdapter Adding resource handlers Standard XML configuration for defining where your static content is mvc resources location js mapping js mvc resources location css mapping css mvc resources location img mapping img and corresponding Java configuration Override public void addResourceHandlers ResourceHandlerRegistry registry registry addResourceHandler js addResourceLocations js registry addResourceHandler

    Original URL path: http://software.sawano.se/2013/02/java-based-configuration-in-spring.html (2016-05-02)
    Open archived version from archive

  • sôft'wâr': Not using Spring Data yet? Well, you should, and here's why.
    just as it usually does as per standard Entity public class User Id GeneratedValue private Long id Column nullable false private String firstName Column nullable false private String lastName Then all we need to do in order to create a repository that will provide us with CRUD and some additional retrieval operations is to create a single interface Like this public interface UserRepository extends JpaRepository User Long The interesting part here is that we extend the interface JpaRepository This interface will give us methods like findAll delete user save user and so on To create custom queries you simply create methods in your UserRepository interface The name of the methods will determine what the query will be For example we could modify our repository to look like this public interface UserRepository extends JpaRepository User Long public List User findByFirstNameOrderByLastNameAsc String firstName You can use getBy as well as findBy public List User getByFirstNameLike String firstName There are several keywords that are available for use in method names and if that is not enough you can also create custom queries in several different ways You can read more about the possibilities in the reference documentation What really appeals to me is the how clean a solution this will give you It allows me to spend a minimal time on getting persistence and then let me go on and focus on whats important A single interface is about as clean as it gets And clean is good I have just scratched the surface here on how Spring Data works and there are a lot more features in Spring Data JPA and if you have the need you can get some pretty advanced usage out of it The example code for the UserRepository shown here is on GitHub so you can see how

    Original URL path: http://software.sawano.se/2012/09/not-using-spring-data-yet-well-you.html (2016-05-02)
    Open archived version from archive

  • sôft'wâr': Mockito: Default values and how to get more out of them
    use the RETURNS SMART NULLS answer in Mockito see the javadoc You can specify the RETURNS SMART NULLS default answer when you are creating your mock like User userMock mock User class Mockito RETURNS SMART NULLS When using RETURNS SMART NULLS the mock will return a SmartNull instead of a null When your code tries to use the SmartNull value you will get a SmartNullPointerException instead of a nullpointer exception and the stack trace will show you where the call to the unstubbed method was made This is really helpful compared to the previous staktrace that revealed nothing You should also notice that RETURNS SMART NULLS will return null SmartNull in fewer cases than default Ok that second solution will help us avoid those awful nullpointer exceptions but you might still get some unwanted or unexpected results since there are a lot of cases where the default value is not null Sometimes you may want a way to totally forbid calls to unstubbed methods and when such a call is made you want to throw an exception letting everybody know about the horrible violation You can achieve this behavior by providing your own custom default answer A mock with such an exception throwing answer would look like this User userMock mock User class new Answer Override public Object answer InvocationOnMock invocation throws Throwable throw new MockitoException Unstubbed method call So what happens when you start writing your givens when userMock getAddress thenReturn new Address Duckburg Or given userMock getAddress willReturn new Address Duckburg if you prefer the BDD style Well you will get that Unstubbed method call stack trace from your default answer Not exactly the result we wanted It turns out that the method you are trying to stub actually gets called when you are stubbing the method catch 22 implementation of Mockito We need to find a new mocking framework Start googling Quick Wait Before you start whipping out your googling skills take a deep breath and start surfing the documentation of Mockito instead or just read this blog post and we will find the third solution It turns out the developers of Mockito have already thought of our problem There is another way you can write your givens doReturn new Address Duckburg when userMock getAddress This way the method getAddress will not be called when you are stubbing it to return an actual value To me this syntax feels very backwards and does not read as well as using the when then syntax and though I know about it I hardly ever uses it And you shouldn t either since the when then syntax is the preferred and recommended way to use Mockito But this reversed notation can indeed be a handy trick when you actually need it And now you know it too so you can take advantage of it and you also know that you should use it sparingly The afterthought As I mentioned in the beginning of this post the need for doing more

    Original URL path: http://software.sawano.se/2012/07/mockito-default-values-and-how-to-get.html (2016-05-02)
    Open archived version from archive



  •