Feed aggregator

Singleton Implementation in Scala

Javalobby Syndicated Feed - Sun, 03-Apr-16 00:31

Implementation: Scala

Since Scala has some language syntactic sugar around “statics” that essentially turn all statics into a single object, it basically suggests that Scala has built-in implementation of Singleton without much more work to do:

class Product private(var state : Int) {
  def DoSomething() = {
    state += 1
    System.out.println("I did something for the " + this.state + " time")
  }
}

object Product {
  private val _instance = new Product(0)
  def instance() =
    _instance
}

Product.instance.DoSomething()
Product.instance.DoSomething()
Product.instance.DoSomething()

Here, we define a companion object in Scala (the “object” declaration) to hold the static instance of the Product, and return it when requested through the “instance()” definition.

Categories: Java

Transforming Collections — Java 8 Collectors API

Javalobby Syndicated Feed - Sat, 02-Apr-16 21:31

Java 8 offers a new Stream API that makes handling collections easier and less verbose and error-prone. Stream API offers a set of methods for filtering and transforming underlying collections, but our interest is to cover the collect(Collector collector) method. This method offers very interesting functionality, such as transforming underlying collection to another collection type, grouping elements of collection, joining elements, and partitioning elements.

Let's get started with an example, and start explaining based on it. I suggest you open new tab with the source code so that you can review the code samples while following the explanation here.

Categories: Java

Ceylon 1.2.1 is Now Available

Javalobby Syndicated Feed - Sat, 02-Apr-16 02:31

Three months after the last major release, Ceylon 1.2.1 is a new maintenance release, with almost 100 issues closed, including new features, improvements and bug fixes such as:

  • you can now iterate java.util.Iterable values in for statements,
  • support for Java 9 and Jigsaw modules,
  • improved experimental support for type functions on the JVM,
  • reduced run-time dependencies for your Ceylon program,
  • better interoperation with JavaScript arrays,
  • better compatibility with previous and future Ceylon releases.

Note that for the JVM backend, this release is backwards-compatible with the previous major release (1.2.0), which means you can use modules compiled with 1.2.0 on a 1.2.1 distribution out of the box. This is not as easy the other way around if you want to run modules compiled for 1.2.1 on a 1.2.0 distribution, which is why we recommend you upgrade to 1.2.1.

Categories: Java

Watch Out For Recursion in Java 8’s [Primitive]Stream.iterate()

Javalobby Syndicated Feed - Sat, 02-Apr-16 00:31

An interesting question by Tagir Valeev on Stack Overflow has recently caught my attention. To keep things short (read the question for details), while the following code works:

public static Stream<Long> longs() {
    return Stream.iterate(1L, i ->
        1L + longs().skip(i - 1L)
                    .findFirst()
                    .get());
}

longs().limit(5).forEach(System.out::println);

Printing:

Categories: Java

The Mediator Pattern: Deep Dive

Javalobby Syndicated Feed - Fri, 01-Apr-16 05:16

“Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.”

Design Patterns: Elements of Reusable Object-Oriented Software

Categories: Java

Potential Java Garbage Collection Interview Questions

Javalobby Syndicated Feed - Fri, 01-Apr-16 02:31

Fig: Java Heap sizes generated from http://gceasy.io

What are the Different Regions in JVM Memory?

There are 5 regions:

Categories: Java

Swagger for Akka HTTP

codecentric Blog - Fri, 01-Apr-16 01:10

In this post I’m hoping to give you a good insight in how to setup Swagger for Akka HTTP.

Swagger is a tool to document REST API’s and overall works quite nicely to test some basic API commands. It already has integrations with many languages / REST frameworks. Since recently, Akka HTTP has been fully incorporated in the Akka platform. Swagger support for Akka HTTP exists, but the setup has some oddities. Here, I hope to provide you with a complete guideline.

Swagger Background

Swagger consists of two main parts; the Swagger UI and a server-side library. The server-side library is responsible for generating the API documentation from the code and supplemental annotations. This generated file is parsed by the Swagger UI, which in turn will provide an HTML app to view and test your API.

The generated API documentation looks something like this (in JSON):

{
  "tags": [{
    "name": "users"
  }],
  "host": "0.0.0.0:8080",
  "paths": {
    "/users": {
      "get": {
        "description": "",
        "tags": ["users"],
        "operationId": "getAllUsers",
        "produces": ["application/json"],
        "parameters": [],
        "summary": "Get list of all users",
        "responses": {
          "200": {
            "description": "successful operation",
            "schema": {
              "type": "array",
              "uniqueItems": true,
              "items": {
                "$ref": "#/definitions/User"
              }
            }
          }
        }
      }
    }
  },
  "basePath": "/",
  "info": {
    "description": "",
    "version": "1.0",
    "title": "",
    "termsOfService": ""
  },
  "schemes": ["http"],
  "definitions": {
    "Function1RequestContextFutureRouteResult": {
      "type": "object"
    },
    "User": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        }
      }
    }
  },
  "swagger": "2.0"
}

As server-side library for generating the API documentation, we will use the swagger-akka-http project.

Project Setup and Dependencies

A new project may be generated with sbt-fresh, giving us already a nice project setup containing most of what we need. The layout should look like this;

+ build.sbt             // specific settings for (single) module
+ project
--+ build.properties    // sbt version
--+ Build.scala         // common settings for all modules
--+ Dependencies.scala  // values for library dependencies
--+ plugins.sbt         // sbt-git, sbt-header, sbt-scalariform
+ README.md
+ src
--+ main
----+ resources
----+ scala
------+ package.scala   // type aliases repoining `Seq` and friends to immutable

For the swagger-akka-http library (and for Akka itself), we need to add the following dependencies to the build.sbt file. Be nice and add these dependencies as variables to the project/Dependencies.scala file

Categories: Agile, Java, TDD & BDD

JavaLand 2016 Retrospective

Javalobby Syndicated Feed - Fri, 01-Apr-16 00:31

Introduction

In this article I will write my impressions of the Java conference I visited in March 7-10 2016 in Brühl, Germany, also known as JavaLand 2016. The conference takes place in Phantasialand, an very interesting theme park. During the conference, many of the exibitions are open for the conference visitors.

Archive link: https://www.javaland.eu/de/archiv-2016/

Categories: Java

Scala: Higher-Order and Anonymous Functions

Javalobby Syndicated Feed - Thu, 31-Mar-16 23:01

Now after we have considered basics of Scala functions, we can make the next step in more complex use cases functional programming. Since functions in Scala are objects we can pass them as arguments in other functions, also we can return them as a result. In this article, I’m going to examine multiple examples of higher-order functions.

What functions? A function which accepts another function as arguments or returns a function is a higher-order function. It sounds like a madness if you have a previous experience with object-oriented programming, but after the reading, you’d definitely understand how it works.

Categories: Java

The Promises and Challenges of std::async Task-based Parallelism in C++11

Javalobby Syndicated Feed - Thu, 31-Mar-16 18:01

One of the biggest and most impactful changes C++11 heralds is a standardized threading library, along with a documented memory model for the language. While extremely useful and obviating the dilemma of non-portable code vs. third-party libraries for threading, this first edition of the threading libraries is not without kinks. This article is a brief overview of how C++11 tries to enable a "task-based parallelism" idiom with the introduction of std::async, and the challenges it runs into.

Warning: this article is opinionated, especially its last third or so. I'll be happy to get corrections and suggestions in comments or email.

Categories: Java

In Defense of Java

Javalobby Syndicated Feed - Thu, 31-Mar-16 04:31

So we have an eBook, The Top 10 Java Performance Problems, that we tweet out from time to time. Without exception, a few people reply with some version of “the problem is you’re using Java.” Java, apparently, is constantly criticized, and people have been predicting its demise for some time. Sure, it’s not as cool, flexible, or fun as some of the newer, more dynamic languages such as Python, Node.js, or Ruby, however, Java remains an important language for applications everywhere.

Migrating from Java seems like a good scapegoat “quick fix”, but it’s not nearly as simple.

Categories: Java

Spring Cloud Brixton.RC1 is Now Available

Javalobby Syndicated Feed - Thu, 31-Mar-16 04:31

On behalf of the team, I am pleased to announce that the first release candidate for the Spring Cloud Brixton Release Train is out. The milestone is available today and can be found in our Spring Milestone repository.

Highlights

Some of the highlights of the Brixton Release Train are:

Categories: Java

Apache Software Foundation: Behind the Scenes

codecentric Blog - Thu, 31-Mar-16 03:00

Ever thought about getting involved in an open source community? The Apache Software Foundation (ASF) is one of the places to do so. But what’s in for you? We talked to someone who should know: Benedikt Ritter is involved in the ASF and answered our questions in the following interview.

The following interview was originally published in the corporate magazin Softwerker vol. 01/15.

From your point of view, what is the Apache Software Foundation all about?

Well, there are a number of principles which are important at the ASF. One of them is “Community over Code”. It means that a vivid, friendly community is more important than the code itself. The rationale behind this is that a good community can continuously improve bad code. But without a community even the best code will not evolve.
Furthermore the ASF is a meritocracy. This implies that anybody has to prove his abilities before he gets a say in the development. Once this proof has been provided, there is no way to evade say. The term “do-ocracy” it tightly coupled to this principle, meaning that those who do something are to decide. So it’s better to introduce a change that works for 90% of the use cases already than not to do it.
Personally I like that the ASF is not driven by politics. There are no big players who pursue their own agenda.

How did you find the ASF?

Anybody working in IT will sooner or later have to deal with the Apache http webserver. Apache httpd is probably the most common product of the ASF. When I worked with a LAMP stack for the first time during my time at university I didn’t know what that was all about…

Apropos httpd – this is not only the most common product, but it is the the first project from which the ASF emerged, isn’t it?

That’s right. The ASF was founded by a group of developers in the mid-nineties. They came together to write patches for the NSCA public domain HTTP daemon. In April 1995 this group released version 0.6.2 of Apache httpd. In 1999 the members of this so-called Apache Group founded the Apache Software Foundation. The myth that they chose the name “Apache” to describe the poor quality of Apache httpd (“a patchy webserver”) dates back to that time. The truth is that the name was chosen to honor the native tribes of America.

Let’s get back to how you got involved in the ASF…

Later during my studies, I worked as a student assistant in a small software company. Coming right from university, I had the urge to always reinvent the wheel. But my team leader told me: “Before you start implementing things yourself, check if somebody has already implemented it for you.” He showed me Apache Commons and I was amazed by the software components that were available there.
Sometime later I subscribed to the Apache Commons mailing list, because I wanted to know how it all worked. I started discussing and I wrote some patches. On a Saturday morning I got an e-mail by the Apache Commons PMC (Project Management Committee) inviting me to become a committer. That was a great moment for me because I convinced others of my abilities by doing good work. In the meantime I’ve become a member of the PMC myself and I send invitation e-mails to others who have convinced me of their abilities.

What is a Project Management Committee?

Every project at the ASF has a Project Management Committee. The PMC is responsible for advancing the project. Members of the PMC may propose new committers. Decisions concerning new committers are made through secret ballot. In general, votes raised by members of the PMC are binding when a vote is held. For example, when a new release is about to be made, the release manager prepares a release candidate (RC) for review. Anybody is invited to review the RC and raise any concerns he or she has or problems he or she discovers. But in order to release a RC the release manager needs three positives votes by members of the PMC. All other votes cannot prevent or accelerate the release. Of course it is pretty unlikely that the release manager decides to release something if there are only three positives votes by PMC members but ten negative votes by other community members. But formally this vote would pass by the rules of the ASF.
Another responsibility of the PMC is to prepare a quarterly report for the Board of Directors, informing the board about the state of the project. Such a report contains information about new committers and PMC members, successful releases, and anything else which may be of interest to the board. The quarterly report provides an opportunity to ask the board of directors for help if a project has problems it cannot deal with on its own. This can be, for example, incapacity due to a lack of active community members or internal conflicts among project members which cannot be resolved. I’ve to admit that I haven’t experienced such a situation until now.

You just introduced a whole lot of new terms: committer, release manager, release candidate, Board of Directors. Can you please elaborate on these?

Sure! Generally there is a difference between contributors and committers. Becoming a contributor is fairly easy: You just contribute something to a project. For example, creating a bug ticket is already a contribution. Other examples include contributions to discussions on one of the mailing lists, improvements of the documentation and providing patches for issues in the bug tracker. Patches can be provided in form of SVN/git diffs or for some time now as pull request against one of the GitHub mirrors of the ASF. Patches will then be reviewed by one of the committers regarding relevance, quality and code style. Often this leads to a discussion about what has to be improved for the patch to be accepted. When the patch has reached the desired quality, it is applied by one of the committers. The diff of each commit is sent to a separate mailing list so that other project members (committers as well as contributors) can review it. If somebody has concerns about a change, he or she can raise them on the mailing list, giving the author of the change the opportunity explain the change. This is a means to keep the quality high.

The release manager does his or her job later in the development process. At some point in time a committer can volunteer to create a new release of a project. Usually he or she will write a short notice to the mailing list like “It has been some time since we released foo 1.1, so I’d like to release foo 1.2 soon. If you’re planning to fix something that should be included, please do it now”. To start the release process, the release manager prepares a release candidate and sends another notice to the mailing list. A release candidate is made up of several parts: An SVN/git tag of the source code, which should be released, binary and source archives, artifacts that will be published to Maven Central, release notes, the project website as well as some code quality reports. The release candidate represents something like “if we decide to release foo 1.2, it will look like this”. If the vote about the release candidate is successful, it will be published. If not, the code has to be improved and the release manager prepares another release candidate.

To explaining the role of the Board of Directors I have to go back a little and talk about the organizational structure of the ASF (editor’s note: the following part is to describe the term “foundation” to German readers). The English term “foundation” can be translated to “Stiftung” in German. Nevertheless under German law the Apache Software Foundation corresponds more to a registered society. There are members in this society. You become members – following the principle of meritocracy – by proving your abilities to the other members through good work and by showing that you care about the ASF as a whole. The members annually elect the Board of Directors, which governs the ASF’s activities in all areas. The board is made up of officers for the various areas, such as fundraising, marketing, trademarks, infrastructure, etc. This is the organizational view of the ASF (see fig. 1). The PMCs take care of the technical matters and report to the Board of Directors. Furthermore new projects are initiated by the Board of Directors.

ApacheOrgChart2012

Fig.1: Apache Org Chart (source: http://www.apache.org/foundation/governance/orgchart)

Can you describe the way new projects are handled at the ASF?

Basically there are two ways new projects are started:

  • An existing project wishes to become part of the ASF. Examples of this are Apache SVN or Apache OpenOffice.
  • A new project is initiated from within the ASF. For example Apache BatchEE was a result of the work on the Apache TomEE project.

No matter how a project is brought to the ASF, the starting point will always be the Incubator. The Incubator has various responsibilities. The most important one is to work on intellectual property (IP) clearance. All code at the ASF has to be released under the Apache License 2.0. When existing projects are to become part of the ASF, there are several “problems” that may arise:

  1. The code of the project has an incompatible license (e.g. GPL). In this case the IP owners may simply change the license.
  2. The project has an incompatible license and it contains code whose IP is not owned by members of the project. In this case the affected parts of the project have to be reimplemented.
  3. The project has dependencies to libraries with incompatible licenses. In this case those dependencies have to be exchanged or have be reimplemented.

It’s extremely important for the ASF to resolve all issues around IP before accepting a new project, because the ASF guarantees that their products may be used in commercial contexts.
Another responsibility of the Incubator is to make sure no projects are bound to fail because there is no vivid community supporting them. For this reason there are several defined points in the incubator process where the project activity is checked. In addition to that the Incubator is a place for ASF newcomers to learn “the Apache Way”.

What is “the Apache Way”?

Part of “the Apache Way” besides the principles I talked about in the beginning, is the way people work on projects. There is (with very few exceptions) no secret-mongering at the ASF. All decisions are discussed publicly and they can later be looked up in the mailing list archives. Furthermore development follows the commit-then-review process. I’ve already talked about that. It’s a way to keep the quality high. A positive side effect is that you adopt an extremely tidy way of working. Commits become very small, so that they are easy to review. Moreover they only contain changes that are part of the bugfix or feature you’re working on. Reformatting source code or reorganization of imports go to separate commits. Things are separated from each other. This helps me deliver good results in my daily work.

What are the benefits of being involved in the ASF?

First and foremost I learn a lot. Since my work is continuously reviewed by very talented people, I see where I have to improve my skills. As a committer it is a lot of fun to work with contributors and to introduce them to the Apache way. By reviewing patches and commits I can see how others approach problems. In addition to that, I get in touch with people from all around the world. Britons behave and communicate very differently from for example Italians. Having to communicate completely via mailing lists doesn’t make things easier in this regard. On top of that I’m always amazed by whom I get to work with. At the Apache Commons project I met Henri Yandell. He is responsible for the Open Source activities at Amazon. Phil Steitz has been CTO at American Express and Gary Gregory is the author of “JUnit in Action” and “Hibernate in Action”. And probably everybody has already heard about Roy Fielding… And last but not least it’s a great feeling to get positive feedback by users, e.g. “Thanks for this library, it saved me a lot of work.”

Do you have any advice to those who want to get involved in the ASF?

My tip would be “fear not, just do it”. At first I was just following discussions, because I was afraid to say something stupid. But only those who ask can be helped. I’d say that you have to be a bit frustration tolerant. Very few patches are accepted right away. It’s completely normal that you have to get used to the style of ASF projects. You shouldn’t get discouraged, but perceive discussions around your contributions as a chance to learn. Concrete assistance can be found on the ASF websites. The most important rules for patches are probably:

  • All files have to contain an Apache License header.
  • Use spaces instead of tabs for indentation.

Thank you very much for this interview, Benedikt. Next time I want to hear more about the Apache Commons project!

The post Apache Software Foundation: Behind the Scenes appeared first on codecentric Blog.

Categories: Agile, Java, TDD & BDD

Writing One-liners in Java 8

Javalobby Syndicated Feed - Thu, 31-Mar-16 02:31

We all love one-liners, don’t we? The ones like these:

  • “War does not determine who is right – only who is left.”
  • “Always borrow money from a pessimist. He won’t expect it back.”
  • “We live in a society where pizza gets to your house before the police.”

For techies like us, “one-liners” mean something different – it’s a program that is written in one line. Of course, C is my favourite for writing one-liners, like the following one that copies a string from source (variable “char *s”) to target (variable “char *t”):

Categories: Java

Try. Finally. If. Not. Null.

Javalobby Syndicated Feed - Wed, 30-Mar-16 23:01
There is a very typical mistake in pre-Java7 "try/finally" scenario, which I keep seeing in so many code reviews. I just have to write about it. Java7 introduced a solution, but it doesn't cover all situations. Sometimes we need to deal with non-AutoCloseable resources. Let's open and close them correctly, please.

This is how it looks (assuming we are in Java 6):

InputStream input = null;
try {
  input = url.openStream();
  // reads the stream, throws IOException
} catch (IOException ex) {
  throw new RuntimeException(ex);
} finally {
  if (input != null) {
    input.close();
  }
}

I already wrote about null and its evil nature. Here it comes again. If you just follow the ruleof "not using NULL anywhere ever," this code would need an immediate refactoring. Its correct version will look like this:

Categories: Java

Java Quiz: Nested Classes

Javalobby Syndicated Feed - Wed, 30-Mar-16 21:31

Starting today, every week, we'll be bringing you a new quiz/puzzler/brain-teaser to help keep you on top of your Java game. Here's your first question: 

What Happens When You Try to Compile and Run the Following Program?

class Outer {

    private int a = 12;
    private int b = 6;

    Outer() {

        NestedA nestedA = new NestedA(4);
        a = a -12;
    }
    class NestedA {

        NestedA(int y){

            NestedB nestedB = new NestedB(y);
            nestedB.methodB(y, a);
            a= a + b - y;
        }
        private void methodA(int z) {

            System.out.print("-a"+a+z+"-b"+(b-z));
        }
        class NestedB {

            NestedB(int i) {
                a = a - i; b = b +i;
            }
            private void methodB(int x, int z) {
                if(x < 5) {
                    a = a+x+b;
                }
                b = b+z; 
                System.out.print("-a"+a+"-b"+b);
            }
        }
    }
    public static void main(String[] args) {

        NestedA nestedA = new Outer().new NestedA(2);
    }
}

Submit your answer here (no compiling!):

Categories: Java

Open Sourcing Eclipse Dropwizard Tools

Javalobby Syndicated Feed - Wed, 30-Mar-16 05:16

Here at Tasktop, we really like industry standards. It's important for us to use well-known tools and frameworks to make transitions between teams easier. When it comes to creating a REST API there is no way around JAX-RS in the Java world. But JAX-RS (or one of its implementations) is not a full server stack. You always need to use some other technologies e.g. to access a database, do logging and much more.

Several projects exist providing such a stack. And one of the coolest projects in the last years is Dropwizard. Dropwizard combines some industry standard technologies like JAX-RS (Jersey), Hibernate, log4j, guava, Jetty (and some more) and glues them together. We use Dropwizard here at Tasktop for several products because it just works and make things easy.

Categories: Java

Developing Scala in Atom With Ensime

Javalobby Syndicated Feed - Wed, 30-Mar-16 04:31

When I began Java software development way back in the time of Java 1.3 I remember using JDeveloper for a time, before switching to the early versions of Eclipse. I stayed with Eclipse for a very long time (about 8 years) before switching to IntelliJ about 4 years ago. I've always been a big fan of IntelliJ, not just for programming Java, but I also kept using it when I started with Scala a couple of years ago. Last months, though, I started noticing that I actually only use a small amount of all the IntelliJ functionality and was slowly getting a bit annoyed with the way IntelliJ slowed down to a crawl for certain Scala projects. Combined with the fact that IntelliJ tripped over some Shapeless, Spray, Scalaz stuff, made me start looking for an alternative leightweight Scala editor.

Since I already am using Atom for taking notes (nvAtom in combination with a synced dropbox folder works great!), and I tried Ensime a couple of months ago, I thought I'd gave that combination another try. In this article, you can read the steps I've taken, the plugins I've installed to get to a fairly good working Ensime/Atom combination.

Categories: Java

Improve Your JUnit Experience with This Annotation

Javalobby Syndicated Feed - Wed, 30-Mar-16 01:46

JUnit is probably part of 90% of all Java projects. And the exciting thing is, we’ll soon have JUnit 5 with Java 8 support. We’ve blogged about an improvement recently.

Back in JUnit 4 land, there’s this little trick that I can only recommend you put in all of your unit tests. Just add this little annotation here and you’ll be much more happy:

Categories: Java

Thread Slivers eBook at Amazon

Syndicate content