With the introduction of human customs like Christmas, have you ever regifted something?
Dear Winter Well-Wisher,
Regifting… that is to say, have I ever given something, which had been given to me in the first place? Well, after meeting Optimus Prime's Autobots on Earth, I was surprised to discover that they had never heard of Cyber Keys before, unlike most Transformers across the galaxy throughout history. As my father Primus granted me my Cyber Key, I passed on this gift in turn to them.
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
✓ Live Streaming✓ Interactive Chat✓ Private Shows✓ HD Quality
Anya is LIVE right now
FREE
Free to watch • No registration required • HD streaming
Installing and configuring the Apache Tomcat 7 admin interface
Install and configure the webinterface of Apache Tomcat7 (including examples and tomcat7 docs). The installation is simple, since we use standard available packages within Debian Wheezy.
With this you just installed the java applets for administration and the manual of your tomcat server, aswell as some example java applications.
By default, Tomcat 7 supports the following user roles that you can use to set up multiple logins for different level of accesses:
manager-gui - allows access to the HTML GUI and the status pages
manager-script - allows access to the text interface and the status pages
manager-jmx - allows access to the JMX proxy and the status pages
manager-status - allows access to the status pages only
To be able to really use the admin interface, you have to edit the following file using your favorite editor and add users that are allowed to administer the java applications that will be published using Apache Tomcat 7.
vi /etc/tomcat7/tomcat-users.xml
We will see the folowing:
<?xml version='1.0' encoding='utf-8'?> <!-- ... license info ... --> <tomcat-users> <!-- NOTE: By default, no user is included in the "manager-gui" role required to operate the "/manager/html" web application. If you wish to use this app, you must define such a user - the username and password are arbitrary. --> <!-- NOTE: The sample user and role entries below are wrapped in a comment and thus are ignored when reading this file. Do not forget to remove <!.. ..> that surrounds them. --> <!-- <role rolename="tomcat"/> <role rolename="role1"/> <user username="tomcat" password="tomcat" roles="tomcat"/> <user username="both" password="tomcat" roles="tomcat,role1"/> <user username="role1" password="tomcat" roles="role1"/> --> </tomcat-users>
Now we will add the role for administration (manager-gui) and create a user for it right above the </tomcat-users> tag.
(You can name the user and define the password as you like but keep in mind that the password is stored in plain text, the rolename has to be manager-gui.)
Save the file and restart your tomcat service using:
service tomcat7 restart
We can test the install by pointing your favorite browser to http://<servername or ip-address>:8080/manager/html
You will see the following screen.
Next Up: Reverse Proxies and loadbalancing of web applications
Creating Solutions and Implementations in Technology
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
✓ Live Streaming✓ Interactive Chat✓ Private Shows✓ HD Quality
Anya is LIVE right now
FREE
Free to watch • No registration required • HD streaming
When installing applications within DTAP (Development, Test, Acceptance, Production) environments, I prefer doing as little compiling als possible to prevent incompatibility with the packages installed and updated with the aptitude package manager within Debian / Ubuntu.
NOTE:
First install Oracle Java 7 using my post on howto Install ORACLE Java 7 on Debian Wheezy
With Java 7 installed we install Tomcat7. Since Tomcat 7 is part of the standard repository of Debian wheezy, we just execute the following command as root or using sudo:
apt-get install tomcat7
You will see the following error:
Setting up tomcat7 (7.0.28-4+deb7u1) ...
Creating config file /etc/default/tomcat7 with new version
Adding system user `tomcat7' (UID 105) ...
Adding new user `tomcat7' (UID 105) with group `tomcat7' ...
Not creating home directory `/usr/share/tomcat7'.
Creating config file /etc/logrotate.d/tomcat7 with new version
[....] no JDK found - please set JAVA_HOME ... failed!
invoke-rc.d: initscript tomcat7, action "start" failed.
The reason for this error is that we use Oracle Java 7 instead of OpenJDK Java 6 that is defined in the standard packages within Debian Wheezy.
To solve this we have to define JAVA_HOME in /etc/default/tomcat7
vi /etc/default/tomcat7
# Run Tomcat as this user ID. Not setting this or leaving it blank will use the
# default of tomcat7.
TOMCAT7_USER=tomcat7
# Run Tomcat as this group ID. Not setting this or leaving it blank will use
# the default of tomcat7.
TOMCAT7_GROUP=tomcat7
# The home directory of the Java development kit (JDK). You need at least
# JDK version 1.5. If JAVA_HOME is not set, some common directories for
# OpenJDK, the Sun JDK, and various J2SE 1.5 versions are tried.
#JAVA_HOME=/usr/lib/jvm/openjdk-6-jdk
JAVA_HOME=/usr/lib/jvm/java-7-oracle
# You may pass JVM startup parameters to Java here. If unset, the default
# options will be: -Djava.awt.headless=true -Xmx128m -XX:+UseConcMarkSweepGC
#
# Use "-XX:+UseConcMarkSweepGC" to enable the CMS garbage collector (improved
# response time). If you use that option and you run Tomcat on a machine with
# exactly one CPU chip that contains one or two cores, you should also add
# the "-XX:+CMSIncrementalMode" option.
JAVA_OPTS="-Djava.awt.headless=true -Xmx128m -XX:+UseConcMarkSweepGC"
# To enable remote debugging uncomment the following line.
# You will then be able to use a java debugger on port 8000.
#JAVA_OPTS="${JAVA_OPTS} -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
# Java compiler to use for translating JavaServer Pages (JSPs). You can use all
# compilers that are accepted by Ant's build.compiler property.
#JSP_COMPILER=javac
# Use the Java security manager? (yes/no, default: no)
#TOMCAT7_SECURITY=no
# Number of days to keep logfiles in /var/log/tomcat7. Default is 14 days.
#LOGFILE_DAYS=14
# Location of the JVM temporary directory
# WARNING: This directory will be destroyed and recreated at every startup !
#JVM_TMP=/tmp/tomcat7-temp
# If you run Tomcat on port numbers that are all higher than 1023, then you
# do not need authbind. It is used for binding Tomcat to lower port numbers.
# NOTE: authbind works only with IPv4. Do not enable it when using IPv6.
# (yes/no, default: no)
#AUTHBIND=no
Start Tomcat with the following command:
service tomcat7 start
root@server:# service tomcat7 start
[....] Starting Tomcat servlet engine: tomcat7.
root@server:#
Tomcat is now installed.
We can test the install by pointing your favorite browser to http://<servername or ip-address>:8080
You will see the following screen.
This is all there is to it, to be able to be able to run Apache Tomcat 7 on Debian Wheezy.
In a future post we will explain how to install and configure the admin interface.
Creating Solutions and Implementations in Technology
Chi non usa JSF può andare direttamente alla sezione JPA per capire come effettuare il setup delle librerie necessarie, il datasource setup, come scrivere un resources/META-INF/persistence.xml file con riferimenti a hibernate.
Punto dritto al sodo e vi spiattelo il codice di seguito:
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;
/**
* Class to manage Entity manager factory and Entity manager in persistence
* context without Context Listener. <br/>
* Class takes care of following basic things: <br/>
* <ul>
* <li>using one time on-demand initialization, it sets up the
* EntityManagerFactory</li>
* <li>it provides a way to create, obtain and properly close an EntityManager</li>
* <li>it provides a way to create, obtain and properly close an EntityManager
* overriding the default configuration read in persistence.xml</li>
* <li>the DBManager class provides an explicit "readOnly" mode which you should
* use when you are not going to persist any changes (effectively no JPA
* transaction is created in readonly mode)</li>
* <li>it provides a way for you to trigger a commit or rollback</li>
* </ul>
*
* @author Alessio Flaviani 19/set/2013 DBManager.java
*/
public class DBManager {
protected static String CLASS_NAME = DBManager.class.getName();
protected static Logger logger = Logger.getLogger(DBManager.class);
private static volatile boolean initialized = false;
private static Boolean lock = new Boolean(true);
private static EntityManagerFactory emf = null;
private EntityManager outer;
private static volatile boolean initializedOver = false;
private static Boolean lockOver = new Boolean(true);
private static EntityManagerFactory emfOver = null;
private EntityManager outerOver;
/**
* Default constructor
*/
public DBManager() {
}
/**
* Open Dba; if readonly no JPA transaction is actually started, meaning you
* will have no persistence store. You can still persist stuff, but the
* entities won't become managed.
*/
public DBManager(boolean readOnly) {
logger.debug("initializing entity manager factory ...");
initialize();
logger.debug("opening entity manager ...");
openEm(readOnly);
}
/**
* Open Dba; if readonly no JPA transaction is actually started, meaning you
* will have no persistence store. You can still persist stuff, but the
* entities won't become managed.
*
* @param entityFactoryConfig
* new properties to override previous configuration, if exist.
*/
public DBManager(Map<String, Object> entityFactoryConfig) {
logger
.debug("initializing entity manager factory overriding default configuration ...");
initialize(entityFactoryConfig);
logger
.debug("opening entity manager overriding default configuration ...");
openEmOver(false);
}
/**
* Thread safe way to initialize the entity manager factory.
*/
private void initialize() {
if (initialized) {
return;
}
synchronized (lock) {
if (initialized) {
return;
}
initialized = true;
try {
emf = Persistence.createEntityManagerFactory("VDH_DB");
logger.info("entity manager factory created at once ...");
} catch (Throwable t) {
logger.error("Failed to setup persistence unit!", t);
return;
}
}
}
/**
* Thread safe way to initialize the entity manager factory with new
* properties to override previous configuration
*
* @param entityFactoryConfig
* void
*/
private void initialize(Map<String, Object> entityFactoryConfig) {
if (initializedOver) {
return;
}
synchronized (lockOver) {
if (initializedOver) {
return;
}
initializedOver = true;
try {
emfOver = Persistence.createEntityManagerFactory(
"com.tiscali.hosting.dns", entityFactoryConfig);
logger.info("entity manager factory overrides ...");
} catch (Throwable t) {
logger
.error(
"Failed to setup persistence unit with configuration overrides!",
t);
return;
}
}
}
/**
* Create an entity manager. if readonly no JPA transaction is actually
* started.
*
* @param readOnly
* void
*/
public void openEm(boolean readOnly) {
if (outer != null) {
return;
}
outer = emf.createEntityManager();
if (!readOnly) {
logger.debug("opening transaction ...");
outer.getTransaction().begin();
}
}
/**
* Create an entity manager. if readonly no JPA transaction is actually
* started.
*
* @param readOnly
* void
*/
public void openEmOver(boolean readOnly) {
if (outerOver != null) {
return;
}
outerOver = emfOver.createEntityManager();
if (!readOnly) {
logger.debug("opening ovveride transaction ...");
outerOver.getTransaction().begin();
}
}
/**
* Get the outer transaction; an active transaction must already exist for
* this to succeed.
* @return EntityManager
*/
public EntityManager getActiveEm() {
if (outer == null) {
throw new IllegalStateException("No transaction was active!");
}
return outer;
}
/**
* Get the outer transaction; an active transaction must already exist for
* this to succeed.
*/
public EntityManager getActiveEmOver() {
if (outerOver == null) {
throw new IllegalStateException(
"No override transaction was active!");
}
return outerOver;
}
/**
* Commit the transaction only if there is an active one
*
* void
*/
public void commit() {
if (outer != null && outer.getTransaction().isActive()
&& !outer.getTransaction().getRollbackOnly()) {
logger.debug("commiting ...");
this.outer.getTransaction().commit();
this.outer.getTransaction().begin();
} else {
logger.error("commit failed, outer is null");
}
}
/**
* Commit the transaction only if there is an active one
*
* void
*/
public void commitOver() {
if (outerOver != null && outerOver.getTransaction().isActive()
&& !outerOver.getTransaction().getRollbackOnly()) {
logger.debug("override commiting ...");
this.outerOver.getTransaction().commit();
this.outerOver.getTransaction().begin();
} else {
logger.error("commit override failed, outer is null");
}
}
/**
* Mark the transaction as rollback only, if there is an active transaction
* to begin with.
*/
public void markRollback() {
if (outer != null) {
logger.debug("mark rollback ...");
outer.getTransaction().setRollbackOnly();
}
}
/**
* Mark the transaction as rollback only, if there is an active transaction
* to begin with.
*/
public void markRollbackOver() {
if (outerOver != null) {
logger.debug("mark rollback override...");
outerOver.getTransaction().setRollbackOnly();
}
}
/**
* True if the transaction has marked as rollback
*
* @return boolean
*/
public boolean isRollbackOnly() {
return outer != null && outer.getTransaction().getRollbackOnly();
}
/**
* True if the transaction has marked as rollback
*
* @return boolean
*/
public boolean isRollbackOnlyOver() {
return outerOver != null
&& outerOver.getTransaction().getRollbackOnly();
}
/**
* Close the entity manager, properly committing or rolling back a
* transaction if one is still active.
*/
public void closeEm() {
if (outer == null) {
return;
}
try {
if (outer.getTransaction().isActive()) {
if (outer.getTransaction().getRollbackOnly()) {
logger.debug("rollbacking ...");
outer.getTransaction().rollback();
} else {
logger.debug("commiting ...");
outer.getTransaction().commit();
}
}
} finally {
if (outer.isOpen())
outer.close();
outer = null;
}
}
/**
* Close the entity manager, properly committing or rolling back a
* transaction if one is still active.
*/
public void closeEmOver() {
if (outerOver == null) {
return;
}
try {
if (outerOver.getTransaction().isActive()) {
if (outerOver.getTransaction().getRollbackOnly()) {
logger.debug("rollbacking override ...");
outerOver.getTransaction().rollback();
} else {
logger.debug("commiting override ...");
outerOver.getTransaction().commit();
}
}
} finally {
if (outerOver.isOpen())
outerOver.close();
outerOver = null;
}
}
}
Ho apportato pochi cambi alla classe riportata nell'articolo precedentemente citato.
La classe permette di gestire l'entity factory manager e l'entity manager in un contesto di persistenza senza implementare un context listener per la creazione,
gestione e chiusura della factory stessa in fase di startup e shutdown del server container.
La classe permette di
sfruttare l'inizializzazione one-time della factory su richiesta
creare, utilizzare e chiudere un'entity manager
creare, utilizzare e chiudere un'entity manager sovrascrivendo la configurazione di default letta nel persistence.xml utilizzato da hibernate
un metodo di gestione delle istanze senza persistenza
una gestione dei commit e dei rollback delle transazioni ottimizzato
Ho introdotto la possibilità di creare entity manager con la configurazione passata a runtime. Nel mio specifico caso ho la necessità di creare l'entity manager leggendo la configurazione del db a cui connettermi in base a delle discriminanti passate come parametro. E' una situazione molto utile per chi deve lavorare su basi dati differenti nello stesso algoritmo.
Ho modificato la gestione dei commit riaprendo la transazione dopo la chiusura della precedente.
La spiegazione è semplice: ho un'architettura complessa costituita da più webservice. Alcuni di essi sono invocati da altri webservice da 1 a n volte.
I metodi dei webservice inglobati in altri webservice gestiscono l'intero ciclo di vita della transazione: apertura entity e transaction, commit o rollback, chiusura entity.
Di conseguenza il metodo inglobante (passatemi il termine :) ) si ritroverebbe la transazione chiusa al completamento del ciclo di vita del metodo inglobato perchè l'entity manager è gestita a livello globale!
Da qui la decisione di riaprire la transazione dopo un commit!
Come scritto da Gimby (l'autore dell'articolo postato in alto):