Salve ragazzi, come ho già scritto in qualche post precedente sto cercando di abbandonare netBeans e sviluppare con Eclipse(lo faccio per prendere dimestichezza con entrambi). Ci sono alcune cose che però non funzionano come dovrebbero,soprattutto quando provo a fare un progetto ed usare hibernate.
Premetto che io uso uno scheletro di progetto già predefinito con alcune classi non scritte da me, ho pensato che l'errore potesse risiedere in queste classi e vorrei che qualcuno mi aiutasse meglio a capire il funzionamento così da poter intervenire sul codice senza fare troppi danni.
I Filtri
package progetto.controllo.filtri;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class FiltroCharsetEncoding implements Filter {
private String encoding;
/* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
//System.out.println("*** Start CharsetEncodingFilter");
servletRequest.setCharacterEncoding(encoding);
// servletRequest.setCharacterEncoding("ISO-8859-1");
servletResponse.setContentType("text/html; charset=UTF-8");
//System.out.println("*** End CharsetEncodingFilter");
filterChain.doFilter(servletRequest, servletResponse);
}
/* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig config) throws ServletException {
encoding = config.getInitParameter("requestEncoding");
if (encoding == null) {
encoding = "UTF-8";
}
}
}
package .progetto.controllo.filtri;
import progetto.persistenza.hibernate.DAOUtilHibernate;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;
public class FiltroHibernate implements Filter {
private static Log log = LogFactory.getLog(FiltroHibernate.class);
private SessionFactory sessionFactory;
public void init(FilterConfig filterConfig) throws ServletException {
log.debug("Initializing filter...");
log.debug("Obtaining SessionFactory from static HibernateUtil singleton");
sessionFactory = DAOUtilHibernate.getSessionFactory();
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
log.debug("Starting a database transaction");
sessionFactory.getCurrentSession().beginTransaction();
chain.doFilter(request, response);
log.debug("Committing the database transaction");
sessionFactory.getCurrentSession().getTransaction().commit();
} catch (StaleObjectStateException staleEx) {
log.error("This interceptor does not implement optimistic concurrency control!");
log.error("Your application will not work until you add compensation actions!");
throw staleEx;
} catch (Throwable ex) {
ex.printStackTrace();
try {
if (sessionFactory.getCurrentSession().getTransaction().isActive()) {
log.debug("Trying to rollback database transaction after exception");
sessionFactory.getCurrentSession().getTransaction().rollback();
}
} catch (Throwable rbEx) {
log.error("Could not rollback transaction after exception!", rbEx);
}
throw new ServletException(ex);
}
}
public void destroy() {}
}
package progetto.controllo.filtri;
import progetto.modello.Modello;
import progetto.modello.Modello;
import progetto.modello.Utente;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class FiltroSessione implements Filter {
private static Log logger = LogFactory.getLog(FiltroSessione.class);
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
disableCaching(httpResponse);
String contextPath = httpRequest.getContextPath();
String servletPath = httpRequest.getServletPath();
if (!servletPath.contains("/operatore/") && !servletPath.contains("/admin/")) {
chain.doFilter(request, response);
return;
}
HttpSession session = httpRequest.getSession();
Modello modelloLogin = (Modello) session.getAttribute("modello");
if (modelloLogin == null) {
schermoErrore(request, response);
return;
}
Utente utente = modelloLogin.getUtente();
if (utente == null) {
schermoErrore(request, response);
return;
}
if (servletPath.contains("/operatore/")) {
if (!utente.getRuolo().equals("operatore")) {
schermoErrore(request, response);
return;
}
}
chain.doFilter(request, response);
}
private void schermoErrore(ServletRequest request, ServletResponse response) throws ServletException, IOException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String contextPath = httpRequest.getContextPath();
String servletPath = httpRequest.getServletPath();
HttpSession session = httpRequest.getSession();
ServletContext application = session.getServletContext();
application.log("FiltroSessione: Sto filtrando la richiesta a " + contextPath + " - " + servletPath);
RequestDispatcher dispatcher = application.getRequestDispatcher("/schermoErrore.jsf");
dispatcher.forward(request, response);
}
private void disableCaching(HttpServletResponse response) {
response.addHeader("Pragma", "no-cache");
response.addHeader("Cache-Control", "no-cache");
// Stronger according to blog comment below that references HTTP spec
response.addHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "must-revalidate");
// some date in the past
response.addHeader("Expires", "Mon, 8 Aug 2006 10:00:00 GMT");
}
}
PhaseListner
package progetto.controllo;
import java.util.Iterator;
import java.util.List;
import javax.faces.component.UIComponent;
import javax.faces.component.UIData;
import javax.faces.component.UIForm;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PhaseListener implements javax.faces.event.PhaseListener {
private Log logger = LogFactory.getLog(this.getClass());
public PhaseId getPhaseId() {
return javax.faces.event.PhaseId.ANY_PHASE;
}
public void beforePhase(PhaseEvent phaseEvent) {
if (phaseEvent.getPhaseId().equals(PhaseId.RESTORE_VIEW)) {
logger.debug("\n");
}
logger.debug("Inizio Fase: " + phaseEvent.getPhaseId());
ispeziona(phaseEvent);
}
public void afterPhase(PhaseEvent phaseEvent) {
logger.debug("Fine fase: " + phaseEvent.getPhaseId());
ispeziona(phaseEvent);
}
private void ispeziona(PhaseEvent phaseEvent) {
if (phaseEvent.getPhaseId().equals(PhaseId.RESTORE_VIEW) ||
phaseEvent.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
FacesContext facesContext = phaseEvent.getFacesContext();
UIViewRoot root = facesContext.getViewRoot();
if (root == null) {
logger.debug("-- UIViewRoot nullo");
} else {
logger.debug("-- UIViewRoot: " + root.getViewId());
//stampaFigli(root);
UIForm form = (UIForm)trovaFiglio(root, "form");
if (form != null) {
}
}
}
}
private UIComponent trovaFiglio(UIComponent componente, String id) {
List listaFigli = componente.getChildren();
for (Iterator it = listaFigli.iterator(); it.hasNext(); ) {
UIComponent figlio = (UIComponent)it.next();
if (figlio.getId().equals(id)) {
return figlio;
}
}
return null;
}
private void stampaFigli(UIComponent componente) {
List listaFigli = componente.getChildren();
for (Iterator it = listaFigli.iterator(); it.hasNext(); ) {
UIComponent figlio = (UIComponent)it.next();
logger.debug("Componente figlio di viewRoot: " + figlio);
}
}
}
DAOUtilHibernate
package progetto.persistenza.hibernate;
import progetto.eccezioni.DAOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class DAOUtilHibernate {
private static Log logger = LogFactory.getLog(DAOUtilHibernate.class);
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
static {
try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = (ServiceRegistry) new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
// Configuration configuration = new Configuration();
// sessionFactory = configuration.configure().buildSessionFactory();
} catch (Throwable ex) {
logger.error("Building SessionFactory failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session getCurrentSession() throws DAOException {
try {
return sessionFactory.getCurrentSession();
} catch (HibernateException ex) {
logger.error(ex);
throw new DAOException(ex);
}
}
public static void beginTransaction() throws DAOException {
try {
sessionFactory.getCurrentSession().beginTransaction();
} catch (HibernateException ex) {
logger.error(ex);
throw new DAOException(ex);
}
}
public static void commit() throws DAOException {
try {
sessionFactory.getCurrentSession().getTransaction().commit();
} catch (HibernateException ex) {
logger.error(ex);
throw new DAOException(ex);
}
}
public static void rollback() {
try {
sessionFactory.getCurrentSession().getTransaction().rollback();
} catch (HibernateException ex) {
logger.error(ex);
}
}
}
DAOGenerico
package progetto.persistenza.hibernate;
import progetto.eccezioni.DAOException;
import progetto.persistenza.IDAOGenerico;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockOptions;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
public class DAOGenericoHibernate<T> implements IDAOGenerico<T> {
private static Log logger = LogFactory.getLog(DAOGenericoHibernate.class);
private Class<T> persistentClass;
@SuppressWarnings("unchecked")
public DAOGenericoHibernate(Class<T> persistentClass) {
this.persistentClass = persistentClass;
}
protected Class<T> getPersistentClass() {
return persistentClass;
}
protected static Session getSession() throws DAOException {
try {
return DAOUtilHibernate.getCurrentSession();
} catch (HibernateException ex) {
logger.error(ex);
throw new DAOException(ex);
}
}
@SuppressWarnings("unchecked")
public T makePersistent(T entity) throws DAOException {
try {
getSession().saveOrUpdate(entity);
} catch (HibernateException ex) {
logger.error(ex);
throw new DAOException(ex);
}
return entity;
}
public void makeTransient(T entity) throws DAOException {
try {
getSession().delete(entity);
} catch (HibernateException ex) {
logger.error(ex);
throw new DAOException(ex);
}
}
@SuppressWarnings("unchecked")
public void lock(T entity) throws DAOException {
try {
getSession().buildLockRequest(LockOptions.UPGRADE).lock(entity);
} catch (HibernateException ex) {
logger.error(ex);
throw new DAOException(ex);
}
}
@SuppressWarnings("unchecked")
public T findById(Long id, boolean lock) throws DAOException {
T entity;
try {
if (lock) {
entity = (T) getSession().get(getPersistentClass(), id, LockOptions.UPGRADE);
} else {
entity = (T) getSession().get(getPersistentClass(), id);
}
// if (lock) {
// entity = (T) getSession().load(getPersistentClass(), id, LockOptions.UPGRADE);
// } else {
// entity = (T) getSession().load(getPersistentClass(), id);
// }
} catch (HibernateException ex) {
logger.error(ex);
throw new DAOException(ex);
}
return entity;
}
@SuppressWarnings("unchecked")
public List<T> findAll() throws DAOException {
return findByCriteria();
}
@SuppressWarnings("unchecked")
public List<T> findAll(int offset, int limite) throws DAOException {
return findByCriteria(offset, limite);
}
@SuppressWarnings("unchecked")
public List<T> findByCriteria(Criterion... criterion) throws DAOException {
try {
Criteria crit = getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion) {
crit.add(c);
}
return crit.list();
} catch (HibernateException ex) {
logger.error(ex);
throw new DAOException(ex);
}
}
@SuppressWarnings("unchecked")
public List<T> findByCriteria(int offset, int limite, Criterion... criterion) throws DAOException {
try {
Criteria crit = getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion) {
crit.add(c);
}
crit.setFirstResult(offset);
crit.setMaxResults(limite);
return crit.list();
} catch (HibernateException ex) {
logger.error(ex);
throw new DAOException(ex);
}
}
@SuppressWarnings("unchecked")
public List<T> findByCriteria(Criteria criteria) throws DAOException {
try {
return criteria.list();
} catch (HibernateException ex) {
logger.error(ex);
throw new DAOException(ex);
}
}
@SuppressWarnings("unchecked")
public T reattach(T obj, Long id) throws DAOException {
try {
T persistentObject = (T) getSession().get(persistentClass, id);
if (logger.isDebugEnabled()) logger.debug("Get ha trovato l'oggetto con id " + id);
return persistentObject;
} catch (Exception ex) {
logger.error(ex);
throw new DAOException(ex);
}
}
@SuppressWarnings("unchecked")
public void evict(T obj) throws DAOException {
getSession().evict(obj);
}
}
questo è lo scheletro di un progetto, non creato da me, e poi io da questo creo il mio progetto(le mie classi, i miei metodi, i miei criteria, ecc). Con netbeans mi ha sempre funzionato tutto quindi non mi sono mai posto il problema di cosa si occupassero i metodi presenti in queste classi, ma ora con eclipse ho diversi problemi quindi pensavo che magari riuscendo a capire meglio a cosa servissero queste classi poi potrei risolvere i problemi che ho in eclipse.
Ringrazio anticipatamente tutti coloro che volessero aiutarmi.