Sunday, November 27, 2016

A Web Service Client for a soap - service

Currently, I can test my web service with a set of soap requests that I call with Soap-ui.

I have to find a way to automatize the system tests for my service, and to integrate them into the build chain.

My intention is to move the soap requests I have in my soap-UI project into a set of java classes, that I can then integrate into my build process.

I started by trying to use Apache CXF for writing my test classes.

This is how I proceeded:

- I created a new IntelliJ project (Facet : WebService Client : JavaEE, WebServices, JAX-WS)
- Separately, I installed the Apache CXF Distribution under my tools - folder (version 3.1.6)
- I downloaded and saved a local copy of the wsdl of the Lossration Service. I edited the pointers to the *.xsd that are included so that they point to a local copy. I did this because wsdl2java requires access to the *.wsdl and related files, and LossratioService is protected (locally: basic authentication, in the diverses environments : https).
- Generate the client classes with the command-line tool of the CXF distribution:

$C:\ieu\tools\apache-cxf-3.1.6\bin\wsdl2java -client -d generated LossratioService.wsdl

- Copy the classes that have been generated to %PROJECT_ROOT%/src/
- Implement the client. Beware the particular problem of the authentication:

public final class Client {
    private static final String WSDL_URL = 
    "http://localhost:8080/LossratioService_v3_0/LossratioService_v3_0/LossratioService?wsdl";
    private static final QName SERVICE_NAME =
            new QName("http://xml.mobi.ch/service/ch/mobi/contractmanagement/LossratioService/v3_0"
            , "LossratioService");

    private static final String USERNAME = "username";
    private static final char[] PASSWORD = "password".toCharArray();

    private Client() {
    }

    public static void main(String args[]) throws Exception {

        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USERNAME, PASSWORD);
            }
        });

        URL wsdlURL = new URL(WSDL_URL);
        LossratioService ss = new LossratioService(wsdlURL, SERVICE_NAME);
        LossratioPortType port = ss.getLossratioPort();

        CallContext ctx = new CallContext();
            ctx.setCaller("ctx-caller");
            ctx.setUser("ctx-user");
            ctx.setUuid("ctx-uuid");

        ShakedownResult resp = port.shakedownTest(ctx);
        port.ping();
 }
}

I found useful hints about access to a protected wsdl on this blog 


How to rename a remote branch in GIT

There is no functionality to rename a remote branch in GIT. In order to do this, you checkout the remote branch as a new local branch with a new name, push it as a new remote branch, and finally delete the old remote branch.

Here's the cookbook:

1. Checkout the remote branch with a new name:
git branch new-branch-name origin/old-branch-name
2. Push the newly named local branch to remote:
git push origin --set-upstream new-branch-name
3. Delete the old remote branch:
git push origin :old-branch-name

Thursday, November 17, 2016

What is a detached HEAD in Git, and how to deal with it

Checkout providing a branch name:

$ git checkout development

Checkout providing a SHA1 hash of a specific commit:

$ git checkout 56a4e5c08
Note: checking out '56a4e5c08'.

You are in 'detached HEAD' state...

A "detached HEAD" describes this exact state - when a specific commit is checked out instead of a branch.

"Detached HEAD" are common

Submodules are checked out at specific commits instead of branches
Rebase creates a temporary detached HEAD

Where a detached HEAD should not show up


When going back in time to try out an older version of your project, for example in the context of a bug, when you want to see how things worked in an older revision.

This is a perfectly valid and common use case. However, you don't have to maneuver yourself into a detached HEAD state to deal with it. Instead, remember how simple and cheap the whole concept of branching is in Git: you can simply create a (temporary) branch and delete it once you're done.

$ git checkout -b test-branch 56a4e5c08
...do your thing...
$ git checkout master
$ git branch -d test-branch

How to re-attach a detached HEAD

To recover from the situation where you have a detached HEAD, you should create a branch that points to the commit currently pointed to by your detached HEAD:

$git branch temp
$git checkout temp
(these two commands can be abbreviated as git checkout -b temp)

This will reattach your HEAD to the new temp branch.

Next, you should compare the current commit (and its history) with the normal branch on which you expected to be working:

$git log --graph --decorate --pretty=oneline --abbrev-commit master $origin/master temp
$git diff master temp
$git diff origin/master temp

(You will probably want to experiment with the log options: add -p, leave off --pretty=… to see the whole log message, etc.)

If your new temp branch looks good, you may want to update (e.g.) master to point to it:

$git branch -f master temp
$git checkout master
(these two commands can be abbreviated as git checkout -B master temp)

You can then delete the temporary branch:

$git branch -d temp

Finally, you will probably want to push the reestablished history:

$git push origin master

References

[1] See an excellent explanation on the concept of detached HEAD
[2] Stackoverflow account on how to deal with a detached HEAD

Friday, November 4, 2016

How to override the hashCode, equals, toString and clone methods in Java


    @Override
    public int hashCode() {
        return new HashCodeBuilder()
                .append(contract)
                .append(periodStart)
                .append(periodEnd)
                .append(reportingDate)
                .toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof DefaKey)) {
            return false;
        }
        DefaKey other = (DefaKey) obj;
        return new EqualsBuilder()
                .append(contract, other.contract)
                .append(periodStart, other.periodStart)
                .append(periodEnd, other.periodEnd)
                .append(reportingDate, other.reportingDate)
                .isEquals();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append(getAmount().toString())
                .append(getDataType().toString())
                .toString();
    }
   
   

Monday, September 12, 2016

JDBC Connection String for Oracle

... It's been a while I hadn't had to do it. Hence: a reminder on how a JDBC connection string looks like for Oracle: 

Here's the template: 
jdbc:oracle:{driver:variants:thin:Thin=thin,OCI=oci,OCI8=oci8}:[{user}[/{password}]]@//{host::localhost}?[:{port::1521}]/{service:identifier:XE

...and here's an example:

jdbc:oracle:thin:myuser/mypwd@localhost:1521:XE

Friday, August 19, 2016

How to set the language in Oracle SQL Developer

After obtaining a new notebook  from my company, I reinstalled my developer tools, including Oracle SQL Developer.

My Notebook is configured in French, and the outcome was that SQL Developer was also configured in french, which is not what I wanted - decrypting Oracle server errors in french is not very helplful.

There is no global preference or setting where the language can be set.

I found a solution in this post in Stackoverflow:

add the following option to to the file sqldeveloper.conf file located under %sqldeveloper-home\sqldeveloper\bin :

AddVMOption -Duser.language=en

Monday, August 1, 2016

Scrum values



This is a reminder of what are the scrum values:
- Commitment
- Openness
- Focus
- Respect
- Courage

... the agile values:
- Individuals and interactions over processes and tools
- Working software over comprehensive documentation
- Customer collaboration over contract negotiation
- Responding to change over following a plan

... and the XP Practices:
- 8 hours days
- Pair programming
- common code ownership



Friday, July 8, 2016

Configuring a cxf client for SSL

Trying to configure a cxf soap client to use ssl.

The endpoint is not local. URL of the wsdl:


https://host/LossratioService_v3_0/LossratioService?wsdl

I couldn't get the configuration of the beans.xml file, so I just started the program with the vm -options to localize the keyfiles:

-Djavax.net.ssl.trustStore=C:/path/to/my/truststore.jks 
 -Djavax.net.ssl.trustStorePassword=mypassword 
 -Djavax.net.ssl.trustStoreType="JKS" 
 -Djavax.net.ssl.keyStore=C:/path/to/my/keystore.p12 
 -Djavax.net.ssl.keyStorePassword=mypassword 
 -Djavax.net.ssl.keyStoreType="PKCS12"


This is the simplest way to get it working. But I still have to run the test in maven, so that won't do it.


Git : stashing, unstashing

If the local repo is in a state I don't want to commit, and I need to switch branch or do some other work, I can use the stash command to take my current state and save it on a stack of unfinished changes to reapply later.

$git stash
$git stash list

Sunday, April 24, 2016

Comparing the order of magnitude of performance

Big O notation lets you compare the order of magnitude of performance rather than the exact performance. 

It also assumes the worst-case response time. 

If you write an algorithm that could take a while or be instantaneous, big O uses the longer one. It uses an n  to reflect the number of elements or size of the data you are talking about.

Most common big O notations:

O(1) - constant time: 
It doesn’t matter how large the collection is, the answer will always take the same time to return. Returning the string literal “Panda” from a method will take constant time, as will returning the last element of an array. 

O(log n) - logarithmic time: 
A logarithm is a mathematical function that grows much more slowly than the data size. You don’t need to know this for the exam, but log(8) gives you 3 in base 2 and log(1024) gives you 10 in base 2. The point is that logarithmic time is better than linear time. Binary search runs in logarithmic time because it doesn’t look at the majority of the elements for large collections.

O(n) - linear time: 
The performance will grow linearly with respect to the size of the collection. Looping through a list and returning the number of elements matching “Panda” will take linear time. 

O(n 2 ) - n squared time:
Code that has nested loops where each loop goes through the data takes n squared time. An example would be putting every pair of pandas together to see if they’ll share an exhibit.

Friday, April 15, 2016

Contract for the Equals method

Reflexive:

x.equals(x) should always be true for every x that is non-null.

Symmetric:

For any non-null x and y references, x.equals(y) should return true if and only if y.equals(x) is true

Transitive:

For any x, y and z non-null references, if x.equals(y) and y.equals(z) both return true, then x.equals(z) should also return true.

Consistent:

Multiple invocations of x.equals(y) should always return the same value, provided no information used in the equals comparisons is modified.

x.equals(null) should return false.

The easy way to write toString methods

Apache Commons provides a method that takes all the instance variables in the toString() method:

public String toString(){
  return ToStringBuilder.reflectionToString(this);
}

public String toString(){
  return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}

Wednesday, March 30, 2016

A simple Json Demo (2)

Building up on the previous demo, I enriched my samples with a method that returns a Json array.

After doing a bit of research, I came up with this solution: my method returns a JsonArray:


...
@GET
@Path("testArray")
@Produces({MediaType.APPLICATION_JSON})
public JsonArray testArray4() throws Exception {

    JsonArray value = Json.createArrayBuilder()
            .add(Json.createObjectBuilder()
                    .add("firstName", "Barak")
                    .add("lastName", "Obama"))
            .add(Json.createObjectBuilder()
                    .add("firstName", "Bill")
                    .add("lastName", "Clinton"))
            .build();
    return value;
}
...

It is available under http://localhost:8080/demoRest/demo/testArray

Note that the deployment occurs using the exploded war of IntelliJ on Glassfish 4.1, which allows defining a custom context root under "/". Otherwise, the *.war file being (oddly) DemoBean_war.war, the URL would be http://localhost:8080/DemoBean_war/demoRest/demo/testArray.

I first made diverse other attempts, which all failed because of the internal binding that takes place during Json processing: using a list of dtos, a list of JsonObject, or a list of dtos wrapped in a GenericEntity: all attempt failed with diverse errors in relations with the libraries available on the server:

java.lang.NoClassDefFoundError: 
  javax/xml/parsers/ParserConfigurationException
java.lang.NoClassDefFoundError: 
  Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
java.lang.ClassNotFoundException: 
  javax.xml.parsers.ParserConfigurationException not found by org.eclipse.persistence.moxy



The solution using a Json Array proved to be working on Glassfish 4.1.1

I found some information about incompatibilities in Jersey Libs of Glasshfish 4.1.1 on the Jersey Jira, but none helped me solving the problems.

I found a hint in Adam's Bien Blog for returning a list of objects with JAX-RS, but this didn't solve the problems that occured when running on Glassfish. 

I also could not deploy successfully the examples on JBoss, but did not investigate further.









Monday, March 28, 2016

A simple, simple json and rest demo

I created a simple demonstration of a Rest - application, based on the examples from the Java EE Tutorial.

My demo just returns a Json object.

I used IntelliJ, configuring module facets for library dependencies.

I did not use any maven for build or dependency management.

Deployment is done on a local Glassfish instance.

Project configuration IntelliJ

Project settings use the facets EJB, Web and Java EE application. Libraries : ejb 3.2, javax.json.processing-1.0, JAX-RS.

Code

Code consists of 2 classes : one application - Class (that inherits from javax.ws.rs.core.Application), and one implementation class, where the json processing takes place, and with the rest annotations.

Application class

package org.nstern.demos.rest;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/demoRest")
  public class RestDemoApplication extends Application {
}

Implementing class

package org.nstern.demos.rest;

import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

@Path("/demo")
public class RestDemoResource {

    @Context    private UriInfo context;

    public RestDemoResource(){}

    @GET    
    @Path("test")
    @Produces({MediaType.APPLICATION_JSON})
    public String testBean() {
        return "123456789";
    }

    @GET    
    @Path("testJson")
    @Produces({MediaType.APPLICATION_JSON})
    public JsonObject testJson() {

        JsonObject model = Json.createObjectBuilder()
                .add("firstName", "Duke")
                .add("lastName", "Java")
                .build();

        return model;
    }
}

Deployment and calling the Rest methods

Artefact is configured in IntelliJ in the Glassfish config (war exploded). I defined a custom context root to avoid cumbersome URLs.

I call the rest method using Chrome advanced rest client:

The two urls are :
http://localhost:8080/demoRest/demo/test
http://localhost:8080/demoRest/demo/testJson

Summary, remarks

I had to struggle before finding out that if I don't define a custom context root, the application will use a strange root URL  - like "http://localhost:8080/demoBean_war_exploded/etc.*"

I found a useful hint about generating artefacts (*.war file) on this blog. (This is pure handling of IntelliJ).

Not that this application has no web.xml

Wednesday, March 23, 2016

How to validate an input field with Angular JS

Angular JS offers a very simple way to validate an entry into an input field with a regular expression with the ng-pattern attribute.

I had to change a behavior of an input field in an application: special characters like 'ä', 'ö', 'ü' were not allowed, but should have.

The interesting thing is that the pattern can be assigned dynamically.

Here is the setup:

for a static pattern, I use a variable (vm.regex) in my controller.

(function () {
    var valApp = angular.module("valApp", []);
    valApp.controller("ListCtrl", ListController);
    function ListController() {
        var vm = this;
        vm.regex ='\\d+';
        ...
    }
})();

... and in the view, the attribute ng-pattern references this variable: 


<div class="container" ng-app="valApp">
  <div class="row" ng-controller="ListCtrl as ctrl">
    <form name="myForm">
      <div class="span4">
          <p>
            <label>Field1:</label>
            <input name="field1" 
            type="text" 
            ng-model="ctrl.item.field1" 
            ng-pattern="'\\d'"/>
          </p>
          <p>
            <label>Field2:</label>
            <input name="field2" 
            type="text" 
            ng-model="ctrl.item.field2" 
            ng-pattern="ctrl.regex"/>
          </p>
      </div>
    </form>
  </div>
</div>

Now, the pattern to allow characters with "Umlauten" (ä,ü,ö) is as follows:

[a-zA-Z0-9öüäÖÜÄ]+


Sunday, January 31, 2016

Setup for a simple EJB demo on Glassfish 4

I reviewed recently a very good serie of tutorials on JavaEE on the Coreservlet site. Though they all are excellent, they are a bit outdated, and I had to try a bit to get the simple example running.

I took the EJB 3 and Web Services tutorial, which describes setup for JBoss 5 and Glassfish. Using Eclipse Mars, I had no trouble to get the EJB - project deployed on Glassfish, and the Web client accessing this EJB.

The standalone client was missing a library, so I kept getting  javax.naming.NamingException: Lookup failed Exceptions when trying to access the remote service.

I searche the correct jndi configuration, but everything looked ok.

Finally, I found in this post in the Glassfish doc something that rang a bell: client libraries : my setup did not include the client libraries for Glassfish, so I added gf-client-module.jar from the Glassfish Libraries (under %GLASSFISH_HOME%/modules). Everything ran like a breeze.

My setup in short:

My client program consist of a single java file, where an initial context is initialized with a jndi.properties in the classpath (under ../src ).

java code for the context and service access:

...  
InitialContext context = new InitialContext();
  NumberService service = (NumberService)context.lookup("NumberCreator"); 
...

Content of jdni.properties:

java.naming.factory.initial=com.sun.enterprise.naming.SerialInitContextFactory
java.naming.factory.url.pkgs=com.sun.enterprise.naming
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl
org.omg.CORBA.ORBInitialHost=localhost
org.omg.CORBA.ORBInitialPort=3700

 Beware that jndi.properties is specific to the server flavor: it is not the same for accessing a service on a JBoss server.

Of course, the service remote interfaces must also be accessible to the client program. Here is an example of one such interface:


package coreservlets.bean;

import javax.ejb.*;

@Remote
public interface NumberService {
  public double getNumber(double range);

}




Saturday, January 23, 2016

Correct usage of the re-render attribute in a JSF / richFaces page

I currently have to take care of a JSF application that causes us a bunch of troubles. Because of my lack of experience with Front-End components, I ran into a problem, that a careful study of the JSF - Documentation would have prevented.

Our JSF page has a radio button with 2 possible values (say "A" and "B"). Setting the value to "B" should trigger another component to be updated (on the view) - in this case, it's a boolean checkbox. On the JSF Bean, the value that is mapped to the checkbox is updated when the user selects "B" in the radio.

To make the Checkbox updated on the web page after selecting "B" in the radio button : just set the reRender attribute of the a4j - Tag of the radio button accordingly:


<h:selectOneRadio 
  id="myId" 
  immediate="true" 
  value="#{MyBean.myAttribute}">
<f:selectItem itemValue="A" itemLabel="A" />
<f:selectItem itemValue="B" itemLabel="B" />

<a4j:support event="onclick"
action="#{MyBean.myMethod}"
reRender="otherPanel,yetAnotherPanel" />