Arquivo da tag: Java

Instant Apache Wicket 6

Olá pessoal

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

http://bit.ly/15w4LEI

João

 

Anúncios

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>

Runtime DAO

Meu novo projeto 😀
Créditos da implementacao inicial: Carlos Eduardo Gusso Tosin

Runtime DAO
Description: the library for generating your DAO classes at runtime
abssss
João Sávio

https://joaosavio.wordpress.com

Artigo na Java Magazine 83!

Olá pessoal!

Finalmente saiu meu artigo na revista Java Magazine! Segue link: http://www.devmedia.com.br/post-18020-Boas-praticas-com-web-services-RESTful.html

Absssss

Minicurso Orientação a Objetos com Java na Uniararas

Agredeço aos participantes mais uma vez! Abaixo algumas fotos:

foto5

foto6