Wednesday, 11 May 2016

WebSphere stdout/stderr logging redirect

Working on an application using log4j and deployed in WebSphere, we had the need to output the logs on the SystemOut.log and SystemErr.log files. In WebSphere with the normal configuration it outputs all the logs in the SystemOut.log.

We wanted only the ERROR and WARN level logs redirected to the SystemErr.log file, so we used the configuration below for the log appenders.

log4j.properties


########################################
# LOG4J-properties
########################################

# This is the configuring for logging displayed in the Application Server
log4j.rootCategory=DEBUG, stdout, stderr

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold=DEBUG
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %t (%d{dd/MM/yy HH:mm:ss}) %c{1} - %m\n
log4j.appender.stdout.filter.filter1=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.stdout.filter.filter1.levelMin=DEBUG
log4j.appender.stdout.filter.filter1.levelMax=INFO

log4j.appender.stderr=org.apache.log4j.ConsoleAppender
log4j.appender.stderr.Threshold=WARN
log4j.appender.stderr.Target=System.err
log4j.appender.stderr.layout=org.apache.log4j.PatternLayout
log4j.appender.stderr.layout.ConversionPattern=[%-5p] %t (%d{dd/MM/yy HH:mm:ss}) %c{1} - %m\n

log4j.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
        <param name="threshold" value="debug" />
        <param name="target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%-5p] %t (%d{dd/MM/yy HH:mm:ss}) %{1} - %m\n" />
        </layout>
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="LevelMin" value="debug" />
            <param name="LevelMax" value="info" />
        </filter>
    </appender>
    <appender name="stderr" class="org.apache.log4j.ConsoleAppender">
        <param name="threshold" value="warn" />
        <param name="target" value="System.err"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%-5p] %t (%d{dd/MM/yy HH:mm:ss}) %c{1} - %m\n" />
        </layout>
    </appender>
    <root>
        <level value="DEBUG"/>
        <appender-ref ref="stdout"/>
        <appender-ref ref="stderr"/>
    </root>
</log4j:configuration>

Sunday, 12 July 2015

Message Bundle from DB - Part 1 (J2EE)

This is the first part of a post about message bundles. Having to work on applications requiring support for different languages I had the need to have a message bundle retrieving the translation from a DB. With a  DB was easier to update labels not correctly translated without the need of restarting the application.

We are going to build a service providing the functionality to store and retrieve localized messages from a database. In the second part we will build the same with the Spring Framework.

Source code: https://github.com/oivarc/j2ee-samples.git

The source code you will find on the repository contains a bit more of what is showed here. There is also a simple page used for test that gives the possibility to add/edit the label in different languages.
The code has been tested using NetBeans, Glassfish 4.1, JavaDB. It uses the EclipseLink for the JPA connection and PrimeFaces for the UI.

Let's start introducing the database structure we will utilize to store the localized messages. The table structure is quite simple, but will allow us to store messages in all the languages we need without changing the structure to add new languages.

MYSQL table structure

CREATE TABLE message_bundle (
  id BIGINT(20) NOT NULL AUTO_INCREMENT,
  bundle_key VARCHAR(255) NOT NULL,
  language CHAR(2) NOT NULL,
  label VARCHAR(255) NOT NULL,
  PRIMARY KEY (id),
  KEY IDX_KEY_LANGUAGE (bundle_key,language)
)

Next we need to define an entity mapping the table:

MessageBundle.java
@Entity
@Table(name = "message_bundle")
public class MessageBundle implements Serializable {

    private static final long serialVersionUID = -1L;
    
    @EmbeddedId
    private MessageBundleKey id;

    @Column(name = "label")
    private String label;

    public MessageBundleKey getId() {
        return id;
    }

    public void setId(final MessageBundleKey someId) {
        id = someId;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(final String someLabel) {
        label = someLabel;
    }

}

MessageBundleKey.java

@Embeddable
public class MessageBundleKey implements Serializable {

    private static final long serialVersionUID = -1L;

    @Column(name = "bundle_key")
    private String key;

    @Column(name = "language")
    private String language;

    /**
     * Default constructor.
     */
    public MessageBundleKey() {
    }

    /**
     * Constructor given the bundle key and language.
     * @param someKey The bundle key.
     * @param someLanguage The language.
     */
    public MessageBundleKey(final String someKey, final String someLanguage) {
        key = someKey;
        language = someLanguage;
    }

    public String getKey() {
        return key;
    }

    public void setKey(final String someKey) {
        key = someKey;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(final String someLanguage) {
        language = someLanguage;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        MessageBundleKey that = (MessageBundleKey) o;

        if (!key.equals(that.key)) {
            return false;
        }
        if (!language.equals(that.language)) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = key.hashCode();
        result = 31 * result + language.hashCode();
        return result;
    }
}

Now we can define the bean that will act as our ResourceBundle. The name of the bean is the one we will use in the JSF pages to access the resource bundle. In the bean is injected a MessageBundleService that contains the methods to retrieve the messages from the database. For brevity I will not report the full code of the service here as you can find it following the link to the code.

DBMessageBundle.java

@Named(value = "msg")
public class DBMessageBundle extends ResourceBundle {

    private static final Logger LOGGER = LoggerFactory.getLogger(DBMessageBundle.class);

    @Inject
    private MessageBundleService messageBundleService; 

    public DBMessageBundle() {
        super();
    }

    @Override
    protected Object handleGetObject(final String key) {
        FacesContext context = FacesContext.getCurrentInstance();
        Locale locale = context.getViewRoot().getLocale();
        LOGGER.debug("Getting message {} for language {} from DB", key, locale.getLanguage());
        return messageBundleService.findByKeyAndLanguage(key, locale.getLanguage()).getLabel();
    }

    @Override
    public Enumeration<String> getKeys() {
        return Collections.enumeration(messageBundleService.findAllKey());
    }

}


MessageBundleService.java

public interface MessageBundleService {

    String BEAN_NAME = "messageBundleService";

    Page<MessageBundle> findPaginated(PageRequest somePageRequest);

    List<String> findAllKey();

    List<MessageBundle> findByKey(String someKey);

    MessageBundle findByKeyAndLanguage(String someKey, String someLanguage);

    MessageBundle saveOrUpdate(MessageBundle someMessageBundle);

    void delete(MessageBundle someMessageBundle);
}

The service allows also the loading of the messages in paginated mode using the Page and PageRequest classes. These classes should be familiar to who is used to the Spring repository.

Page.java


public class Page<T> implements Serializable {



    /**

     * The content of the page.

     */
    private List<T> content;

    /**
     * The total amount of entities.
     */
    private int count;

...

}

PageRequest.java

public class PageRequest implements Serializable {

    private int start;

    private int pageSize;

    private SortOrder sortOrder;

    private String sortField;

    private Map<String, String> filters = new HashMap<>();

...

}


Ok, now that we have our custom ResourceBundle let's see how we use it in our JSF pages. The example is a PrimeFaces output label. 

 <p:outputLabel for="pageLanguage" value="#{msg['messagebundleSample.pageLanguage']}" />


That's all for now. 

In the second part I will show what to do to implement the same with Spring, providing a working example. 

Tuesday, 17 March 2015

Spring Data Repositories: Query by Specification

Working with Spring and Spring Data repositories I got the need to have flexible queries based on some of the property of an entity class that should be put in OR in the query if they were present. Instead of creating a query for each combination of properties, I used one of the facilities provided by Spring-Data: the query by Specification.

Before going into the details some background information. What I am going to show is an example based on the JpaRepository using Hibernate as persistency layer.

A full working example can be found here: query-by-spec

The trick is in the use of the Specification interface in combination with a JpaSpecificationExecutor.
Let's start...

First we define an entity with some properties:

@Entity
@Table(name = "person")
public class Person {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(name = "name")
private String name;

@Column(name = "surname")
private String surname;

@Column(name = "city")
private String city;

@Column(name = "age")
private Integer age;

        ....

}

Then we define our repository:

public interface PersonRepository extends JpaRepository<Person, Long>, JpaSpecificationExecutor<Person> {

}

As you can see we have extended another interface the JpaSpecificationExecutor. This interface defines the methods to perform the search via a Specification class.

What we have to do now is to define our specification that will return the Predicate containing the constraints for the query (in the example the PersonSpecification is performing the query select * from person where name = ? or (surname = ? and age = ?) ):

public class PersonSpecification implements Specification<Person> {

    private Person filter;

    public PersonSpecification(Person filter) {
        super();
        this.filter = filter;
    }

    public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> cq,
            CriteriaBuilder cb) {

        Predicate p = cb.disjunction();

        if (filter.getName() != null) {
            p.getExpressions()
                    .add(cb.equal(root.get("name"), filter.getName()));
        }

        if (filter.getSurname() != null && filter.getAge() != null) {
            p.getExpressions().add(
                    cb.and(cb.equal(root.get("surname"), filter.getSurname()),
                            cb.equal(root.get("age"), filter.getAge())));
        }

        return p;

    }

}

Now it is time to use it. The following code fragment shows how to use the Specification we just created: 

...
        Person filter = new Person();
        filter.setName("Mario");
        filter.setSurname("Verdi");
        filter.setAge(25);

        Specification<Person> spec = new PersonSpecification(filter);

        List<Person> result = repository.findAll(spec);

...


Sunday, 28 April 2013

How to take screenshots of your android app

In this post I will explain how to take the screenshots you need to publish your app on google play shop.
I know that searching around the web you can find a lot of other posts on the same argument, but I wrote this as my reminder.

Prerequisites


This article suppose you have already installed the Android SDK and that you know how to setup you device to use the debugging mode. I will write other articles on those topics in future posts.

Take a screenshot

Taking a screenshot is a very easy operation to do. If you follow the steps below you will get it in few seconds (well few if you match the prerequisites :-) ). Ok, stop talking and let's take the shots:

1. Connect your device in debug mode to the pc
2. Start your Eclipse with the Android SDK configured
3. Switch to the DDMS perspective


4. On the left panel you should see the devices you connected to the pc in debug mode. Select the one from which you want to take screenshots


 5. Click on the small camera icon on the top and you will get the "Device Screen Capture" popup.




6. And finally the last step. Click on "Save" and you will get your screenshot in png format.

To get additional screenshots you just need to switch activity on your phone and click on the "Refresh" button on the "Device Screen Capture" popup and click "Save".

Easy!!! Enjoy your screenshots.

Sunday, 10 March 2013

JSF2 View Scope with Spring Core

Working with Spring and JSF2 I encountered the need to use something like a ViewScope bean.

The Spring Framework support the following scopes bean scopes:

  • singleton
  • prototype
  • request
  • session
  • globalSession

Adding a new scope is quite simple using Spring. To add the View Scope in the Spring IoC container it is necessary to create a custom scope which implements the org.springframework.beans.factory.config.Scope interface and register it with the Spring Custom Scope Configurer.



ViewScope implementation


package eu.ac.tutorial.spring.scope;

import java.util.Map;
import javax.faces.context.FacesContext;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

public class ViewScope implements Scope {

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {

        if (FacesContext.getCurrentInstance().getViewRoot() != null) {
            Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
            if (viewMap.containsKey(name)) {
                return viewMap.get(name);
            } else {
                Object object = objectFactory.getObject();
                viewMap.put(name, object);
                return object;
            }
        } else {
            return null;
        }

    }

    @Override
    public String getConversationId() {
        return null;
    }

    @Override
    public void registerDestructionCallback(String arg0, Runnable arg1) {

    }

    @Override
    public Object remove(String name) {

        if (FacesContext.getCurrentInstance().getViewRoot() != null) {
            return FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove(name);
        } else {
            return null;
        }

    }

    @Override
    public Object resolveContextualObject(String arg0) {
        return null;
    }

}



Spring Configuration


<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="view">
                <bean class="eu.ac.tutorial.spring.scope.ViewScope"/>
            </entry>
        </map>
    </property>
</bean>



Usage


Now you can use it:

package eu.ac.tutorial.spring.web;

import javax.inject.Named;
import org.springframework.context.annotation.Scope;

/**
* ContactListPage JSF backing bean.
*/
@Component("contacListView")
@Scope("view")
public class ContactListView {

   @Autowire
   private ContactService contactService;

   public ContactListView() {
   }

   // etc…
}