50% de desconto na Packt Publishing

Explore something new this Columbus Day with Packt’s biggest ever sale
Packt Publishing is giving everyone the chance to explore its full range of over 1600 DRM-free eBooks this Columbus Day at a massive 50% off at http://www.packtpub.com. Customers simply use the code COL50 in their cart – as many times as they like. Offer valid for today, October 17th. The offer even extends to Packt’s bestselling pre-order of 2013, the highly acclaimed Mastering Web Application Development with AngularJS.
But that’s not all – to mark the transition out of beta stage, the publisher will also be including its Packt Video product range in this limited offer. These practical screencast tutorials give users the working knowledge they need to get the job done, and all videos will be featured in the Columbus Day sale at 50% off – that includes the hugely popular Kali Linux – Backtrack Evolved: A Penetration Tester’s Guide.
The exclusive 50% discount code COL50 will be active on all eBooks and Videos until Thursday October 17th.

220x250

Instant Apache Wicket 6

Olá pessoal

Um bom livro para começar a aprender Apache Wicket:

http://bit.ly/15w4LEI

João

 

Script para deploy glassfish + maven

Olá pessoal! Este script é para automatizar o deploy de um arquivo WAR no servidor GLASSFISH!


GLASSFISH_HOME=
mvn clean install
WAR=`ls target/ | grep "\.war"`
WAR_NAME=`echo $WAR | sed 's/.war//g'`

$GLASSFISH_HOME/bin/asadmin undeploy $WAR_NAME
$GLASSFISH_HOME/bin/asadmin deploy target/$WAR
$GLASSFISH_HOME/bin/stopserv
$GLASSFISH_HOME/bin/startserv &
sleep 7
firefox http://localhost:8080/$WAR_NAME &
echo DONE

Hibernate Spatial

Para quem trabalha com dados geográficos, um interessante projeto é o Hibernate Spatial, que te permite fazer um mapemento objeto-relacional de dados geográficos, juntamento com a biblioteca JTS Topology Suite. Por exemplo:

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.hibernate.annotations.Type;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;

@Entity
public class SpatialTestEntity  {

	private static final long serialVersionUID = -1791595461594359407L;

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

	@Type(type = "org.hibernatespatial.GeometryUserType")
	private Point point;

	@Type(type = "org.hibernatespatial.GeometryUserType")
	private Polygon polygon;

	@Type(type = "org.hibernatespatial.GeometryUserType")
	private MultiPolygon multiPolygon;

	@Type(type = "org.hibernatespatial.GeometryUserType")
	private Geometry geometry;

        //...
}

Como usar vários bancos de dados com JPA/Hibernate

Olá pessoal! Hoje estou postando duas classes do meu projeto Generic Spatial DAO. Elas exemplificam como lidar com vários persistence unit e mostra o uso da classe ThreadLocal. Explicações no próprio código.


import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.Logger;

/**
 *
 * @author joaosavio
 *
 */
public class EntityManagerFactoryService {

	private static final Logger LOG = Logger.getLogger(EntityManagerFactoryService.class);
	private static Map<String, EntityManagerFactory> factories = new HashMap<String, EntityManagerFactory>();

	/**
	 * This method returns an entity manager factory for a target persistence unit
         *
	 * @param persistenceUnitName
	 * @return an entity manager factory for a target persistence unit
	 */
	public static EntityManagerFactory getEntityManagerFactory(
			String persistenceUnitName) {
		if (factories.containsKey(persistenceUnitName)) {
			return factories.get(persistenceUnitName);
		}
		EntityManagerFactory emf;
		try {
			emf = Persistence.createEntityManagerFactory(persistenceUnitName);
		} catch (Exception e) {
			// handle exception
		}
		factories.put(persistenceUnitName, emf);
		return emf;
	}

	/**
	 * Close entity manager factories. Use this method when application life cycle ends
	 */
	public static void closeFactories() {
		LOG.info("Closing entity manager factories");
		for (Map.Entry entry : factories.entrySet()) {
			entry.getValue().close();
		}
		factories.clear();
	}
}

 

package org.genericspatialdao.services;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

import org.apache.log4j.Logger;
import org.genericspatialdao.exceptions.DAOException;

/**
 * 
 * @author Joao Savio C. Longo - joaosavio@gmail.com
 * 
 */
public class EntityManagerService {

	private static final String THERE_IS_NO_ENTITY_MANAGER_IN_SESSION = "There is no entity manager in session";
	private static final String THERE_IS_NO_SESSION = "There is no session";

	private static final Logger LOG = Logger
			.getLogger(EntityManagerService.class);

        // there is a session for each persistence unit
	private static Map<String, ThreadLocal<EntityManager>> sessions = new HashMap<String, ThreadLocal<EntityManager>>();

	/**
	 * Get or create an entity manager
	 * 
	 * @return an entity manager for a target persistence unit
	 */
	public static synchronized EntityManager getEntityManager(
			String persistenceUnitName) {
		ThreadLocal<EntityManager> session = sessions.get(persistenceUnitName);
		if (session == null) {
			session = new ThreadLocal<EntityManager>();
			sessions.put(persistenceUnitName, session);
		}
		EntityManager em = session.get();
		if (em == null) {
			EntityManagerFactory emf = EntityManagerFactoryService
					.getEntityManagerFactory(persistenceUnitName);
			LOG.info("Creating entity manager");
			em = emf.createEntityManager();
			session.set(em);
		}
		return em;
	}

	/**
	 * Get the entity manager for session of a target persistence unit
	 * 
	 * @return the entity manager for session of a target persistence unit
	 */
	public static synchronized EntityManager getEntityManagerForSession(
			String persistenceUnit) {
		LOG.debug("Getting entity manager for session: " + persistenceUnit);
		ThreadLocal<EntityManager> session = sessions.get(persistenceUnit);
		checkSession(session);
		EntityManager entityManager = session.get();
		checkEntityManager(entityManager);
		return entityManager;
	}

	/**
	 * Closes entity manager and remove it from session of a target persistence
	 * unit
	 */
	public static synchronized void close(String persistenceUnit) {
		ThreadLocal<EntityManager> session = sessions.get(persistenceUnit);
		checkSession(session);
		EntityManager entityManager = session.get();
		if (entityManager != null) {
			if (entityManager.isOpen()) {
				LOG.info("Closing entity manager");
				entityManager.close();
			}
			LOG.debug("Removing entity manager from session");
			session.set(null);
		}
	}

	public static void closeAll() {
		LOG.info("Closing all entity managers");
		for (String persistenceUnit : sessions.keySet()) {
			close(persistenceUnit);
		}
	}

	/**
	 * Closes quietly entity manager and session of a target persistence unit
	 */
	public static synchronized void closeQuietly(String persistenceUnit) {
		try {
			close(persistenceUnit);
		} catch (DAOException e) {
			LOG.warn("Exception caught in closeQuietly method: "
					+ e.getMessage());
		}
	}

	/**
	 * Begin a transaction if it is not active
	 */
	public static void beginTransaction(String persistenceUnit) {
		EntityManager em = getEntityManagerForSession(persistenceUnit);
		EntityTransaction transaction = em.getTransaction();
		if (!transaction.isActive()) {
			LOG.debug("Beginning transaction");
			transaction.begin();
		}
	}

	/**
	 * Commit if transaction is active
	 */
	public static void commit(String persistenceUnit) {
		EntityManager em = getEntityManagerForSession(persistenceUnit);
		EntityTransaction transaction = em.getTransaction();
		if (transaction.isActive()) {
			LOG.info("Commiting");
			transaction.commit();
		} else {
			LOG.warn("Commit invoked but transaction is not active");
		}
	}

	/**
	 * Rollback if transaction is active
	 */
	public static void rollback(String persistenceUnit) {
		EntityManager em = getEntityManagerForSession(persistenceUnit);
		EntityTransaction transaction = em.getTransaction();
		if (transaction.isActive()) {
			LOG.info("Rollbacking");
			transaction.rollback();
		} else {
			LOG.warn("Rollback invoked but transaction is not active");
		}
	}

	private static void checkEntityManager(EntityManager entityManager) {
		if (entityManager == null) {
			LOG.error(THERE_IS_NO_ENTITY_MANAGER_IN_SESSION);
			throw new DAOException(THERE_IS_NO_ENTITY_MANAGER_IN_SESSION);
		}
	}

	private static void checkSession(ThreadLocal<EntityManager> session) {
		if (session == null) {
			LOG.error(THERE_IS_NO_SESSION);
			throw new DAOException(THERE_IS_NO_SESSION);
		}
	}
}

Usamos o código acima da seguinte maneira:

EntityManager em = EntityManagerService.getEntityManager(persistenceUnitName);

Simples não?

Executor de comandos em Java

/**
 *
 * @author joaosavio
 */
public class CommandExecutor {
    /**
     * Executes a command line
     * @param line
     * @return the exit code
     */
    public int execute(String line) {
        return execute(line, null);
    }
     
    /**
     * Executes a command line
     * @param line
     * @param expectedExitCode
     * @return the exit code
     */
    public int execute(String line, Integer expectedExitCode) {
        CommandLine commandLine = CommandLine.parse(line);
        Executor executor = new DefaultExecutor();
       
        if (expectedExitCode != null) {
            executor.setExitValue(expectedExitCode); 
        }
        try {
            int exitValue = executor.execute(commandLine);
            return exitValue;
        } catch (ExecuteException e) {
            // handle the exception
        } catch (IOException e) {
            // handle the exception
        } 
    }
}

No pom.xml adicione:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-exec</artifactId>
    <version>1.1</version>
</dependency>

Java para XML / XML para Java

Olá pessoal!
Vou colocar alguns tutoriais sobre Java a partir de hoje! Tentarei colocar códigos auto-explicativos🙂

absss

package com.joaosavio.xmltest.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 *
 * @author joaosavio
 */
public class XmlUtil {
    /**
     * Create a XML file from Java object
     * @param clazz
     * @param objectClass
     * @param fullPath
     * @return a XML file
     */
    public static File createFile(Class clazz, Object objectClass, String fullPath) {
        File file = new File(fullPath);
        FileWriter fw = null;
        try {
            file.createNewFile();
            JAXBContext context = JAXBContext.newInstance(clazz);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            fw = new FileWriter(file);
            marshaller.marshal(objectClass, fw);
            return file;
        } catch (JAXBException e) {
            // handle the exception
        } catch (IOException e) {
            // handle the exception     
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException ex) {
                // handle the exception
            }
        }
    }

    /**
     * Create a XML String from Java object
     * @param clazz
     * @param objectClass
     * @return a XML String
     */
    public static String createString(Class clazz, Object objectClass) {
        StringWriter sw = new StringWriter();
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
            marshaller.marshal(objectClass, sw);
            String result = sw.toString();
            return result;
        } catch (JAXBException e) {
            // handle the exception
        }  finally {
            try {
                sw.close();
            } catch (IOException ex) {
                // handle the exception
            }
        }
    }

    /**
     * Read a XML file
     * @param clazz
     * @param fileFullPath
     * @return a Java Object
     */
    public static Object readFile(Class clazz, String fileFullPath) {
        File file = new File(fileFullPath);
        if (!file.exists()) {
            // throw an exception
        }

        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return unmarshaller.unmarshal(file);
        } catch (JAXBException e) {
            // handle the exception
        }
    }

    /**
     * Read a XML String
     * @param clazz
     * @param xml
     * @return a Java object
     */
    public static Object readString(Class clazz, String xml) {
        Reader reader = new StringReader(xml);
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return unmarshaller.unmarshal(reader);
        } catch (JAXBException e) {
            // handle the exception
        } finally {   
            try {
                reader.close();
            } catch (IOException ex) {
                // handle the exception
            }
        }
    }
}

No pom.xml adicione:

<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.2.4-1</version>
</dependency>