Translate marked German – English Text with a right click – everywhere under MacOS X

There are a number of online translation services that you can use to translate words, phrases, or even entire bodies of text into another language; however, if you need to do so in OS X then there is a quick way to do so by using the Dictionary utility.

Also German-English is supported with this extension. (Many thanks to ddict to sharing the data!)

The Dictionary is Apple’s built-in word look-up tool that offers word definitions and thesaurus capabilities, along with access to Apple knowledgebase documentation and Wikipedia articles. It is the tool that the system uses when you right-click a word and choose the option to look it up.

While this tool generally is used for looking up definitions and similar words in the current system language, the dictionary does support a few languages for which it will display information about a selected word in another language. This is not the intended use of the Dictionary, so it is a somewhat crude and limited approach; however, it will give you a number of translated words, and being a contextual option makes it rather convenient.

Translation is available for Spanish, Japanese, Chinese (simplified), and Korean, and can be enabled in the Dictionary app’s preferences:

  1. Open the Dictionary App.
  2. Go to the program’s preferences.
  3. Check one of the four available “Language-English” options that is relevant for you (also the new installed Deutsch-Englisch).
  4. Optionally re-order the checked entries (this is the order that they will appear in the contextual panel).

When done, close the Dictionary and then three-finger tap a word in a program like Safari, Pages, or TextEdit, or right-click the word and choose the Look Up option. Then you should see it translated into the selected language somewhere in the panel that appears. This should work both ways, so words in English should appear in the non-English language, and vice versa.

.scss file type with the native Eclipse CSS Editor

I just figured out how to do this in Eclipse. I admit that this solution does not have 100% SASS support, the colors get a little funky when using nested css, but it’s really better than looking at plain text and you don’t need to install a separate editor.

You need to associate the .scss file type with the native Eclipse CSS Editor in Eclipse[Part 1]. After you do that, you need to add the .scss file type to the native CSS Editor as well so the CSS Editor will be able to open it [Part 2]. Here are the steps for eclipse (I’m running Eclipse Java EE IDE for Web Developers, Neo 2):

Part 1 – Associate the .scss file type with the native Eclipse CSS Editor

  1. Go to Window > Preferences
  2. Drill down to General > Editors > File Associations
  3. In File Associations pane, click the ‚Add…“ button on the top right.
  4. For File Type:, enter *.scss and then click OK.
  5. Find the *.scss entry in the File Associations list and select it.
  6. After selecting *.scss, on the bottom pane Associated editors:, click the Add... button.
  7. Make sure Internal editors is selected on the top, then find and select CSS Editor and then click OK.

This associated the file type .scss with eclipses native CSS Editor. Now we have to configure the native CSS Editor to support .scss files. To do this, follow this steps:

Part 2 – Add the .scss file type to the native CSS Editor

  1. Go to Window > Preferences
  2. Drill down to General > Content Types
  3. In the Content Types pane, expand Text, then select CSS
  4. After CSS is selected, on the bottom File associations: pane, click the Add... button.
  5. For Content type:, enter *.scss and then click OK.
  6. Click OK to close out the Preferences window.

All done. All you need to do now is close any .scss files that you have open then re-open them and wha-la, css colors in Eclipse for .scss files!

Note: If the css colours do not appear you may have to do the following: Right click the .scss file > Open With > CSS Editor.

Native Queries – How to call native SQL queries with JPA

Native Queries – How to call native SQL queries with JPA

 

The Java Persistence Query Language (JPQL) is the most common way to query data from a database with JPA. But it supports only a small subset of the SQL standard and it also provides no support for database specific features.

So what shall you do, if you need to use a database specific query feature or your DBA gives you a highly optimized query that can not be transformed into JPQL? Just ignore it and do all the work in the Java code?

Of course not! JPA has its own query language but it also supports native SQL. You can create these queries in a very similar way as JPQL queries and they can even return managed entities, if you want.

 

Create dynamic native queries

Creating a dynamic native query is quite simple. The EntityManager interface provides a method called createNativeQuery for it. This method returns an implementation of the Query interface which is the same as if you call the createQuery method to create a JPQL query.

The following code snippet shows a simple example in which I used a native query to select the first and last names from the author table. I know, there is no need to do this with a native SQL query. I could use a standard JPQL query for this, but I want to focus on the JPA part and not bother you with some crazy SQL stuff 😉
The persistence provider does not parse the SQL statement, so you can use any SQL statement that is supported by your database. In one of my recent projects for example, I used it to query PostgreSQL specific jsonb columns with Hibernate and mapped the query results to POJOs and entities.

Query q = em.createNativeQuery(SELECT a.firstname, a.lastname FROM Author a);
List<Object[]> authors = q.getResultList();
for (Object[] a : authors) {
System.out.println(Author
+ a[0]
+
+ a[1]);
}

As you can see, the created Query can be used in the same way as any JPQL query. I didn’t provide any mapping information for the result and so the EntityManager returns a List of Object[] which need to be handled afterwards. Instead of mapping the result yourself, you can also provide additional mapping information and let the EntityManager do the mapping for you. I get into more details about that in the result handling section at the end of this post.

 

Parameter binding

Similar to JPQL queries, you can and should use parameter bindings for your query parameters instead of putting the values directly into the query String. This provides several advantages:

  • you do not need to worry about SQL injection,
  • the persistence provider maps your query parameters to the correct types and
  • the persistence provider can do internal optimizations to provide a better performance.

JPQL and native SQL queries use the same Query interface which provides a setParameter method for positional and named parameter bindings. But the use of named parameter bindings for native queries is not defined by the JPA specification. Positional parameters are referenced as “?” in your native Query and their numbering starts at 1.

Query q = em.createNativeQuery(SELECT a.firstname, a.lastname FROM Author a WHERE a.id = ?);
q.setParameter(1, 1);
Object[] author = (Object[]) q.getSingleResult();
System.out.println(Author
+ author[0]
+
+ author[1]);

EclipseLink also supports named parameter bindings for native queries but as I already said, this is not defined by the specification and might not be portable to other JPA implementations.
By using named parameter bindings, you define a name for each parameter and provide it to the setParameter method to bind a value to it. The name is case-sensitive and needs to be prefixed with a “:” symbol.

Query q = em.createNativeQuery(SELECT a.firstname, a.lastname FROM Author a WHERE a.id = :id);
q.setParameter(id, 1);
Object[] author = (Object[]) q.getSingleResult();
System.out.println(Author
+ author[0]
+
+ author[1]);

 

Result handling

As you have seen in the previous code snippets, your native Query returns an Object[] or a Listof Object[]. You can change that, if you provide additional mapping information to the EntityManager. By doing this you can tell the EntityManager to map the result into managed entities, scalar values of specific types or POJOs. The simplest way to map the result of a native query into a managed entity is to select all properties of the entity and provide its as a parameter to the createNativeQuery method.

Query q = em.createNativeQuery(SELECT a.id, a.version, a.firstname, a.lastname FROM Author a, Author.class);
List<Author> authors = q.getResultList();
for (Author a : authors) {
System.out.println(Author
+ a.getFirstName()
+
+ a.getLastName());
}

All other mappings, like the following one which maps the query result into a POJO, need to be defined as SQLResultSetMappings.

@SqlResultSetMapping(
name = AuthorValueMapping,
classes = @ConstructorResult(
targetClass = AuthorValue.class,
columns = {
@ColumnResult(name = id, type = Long.class),
@ColumnResult(name = firstname),
@ColumnResult(name = lastname),
@ColumnResult(name = numBooks, type = Long.class)}))

To use this mapping, you need to provide the name of the mapping as a parameter to the createNativeQuery method.

Query q = em.createNativeQuery(SELECT a.id, a.firstname, a.lastname, count(b.id) as numBooks FROM Author a JOIN BookAuthor ba on a.id = ba.authorid JOIN Book b ON b.id = ba.bookid GROUP BY a.id, AuthorValueMapping);
List<AuthorValue> authors = q.getResultList();
for (AuthorValue a : authors) {
System.out.println(Author
+ a.getFirstName()
+
+ a.getLastName()
+ wrote
+ a.getNumBooks()
+ books.);
}

These mappings are quite powerful and you can even combine them to map a query result into multiple entities, POJOs and scalar values. Have a look at the following posts to dive deeper into SQLResultMappings:

  • Result Set Mapping: The Basics
  • Result Set Mapping: Complex Mappings
  • Result Set Mapping: Constructor Result Mappings
  • Result Set Mapping: Hibernate specific features

 

Create named native queries

You will not be surprised, if I tell you that the definition and usage of a named native query is again very similar to a named JPQL query.

In the previous code snippets, I created 3 dynamic native queries to select the names of all authors, to select all authors as entities and to select all authors and map them into AuthorValuePOJOs. I used the same queries in the following code snippet and created named queries for them.

@NamedNativeQueries({
@NamedNativeQuery(name = selectAuthorNames, query = SELECT a.firstname, a.lastname FROM Author a),
@NamedNativeQuery(name = selectAuthorEntities, query = SELECT a.id, a.version, a.firstname, a.lastname FROM Author a, resultClass = Author.class),
@NamedNativeQuery(name = selectAuthorValue, query = SELECT a.id, a.firstname, a.lastname, count(b.id) as numBooks FROM Author a JOIN BookAuthor ba on a.id = ba.authorid JOIN Book b ON b.id = ba.bookid GROUP BY a.id, resultSetMapping = AuthorValueMapping)
})

As you can see, the definition looks very similar to the definition of named JPQL queries and you can even provide the result class or the name of an SQLResultSetMapping. The named native queries are used in exactly the same way as named JPQL queries. You only need to provide the name of the named native query as a parameter to the createNamedQuery method of the EntityManager.

Query q = em.createNamedQuery(selectAuthorValue);
List<AuthorValue> authors = q.getResultList();
for (AuthorValue a : authors) {
System.out.println(Author
+ a.getFirstName()
+
+ a.getLastName()
+ wrote
+ a.getNumBooks()
+ books.);
}

 

Conclusion

JPQL provides an easy way to query data from the database but it supports only a small subset of the SQL standard and it also does not support database specific features. But this is not a real issue. You can use all these features by creating native SQL queries via EntityManager.createNativeQuery(String sql) which are send directly to the database.

Do you have any questions or comments? Do you use native SQL queries often in your projects or do you try to avoid them?
Tell about it in the comments below.

Managing transactions in EJB 3.0

Transaction represents a group of activities that must be performed as a single work unit. This clarifies that a transaction is complete if and only if all the work items within a work group results in success. If any of the work items fails, then the transaction as a whole will be treated as a failure. Managing transactions is vital not only for Enterprise applications but also for any flavour of applications. In this article we will explore the various services provided by the EJBcontainer with respect to transaction management. This article assumes that the reader has a basic understanding on EJB technology such the various EJB containers, enterprise beans etc along with the fundamental concepts of transactions such as ACID properties, commit and rollback.

Container managed transactions in EJB 3.0

It is possible for applications to provide an indication that the transactions can be managed by the Container. Such transactions which are not managed through the application’s code but through the container are called Container managed transactions. It is the responsibility of the application developer to specify the transaction demarcation through transactional attributes. This information can be specified either through Annotations or through the configuration file. Note that specifying the transactional metadata through annotations is not available until the version 3.

Transactional Attributes

Container managed transactions are supported through various transactional attributes. The available transactional attributes are as follows

  • Required
  • Requires New
  • Supports
  • Not Supported
  • Mandatory
  • Never

Required

This is the default attribute if the transactional attribute is not specified. This indicates to the container that the annotated business method has to execute within a transaction. More specifically, when there is an active transaction, and if a business method is called from within the active transaction, then the method executes as if it is part of the transaction. This means that the success or the failure of the transaction will be propagated to this transaction. When the caller is not part of a transaction, then a new transaction is started. Consider the following code snippet,

package net.javabeat.articles.ejb.txnmgmt.container.required;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class EmployeeDetailBean implements EmployeeDetailLocal {

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void createEmployeeDetail() {

    }
}

In the above enterprise bean definition, we have annotated the method createEmployeeDetail() with the ‘Required’ annotation. This business method will be called from the EmployeeBean which is defined below.

package net.javabeat.articles.ejb.txnmgmt.container.required;

import javax.ejb.EJB;
import javax.ejb.Stateless;

@Stateless
public class EmployeeBean implements EmployeeLocal {

    @EJB
    private EmployeeDetailLocal employeeDetailBean;

    public void createEmployee() {
        // Create employee here
        employeeDetailBean.createEmployeeDetail();
    }
}

As we can see in the createEmployee() method, the employee object is expected to be created first followed by the creation of employee detail object. Now if there is exception before the return of the business method ‘createEmployee()’ then the employee detail object won’t be created.

Requires New

The transactional attribute ‘Requires New’ will also start a new transaction irrespective of the fact that the caller is in active transaction or not. This attribute can be applied to business methods where the result of the calling transaction is not dependent on the business method that is annotated with ‘Requires New’.

package net.javabeat.articles.ejb.txnmgmt.container.requiresnew;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class DepartmentBean implements DepartmentBeanRemote {

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void createDepartment() {
    }
}

Considering the above example, we have a business method that creates a department object and the method is annotated with the transactional attribute ‘Requires New’. Now consider the below code,

package net.javabeat.articles.ejb.txnmgmt.container.requiresnew;

import javax.ejb.EJB;
import javax.ejb.Stateless;

@Stateless
public class EmployeeBean implements EmployeeBeanRemote {

    @EJB
    private DepartmentBeanRemote departmentBean;

    public void createEmployee() {
        // Create employee object here
        departmentBean.createDepartment();
       // Assign the newly created department object to the employee object
    }
}

Here after creating the employee object, we call the enterprise bean for creating a department. Let us assume that we a creating a new employee object and during the course of creation, we also want to create a new department object and assign it to the employee object. Now imagine a transactional failure before the return of the method createEmployee(), in which case, the creation of the department won’t be rolled back because the department creation process is in a separate transaction. This also means that when we create a different employee object we can assign this employee object to the already created department object.

Supports

The transactional attribute ‘Supports’ defines that the transactional mode has to be propagated from the caller to the business method that is annotated with ‘Supports’. This means that if the caller is in an active transaction, then the business method will also execute as part of the active transaction. This means that a failure in the business method will revert the caller’s transaction also. If the caller is not part of the transactional context, then the business method will also execute in a non-transactional context.

Not Supported

This transactional attribute can be used for scenarios where a part of the business operation shouldn’t be executed in a transactional context at all. If the caller is part of the transaction, then the caller’s transaction is suspended and resumed once the execution of the business method that is annotated with ‘Not Supports’ is completed. If the caller is not part of any transaction, then also the business method will execute outside the transactional context.

package net.javabeat.articles.ejb.txnmgmt.container.requiresnew.notsupported;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class MailSenderBean implements MailSenderLocal {

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void sendMail() {
    }

}

In the above example, we have modeled a simple sessionbean that sends a mail. Let us assume that this bean will be used as part of some user registration process. That is, once the user is registered, the application will try to send a mail by calling this enterprise bean. Because the operation of sending a mail to the customer can’t be part of a transaction, the method is annotated with ‘Not Supported’. Have a look at the caller’s code.

package net.javabeat.articles.ejb.txnmgmt.container.requiresnew.notsupported;

import javax.ejb.EJB;
import javax.ejb.Stateless;

@Stateless
public class UserRegistrationBean implements UserRegistrationLocal {

    @EJB
    private MailSenderLocal mailSenderBean;

    public void registerUser() {

        // Do user registration here
        mailSenderBean.sendMail();
    }
}

Mandatory

The transactional attribute ‘Mandatory’ can be used when we wanted to make sure that some business method has to be executed as part of a transaction. If the caller’s code is not part of the transaction, then an exception will be thrown. Have a look at the below code.

package net.javabeat.articles.ejb.txnmgmt.container.mandatory;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class MoneyTransferBean implements MoneyTransferLocal {

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void transferMoney() {

        deductMoneyFromSource();
        addMoneyToDestination();
    }

    @TransactionAttribute(TransactionAttributeType.MANDATORY)
    public void deductMoneyFromSource() {
    }

    @TransactionAttribute(TransactionAttributeType.MANDATORY)
    public void addMoneyToDestination() {
    }
}

We have defined three business methods ‘transferMoney’, ‘deductMoneyFromSource’ and ‘addMoneyToDestination’. If we assume that the business method ‘deductMoneyFromSource’ and ‘addMoneyToDestination’ should be part of some transactional method ‘transferMoney’, then these methods have to be annotated with ‘Mandatory’ annotation. This ensures that the business methods ‘deductMoneyFromSource’ and ‘addMoneyToDestination’ cannot be and shouldn’t be executed from a non-transactional environmental context.

Never

This is a rarely used transactional attribute as an exception will be thrown if a caller, as part of an active transaction, executes a business method that is annotated with ‘Never’.

package net.javabeat.articles.ejb.txnmgmt.container.never;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class DataLoaderBean implements DataLoaderLocal {

    @TransactionAttribute(TransactionAttributeType.NEVER)
    public void loadDataFromXml(String xmlFilename) {
    }

    @TransactionAttribute(TransactionAttributeType.NEVER)
    public void loadDataFromFlatFile(String filename) {
    }

}

In the above example, we have business methods for loading data from a non-transactional data resource such as the file system. Hence we have given the transactional attribute as ‘Never’.

Bean Managed transactions in EJB 3.0

Now that we have seen the advantages and the usage of CMT, let’s see where and how to use Bean Managed Transactions. Even though it is quite uncommon, still there are scenarios where customizations with respect to transaction handling might be required at the application level. The level of customization include when to begin a transaction in a business method, when to commit a transaction by defining a successful scenario and when to rollback a transaction for a failure scenario. For example consider the sample code,

package net.javabeat.articles.ejb.txnmgmt.bean;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.transaction.UserTransaction;

@TransactionManagement(value=TransactionManagementType.BEAN)
@Stateless
public class BillPaymentBeanBean implements BillPaymentBeanLocal {

    @Resource
    private UserTransaction userTransaction;

    public void payBill() throws Exception{

        try{
            userTransaction.begin();

            provideBillDetailsInfo();
            identifyCustomerAccount();
            makeBillPayment();

            userTransaction.commit();
        }catch (IncorrectBillDetailsException exception){
            userTransaction.rollback();
        }catch (InvalidCustomerAccountException exception){
            userTransaction.rollback();
        }catch (PaymentException exception){
            userTransaction.rollback();
        }
    }

    private void identifyCustomerAccount()
        throws InvalidCustomerAccountException {
    }

    private void makeBillPayment() throws PaymentException{
    }

    private void provideBillDetailsInfo()
        throws IncorrectBillDetailsException{
    }
}

The first obvious thing to be noted in BMT is that we have to use @TransactionManagement(BEAN) to instruct the container that we are using Bean managed transactions for this enterprise bean. The above example shows how to use BMT with the help of UserTransaction interface. UserTransaction provides a single entry point for managing bean managed transactions and to obtain a valid reference to this interface, the annotation @Resource can be used. This makes sure that the container populates the UserTransaction reference and makes it available. To signal the logical beginning of a transaction, the method begin() can be used. Similarly there are commit() and rollback() signaling that the transaction is successful or failure respectively. Note that in the above example case, whenever we encounter a exception scenario, we indicate that the transaction is a failure by calling the rollback() method. The code snippet for the related exception classes are given below.

package net.javabeat.articles.ejb.txnmgmt.bean;
public class IncorrectBillDetailsException extends Exception{
}

package net.javabeat.articles.ejb.txnmgmt.bean;

public class InvalidCustomerAccountException extends Exception {
}

package net.javabeat.articles.ejb.txnmgmt.bean;

public class PaymentException extends Exception{

}

Handling Exceptions in EJB 3.0

It is important to understand the effect of exceptions when dealing with transactional business methods. In the context of Enterprise beans, exceptions can be either classified as System Exception or Application Exception.

System Exception

The default behaviour of the EJB Container is to rollback the transaction whenever a System exception occurs. Any Exception that is a subclass of RuntimeException or RemoteException will be classified and treated as a System exception. This is the default exception handling when the transaction is managed by the container. When a system error is encountered, the calling client will always perceive that exception as a instance of EJBException or RemoteException. However in the case of Bean managed transactions, it is upto the application as how to handle the system exception, though it is considered as a bad programming practice to catch a system exception and not performing a rollback. For example, consider the following code snippet

@Resource
private UserTransaction transaction;
public void someBizMethod(){

	try{
		transaction.begin();
	}catch (NullPointerException npe){
		transaction.commit();
	}
}

In the above exception, even through NullPointerException is a system exception (because NullPointerException is an instance of RuntimeException), we are making a commit by calling the transaction’s commit() method.

Application Exception

Application exceptions are generally thrown when the attempt is made to execute a business method results in an error because during the course of the execution it is identified that some business logic went wrong. For example, while performing money transfer between two accounts it is mandatory that sufficient funds have to be present in the source account. An application error can be thrown during the execution of this business method because of insufficient funds. By default when an application error is thrown, the container won’t rollback the transaction as opposed to System exceptions. Also the exception will be reached its client in its regular form, i.e unlike System exceptions, where the source of the exception will be wrapped as either EJBException or RemoteException.
There can be cases where we want to make the transaction rollback for an application exception. In the case of a Bean managed transaction, this scenario is straight-forward, as the application has the control over the UserTransaction. Rolling the transaction would be as simple to call the method rollback(). However, in the case of the Container managed transactions, the situation becomes quite tricky and the annotation @ApplicationException comes to the rescue. For example, let us consider that in the example of money transfer, if sufficient amount is not available in the source account, then we want to throw a customized exception called InsufficientFundsException and also to rollback the transaction.

@ApplicationException(rollback=true)
public class InsufficientFundsException extends Exception{
	public InsufficientFundsException(String message){
	}
}

In the above code snippet, we have created a customized exception along with the annotation Application Exception with the attribute rollback set to true. This ensures that for a business method, that declares this exception at the throws clause, when this exception is encountered during the execution of the business operation, the container will request for a transaction rollback.

Persistence Context and Entity Manager

Closely associated with EJB transactions are Entity Manager and Persistence Contexts. Entity Manager is an interface for managing entites whereas Persistence Context is an annotation that can be applied on Entity Manager instances. The annotation has name, persistence unit name and type. The persistence unit name, if specified has to match the unit name that is defined in the persistence.xml file. Persistence context can either be transaction scoped or extended scoped. If the persistence context operates in transaction scope, then it means that the entities that are associated with the persistence context have the life-time equal to that of the transaction. That is, when the transaction ends, any changes done to the entities wont get notified to the persistence context. However, in the case of the extended persistence context, the entities will be attached to the persistence context even after the completion of the transaction. The entities will be detached from the persistence context only when the method close() is called on the Entity Manager object.
Consider the following piece of code,

package net.javabeat.articles.ejb.transactions.application;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class ApplicationFacade implements ApplicationFacadeRemote {

    @PersistenceContext
    private EntityManager em;

    public void create(Application application) {
        em.persist(application);
    }

    public void edit(Application application) {
        em.merge(application);
    }

    public void remove(Application application) {
        em.remove(em.merge(application));
    }

    public Application find(Object id) {
        return em.find(Application.class, id);
    }

    public List findAll() {
        return em.createQuery("select object(o) from Application as o").getResultList();
    }
}

Note that the entity manager reference is injected by the container as it is annotated with @PersistenceContext annotation. If the persistent unit name is not specified as part of the annotation, then by default, the file name persistence.xml will be looked up for finding the persistence name. The contents of the persistence.xml is given below,

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="Application-ejbPU" transaction-type="JTA">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>
    <jta-data-source>new</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="toplink.ddl-generation" value="drop-and-create-tables"/>
    </properties>
  </persistence-unit>
</persistence>

Conclusion

This article started by exploring the various techniques of managing transactions in an EJBenvironment – namely the Container Managed transactions and Bean managed transactions. The various transactional attributes that are applicable for contained managed transactions are given a healthier discussion under the section ‘Transactional attributes’. Also for easier understanding, many sample code snippets were presented for illustration. Then the article went on with discussing the usage the Bean managed transactions. Because it is essential to understand the impact of exception handling with respect to transactions, the final section of the article explained the exception handling mechanisms for System Exceptions and Application Exceptions.

Install GlassFish 4.1 on a Centos 7

install-glassfish-on-a-centos-7-vpsIn this tutorial, we will explain how to install GlassFish Server Open Source Edition 4.1 on a Centos 7.1 VPS. GlassFish is an open-source application server project and it’s Oracle’s concrete implementation of Java EE. This guide should work on other Linux systems as well but was tested and written for a Centos 7.

Login to your System via SSH

ssh root@host

Update the system and install necessary packages

[root]$ yum -y update
[root]$ yum install unzip wget

Create a new system user

Create a new user for the Glassfish server:

[root]$ adduser \
   --comment 'Glassfish User' \
   --home-dir /home/glassfish \
   glassfish

Install Oracle JDK 8

GlassFish 4.1 requires JDK 8 u20 or above. Use the command below to download the Oracle JDK 8 from the command line using wget:

[root]$ wget --no-cookies \
    --no-check-certificate \
    --header "Cookie: oraclelicense=accept-securebackup-cookie" \
    "http://download.oracle.com/otn-pub/java/jdk/8u45-b14/jdk-8u45-linux-x64.rpm" \
    -O jdk-8u45-linux-x64.rpm

Once the rpm package is downloaded, install it with:

[root]$ yum install jdk-8u45-linux-x64.rpm

To check if JAVA has been properly installed on your CentOS box run java -version, and the output should be similar to the following:

[root]$ java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

Download and extract the GlassFish 4.1 archive

Switch to the glassfish user:

[root]$ su - glassfish

As the glassfish user, download and extract the latest GlassFish 4.1 archive

[glassfish]$ wget http://download.java.net/glassfish/4.1/release/glassfish-4.1.zip
[glassfish]$ unzip glassfish-4.1.zip
[glassfish]$ rm -f glassfish-4.1.zip

Switch back to the root user:

[glassfish]$ exit

Create systemd service

To create a new systemd service for GlassFish, open your editor of choice and create a new file:

[root]$ nano /etc/systemd/system/glassfish.service

and add the following code lines:

[Unit]
Description = GlassFish Server v4.1
After = syslog.target network.target

[Service]
User=glassfish
ExecStart = /usr/bin/java -jar /home/glassfish/glassfish4/glassfish/lib/client/appserver-cli.jar start-domain
ExecStop = /usr/bin/java -jar /home/glassfish/glassfish4/glassfish/lib/client/appserver-cli.jar stop-domain
ExecReload = /usr/bin/java -jar /home/glassfish/glassfish4/glassfish/lib/client/appserver-cli.jar restart-domain
Type = forking

[Install]
WantedBy = multi-user.target

Start the glassfish server and set it to start automatically on boot:

systemctl enable glassfish.service
systemctl start glassfish.service

To verify the unit started, run journalctl -f -u glassfish.service and you should see something like below:

[root]$ journalctl -f -u glassfish.service
Apr 26 17:36:13 vps systemd[1]: Starting GlassFish Server v4.1...
Apr 26 17:36:19 vps java[2767]: Waiting for domain1 to start .....
Apr 26 17:36:19 vps java[2767]: Successfully started the domain : domain1
Apr 26 17:36:19 vps java[2767]: domain  Location: /home/glassfish/glassfish4/glassfish/domains/domain1
Apr 26 17:36:19 vps java[2767]: Log File: /home/glassfish/glassfish4/glassfish/domains/domain1/logs/server.log
Apr 26 17:36:19 vps java[2767]: Admin Port: 4848
Apr 26 17:36:19 vps java[2767]: Command start-domain executed successfully.
Apr 26 17:36:19 vps systemd[1]: Started GlassFish Server v4.1.

Firewall

The default GlassFish port numbers are:

  • Administration: 4848
  • HTTP listener: 8080
  • HTTPS listener: 8181

For example to open port 8080 in the firewall, run:

firewall-cmd --zone=pubic --add-port=8080/tcp --permanent  
firewall-cmd --reload  


For slower systems

# vi /etc/systemd/system.conf
DefaultTimeoutStartSec=90s

That’s it. You have successfully installed your GlassFish . For more information about GlassFish , please refer to the Glassfish website.

Converting between Date and java8 java.time.LocalDateTime, LocalDate and LocalTime

Java8 has new date and time classes to “replace” the old not-so-beloved java.util.Date class.

Unfortunately though, converting between the two is somewhat less obvious than you might expect.

Convert java.util.Date to java.time.LocalDateTime

Date ts = ...;
Instant instant = Instant.ofEpochMilli(ts.getTime());
LocalDateTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

The big trick (for all these conversions) is to convert to Instant. This can be converted to LocalDateTime by telling the system which timezone to use. This needs to be the system default locale, otherwise the time will change.

Convert java.util.Date to java.time.LocalDate

Date date = ...;
Instant instant = Instant.ofEpochMilli(date.getTime());
LocalDate res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();

Convert java.util.Date to java.time.LocalTime

Date time = ...;
Instant instant = Instant.ofEpochMilli(time.getTime());
LocalTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalTime();

Convert java.time.LocalDateTime to java.util.Date

LocalDateTime ldt = ...;
Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant();
Date res = Date.from(instant);

Convert java.time.LocalDate to java.util.Date

LocalDate ld = ...;Instant instant = ld.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date res = Date.from(instant);

Convert java.time.LocalTime to java.util.Date

LocalTime lt = ...;
Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
        atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);

This one is a little, funny, you need to inject a date to convert the time… Gives you the option of start of epoch or something else.

Einholen der Zustimmung für Cookies

Warum ist das wichtig?

Gemäß europäischen Gesetzen müssen Publisher von digitalem Content die Besucher ihrer Websites und Apps darüber informieren, wie sie Cookies und andere Formen der lokalen Speicherung verwenden. In vielen Fällen machen diese Gesetze auch das Einholen einer Zustimmung erforderlich.

Diese Website wurde von Google erstellt. Wir arbeiten mit zahlreichen Publishern als Partner zusammen. Auf Grundlage dieser Erfahrungen möchten wir Ihnen einfach zu implementierende Tools bereitstellen, mit denen Sie Ihren gesetzlichen Verpflichtungen nachkommen und die Zustimmung Ihrer Besucher zur Verwendung von Cookies einholen können.

Was muss ich tun?

Über die Anforderungen an die Einhaltung der einschlägigen Gesetze informieren die Datenschutzbehörden und die Verbände der Online-Werbewirtschaft (Interactive Advertising Bureaus, IABs) (siehe unten) in ganz Europa. Außerdem sollten Sie sich speziell zu Ihrer Website oder Ihrer App rechtlich beraten lassen. Wir sind uns allerdings bewusst, dass viele Publisher keine Möglichkeit haben, eine Rechtsberatung in Anspruch zu nehmen.

Es gibt verschiedene, zum Teil kostenlose Tools und Lösungen, mit denen Sie auf Ihrer Website eine Funktion implementieren können, um die Zustimmung zur Verwendung von Cookies einzuholen. Eine Auswahl:

Diese Lösungen bieten unterschiedliche Konfigurationsmöglichkeiten. Bei einigen davon können Nutzer auswählen, welche Cookies von Ihrer Website sie zulassen möchten. So könnten Sie Besuchern beispielsweise die Option bieten, Werbecookies zu blockieren. Beachten Sie bitte, dass durch solche Konfigurationen die Cookies auf Ihrer Website nicht automatisch gesteuert werden.

Wenn Sie den Werbedienst eines Drittanbieters wie Google AdSense verwenden, sind einige Schritte erforderlich, um die Werbe-Tags auf Ihren Seiten an die verwendete Lösung anzupassen. Erst dann ist sichergestellt, dass die Vorgaben Ihrer Nutzer eingehalten werden. Alle Anbieter stellen entsprechende Anleitungen oder Supportservices bereit. Wenn Sie diese notwendigen Schritte nicht für alle Tags auf Ihren Seiten ausführen, besteht die Gefahr, dass Nutzer fälschlicherweise annehmen, sie hätten Werbe-Cookies deaktiviert. Tatsächlich werden diese Cookies jedoch weiterhin verwendet. Testen Sie daher sorgfältig jede Implementierung dieser Tools auf Ihrer eigenen Website.

Welche Angaben muss mein Hinweis zum Einholen der Zustimmung enthalten?

Leider können wir Ihnen nicht den genauen Wortlaut des Hinweises für Ihre Website oder App nennen, da er weitgehend davon abhängt, wie genau Sie Cookies und Daten verwenden und welche Drittanbieterlösung Sie einsetzen. Wir können Ihnen jedoch einige Tipps geben.

Der folgende Hinweis könnte für Ihre Website geeignet sein, wenn Sie Google AdSense, Google Analytics oder ähnliche Produkte anderer Anbieter verwenden. Dieser Hinweis muss an die Art der Verwendung von Cookies und anderen Daten auf Ihrer Website angepasst werden.

Wir verwenden Cookies, um Inhalte und Anzeigen zu personalisieren, Funktionen für soziale Medien anbieten zu können und die Zugriffe auf unsere Website zu analysieren. Außerdem geben wir Informationen zu Ihrer Nutzung unserer Website an unsere Partner für soziale Medien, Werbung und Analysen weiter. Details ansehen

Der Hinweis für eine App unterscheidet sich etwas:

Wir verwenden Gerätekennungen, um Inhalte und Anzeigen zu personalisieren, Funktionen für soziale Medien anbieten zu können und die Zugriffe auf unsere App zu analysieren. Außerdem geben wir diese Kennungen und andere Informationen über Ihr Gerät an unsere Partner für soziale Medien, Werbung und Analysen weiter. Details ansehen

Worauf sollte der Link „Details ansehen“ verweisen?

Über den Link in Ihrer Nachricht könnte der Bereich, der die Nachricht enthält, erweitert werden. So werden zusätzliche Informationen angezeigt oder es wird eine neue Seite mit weiteren Einzelheiten geöffnet. Diese neue Seite könnte Teil Ihrer Datenschutzerklärung sein oder eine Richtlinie für Cookies enthalten.

Wie bereits erwähnt, können wir den Wortlaut des Hinweises nicht genau vorgeben. Er richtet sich danach, welche Cookies und andere Daten sowie welche Dienste Sie verwenden und welche Optionen zur Deaktivierung Sie auf Ihrer Website anbieten. Wir können Ihnen allerdings einige Tipps zu den Google-Produkten geben, die Sie auf Ihrer Website einsetzen.

Wenn Sie Google-Produkte wie Google AdSense oder DoubleClick for Publishers verwenden, sind Sie vertraglich dazu verpflichtet, die EU-Richtlinie zum Einholen der Zustimmung von Google zu befolgen. Wenn Sie Google Analytics-Werbefunktionen verwenden, müssen Sie die Richtlinienanforderungen für Google Analytics-Werbefunktionen beachten. Um dieser Offenlegungspflicht hinsichtlich der Nutzung von Daten durch Google nachzukommen, können Sie einen gut sichtbaren Link einbinden, der auf folgende Seite verweist: Datennutzung durch Google bei Ihrer Nutzung von Websites oder Apps unserer Partner.

Zur Einhaltung der Google-Richtlinien ist es hilfreich, wenn Sie einen Mechanismus zum Einholen der Zustimmung von EU-Besuchern implementieren, bei dem ein Link auf eine Seite mit zusätzlichen Informationen verweist. Auf dieser Seite können Sie wiederum einen Link zur Google-Seite einfügen, auf der die Verwendung von Daten durch Google erläutert wird. So wird es auch einfacher, den europäischen Gesetzen zu Cookies und zum Datenschutz zu entsprechen.

Generate Java Class from XML schema using JAXB „xjc“ Command

In this Blog entry we will see how to do the reverse (i.e.) generate Java classes from XML Schema. This is done using JAXB binding compiler ‘xjc’ command.

Environment Used:

  • JDK 6 (Java SE 6) or later.
  • JAXB 2.1 API

Introduction

Before using JAXB to create or access an XML document from Java application, we have to do the following steps:

  1. Binding the schema
    • Binding a schema means generating a set of Java classes that represents the schema for the XML document (Schema is not required for simple marshalling and unmarshalling).
  2. Marshal the content tree /Unmarshal the XML document.
    • After binding the schema, you can convert Java objects to and from XML document.

In this example we will see how to bind the schema. For that, we use Java Architecture for XML Binding (JAXB) binding compiler tool, xjc, to generate Java classes from XML schema.

Process JDK Tool
From XML schema -> Java source file(s) (i.e.) XSD -> Java xjc

‘xjc’ Command Line Options

Usage:

xjc [-options …] … [-b ] …
If dir is specified, all schema files in it will be compiled.
If jar is specified, /META-INF/sun-jaxb.episode binding file will be compiled.

Complete list of options for ‘xjc’ is available in the help option.

xjc -help

Generate Java classes using ‘xjc’

Follow the steps below to generate a set of Java source files from XML schema.

  1. Create a new Java project folder and name it as “JAXBXJCTool”.
  2. Create a new XSD file and name it as “employee.xsd” and copy the following lines. This is the XML schema in our example which is to be bound to java classes.
    01
    02
    03
    04
    05
    06
    07
    08
    09
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="employee" type="employee"/>
      <xs:complexType name="employee">
        <xs:sequence>
          <xs:element name="name" type="xs:string" minOccurs="0"/>
          <xs:element name="salary" type="xs:double"/>
          <xs:element name="designation" type="xs:string" minOccurs="0"/>
          <xs:element name="address" type="address" minOccurs="0"/>
        </xs:sequence>
        <xs:attribute name="id" type="xs:int" use="required"/>
      </xs:complexType>
      <xs:complexType name="address">
        <xs:sequence>
          <xs:element name="city" type="xs:string" minOccurs="0"/>
          <xs:element name="line1" type="xs:string" minOccurs="0"/>
          <xs:element name="line2" type="xs:string" minOccurs="0"/>
          <xs:element name="state" type="xs:string" minOccurs="0"/>
          <xs:element name="zipcode" type="xs:long"/>
        </xs:sequence>
      </xs:complexType>
    </xs:schema>
  3. Save the file.
  4. Create a new folder ‘src’ inside the project folder.
  5. In Windows open Command Prompt (Windows button + R and type cmd) or Terminal in Linux and go to the project folder (use cd command) where it exists in your machine and type the following command.

    C:\Users\iByteCode\Desktop\JAXBXJCTool>xjc -d src -p com.theopentutorials.jaxb.beans employee.xsd

    This will generate set of Java source files with appropriate annotation inside ‘src’ folder.

The complete folder structure after executing the above command is shown below.

Bildschirmfoto 2016-01-25 um 23.00.17

Deleting rows from a table and inserting into another table in one query

It is relatively easy to insert rows from one table that match a certain condition into another table, e.g.:
INSERT INTO table2 (col1, col2) SELECT mycol99 as col1, col2 FROM table1 WHERE id < 1000 AND col2 IS NOT NULL;

This inserts rows from table1 that match the SQL condition id < 1000 AND col2 IS NOT NULL into table2. It uses the column mycol99 from table1 as the value for col1 (in table2) and col2 as col2.

Sometimes you want to ‚move‘ the rows from one table to another, i.e. INSERT some rows into table2, then delete them from table1. This can be done with:

INSERT INTO table2 (col1, col2) SELECT mycol99 as col1, col2 FROM table1 WHERE id < 1000 AND col2 IS NOT NULL; DELETE FROM table1 WHERE id < 1000 AND col2 IS NOT NULL;

This will work, and if you run it all within a transaction, it will be consistant (I think). However it’s not æstheically pleasing. You are doing things in 2 statements, when you only conceptially mean to do one action. It breaks „Don’t Repeat Yourself“ (DRY), the WHERE condition is repeated. If you want to change the WHERE condition, you have to do it in 2 places.

Luckily, as of PostgreSQL 9, you can do this all in one statement:

WITH output AS ( delete from table1 where id < 1000 AND col2 IS NOT NULL RETURNING mycol99 as col1, col2) INSERT INTO table2 (col1, col2) SELECT col1, col2 FROM output;"

Simples.

iSCSI Service (open-iscsi) Startup Best Practices for XenServer

Objective

This article contains best practices for setting the iSCSI Service (open-iscsi) to start automatically in XenServer.


Instructions

Complete the following procedure:

  1. Set open-iscsi service run level to On:
    # chkconfig –list (list all services)
    # chkconfig –list open-iscsi (list iscsi service)
    # chkconfig open-iscsi on (sets service to always run automatically)
    # chkconfig open-iscsi off (sets service to not always run automatically)You should get these options when set to run automatically# chkconfig –list open-iscsi
    open-iscsi     0:off 1:off 2:on 3:on 4:on 5:on 6:off 
  2. Enable automatic startup in iscsid.conf file by editing the /etc/iscsi/iscsid.conf file and uncommented:
    node.startup = automaticAnd commented:# node.startup = manual
  3. Enable automatic startup in the node iqn IP address default file:/etc/iscsi/nodes/iqn.1992-08.com.netapp:sn.135027806/10.12.45.10,3260,2000/default
    [root@ftlchristophxen41a 10.12.45.10,3260,2000]# more default
    node.name = iqn.1992-08.com.netapp:sn.135027806
    node.tpgt = 2000
    node.startup = automatic
    iface.hwaddress = default
    iface.iscsi_ifacename = default
    iface.net_ifacename = default
    iface.transport_name = tcp
    node.discovery_address = 10.12.45.10
    node.discovery_port = 3260
    node.discovery_type = send_targets
    node.session.initial_cmdsn = 0
    node.session.initial_login_retry_max = 4
    node.session.cmds_max = 128
    node.session.queue_depth = 32
    node.session.auth.authmethod = None
    node.session.timeo.replacement_timeout = 144
    node.session.err_timeo.abort_timeout = 10
    node.session.err_timeo.reset_timeout = 30
    node.session.iscsi.FastAbort = No
    node.session.iscsi.InitialR2T = No
    node.session.iscsi.ImmediateData = Yes
    node.session.iscsi.FirstBurstLength = 262144
    node.session.iscsi.MaxBurstLength = 16776192
    node.session.iscsi.DefaultTime2Retain = 0
    node.session.iscsi.DefaultTime2Wait = 2
    node.session.iscsi.MaxConnections = 1
    node.session.iscsi.MaxOutstandingR2T = 1
    node.session.iscsi.ERL = 0
    node.conn[0].address = 10.12.45.10
    node.conn[0].port = 3260
    node.conn[0].startup = automatic
    node.conn[0].tcp.window_size = 524288
    node.conn[0].tcp.type_of_service = 0
    node.conn[0].timeo.logout_timeout = 15
    node.conn[0].timeo.login_timeout = 15
    node.conn[0].timeo.auth_timeout = 45
    node.conn[0].timeo.active_timeout = 5
    node.conn[0].timeo.idle_timeout = 60
    node.conn[0].timeo.ping_timeout = 5
    node.conn[0].timeo.noop_out_interval = 10
    node.conn[0].timeo.noop_out_timeout = 15
    node.conn[0].iscsi.MaxRecvDataSegmentLength = 131072
    node.conn[0].iscsi.HeaderDigest = None,CRC32C
    node.conn[0].iscsi.DataDigest = None
    node.conn[0].iscsi.IFMarker = No
    node.conn[0].iscsi.OFMarker = No
  4. Enable automatic startup in the send_tragets IP address st_config file./etc/iscsi/send_targets/10.12.45.10,3260/st_config
    [root@ftlchristophxen41a 10.12.45.10,3260]# more st_config
    discovery.startup = automatic
    discovery.type = sendtargets
    discovery.sendtargets.address = 10.12.45.10
    discovery.sendtargets.port = 3260
    discovery.sendtargets.auth.authmethod = None
    discovery.sendtargets.timeo.login_timeout = 15
    discovery.sendtargets.reopen_max = 5
    discovery.sendtargets.timeo.auth_timeout = 45
    discovery.sendtargets.timeo.active_timeout = 30
    discovery.sendtargets.timeo.idle_timeout = 60
    discovery.sendtargets.iscsi.MaxRecvDataSegmentLength = 32768

Additional Informations

https://shop.heise.de/katalog/hochverfugbar-ohne-san