Add Source Code Linter Pipeline
This commit is contained in:
parent
0d0e7140c4
commit
d252f6ef50
313 changed files with 36277 additions and 0 deletions
|
@ -0,0 +1,37 @@
|
|||
package +zoccolo+.security.ldap.userdetails.ad;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.ldap.core.DirContextOperations;
|
||||
import org.springframework.ldap.core.DistinguishedName;
|
||||
import org.springframework.ldap.core.LdapRdn;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider;
|
||||
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
|
||||
|
||||
/**
|
||||
* An {@link LdapAuthoritiesPopulator} that is based on the {@link ActiveDirectoryLdapAuthenticationProvider}. The
|
||||
* implementation obtains the {@link GrantedAuthority}'s from the userData's memberOf attribute. It then uses the last
|
||||
* {@link LdapRdn}'s value as the {@link GrantedAuthority}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @see ActiveDirectoryLdapAuthenticationProvider
|
||||
*/
|
||||
public final class ActiveDirectoryLdapAuthoritiesPopulator
|
||||
implements LdapAuthoritiesPopulator {
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
|
||||
String[] groups = userData.getStringAttributes("memberOf");
|
||||
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
||||
|
||||
for (String group : groups) {
|
||||
LdapRdn authority = new DistinguishedName(group).removeLast();
|
||||
authorities.add(new SimpleGrantedAuthority(authority.getValue()));
|
||||
}
|
||||
return authorities;
|
||||
}
|
||||
}
|
55
screwdriver-3.5.6/box/snippets/java/AntiSamyListener.java
Normal file
55
screwdriver-3.5.6/box/snippets/java/AntiSamyListener.java
Normal file
|
@ -0,0 +1,55 @@
|
|||
package +zoccolo+.web.listener;
|
||||
|
||||
import +zoccolo+.web.sanitizer.XssSanitizer;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.owasp.validator.html.PolicyException;
|
||||
|
||||
public class AntiSamyListener
|
||||
implements ServletContextListener {
|
||||
|
||||
public static final String POLICY_FILE_PATH = "policy_file_path";
|
||||
public static final String ANTISAMY_SANITIZER = "sanitizer";
|
||||
|
||||
static Logger log = Logger.getLogger(AntiSamyListener.class);
|
||||
|
||||
public void contextDestroyed(ServletContextEvent servletContextEvent) {
|
||||
log.info("Context destroyed");
|
||||
}
|
||||
|
||||
public void contextInitialized(ServletContextEvent servletContextEvent) {
|
||||
ServletContext servletContext = servletContextEvent.getServletContext();
|
||||
String policyFilePath = (String) servletContext.getInitParameter(POLICY_FILE_PATH);
|
||||
if (policyFilePath == null) {
|
||||
throw new RuntimeException(
|
||||
"Policy file path is null. Please set it up in web.xml!!!");
|
||||
}
|
||||
log.info("XSS Policy file path read.");
|
||||
|
||||
InputStream is = getClass().getClassLoader().getResourceAsStream(
|
||||
policyFilePath);
|
||||
try {
|
||||
is.available();
|
||||
log.info("XSS Policy file loaded.");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Policy file " + policyFilePath
|
||||
+ " does not exists!");
|
||||
}
|
||||
|
||||
try {
|
||||
XssSanitizer sanitizer = new XssSanitizer(policyFilePath);
|
||||
log.info("XSS Sanitizer created.");
|
||||
servletContext.setAttribute(ANTISAMY_SANITIZER, sanitizer);
|
||||
log.info("XSS bound in Servlet Context as: " + ANTISAMY_SANITIZER);
|
||||
} catch (PolicyException pex) {
|
||||
throw new RuntimeException("Policy exception: " + pex.getMessage());
|
||||
}
|
||||
}
|
||||
/* screwdriver_knife */
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package +zoccolo+.web.authentication;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import +zoccolo+.web.authentication.+userpass+UsernamePasswordAuthenticationToken;
|
||||
import +zoccolo+.web.authentication.authority.UserAuthorityUtils;
|
||||
import +domain+.screwdriver.+dsname+.+dbschema+.+tabuser+;
|
||||
import +zoccolo+.+rail+.dao.I+Rail++tabuser+Dao;
|
||||
|
||||
/** Autenticazione */
|
||||
@Component
|
||||
public class +Applicaz+UserAuthenticationProvider
|
||||
implements AuthenticationProvider {
|
||||
|
||||
private I+Rail++tabuser+Dao<+tabuser+> +rail++tabuser+;
|
||||
|
||||
@Autowired
|
||||
public +Applicaz+UserAuthenticationProvider(I+Rail++tabuser+Dao<+tabuser+> +rail++tabuser+) {
|
||||
if (+rail++tabuser+ == null) {
|
||||
throw new IllegalArgumentException(
|
||||
"Screwdriver: +rail++tabuser+ cannot be null");
|
||||
}
|
||||
this.+rail++tabuser+ = +rail++tabuser+;
|
||||
}
|
21
screwdriver-3.5.6/box/snippets/java/Belonger.java
Normal file
21
screwdriver-3.5.6/box/snippets/java/Belonger.java
Normal file
|
@ -0,0 +1,21 @@
|
|||
package +zoccolo+.security;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
|
||||
public class Belonger extends User {
|
||||
|
||||
public Belonger(String username, String password, boolean enabled,
|
||||
boolean accountNonExpired, boolean credentialsNonExpired,
|
||||
boolean accountNonLocked,
|
||||
Collection<? extends GrantedAuthority> authorities) {
|
||||
super(username, password, enabled, accountNonExpired,
|
||||
credentialsNonExpired, accountNonLocked, authorities);
|
||||
}
|
||||
|
||||
private static final long serialVersionUID = 4190186200539186925L;
|
||||
|
||||
/* screwdriver_knife */
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package +zoccolo+.web.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
@ -0,0 +1,6 @@
|
|||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.ldap.userdetails.InetOrgPerson;
|
||||
import org.springframework.security.ldap.userdetails.LdapUserDetails;
|
||||
import org.springframework.security.ldap.userdetails.Person;
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
package +zoccolo+.web.filter;
|
||||
|
||||
import +zoccolo+.web.servlet.HttpRequestWrapper;
|
||||
|
||||
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 javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class CrossSiteScriptingFilter implements Filter {
|
||||
|
||||
static Logger log = Logger.getLogger(CrossSiteScriptingFilter.class);
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private FilterConfig filterConfig;
|
||||
|
||||
/**
|
||||
* @see Filter#destroy()
|
||||
*/
|
||||
public void destroy() {
|
||||
this.filterConfig = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
|
||||
*/
|
||||
public void doFilter(ServletRequest request, ServletResponse response,
|
||||
FilterChain chain) throws IOException, ServletException {
|
||||
|
||||
String sessionid = ((HttpServletRequest) request).getSession().getId();
|
||||
// be careful overwriting: JSESSIONID may have been set with other flags
|
||||
((HttpServletResponse) response).setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + ";Path=/; HttpOnly");
|
||||
|
||||
chain.doFilter(new HttpRequestWrapper((HttpServletRequest)request), response);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see Filter#init(FilterConfig)
|
||||
*/
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
this.filterConfig = filterConfig;
|
||||
log.info("CrossSiteScriptingFilter correctly initialized.");
|
||||
}
|
||||
|
||||
/* screwdriver_knife */
|
||||
|
||||
}
|
||||
|
23
screwdriver-3.5.6/box/snippets/java/Crud.java
Normal file
23
screwdriver-3.5.6/box/snippets/java/Crud.java
Normal file
|
@ -0,0 +1,23 @@
|
|||
// R = READ
|
||||
private ModelAndView screw+jsp+R(+Jsp+Form +jsp+Form) {
|
||||
return new ModelAndView("+screwModel+", "belong",
|
||||
+jsp+Form);
|
||||
}
|
||||
|
||||
// C = CREATE
|
||||
private ModelAndView screw+jsp+C(+Jsp+Form +jsp+Form) {
|
||||
Notice notice = new Notice();
|
||||
return new ModelAndView("answers/ok", "belong", notice);
|
||||
}
|
||||
|
||||
// U = UPDATE
|
||||
private ModelAndView screw+jsp+U(+Jsp+Form +jsp+Form) {
|
||||
Notice notice = new Notice();
|
||||
return new ModelAndView("answers/ok", "belong", notice);
|
||||
}
|
||||
|
||||
// D = DELETE
|
||||
private ModelAndView screw+jsp+D(+Jsp+Form +jsp+Form) {
|
||||
Notice notice = new Notice();
|
||||
return new ModelAndView("answers/ok", "belong", notice);
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package +zoccolo+.web.authentication;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import +zoccolo+.web.authentication.authority.UserAuthorityUtils;
|
||||
import +tabposition+.+tabella+;
|
||||
|
||||
/**
|
||||
* An implementation of {@link UserContext} that looks up the {@link CalendarUser} using the Spring Security's
|
||||
* {@link Authentication} by principal name.
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class SpringSecurityUserContext implements UserContext {
|
||||
/**
|
||||
* Get the {@link CalendarUser} by casting the {@link Authentication}'s principal to a {@link CalendarUser}.
|
||||
*/
|
||||
@Override
|
||||
public +tabella+ getCurrentUser() {
|
||||
SecurityContext context = SecurityContextHolder.getContext();
|
||||
Authentication authentication = context.getAuthentication();
|
||||
if (authentication == null) {
|
||||
return null;
|
||||
}
|
||||
return (+tabella+) authentication.getPrincipal();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link CalendarUser} as the current {@link Authentication}'s principal. It uses
|
||||
*/
|
||||
@Override
|
||||
public void setCurrentUser(+tabella+ user) {
|
||||
if (user == null) {
|
||||
throw new IllegalArgumentException("user cannot be null");
|
||||
}
|
||||
Collection<? extends GrantedAuthority> authorities = UserAuthorityUtils.createAuthorities(user);
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user,
|
||||
user.get+password+(),authorities);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package +zoccolo+.web.authentication;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
import +zoccolo+.web.authentication.DomainUsernamePasswordAuthenticationToken;
|
||||
|
||||
/**
|
||||
* An extension to the existing {@link UsernamePasswordAuthenticationFilter} that obtains a domain parameter and then
|
||||
* creates a {@link DomainUsernamePasswordAuthenticationToken}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
public final class DomainUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
|
||||
|
||||
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
|
||||
throws AuthenticationException {
|
||||
if (!request.getMethod().equals("POST")) {
|
||||
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
|
||||
}
|
||||
|
||||
String username = obtainUsername(request);
|
||||
String password = obtainPassword(request);
|
||||
String domain = request.getParameter("domain");
|
||||
|
||||
DomainUsernamePasswordAuthenticationToken authRequest = new DomainUsernamePasswordAuthenticationToken(username,
|
||||
password, domain);
|
||||
|
||||
setDetails(request, authRequest);
|
||||
return this.getAuthenticationManager().authenticate(authRequest);
|
||||
}
|
||||
/* screwdriver_knife */
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package +zoccolo+.web.authentication;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
import +jpapath+.+tabella+;
|
||||
|
||||
public final class DomainUsernamePasswordAuthenticationToken
|
||||
|
||||
extends UsernamePasswordAuthenticationToken {
|
||||
|
||||
private final String domain;
|
||||
|
||||
public DomainUsernamePasswordAuthenticationToken(String principal, String credentials, String domain) {
|
||||
super(principal, credentials);
|
||||
this.domain = domain;
|
||||
}
|
||||
|
||||
public DomainUsernamePasswordAuthenticationToken(+tabella+ principal, String credentials, String domain,
|
||||
Collection<? extends GrantedAuthority> authorities) {
|
||||
super(principal, credentials, authorities);
|
||||
this.domain = domain;
|
||||
}
|
||||
|
||||
public String getDomain() {
|
||||
return domain;
|
||||
}
|
||||
|
||||
private static final long serialVersionUID = -5138870746127783L;
|
||||
|
||||
/* screwdriver_knife */
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package +zoccolo+.web.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import +zoccolo+.web.model.utility.Notice;
|
||||
/** <p>
|
||||
* Home page controller.
|
||||
* </p>
|
||||
*/
|
||||
@Controller
|
||||
public class DoorControllerBelong {
|
||||
|
||||
@RequestMapping("/")
|
||||
public String welcome() {
|
||||
return "home/index";
|
||||
}
|
||||
|
||||
@RequestMapping("/default")
|
||||
public String welcomeDefault() {
|
||||
return "home/index";
|
||||
}
|
||||
|
||||
@RequestMapping("/login/form")
|
||||
public String chiSei() {
|
||||
return "home/login";
|
||||
}
|
||||
|
||||
+signup+
|
||||
|
||||
@RequestMapping("/answers/errorPage")
|
||||
public ModelAndView materia_1(HttpServletRequest request) {
|
||||
Notice notice = new Notice();
|
||||
notice.setScrewFormattedText("Unauthorized access, user "
|
||||
+ request.getUserPrincipal().getName()
|
||||
+ " has no sufficient faculties.");
|
||||
return new ModelAndView("answers/error", "belong", notice);
|
||||
}
|
||||
|
||||
/* screwdriver_knife */
|
||||
}
|
19
screwdriver-3.5.6/box/snippets/java/GenericComponent.java
Normal file
19
screwdriver-3.5.6/box/snippets/java/GenericComponent.java
Normal file
|
@ -0,0 +1,19 @@
|
|||
package +zoccolo+.web.controller;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
public class GenericComponent {
|
||||
|
||||
protected final Log logger = LogFactory.getLog(this.getClass());
|
||||
|
||||
@Autowired
|
||||
public ApplicationContext context;
|
||||
|
||||
public String getMessage(String key, Object ...variables) {
|
||||
return context.getMessage(key, variables, null);
|
||||
}
|
||||
|
||||
}
|
43
screwdriver-3.5.6/box/snippets/java/GenericController.java
Normal file
43
screwdriver-3.5.6/box/snippets/java/GenericController.java
Normal file
|
@ -0,0 +1,43 @@
|
|||
package +zoccolo+.web.controller;
|
||||
|
||||
import +zoccolo+.web.controller.GenericComponent;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
public class GenericController extends GenericComponent {
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ModelAndView handleError(HttpServletRequest req, Exception exception) {
|
||||
logger.error("Request: " + req.getRequestURL() + " raised " + exception);
|
||||
|
||||
exception.printStackTrace();
|
||||
ModelAndView mav = new ModelAndView("page.error");
|
||||
|
||||
return mav;
|
||||
}
|
||||
|
||||
|
||||
protected String localizeViewName(String viewBaseName, HttpServletRequest request) {
|
||||
|
||||
String ret = viewBaseName;
|
||||
String lang = getSessionAttribute("lang", request);
|
||||
|
||||
if ("en".equals(lang))
|
||||
ret += ".en";
|
||||
return ret;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected <T> T getSessionAttribute(String name, HttpServletRequest request) {
|
||||
try {
|
||||
T toReturn = (T) request.getSession().getAttribute(name);
|
||||
return toReturn == null ? null : toReturn;
|
||||
} catch (ClassCastException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
114
screwdriver-3.5.6/box/snippets/java/GenericCrud.java
Normal file
114
screwdriver-3.5.6/box/snippets/java/GenericCrud.java
Normal file
|
@ -0,0 +1,114 @@
|
|||
package +zoccolo+.generic;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.hibernate.Criteria;
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.Query;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.criterion.Criterion;
|
||||
import org.hibernate.criterion.Order;
|
||||
import org.hibernate.criterion.Projections;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
|
||||
public abstract interface GenericCrud<T, ID extends Serializable> {
|
||||
|
||||
public abstract void clear()
|
||||
|
||||
throws DataAccessException, Exception;
|
||||
|
||||
public abstract void delete(T entity)
|
||||
|
||||
throws DataAccessException, Exception;
|
||||
|
||||
public abstract void deleteById(ID id)
|
||||
|
||||
throws DataAccessException, Exception;
|
||||
|
||||
public abstract List<T> findAll()
|
||||
|
||||
throws HibernateException, Exception;
|
||||
|
||||
public abstract List<T> findAll(Order order)
|
||||
|
||||
throws HibernateException, Exception;
|
||||
|
||||
public abstract List<T> findByCriteria(Criterion... criterion)
|
||||
|
||||
throws HibernateException, Exception;
|
||||
|
||||
public abstract List<T> findByCriteria(Order order, Criterion... criterion)
|
||||
|
||||
throws HibernateException, Exception;
|
||||
|
||||
public abstract T findUniqueByCriteria(Criterion... criterion)
|
||||
|
||||
throws HibernateException, Exception;
|
||||
|
||||
public abstract List<T> findByExample(T exampleInstance,
|
||||
String[] excludeProperty)
|
||||
|
||||
throws HibernateException, Exception;
|
||||
|
||||
public abstract T findById(ID id, boolean lock)
|
||||
|
||||
throws DataAccessException, Exception;
|
||||
|
||||
public abstract void flush()
|
||||
|
||||
throws DataAccessException, Exception;
|
||||
|
||||
public abstract T makePersistent(T entity)
|
||||
|
||||
throws DataAccessException, Exception;
|
||||
|
||||
public abstract void makeTransient(T entity)
|
||||
|
||||
throws DataAccessException, Exception;
|
||||
|
||||
public abstract void save(T entity)
|
||||
|
||||
throws DataAccessException, Exception;
|
||||
|
||||
public abstract void saveOrUpdate(T entity)
|
||||
|
||||
throws DataAccessException, Exception;
|
||||
|
||||
public void update(T entity)
|
||||
|
||||
throws DataAccessException, Exception;
|
||||
|
||||
public void merge(T entity)
|
||||
|
||||
throws DataAccessException, Exception;
|
||||
|
||||
public String getDialect()
|
||||
|
||||
throws HibernateException, Exception;
|
||||
|
||||
public List<Object> oneColumnQuery(final String q)
|
||||
|
||||
throws HibernateException, Exception;
|
||||
|
||||
public List<Object[]> manyColumnQuery(final String q)
|
||||
|
||||
throws HibernateException;
|
||||
|
||||
public Integer howManyRows(Criterion... criterion)
|
||||
|
||||
throws DataAccessException;
|
||||
|
||||
public Integer howManyRows()
|
||||
|
||||
throws DataAccessException;
|
||||
|
||||
public Integer howManyRowsAlias(String p, String alias,
|
||||
Criterion... criterion)
|
||||
|
||||
throws DataAccessException;
|
||||
|
||||
/* screwdriver_knife */
|
||||
|
||||
}
|
221
screwdriver-3.5.6/box/snippets/java/GenericRailDaoImplJPA1.java
Normal file
221
screwdriver-3.5.6/box/snippets/java/GenericRailDaoImplJPA1.java
Normal file
|
@ -0,0 +1,221 @@
|
|||
package +zoccolo+.+rail+;
|
||||
|
||||
import +zoccolo+.generic.GenericCrud;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.hibernate.Criteria;
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.LockMode;
|
||||
import org.hibernate.Query;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.criterion.Criterion;
|
||||
import org.hibernate.criterion.Example;
|
||||
import org.hibernate.criterion.Order;
|
||||
import org.hibernate.criterion.Projections;
|
||||
import org.hibernate.impl.SessionFactoryImpl;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.orm.hibernate3.HibernateTemplate;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Transactional("+rail+TxManager")
|
||||
public abstract class Generic+Rail+DaoImpl<T, ID extends Serializable>
|
||||
implements GenericCrud<T, ID> {
|
||||
|
||||
private final Class<T> persistentClass;
|
||||
|
||||
@Autowired(required = true)
|
||||
@Qualifier("+rail+Template")
|
||||
protected HibernateTemplate +rail+Template;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Generic+Rail+DaoImpl() {
|
||||
this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
|
||||
.getGenericSuperclass()).getActualTypeArguments()[0];
|
||||
}
|
||||
|
||||
public void clear() throws DataAccessException {
|
||||
+rail+Template.clear();
|
||||
}
|
||||
|
||||
public void delete(T entity) throws DataAccessException {
|
||||
+rail+Template.delete(entity);
|
||||
}
|
||||
|
||||
public void deleteById(ID id) throws DataAccessException {
|
||||
T entity = +rail+Template.get(persistentClass, id);
|
||||
+rail+Template.delete(entity);
|
||||
}
|
||||
|
||||
public List<T> findAll() throws HibernateException {
|
||||
return findByCriteria();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<T> findAll(Order order) throws HibernateException {
|
||||
Criteria crit = +rail+Template.getSessionFactory().getCurrentSession()
|
||||
.createCriteria(persistentClass);
|
||||
crit.addOrder(order);
|
||||
return crit.list();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<T> findByCriteria(Order order, Criterion... criterion)
|
||||
throws HibernateException {
|
||||
Criteria criteria = +rail+Template.getSessionFactory().getCurrentSession()
|
||||
.createCriteria(persistentClass).addOrder(order);
|
||||
for (Criterion c : criterion) {
|
||||
criteria.add(c);
|
||||
}
|
||||
return criteria.list();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<T> findByCriteria(Criterion... criterion)
|
||||
throws HibernateException {
|
||||
Criteria criteria = +rail+Template.getSessionFactory()
|
||||
.getCurrentSession().createCriteria(persistentClass);
|
||||
for (Criterion c : criterion) {
|
||||
criteria.add(c);
|
||||
}
|
||||
return criteria.list();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public String getDialect()
|
||||
|
||||
throws HibernateException {
|
||||
|
||||
SessionFactoryImpl sfi = (SessionFactoryImpl) +rail+Template
|
||||
.getSessionFactory();
|
||||
return sfi.getDialect().toString();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<Object> oneColumnQuery(final String q)
|
||||
|
||||
throws HibernateException {
|
||||
|
||||
Session session = +rail+Template.getSessionFactory()
|
||||
.getCurrentSession();
|
||||
Query query = session.createQuery(q);
|
||||
return (List<Object>) query.list();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<Object[]> manyColumnQuery(final String q)
|
||||
|
||||
throws HibernateException {
|
||||
|
||||
Session session = +rail+Template.getSessionFactory()
|
||||
.getCurrentSession();
|
||||
Query query = session.createQuery(q);
|
||||
return (List<Object[]>) query.list();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer howManyRows(Criterion... criterion)
|
||||
|
||||
throws DataAccessException {
|
||||
|
||||
Criteria criteria = +rail+Template.getSessionFactory().getCurrentSession()
|
||||
.createCriteria(persistentClass)
|
||||
.setProjection(Projections.rowCount());
|
||||
for (Criterion c : criterion) {
|
||||
criteria.add(c);
|
||||
}
|
||||
return (Integer)criteria.uniqueResult();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer howManyRowsAlias(String p, String alias, Criterion... criterion)
|
||||
|
||||
throws DataAccessException {
|
||||
|
||||
Criteria criteria = +rail+Template.getSessionFactory().getCurrentSession()
|
||||
.createCriteria(persistentClass)
|
||||
.setProjection(Projections.rowCount());
|
||||
criteria.createAlias(p, alias);
|
||||
for (Criterion c : criterion) {
|
||||
criteria.add(c);
|
||||
}
|
||||
return (Integer)criteria.uniqueResult();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer howManyRows() throws DataAccessException {
|
||||
Criteria criteria = +rail+Template.getSessionFactory().getCurrentSession()
|
||||
.createCriteria(persistentClass)
|
||||
.setProjection(Projections.rowCount());
|
||||
return (Integer)criteria.uniqueResult();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public T findUniqueByCriteria(Criterion... criterion)
|
||||
throws HibernateException {
|
||||
Criteria crit = +rail+Template.getSessionFactory().getCurrentSession()
|
||||
.createCriteria(persistentClass);
|
||||
for (Criterion c : criterion) {
|
||||
crit.add(c);
|
||||
}
|
||||
return (T) crit.uniqueResult();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<T> findByExample(T exampleInstance, String[] excludeProperty)
|
||||
throws HibernateException {
|
||||
Criteria crit = +rail+Template.getSessionFactory().getCurrentSession()
|
||||
.createCriteria(persistentClass);
|
||||
Example example = Example.create(exampleInstance);
|
||||
for (String exclude : excludeProperty) {
|
||||
example.excludeProperty(exclude);
|
||||
}
|
||||
crit.add(example);
|
||||
return crit.list();
|
||||
}
|
||||
|
||||
public T findById(ID id, boolean lock) throws DataAccessException {
|
||||
T entity;
|
||||
if (lock)
|
||||
entity = +rail+Template.load(persistentClass, id, LockMode.UPGRADE);
|
||||
else
|
||||
entity = +rail+Template.load(persistentClass, id);
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
public void flush() throws DataAccessException {
|
||||
+rail+Template.flush();
|
||||
}
|
||||
|
||||
public T makePersistent(T entity) throws DataAccessException {
|
||||
+rail+Template.saveOrUpdate(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
public void makeTransient(T entity) throws DataAccessException {
|
||||
+rail+Template.delete(entity);
|
||||
}
|
||||
|
||||
public void save(T entity) throws DataAccessException {
|
||||
+rail+Template.save(entity);
|
||||
}
|
||||
|
||||
public void saveOrUpdate(T entity) throws DataAccessException {
|
||||
+rail+Template.saveOrUpdate(entity);
|
||||
}
|
||||
|
||||
public void update(T entity) throws DataAccessException {
|
||||
+rail+Template.update(entity);
|
||||
}
|
||||
|
||||
public void merge(T entity) throws DataAccessException {
|
||||
+rail+Template.merge(entity);
|
||||
}
|
||||
/* screwdriver_knife */
|
||||
}
|
332
screwdriver-3.5.6/box/snippets/java/GenericRailDaoImplJPA2.java
Normal file
332
screwdriver-3.5.6/box/snippets/java/GenericRailDaoImplJPA2.java
Normal file
|
@ -0,0 +1,332 @@
|
|||
package +zoccolo+.+rail+;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.persistence.Tuple;
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Expression;
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import javax.persistence.criteria.Root;
|
||||
import javax.persistence.Query;
|
||||
|
||||
import org.apache.log4j.LogManager;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import +zoccolo+.jpa.Filter;
|
||||
import +zoccolo+.jpa.Order;
|
||||
import +zoccolo+.jpa.OrderBuilder.OrderType;
|
||||
import +zoccolo+.jpa.PaginatedFilter;
|
||||
import +zoccolo+.jpa.SearchParameter;
|
||||
import +zoccolo+.jpa.dao.GenericDao;
|
||||
|
||||
/**
|
||||
* Implementation of the interface for dao management.<br>
|
||||
* <b>IMPORTANT</b> - Reference to the persistence context JPA is set in this implementation.
|
||||
*
|
||||
* @param <T>
|
||||
*/
|
||||
public abstract class Generic+Rail+DaoImpl<T> implements GenericDao<T> {
|
||||
|
||||
public static final Logger logger = LogManager.getLogger(Generic+Rail+DaoImpl.class);
|
||||
|
||||
@PersistenceContext(unitName="+rail+EntityManagerFactory")
|
||||
protected EntityManager em;
|
||||
|
||||
protected String generateDebugParameters(List<SearchParameter<String>> parameters) {
|
||||
if (parameters == null || parameters.size() == 0) {
|
||||
return "[]";
|
||||
}
|
||||
StringBuffer paramsDebug = new StringBuffer("[");
|
||||
for (SearchParameter<String> parameter : parameters) {
|
||||
paramsDebug.append(" ").append(parameter.getName()).append("=").append(parameter.getValue());
|
||||
}
|
||||
paramsDebug.append("]");
|
||||
|
||||
return paramsDebug.toString();
|
||||
}
|
||||
|
||||
protected List<javax.persistence.criteria.Order> createOrderClauseList(CriteriaBuilder cb, Root<T> root, Order[] order) {
|
||||
List<javax.persistence.criteria.Order> orderList = new ArrayList<javax.persistence.criteria.Order>();
|
||||
if (order == null) return orderList;
|
||||
|
||||
for (Order ord : order) {
|
||||
if (OrderType.ASC.toString().equals(ord.getAsc())) {
|
||||
orderList.add(cb.asc(root.get(ord.getOrder())));
|
||||
} else {
|
||||
orderList.add(cb.desc(root.get(ord.getOrder())));
|
||||
}
|
||||
}
|
||||
return orderList;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor=PersistenceException.class)
|
||||
public T create(T entity) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Create entity: " + entity);
|
||||
em.persist(entity);
|
||||
em.flush();
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor=PersistenceException.class)
|
||||
public T update(T entity) {
|
||||
// Check if instance is detached
|
||||
if (!em.contains(entity)) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Update entity: " + entity);
|
||||
entity = em.merge(entity);
|
||||
}
|
||||
em.flush();
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor=PersistenceException.class)
|
||||
public void remove(T entity) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Remove entity: " + entity);
|
||||
// check if instance is detached
|
||||
if (!em.contains(entity)) {
|
||||
entity = em.merge(entity);
|
||||
}
|
||||
em.remove(entity);
|
||||
em.flush();
|
||||
}
|
||||
|
||||
public T findUniqueById(Class<T> entityClass, Integer id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("findUniqueById(" + entityClass.getName() + ", " + id + ")");
|
||||
T result = em.find(entityClass, id);
|
||||
return result;
|
||||
}
|
||||
|
||||
public T findUniqueById(Class<T> entityClass, Long id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("findUniqueById(" + entityClass.getName() + ", " + id + ")");
|
||||
T result = em.find(entityClass, id);
|
||||
return result;
|
||||
}
|
||||
|
||||
public T findUniqueById(Class<T> entityClass, String id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("findUniqueById(" + entityClass.getName() + ", '" + id + "')");
|
||||
T result = em.find(entityClass, id);
|
||||
return result;
|
||||
}
|
||||
|
||||
public Collection<T> findListBy(Class<T> entityClass, String fieldName,
|
||||
Class<?> fieldClass, Object fieldValue) {
|
||||
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
|
||||
CriteriaQuery<T> cq = cb.createQuery(entityClass);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
Predicate predicate = cb.equal(
|
||||
root.get(fieldName).as(fieldClass),
|
||||
fieldValue);
|
||||
|
||||
cq.where(predicate);
|
||||
|
||||
TypedQuery<T> tq = em.createQuery(cq);
|
||||
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of findListBy(" + entityClass + ","
|
||||
+ " '" + fieldName + "'" + " " + fieldClass + "" + " '" + fieldValue + "')");
|
||||
Collection<T> results = tq.getResultList();
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
public List<T> like(Class<T> fieldClazz, String fieldName,
|
||||
Class<String> valueClazz, String fieldValue) {
|
||||
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
|
||||
CriteriaQuery<T> cq = cb.createQuery(fieldClazz);
|
||||
Root<T> root = cq.from(fieldClazz);
|
||||
|
||||
|
||||
Predicate predicate = cb.like(
|
||||
(Expression<String>)cb.upper( root.get(fieldName).as(valueClazz)), "%"+
|
||||
fieldValue.toUpperCase()+"%");
|
||||
|
||||
cq.where(predicate);
|
||||
|
||||
TypedQuery<T> tq = em.createQuery(cq);
|
||||
|
||||
List<T> results = tq.getResultList();
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
public Collection<T> findAll(Class<T> entityClass, Order ... order) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
|
||||
CriteriaQuery<T> cq = cb.createQuery(entityClass);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
cq.orderBy(createOrderClauseList(cb, root, order));
|
||||
|
||||
TypedQuery<T> tq = em.createQuery(cq);
|
||||
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of findAll(" + entityClass + ") method");
|
||||
Collection<T> result = tq.getResultList();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public Boolean exists(Class<T> entityClass, Integer id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of exists(" + entityClass + ", " + id + ") method");
|
||||
T result = em.find(entityClass, id);
|
||||
return result == null ? false : true;
|
||||
}
|
||||
|
||||
public Boolean exists(Class<T> entityClass, Long id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of exists(" + entityClass + ", " + id + ") method");
|
||||
T result = em.find(entityClass, id);
|
||||
return result == null ? false : true;
|
||||
}
|
||||
|
||||
public Boolean exists(Class<T> entityClass, String id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of exists(" + entityClass + ", " + id + ") method");
|
||||
T result = em.find(entityClass, id);
|
||||
return result == null ? false : true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Metodo da implementare per effettuare un'inizializzazione di una entity
|
||||
* con caricamenti di dati lazy. Per default restituisce la entity
|
||||
* inalterata.
|
||||
*
|
||||
* la <code>HibernateUtils.initialize()</code>.
|
||||
*
|
||||
* @param entity
|
||||
* @return
|
||||
*/
|
||||
protected T load(T entity) {
|
||||
return entity;
|
||||
}
|
||||
|
||||
protected void setPagination(TypedQuery<Tuple> tq, Filter filter) {
|
||||
if (filter instanceof PaginatedFilter) {
|
||||
PaginatedFilter pfilter = (PaginatedFilter) filter;
|
||||
|
||||
int firstResult = pfilter.getFirstResult();
|
||||
int pageSize = pfilter.getPageSize();
|
||||
|
||||
if (logger.isTraceEnabled()) logger.trace("Range (" + firstResult + ", " + pageSize + ")");
|
||||
tq.setFirstResult(firstResult);
|
||||
tq.setMaxResults(pageSize);
|
||||
}
|
||||
}
|
||||
|
||||
public Long count(Class<T> entityClass) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
cq.select(cb.count(root));
|
||||
|
||||
TypedQuery<Long> tq = em.createQuery(cq);
|
||||
Long result = tq.getSingleResult();
|
||||
return result;
|
||||
}
|
||||
|
||||
public Long count(Class<T> entityClass, Filter filter) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
List<Predicate> predicates = new ArrayList<Predicate>();
|
||||
if (!filter.getParams().isEmpty()) {
|
||||
predicates.add(getLikePredicate(cb, root, filter.getParams()));
|
||||
}
|
||||
if (predicates.size() > 0) {
|
||||
cq.where(cb.and(predicates.toArray(new Predicate[] {})));
|
||||
}
|
||||
|
||||
cq.select(cb.count(root));
|
||||
|
||||
TypedQuery<Long> tq = em.createQuery(cq);
|
||||
Long result = tq.getSingleResult();
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<T> fetch(Class<T> entityClass, Filter filter, Order... order) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
List<Predicate> predicates = new ArrayList<Predicate>();
|
||||
if (!filter.getParams().isEmpty()) {
|
||||
predicates.add(getLikePredicate(cb, root, filter.getParams()));
|
||||
}
|
||||
if (predicates.size() > 0) {
|
||||
cq.where(cb.and(predicates.toArray(new Predicate[] {})));
|
||||
}
|
||||
|
||||
cq.select(cb.tuple(root));
|
||||
|
||||
cq.distinct(true);
|
||||
|
||||
cq.orderBy(createOrderClauseList(cb, root, order));
|
||||
|
||||
TypedQuery<Tuple> tq = em.createQuery(cq);
|
||||
|
||||
setPagination(tq, filter);
|
||||
List<Tuple> results = tq.getResultList();
|
||||
List<T> loadedResults = new ArrayList<T>();
|
||||
for (Tuple result : results) {
|
||||
loadedResults.add(load((T) result.get(0)));
|
||||
}
|
||||
return loadedResults;
|
||||
}
|
||||
|
||||
|
||||
public boolean existsByFilename(Class<T> entityClass, SearchParameter<String> fileName) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
Predicate p = cb.equal(root.get(fileName.getName()).as(String.class), fileName.getValue());
|
||||
cq.where(p);
|
||||
|
||||
cq.select(cb.count(root));
|
||||
|
||||
TypedQuery<Long> tq = em.createQuery(cq);
|
||||
Long result = tq.getSingleResult();
|
||||
return result > 0;
|
||||
}
|
||||
|
||||
private Predicate getLikePredicate(CriteriaBuilder cb, Root<T> root, List<SearchParameter<String>> parameters) {
|
||||
List<Predicate> orPredicates = new ArrayList<Predicate>();
|
||||
|
||||
for (SearchParameter<String> parameter : parameters) {
|
||||
orPredicates.add(cb.like(cb.upper(root.get(parameter.getName()).as(String.class)), "%" + parameter.getValue().toUpperCase() + "%"));
|
||||
}
|
||||
|
||||
return cb.or(orPredicates.toArray(new Predicate[] {}));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
|
||||
public List<Object> oneColumnQuery(final String string) {
|
||||
Query qu = em.createQuery(string);
|
||||
List<Object> sE = qu.getResultList();
|
||||
return sE;
|
||||
}
|
||||
|
||||
public List<Object[]> manyColumnQuery(final String string) {
|
||||
Query qu = em.createQuery(string);
|
||||
List<Object[]> sE = qu.getResultList();
|
||||
return sE;
|
||||
}
|
||||
|
||||
public Object findByPrimary(Class<T> entityClass, Object chiave) {
|
||||
Object x = em.find(entityClass, chiave);
|
||||
return x;
|
||||
}
|
||||
/* screwdriver_knife */
|
||||
}
|
|
@ -0,0 +1,349 @@
|
|||
package +zoccolo+.+rail+;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.persistence.Tuple;
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Expression;
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import javax.persistence.criteria.Root;
|
||||
import javax.persistence.Query;
|
||||
|
||||
import org.apache.log4j.LogManager;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import +zoccolo+.jpa.Filter;
|
||||
import +zoccolo+.jpa.Order;
|
||||
import +zoccolo+.jpa.OrderBuilder.OrderType;
|
||||
import +zoccolo+.jpa.PaginatedFilter;
|
||||
import +zoccolo+.jpa.SearchParameter;
|
||||
import +zoccolo+.jpa.dao.GenericDao;
|
||||
|
||||
/**
|
||||
* Implementation of the interface for dao management.<br>
|
||||
* <b>IMPORTANT</b> - Reference to the persistence context JPA is set in this implementation.
|
||||
*
|
||||
* @param <T>
|
||||
*/
|
||||
public abstract class Generic+Rail+DaoImpl<T> implements GenericDao<T> {
|
||||
|
||||
public static final Logger logger = LogManager.getLogger(Generic+Rail+DaoImpl.class);
|
||||
|
||||
@PersistenceContext(unitName="+rail+EntityManagerFactory")
|
||||
protected EntityManager em;
|
||||
|
||||
protected String generateDebugParameters(List<SearchParameter<String>> parameters) {
|
||||
if (parameters == null || parameters.size() == 0) {
|
||||
return "[]";
|
||||
}
|
||||
StringBuffer paramsDebug = new StringBuffer("[");
|
||||
for (SearchParameter<String> parameter : parameters) {
|
||||
paramsDebug.append(" ").append(parameter.getName()).append("=").append(parameter.getValue());
|
||||
}
|
||||
paramsDebug.append("]");
|
||||
|
||||
return paramsDebug.toString();
|
||||
}
|
||||
|
||||
protected List<javax.persistence.criteria.Order> createOrderClauseList(CriteriaBuilder cb, Root<T> root, Order[] order) {
|
||||
List<javax.persistence.criteria.Order> orderList = new ArrayList<>();
|
||||
if (order == null) return orderList;
|
||||
|
||||
for (Order ord : order) {
|
||||
if (OrderType.ASC.toString().equals(ord.getAsc())) {
|
||||
orderList.add(cb.asc(root.get(ord.getOrder())));
|
||||
} else {
|
||||
orderList.add(cb.desc(root.get(ord.getOrder())));
|
||||
}
|
||||
}
|
||||
return orderList;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor=PersistenceException.class)
|
||||
public T create(T entity) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Create entity: " + entity);
|
||||
em.persist(entity);
|
||||
em.flush();
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor=PersistenceException.class)
|
||||
public T update(T entity) {
|
||||
// Check if instance is detached
|
||||
if (!em.contains(entity)) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Update entity: " + entity);
|
||||
entity = em.merge(entity);
|
||||
}
|
||||
em.flush();
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor=PersistenceException.class)
|
||||
public void remove(T entity) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Remove entity: " + entity);
|
||||
// check if instance is detached
|
||||
if (!em.contains(entity)) {
|
||||
entity = em.merge(entity);
|
||||
}
|
||||
em.remove(entity);
|
||||
em.flush();
|
||||
}
|
||||
|
||||
@Override
|
||||
public T findUniqueById(Class<T> entityClass, Integer id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("findUniqueById(" + entityClass.getName() + ", " + id + ")");
|
||||
T result = em.find(entityClass, id);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T findUniqueById(Class<T> entityClass, Long id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("findUniqueById(" + entityClass.getName() + ", " + id + ")");
|
||||
T result = em.find(entityClass, id);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T findUniqueById(Class<T> entityClass, String id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("findUniqueById(" + entityClass.getName() + ", '" + id + "')");
|
||||
T result = em.find(entityClass, id);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<T> findListBy(Class<T> entityClass, String fieldName,
|
||||
Class<?> fieldClass, Object fieldValue) {
|
||||
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
|
||||
CriteriaQuery<T> cq = cb.createQuery(entityClass);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
Predicate predicate = cb.equal(
|
||||
root.get(fieldName).as(fieldClass),
|
||||
fieldValue);
|
||||
|
||||
cq.where(predicate);
|
||||
|
||||
TypedQuery<T> tq = em.createQuery(cq);
|
||||
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of findListBy(" + entityClass + ","
|
||||
+ " '" + fieldName + "'" + " " + fieldClass + "" + " '" + fieldValue + "')");
|
||||
Collection<T> results = tq.getResultList();
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<T> like(Class<T> fieldClazz, String fieldName,
|
||||
Class<String> valueClazz, String fieldValue) {
|
||||
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
|
||||
CriteriaQuery<T> cq = cb.createQuery(fieldClazz);
|
||||
Root<T> root = cq.from(fieldClazz);
|
||||
|
||||
|
||||
Predicate predicate = cb.like(
|
||||
(Expression<String>)cb.upper( root.get(fieldName).as(valueClazz)), "%"+
|
||||
fieldValue.toUpperCase()+"%");
|
||||
|
||||
cq.where(predicate);
|
||||
|
||||
TypedQuery<T> tq = em.createQuery(cq);
|
||||
|
||||
List<T> results = tq.getResultList();
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Collection<T> findAll(Class<T> entityClass, Order ... order) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
|
||||
CriteriaQuery<T> cq = cb.createQuery(entityClass);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
cq.orderBy(createOrderClauseList(cb, root, order));
|
||||
|
||||
TypedQuery<T> tq = em.createQuery(cq);
|
||||
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of findAll(" + entityClass + ") method");
|
||||
Collection<T> result = tq.getResultList();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean exists(Class<T> entityClass, Integer id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of exists(" + entityClass + ", " + id + ") method");
|
||||
T result = em.find(entityClass, id);
|
||||
return result == null ? false : true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean exists(Class<T> entityClass, Long id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of exists(" + entityClass + ", " + id + ") method");
|
||||
T result = em.find(entityClass, id);
|
||||
return result == null ? false : true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean exists(Class<T> entityClass, String id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of exists(" + entityClass + ", " + id + ") method");
|
||||
T result = em.find(entityClass, id);
|
||||
return result == null ? false : true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Metodo da implementare per effettuare un'inizializzazione di una entity
|
||||
* con caricamenti di dati lazy. Per default restituisce la entity
|
||||
* inalterata.
|
||||
*
|
||||
* la <code>HibernateUtils.initialize()</code>.
|
||||
*
|
||||
* @param entity
|
||||
* @return
|
||||
*/
|
||||
protected T load(T entity) {
|
||||
return entity;
|
||||
}
|
||||
|
||||
protected void setPagination(TypedQuery<Tuple> tq, Filter filter) {
|
||||
if (filter instanceof PaginatedFilter) {
|
||||
PaginatedFilter pfilter = (PaginatedFilter) filter;
|
||||
|
||||
int firstResult = pfilter.getFirstResult();
|
||||
int pageSize = pfilter.getPageSize();
|
||||
|
||||
if (logger.isTraceEnabled()) logger.trace("Range (" + firstResult + ", " + pageSize + ")");
|
||||
tq.setFirstResult(firstResult);
|
||||
tq.setMaxResults(pageSize);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long count(Class<T> entityClass) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
cq.select(cb.count(root));
|
||||
|
||||
TypedQuery<Long> tq = em.createQuery(cq);
|
||||
Long result = tq.getSingleResult();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long count(Class<T> entityClass, Filter filter) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
if (!filter.getParams().isEmpty()) {
|
||||
predicates.add(getLikePredicate(cb, root, filter.getParams()));
|
||||
}
|
||||
if (predicates.size() > 0) {
|
||||
cq.where(cb.and(predicates.toArray(new Predicate[] {})));
|
||||
}
|
||||
|
||||
cq.select(cb.count(root));
|
||||
|
||||
TypedQuery<Long> tq = em.createQuery(cq);
|
||||
Long result = tq.getSingleResult();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<T> fetch(Class<T> entityClass, Filter filter, Order... order) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
if (!filter.getParams().isEmpty()) {
|
||||
predicates.add(getLikePredicate(cb, root, filter.getParams()));
|
||||
}
|
||||
if (predicates.size() > 0) {
|
||||
cq.where(cb.and(predicates.toArray(new Predicate[] {})));
|
||||
}
|
||||
|
||||
cq.select(cb.tuple(root));
|
||||
|
||||
cq.distinct(true);
|
||||
|
||||
cq.orderBy(createOrderClauseList(cb, root, order));
|
||||
|
||||
TypedQuery<Tuple> tq = em.createQuery(cq);
|
||||
|
||||
setPagination(tq, filter);
|
||||
List<Tuple> results = tq.getResultList();
|
||||
List<T> loadedResults = new ArrayList<T>();
|
||||
for (Tuple result : results) {
|
||||
loadedResults.add(load((T) result.get(0)));
|
||||
}
|
||||
return loadedResults;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsByFilename(Class<T> entityClass, SearchParameter<String> fileName) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
Predicate p = cb.equal(root.get(fileName.getName()).as(String.class), fileName.getValue());
|
||||
cq.where(p);
|
||||
|
||||
cq.select(cb.count(root));
|
||||
|
||||
TypedQuery<Long> tq = em.createQuery(cq);
|
||||
Long result = tq.getSingleResult();
|
||||
return result > 0;
|
||||
}
|
||||
|
||||
private Predicate getLikePredicate(CriteriaBuilder cb, Root<T> root, List<SearchParameter<String>> parameters) {
|
||||
List<Predicate> orPredicates = new ArrayList<Predicate>();
|
||||
|
||||
for (SearchParameter<String> parameter : parameters) {
|
||||
orPredicates.add(cb.like(cb.upper(root.get(parameter.getName()).as(String.class)), "%" + parameter.getValue().toUpperCase() + "%"));
|
||||
}
|
||||
|
||||
return cb.or(orPredicates.toArray(new Predicate[] {}));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public List<Object> oneColumnQuery(final String string) {
|
||||
Query qu = em.createQuery(string);
|
||||
List<Object> sE = qu.getResultList();
|
||||
return sE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Object[]> manyColumnQuery(final String string) {
|
||||
Query qu = em.createQuery(string);
|
||||
List<Object[]> sE = qu.getResultList();
|
||||
return sE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object findByPrimary(Class<T> entityClass, Object chiave) {
|
||||
Object x = em.find(entityClass, chiave);
|
||||
return x;
|
||||
}
|
||||
/* screwdriver_knife */
|
||||
}
|
83
screwdriver-3.5.6/box/snippets/java/HttpRequestWrapper.java
Normal file
83
screwdriver-3.5.6/box/snippets/java/HttpRequestWrapper.java
Normal file
|
@ -0,0 +1,83 @@
|
|||
package +zoccolo+.web.servlet;
|
||||
|
||||
import +zoccolo+.web.listener.AntiSamyListener;
|
||||
|
||||
import +zoccolo+.web.sanitizer.XssSanitizer;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletRequestWrapper;
|
||||
|
||||
import org.owasp.validator.html.CleanResults;
|
||||
import org.owasp.validator.html.PolicyException;
|
||||
import org.owasp.validator.html.ScanException;
|
||||
|
||||
public class HttpRequestWrapper extends HttpServletRequestWrapper {
|
||||
|
||||
private XssSanitizer sanitizer;
|
||||
|
||||
public HttpRequestWrapper(HttpServletRequest servletRequest) {
|
||||
super(servletRequest);
|
||||
this.sanitizer = (XssSanitizer)
|
||||
this.getSession().getServletContext().
|
||||
getAttribute(AntiSamyListener.ANTISAMY_SANITIZER);
|
||||
if(this.sanitizer == null)
|
||||
throw new RuntimeException("Antisamy is not bound in ServletContext");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getParameterValues(String parameter) {
|
||||
String[] retVal = null;
|
||||
String[] values = super.getParameterValues(parameter);
|
||||
if(values != null)
|
||||
{
|
||||
retVal = new String[values.length];
|
||||
for(int i = 0; i < values.length; i++)
|
||||
{
|
||||
if(values[i] != null)
|
||||
retVal[i] = this.cleanXss(values[i]);
|
||||
else
|
||||
retVal[i] = values[i];
|
||||
}
|
||||
}
|
||||
return retVal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getParameter(String parameter) {
|
||||
String paramValue = super.getParameter(parameter);
|
||||
if(paramValue != null)
|
||||
return this.cleanXss(paramValue);
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHeader(String name) {
|
||||
String value = super.getHeader(name);
|
||||
if(value != null)
|
||||
return this.cleanXss(value);
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
private String cleanXss(String parameterValue){
|
||||
String retVal = null;
|
||||
if(parameterValue != null) {
|
||||
try
|
||||
{
|
||||
CleanResults cr = this.sanitizer.scan(parameterValue);
|
||||
retVal = cr.getCleanHTML();
|
||||
}
|
||||
catch (ScanException e)
|
||||
{
|
||||
throw new RuntimeException("ScanException: "+e.getMessage());
|
||||
}
|
||||
catch (PolicyException e)
|
||||
{
|
||||
throw new RuntimeException("ScanException: "+e.getMessage());
|
||||
}
|
||||
}
|
||||
return retVal;
|
||||
}
|
||||
/* screwdriver_knife */
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package +zoccolo+.web.filter;
|
||||
|
||||
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 javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpServletResponseWrapper;
|
||||
|
||||
/**
|
||||
* Servlet Filter implementation class JsessionIdRemoveFilter
|
||||
*/
|
||||
public class JsessionIdRemoveFilter implements Filter {
|
||||
|
||||
/**
|
||||
* Default constructor.
|
||||
*/
|
||||
public JsessionIdRemoveFilter() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @see Filter#destroy()
|
||||
*/
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
|
||||
*/
|
||||
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
|
||||
if (!(req instanceof HttpServletRequest)) {
|
||||
chain.doFilter(req, res);
|
||||
return;
|
||||
}
|
||||
|
||||
HttpServletRequest request = (HttpServletRequest) req;
|
||||
HttpServletResponse response = (HttpServletResponse) res;
|
||||
// Redirect requests with JSESSIONID in URL to clean version
|
||||
// (old links bookmarked/stored by bots)
|
||||
// This is ONLY triggered if the request did not also contain a
|
||||
// JSESSIONID cookie! Which should be fine for bots...
|
||||
if (request.isRequestedSessionIdFromURL()) {
|
||||
String url = request.getRequestURL()
|
||||
.append(request.getQueryString() != null ? "?"
|
||||
+ request.getQueryString() :
|
||||
"").toString();
|
||||
response.setHeader("Location", url);
|
||||
response.sendError(HttpServletResponse.SC_MOVED_PERMANENTLY);
|
||||
return;
|
||||
}
|
||||
// Prevent rendering of JSESSIONID in URLs for all outgoing links
|
||||
HttpServletResponseWrapper wrappedResponse = new
|
||||
HttpServletResponseWrapper(
|
||||
response) {
|
||||
@Override
|
||||
public String encodeRedirectUrl(String url) {
|
||||
return url;
|
||||
}
|
||||
@Override
|
||||
public String encodeRedirectURL(String url) {
|
||||
return url;
|
||||
}
|
||||
@Override
|
||||
public String encodeUrl(String url) {
|
||||
return url;
|
||||
}
|
||||
@Override
|
||||
public String encodeURL(String url) {
|
||||
return url;
|
||||
}
|
||||
};
|
||||
|
||||
chain.doFilter(req, wrappedResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see Filter#init(FilterConfig)
|
||||
*/
|
||||
public void init(FilterConfig fConfig) throws ServletException {
|
||||
}
|
||||
/* screwdriver_knife */
|
||||
}
|
27
screwdriver-3.5.6/box/snippets/java/King.java
Normal file
27
screwdriver-3.5.6/box/snippets/java/King.java
Normal file
|
@ -0,0 +1,27 @@
|
|||
package +zoccolo+.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class King implements Serializable {
|
||||
|
||||
private String userid;
|
||||
private String password;
|
||||
|
||||
private static final long serialVersionUID = 8433999509932007961L;
|
||||
|
||||
public String getUserid() {
|
||||
return userid;
|
||||
}
|
||||
|
||||
public void setUserid(String userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
13
screwdriver-3.5.6/box/snippets/java/KingDao.java
Normal file
13
screwdriver-3.5.6/box/snippets/java/KingDao.java
Normal file
|
@ -0,0 +1,13 @@
|
|||
package +zoccolo+.web.authentication;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.dao.EmptyResultDataAccessException;
|
||||
|
||||
import +zoccolo+.domain.King;
|
||||
|
||||
public interface KingDao {
|
||||
|
||||
King getUser(String id);
|
||||
|
||||
}
|
17
screwdriver-3.5.6/box/snippets/java/KingDaoImpl.java
Normal file
17
screwdriver-3.5.6/box/snippets/java/KingDaoImpl.java
Normal file
|
@ -0,0 +1,17 @@
|
|||
package +zoccolo+.web.authentication;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.dao.EmptyResultDataAccessException;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import +zoccolo+.domain.King;
|
||||
|
||||
@Repository
|
||||
public class KingDaoImpl implements KingDao {
|
||||
|
||||
public King getUser(String id) {
|
||||
King king = new King();
|
||||
return king;
|
||||
}
|
||||
}
|
16
screwdriver-3.5.6/box/snippets/java/LoggedUser.java
Normal file
16
screwdriver-3.5.6/box/snippets/java/LoggedUser.java
Normal file
|
@ -0,0 +1,16 @@
|
|||
package +zoccolo+.web.annotation;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.PARAMETER)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface LoggedUser {
|
||||
|
||||
/* screwdriver_knife */
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package +zoccolo+.web.resolver;
|
||||
|
||||
import +zoccolo+.security.Belonger;
|
||||
import +zoccolo+.web.annotation.LoggedUser;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.support.WebArgumentResolver;
|
||||
import org.springframework.web.bind.support.WebDataBinderFactory;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
|
||||
@Component
|
||||
public class LoggedUserMethodArgumentResolver
|
||||
implements HandlerMethodArgumentResolver {
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(MethodParameter methodParameter) {
|
||||
return
|
||||
methodParameter.getParameterAnnotation(LoggedUser.class) != null
|
||||
&& methodParameter.getParameterType().equals(Belonger.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolveArgument(MethodParameter methodParameter,
|
||||
ModelAndViewContainer mavContainer,
|
||||
NativeWebRequest webRequest,
|
||||
WebDataBinderFactory binderFactory) throws Exception {
|
||||
|
||||
if (this.supportsParameter(methodParameter)) {
|
||||
Principal principal = webRequest.getUserPrincipal();
|
||||
return principal==null?null:(Belonger) ((Authentication) principal).getPrincipal();
|
||||
}
|
||||
else {
|
||||
return WebArgumentResolver.UNRESOLVED;
|
||||
}
|
||||
}
|
||||
|
||||
/* screwdriver_knife */
|
||||
|
||||
}
|
40
screwdriver-3.5.6/box/snippets/java/Notice.java
Normal file
40
screwdriver-3.5.6/box/snippets/java/Notice.java
Normal file
|
@ -0,0 +1,40 @@
|
|||
package +zoccolo+.web.model.utility;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class Notice {
|
||||
|
||||
/** ordinary logger */
|
||||
@SuppressWarnings("unused")
|
||||
private static final Logger logger = Logger.getLogger(
|
||||
Notice.class);
|
||||
|
||||
/** proprietà del bean */
|
||||
private String screwFormattedText;
|
||||
|
||||
/** proprietà del bean */
|
||||
private String screwFreeText;
|
||||
|
||||
/** standard get method */
|
||||
public String getScrewFreeText() {
|
||||
return screwFreeText;
|
||||
}
|
||||
|
||||
/** standard set method, argument String */
|
||||
public void setScrewFreeText(String screwFreeText) {
|
||||
this.screwFreeText = screwFreeText;
|
||||
}
|
||||
|
||||
/** standard get method */
|
||||
public String getScrewFormattedText() {
|
||||
|
||||
return this.screwFormattedText;
|
||||
}
|
||||
|
||||
/** standard set method, argument String */
|
||||
public void setScrewFormattedText(String s) {
|
||||
|
||||
this.screwFormattedText = s;
|
||||
}
|
||||
/* screwdriver_knife */
|
||||
}
|
33
screwdriver-3.5.6/box/snippets/java/QuartzJob.java
Normal file
33
screwdriver-3.5.6/box/snippets/java/QuartzJob.java
Normal file
|
@ -0,0 +1,33 @@
|
|||
package +zoccolo+.job;
|
||||
|
||||
import +zoccolo+.task.impl.+Quartztask+TaskImpl;
|
||||
|
||||
import org.quartz.JobExecutionContext;
|
||||
import org.quartz.JobExecutionException;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.quartz.QuartzJobBean;
|
||||
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
|
||||
|
||||
public class +Quartzjob+ extends QuartzJobBean {
|
||||
|
||||
private static final Logger log = Logger.getLogger(+Quartzjob+.class);
|
||||
|
||||
@Autowired
|
||||
+Quartztask+TaskImpl task;
|
||||
|
||||
@Override
|
||||
protected void executeInternal(JobExecutionContext arg0)
|
||||
|
||||
throws JobExecutionException {
|
||||
|
||||
try {
|
||||
log.debug("executeInternal...");
|
||||
SpringBeanAutowiringSupport
|
||||
.processInjectionBasedOnCurrentContext(this);
|
||||
task.execute(arg0);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
8
screwdriver-3.5.6/box/snippets/java/QuartzTask.java
Normal file
8
screwdriver-3.5.6/box/snippets/java/QuartzTask.java
Normal file
|
@ -0,0 +1,8 @@
|
|||
package +zoccolo+.task;
|
||||
|
||||
import org.quartz.JobExecutionContext;
|
||||
|
||||
public interface +Quartztask+Task {
|
||||
|
||||
public void execute(JobExecutionContext ctx) throws Exception;
|
||||
}
|
24
screwdriver-3.5.6/box/snippets/java/QuartzTaskImpl.java
Normal file
24
screwdriver-3.5.6/box/snippets/java/QuartzTaskImpl.java
Normal file
|
@ -0,0 +1,24 @@
|
|||
package +zoccolo+.task.impl;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.quartz.JobExecutionContext;
|
||||
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
|
||||
|
||||
import +zoccolo+.task.+Quartztask+Task;
|
||||
|
||||
public class +Quartztask+TaskImpl implements +Quartztask+Task {
|
||||
|
||||
private static final Logger log = Logger.getLogger(
|
||||
+Quartztask+TaskImpl.class);
|
||||
|
||||
public void execute(JobExecutionContext ctx)
|
||||
|
||||
throws Exception {
|
||||
|
||||
SpringBeanAutowiringSupport
|
||||
.processInjectionBasedOnCurrentContext(this);
|
||||
/* screwdriver_knife */
|
||||
}
|
||||
}
|
38
screwdriver-3.5.6/box/snippets/java/ScrewInterceptor.java
Normal file
38
screwdriver-3.5.6/box/snippets/java/ScrewInterceptor.java
Normal file
|
@ -0,0 +1,38 @@
|
|||
package +zoccolo+.web.interceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
public class +nocciolo+ implements HandlerInterceptor {
|
||||
|
||||
public void afterCompletion(HttpServletRequest arg0,
|
||||
HttpServletResponse arg1, Object arg2, Exception arg3)
|
||||
throws Exception {
|
||||
// TODO Auto-generated method stub
|
||||
}
|
||||
|
||||
public void postHandle(HttpServletRequest arg0,
|
||||
HttpServletResponse arg1, Object arg2, ModelAndView arg3)
|
||||
throws Exception {
|
||||
// TODO Auto-generated method stub
|
||||
}
|
||||
|
||||
public boolean preHandle(HttpServletRequest arg0,
|
||||
HttpServletResponse arg1, Object arg2) throws Exception {
|
||||
/* 2020-01-20: if I set "return false", I obtain a white home page,
|
||||
* nothing works. */
|
||||
return true;
|
||||
}
|
||||
|
||||
public void afterConcurrentHandlingStarted(
|
||||
HttpServletRequest request, HttpServletResponse response, Object handler)
|
||||
throws Exception {
|
||||
// TODO Auto-generated method stub
|
||||
}
|
||||
|
||||
/* screwdriver_knife */
|
||||
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package +zoccolo+.web.authentication;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import +zoccolo+.web.authentication.authority.UserAuthorityUtils;
|
||||
import +tabposition+.+tabella+;
|
||||
|
||||
/**
|
||||
* An implementation of {@link UserContext} that looks up the {@link CalendarUser} using the Spring Security's
|
||||
* {@link Authentication} by principal name.
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class SpringSecurityUserContext implements UserContext {
|
||||
/**
|
||||
* Get the {@link CalendarUser} by casting the {@link Authentication}'s principal to a {@link CalendarUser}.
|
||||
*/
|
||||
@Override
|
||||
public +tabella+ getCurrentUser() {
|
||||
SecurityContext context = SecurityContextHolder.getContext();
|
||||
Authentication authentication = context.getAuthentication();
|
||||
if (authentication == null) {
|
||||
return null;
|
||||
}
|
||||
return (+tabella+) authentication.getPrincipal();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link CalendarUser} as the current {@link Authentication}'s principal. It uses
|
||||
*/
|
||||
@Override
|
||||
public void setCurrentUser(+tabella+ user) {
|
||||
if (user == null) {
|
||||
throw new IllegalArgumentException("user cannot be null");
|
||||
}
|
||||
Collection<? extends GrantedAuthority> authorities = UserAuthorityUtils.createAuthorities(user);
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user,
|
||||
user.get+password+(),authorities);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package +zoccolo+.web.authentication;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
import +zoccolo+.web.authentication.SimpleUsernamePasswordAuthenticationToken;
|
||||
|
||||
/**
|
||||
* An extension to the existing
|
||||
* {@link UsernamePasswordAuthenticationFilter} that obtains
|
||||
* a domain parameter and then
|
||||
* creates a {@link DomainUsernamePasswordAuthenticationToken}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
public final class SimpleUsernamePasswordAuthenticationFilter
|
||||
|
||||
extends UsernamePasswordAuthenticationFilter {
|
||||
|
||||
public Authentication attemptAuthentication(HttpServletRequest
|
||||
request, HttpServletResponse response)
|
||||
|
||||
throws AuthenticationException {
|
||||
|
||||
if (!request.getMethod().equals("POST")) {
|
||||
throw new AuthenticationServiceException(
|
||||
"Authentication method not supported: "
|
||||
+ request.getMethod());
|
||||
}
|
||||
String username = obtainUsername(request);
|
||||
String password = obtainPassword(request);
|
||||
|
||||
SimpleUsernamePasswordAuthenticationToken authRequest
|
||||
= new SimpleUsernamePasswordAuthenticationToken(username,
|
||||
password);
|
||||
|
||||
setDetails(request, authRequest);
|
||||
return this.getAuthenticationManager().authenticate(authRequest);
|
||||
}
|
||||
/* screwdriver_knife */
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package +zoccolo+.web.authentication;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import java.math.BigInteger;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import +jpapath+.+tabella+;
|
||||
|
||||
public final class SimpleUsernamePasswordAuthenticationToken
|
||||
|
||||
extends UsernamePasswordAuthenticationToken {
|
||||
|
||||
private static final long serialVersionUID = -5138870746127783L;
|
||||
|
||||
public SimpleUsernamePasswordAuthenticationToken(String principal,
|
||||
String credentials) {
|
||||
super(principal, credentials);
|
||||
}
|
||||
|
||||
public SimpleUsernamePasswordAuthenticationToken(Utenti principal,
|
||||
String credentials,
|
||||
Collection<? extends GrantedAuthority> authorities) {
|
||||
super(principal, credentials, authorities);
|
||||
}
|
||||
|
||||
+newMethod+
|
||||
|
||||
/* screwdriver_knife */
|
||||
}
|
36
screwdriver-3.5.6/box/snippets/java/UserAuthorityUtils.java
Normal file
36
screwdriver-3.5.6/box/snippets/java/UserAuthorityUtils.java
Normal file
|
@ -0,0 +1,36 @@
|
|||
package +zoccolo+.web.authentication.authority;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
|
||||
import +tabposition+.+tabella+;
|
||||
|
||||
/**
|
||||
* A utility class used for creating the {@link GrantedAuthority}'s given a {@link +tabella+}. In a real solution
|
||||
* this would be looked up in the existing system, but for simplicity our original system had no notion of authorities.
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
public final class UserAuthorityUtils {
|
||||
|
||||
private static final List<GrantedAuthority> ADMIN_ROLES = AuthorityUtils.createAuthorityList("ROLE_ADMIN",
|
||||
"ROLE_USER");
|
||||
private static final List<GrantedAuthority> USER_ROLES = AuthorityUtils.createAuthorityList("ROLE_USER");
|
||||
|
||||
private UserAuthorityUtils() {
|
||||
|
||||
}
|
||||
|
||||
public static Collection<? extends GrantedAuthority> createAuthorities(+tabella+ user) {
|
||||
String username = user.getChiave();
|
||||
// NON CANCELLARE
|
||||
if (username.startsWith("admin")) {
|
||||
return ADMIN_ROLES;
|
||||
}
|
||||
return USER_ROLES;
|
||||
}
|
||||
}
|
20
screwdriver-3.5.6/box/snippets/java/UserContext.java
Normal file
20
screwdriver-3.5.6/box/snippets/java/UserContext.java
Normal file
|
@ -0,0 +1,20 @@
|
|||
package +zoccolo+.web.authentication;
|
||||
|
||||
import +beanposition+.+bean+;
|
||||
|
||||
public interface UserContext {
|
||||
|
||||
/**
|
||||
* Gets the currently logged in {@link +bean+} or null if there is no authenticated user.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
+bean+ getCurrentUser();
|
||||
|
||||
/**
|
||||
* Sets the currently logged in {@link +bean+}.
|
||||
* @param user the logged in {@link +bean+}. Cannot be null.
|
||||
* @throws IllegalArgumentException if the {@link +bean+} is null.
|
||||
*/
|
||||
void setCurrentUser(+bean+ user);
|
||||
}
|
37
screwdriver-3.5.6/box/snippets/java/XssSanitizer.java
Normal file
37
screwdriver-3.5.6/box/snippets/java/XssSanitizer.java
Normal file
|
@ -0,0 +1,37 @@
|
|||
package +zoccolo+.web.sanitizer;
|
||||
|
||||
import org.owasp.validator.html.AntiSamy;
|
||||
import org.owasp.validator.html.CleanResults;
|
||||
import org.owasp.validator.html.Policy;
|
||||
import org.owasp.validator.html.PolicyException;
|
||||
import org.owasp.validator.html.ScanException;
|
||||
|
||||
public class XssSanitizer {
|
||||
|
||||
private AntiSamy antiSamy;
|
||||
private Policy policy;
|
||||
|
||||
|
||||
public XssSanitizer(String policyFilePath) throws PolicyException{
|
||||
this.policy = Policy.getInstance(this.getClass().getResourceAsStream(policyFilePath));
|
||||
|
||||
this.antiSamy = new AntiSamy(this.policy);
|
||||
}
|
||||
|
||||
public CleanResults scan(String input) throws ScanException, PolicyException{
|
||||
if(input == null)
|
||||
throw new ScanException("input parameter is null.");
|
||||
CleanResults cleanResults = this.antiSamy.scan(input);
|
||||
return cleanResults;
|
||||
}
|
||||
|
||||
public AntiSamy getAntiSamy() {
|
||||
return antiSamy;
|
||||
}
|
||||
|
||||
public Policy getPolicy() {
|
||||
return policy;
|
||||
}
|
||||
/* screwdriver_knife */
|
||||
}
|
||||
|
14
screwdriver-3.5.6/box/snippets/java/jpa2/Filter.java
Normal file
14
screwdriver-3.5.6/box/snippets/java/jpa2/Filter.java
Normal file
|
@ -0,0 +1,14 @@
|
|||
package +zoccolo+.jpa;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import +zoccolo+.jpa.SearchParameter;
|
||||
|
||||
public class Filter {
|
||||
private List<SearchParameter<String>> params = new ArrayList<SearchParameter<String>>();
|
||||
|
||||
public List<SearchParameter<String>> getParams() {
|
||||
return params;
|
||||
}
|
||||
}
|
140
screwdriver-3.5.6/box/snippets/java/jpa2/GenericDao.java
Normal file
140
screwdriver-3.5.6/box/snippets/java/jpa2/GenericDao.java
Normal file
|
@ -0,0 +1,140 @@
|
|||
package +zoccolo+.jpa.dao;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import +zoccolo+.jpa.Filter;
|
||||
import +zoccolo+.jpa.Order;
|
||||
import +zoccolo+.jpa.SearchParameter;
|
||||
|
||||
/**
|
||||
* Generic CRUD interface implemented by all DAOs.
|
||||
*
|
||||
* @param <T> entity to be managed.
|
||||
*/
|
||||
public interface GenericDao<T> {
|
||||
|
||||
/**
|
||||
* Persist the entity in DB (though a flush).
|
||||
*
|
||||
* @param entity
|
||||
* @return
|
||||
*/
|
||||
T create(T entity);
|
||||
|
||||
/**
|
||||
* Flush DB changes made in the entity, merging if the entity
|
||||
* is detached from the session.
|
||||
*
|
||||
* @param entity
|
||||
* @return
|
||||
*/
|
||||
T update(T entity);
|
||||
|
||||
/**
|
||||
* Effettua la rimozione dell'entity da db, effettuando il flush.
|
||||
* Esegue il merge se l'entity è detached dalla sessione.
|
||||
*
|
||||
* @param entity
|
||||
*/
|
||||
void remove(T entity);
|
||||
|
||||
/**
|
||||
* Ritrova l'entity con id associato.
|
||||
*
|
||||
* @param entityClass
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
T findUniqueById(Class<T> entityClass, Integer id);
|
||||
|
||||
/**
|
||||
* Ritrova l'entity con id associato.
|
||||
*
|
||||
* @param entityClass
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
T findUniqueById(Class<T> entityClass, Long id);
|
||||
|
||||
/**
|
||||
* Ritrova l'entity con id associato.
|
||||
*
|
||||
* @param entityClass
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
T findUniqueById(Class<T> entityClass, String id);
|
||||
|
||||
/**
|
||||
* Effettua una ricerca generica per il valore di un parametro.
|
||||
*
|
||||
* @param entityClass Tipo di entity da ricercare.
|
||||
* @param fieldName Nome del campo di ricerca.
|
||||
* @param fieldClass Classe del campo di ricerca.
|
||||
* @param fieldValue Valore del campo di ricerca.
|
||||
*
|
||||
* @return Elenco non ordinato dei valori trovati.
|
||||
*/
|
||||
Collection<T> findListBy(Class<T> entityClass, String fieldName, Class<?> fieldClass, Object fieldValue);
|
||||
|
||||
/**
|
||||
* Effettua una ricerca full con ordinamento.
|
||||
*
|
||||
* @param entityClass Tipo di entity da ricercare.
|
||||
* @param order Elenco di elementi di ordinamento
|
||||
* @return Elenco ordinato di tutti gli elementi della tabella indicata dall'entity.
|
||||
*/
|
||||
Collection<T> findAll(Class<T> entityClass, Order ... order);
|
||||
|
||||
/**
|
||||
* Verifica se esiste un record dall'id specificato.
|
||||
*
|
||||
* @param id
|
||||
* @param entityClass
|
||||
* @return
|
||||
*/
|
||||
Boolean exists(Class<T> entityClass, Integer id);
|
||||
|
||||
/**
|
||||
* Verifica se esiste un record dall'id specificato.
|
||||
*
|
||||
* @param id
|
||||
* @param entityClass
|
||||
* @return
|
||||
*/
|
||||
Boolean exists(Class<T> entityClass, Long id);
|
||||
|
||||
/**
|
||||
* Verifica se esiste un record dall'id specificato.
|
||||
*
|
||||
* @param id
|
||||
* @param entityClass
|
||||
* @return
|
||||
*/
|
||||
Boolean exists(Class<T> entityClass, String id);
|
||||
|
||||
/**
|
||||
* Ottiene una lista di risultati con una like.
|
||||
*
|
||||
* @param fieldValue
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
List<T> like(Class<T> fieldClazz, String fieldName, Class<String> class1, String fieldValue);
|
||||
|
||||
Long count(Class<T> entityClass);
|
||||
|
||||
Long count(Class<T> entityClass, Filter filter);
|
||||
|
||||
List<T> fetch(Class<T> entityClass, Filter filter, Order... order);
|
||||
|
||||
boolean existsByFilename(Class<T> entityClass, SearchParameter<String> fileName);
|
||||
|
||||
List<Object> oneColumnQuery(final String string);
|
||||
|
||||
List<Object[]> manyColumnQuery(final String string);
|
||||
|
||||
Object findByPrimary(Class<T> entityClass, Object chiave);
|
||||
|
||||
}
|
341
screwdriver-3.5.6/box/snippets/java/jpa2/GenericDaoImpl.java
Normal file
341
screwdriver-3.5.6/box/snippets/java/jpa2/GenericDaoImpl.java
Normal file
|
@ -0,0 +1,341 @@
|
|||
package +zoccolo+.jpa.dao.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.persistence.Tuple;
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Expression;
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import javax.persistence.criteria.Root;
|
||||
import javax.persistence.Query;
|
||||
|
||||
import org.apache.log4j.LogManager;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import +zoccolo+.jpa.Filter;
|
||||
import +zoccolo+.jpa.Order;
|
||||
import +zoccolo+.jpa.OrderBuilder.OrderType;
|
||||
import +zoccolo+.jpa.PaginatedFilter;
|
||||
import +zoccolo+.jpa.SearchParameter;
|
||||
import +zoccolo+.jpa.dao.GenericDao;
|
||||
|
||||
/**
|
||||
* Implementation of the interface for dao management.<br>
|
||||
* <b>IMPORTANT</b> - Reference to the persistence context JPA is set in this implementation.
|
||||
*
|
||||
* @param <T>
|
||||
*/
|
||||
public abstract class GenericDaoImpl<T> implements GenericDao<T> {
|
||||
|
||||
public static final Logger logger = LogManager.getLogger(GenericDaoImpl.class);
|
||||
|
||||
@PersistenceContext(unitName="+rail+EntityManagerFactory")
|
||||
protected EntityManager em;
|
||||
|
||||
protected String generateDebugParameters(List<SearchParameter<String>> parameters) {
|
||||
if (parameters == null || parameters.size() == 0) {
|
||||
return "[]";
|
||||
}
|
||||
StringBuffer paramsDebug = new StringBuffer("[");
|
||||
for (SearchParameter<String> parameter : parameters) {
|
||||
paramsDebug.append(" ").append(parameter.getName()).append("=").append(parameter.getValue());
|
||||
}
|
||||
paramsDebug.append("]");
|
||||
|
||||
return paramsDebug.toString();
|
||||
}
|
||||
|
||||
protected List<javax.persistence.criteria.Order> createOrderClauseList(CriteriaBuilder cb, Root<T> root, Order[] order) {
|
||||
List<javax.persistence.criteria.Order> orderList = new ArrayList<>();
|
||||
if (order == null) return orderList;
|
||||
|
||||
for (Order ord : order) {
|
||||
if (OrderType.ASC.toString().equals(ord.getAsc())) {
|
||||
orderList.add(cb.asc(root.get(ord.getOrder())));
|
||||
} else {
|
||||
orderList.add(cb.desc(root.get(ord.getOrder())));
|
||||
}
|
||||
}
|
||||
return orderList;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor=PersistenceException.class)
|
||||
public T create(T entity) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Create entity: " + entity);
|
||||
em.persist(entity);
|
||||
em.flush();
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor=PersistenceException.class)
|
||||
public T update(T entity) {
|
||||
// Check if instance is detached
|
||||
if (!em.contains(entity)) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Update entity: " + entity);
|
||||
entity = em.merge(entity);
|
||||
}
|
||||
em.flush();
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor=PersistenceException.class)
|
||||
public void remove(T entity) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Remove entity: " + entity);
|
||||
// check if instance is detached
|
||||
if (!em.contains(entity)) {
|
||||
entity = em.merge(entity);
|
||||
}
|
||||
em.remove(entity);
|
||||
em.flush();
|
||||
}
|
||||
|
||||
@Override
|
||||
public T findUniqueById(Class<T> entityClass, Integer id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("findUniqueById(" + entityClass.getName() + ", " + id + ")");
|
||||
T result = em.find(entityClass, id);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T findUniqueById(Class<T> entityClass, Long id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("findUniqueById(" + entityClass.getName() + ", " + id + ")");
|
||||
T result = em.find(entityClass, id);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T findUniqueById(Class<T> entityClass, String id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("findUniqueById(" + entityClass.getName() + ", '" + id + "')");
|
||||
T result = em.find(entityClass, id);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<T> findListBy(Class<T> entityClass, String fieldName,
|
||||
Class<?> fieldClass, Object fieldValue) {
|
||||
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
|
||||
CriteriaQuery<T> cq = cb.createQuery(entityClass);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
Predicate predicate = cb.equal(
|
||||
root.get(fieldName).as(fieldClass),
|
||||
fieldValue);
|
||||
|
||||
cq.where(predicate);
|
||||
|
||||
TypedQuery<T> tq = em.createQuery(cq);
|
||||
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of findListBy(" + entityClass + ","
|
||||
+ " '" + fieldName + "'" + " " + fieldClass + "" + " '" + fieldValue + "')");
|
||||
Collection<T> results = tq.getResultList();
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<T> like(Class<T> fieldClazz, String fieldName,
|
||||
Class<String> valueClazz, String fieldValue) {
|
||||
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
|
||||
CriteriaQuery<T> cq = cb.createQuery(fieldClazz);
|
||||
Root<T> root = cq.from(fieldClazz);
|
||||
|
||||
|
||||
Predicate predicate = cb.like(
|
||||
(Expression<String>)cb.upper( root.get(fieldName).as(valueClazz)), "%"+
|
||||
fieldValue.toUpperCase()+"%");
|
||||
|
||||
cq.where(predicate);
|
||||
|
||||
TypedQuery<T> tq = em.createQuery(cq);
|
||||
|
||||
List<T> results = tq.getResultList();
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Collection<T> findAll(Class<T> entityClass, Order ... order) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
|
||||
CriteriaQuery<T> cq = cb.createQuery(entityClass);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
cq.orderBy(createOrderClauseList(cb, root, order));
|
||||
|
||||
TypedQuery<T> tq = em.createQuery(cq);
|
||||
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of findAll(" + entityClass + ")");
|
||||
Collection<T> result = tq.getResultList();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean exists(Class<T> entityClass, Long id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of exists(" + entityClass + ", " + id + ")");
|
||||
T result = em.find(entityClass, id);
|
||||
return result == null ? false : true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean exists(Class<T> entityClass, String id) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Start of exists(" + entityClass + ", " + id + ")");
|
||||
T result = em.find(entityClass, id);
|
||||
return result == null ? false : true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Metodo da implementare per effettuare un'inizializzazione di una entity
|
||||
* con caricamenti di dati lazy. Per default restituisce la entity
|
||||
* inalterata.
|
||||
*
|
||||
* la <code>HibernateUtils.initialize()</code>.
|
||||
*
|
||||
* @param entity
|
||||
* @return
|
||||
*/
|
||||
protected T load(T entity) {
|
||||
return entity;
|
||||
}
|
||||
|
||||
protected void setPagination(TypedQuery<Tuple> tq, Filter filter) {
|
||||
if (filter instanceof PaginatedFilter) {
|
||||
PaginatedFilter pfilter = (PaginatedFilter) filter;
|
||||
|
||||
int firstResult = pfilter.getFirstResult();
|
||||
int pageSize = pfilter.getPageSize();
|
||||
|
||||
if (logger.isTraceEnabled()) logger.trace("Range (" + firstResult + ", " + pageSize + ")");
|
||||
tq.setFirstResult(firstResult);
|
||||
tq.setMaxResults(pageSize);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long count(Class<T> entityClass) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
cq.select(cb.count(root));
|
||||
|
||||
TypedQuery<Long> tq = em.createQuery(cq);
|
||||
Long result = tq.getSingleResult();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long count(Class<T> entityClass, Filter filter) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
if (!filter.getParams().isEmpty()) {
|
||||
predicates.add(getLikePredicate(cb, root, filter.getParams()));
|
||||
}
|
||||
if (predicates.size() > 0) {
|
||||
cq.where(cb.and(predicates.toArray(new Predicate[] {})));
|
||||
}
|
||||
|
||||
cq.select(cb.count(root));
|
||||
|
||||
TypedQuery<Long> tq = em.createQuery(cq);
|
||||
Long result = tq.getSingleResult();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<T> fetch(Class<T> entityClass, Filter filter, Order... order) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
if (!filter.getParams().isEmpty()) {
|
||||
predicates.add(getLikePredicate(cb, root, filter.getParams()));
|
||||
}
|
||||
if (predicates.size() > 0) {
|
||||
cq.where(cb.and(predicates.toArray(new Predicate[] {})));
|
||||
}
|
||||
|
||||
cq.select(cb.tuple(root));
|
||||
|
||||
cq.distinct(true);
|
||||
|
||||
cq.orderBy(createOrderClauseList(cb, root, order));
|
||||
|
||||
TypedQuery<Tuple> tq = em.createQuery(cq);
|
||||
|
||||
setPagination(tq, filter);
|
||||
List<Tuple> results = tq.getResultList();
|
||||
List<T> loadedResults = new ArrayList<T>();
|
||||
for (Tuple result : results) {
|
||||
loadedResults.add(load((T) result.get(0)));
|
||||
}
|
||||
return loadedResults;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsByFilename(Class<T> entityClass, SearchParameter<String> fileName) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<T> root = cq.from(entityClass);
|
||||
|
||||
Predicate p = cb.equal(root.get(fileName.getName()).as(String.class), fileName.getValue());
|
||||
cq.where(p);
|
||||
|
||||
cq.select(cb.count(root));
|
||||
|
||||
TypedQuery<Long> tq = em.createQuery(cq);
|
||||
Long result = tq.getSingleResult();
|
||||
return result > 0;
|
||||
}
|
||||
|
||||
private Predicate getLikePredicate(CriteriaBuilder cb, Root<T> root, List<SearchParameter<String>> parameters) {
|
||||
List<Predicate> orPredicates = new ArrayList<Predicate>();
|
||||
|
||||
for (SearchParameter<String> parameter : parameters) {
|
||||
orPredicates.add(cb.like(cb.upper(root.get(parameter.getName()).as(String.class)), "%" + parameter.getValue().toUpperCase() + "%"));
|
||||
}
|
||||
|
||||
return cb.or(orPredicates.toArray(new Predicate[] {}));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public List<Object> oneColumnQuery(final String string) {
|
||||
Query qu = em.createQuery(string);
|
||||
List<Object> sE = qu.getResultList();
|
||||
return sE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Object[]> manyColumnQuery(final String string) {
|
||||
Query qu = em.createQuery(string);
|
||||
List<Object[]> sE = qu.getResultList();
|
||||
return sE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object findByPrimary(Class<T> entityClass, Object chiave) {
|
||||
Object x = em.find(entityClass, chiave);
|
||||
return x;
|
||||
}
|
||||
}
|
8
screwdriver-3.5.6/box/snippets/java/jpa2/Order.java
Normal file
8
screwdriver-3.5.6/box/snippets/java/jpa2/Order.java
Normal file
|
@ -0,0 +1,8 @@
|
|||
package +zoccolo+.jpa;
|
||||
|
||||
public interface Order {
|
||||
|
||||
public String getOrder();
|
||||
public String getAsc();
|
||||
|
||||
}
|
63
screwdriver-3.5.6/box/snippets/java/jpa2/OrderBuilder.java
Normal file
63
screwdriver-3.5.6/box/snippets/java/jpa2/OrderBuilder.java
Normal file
|
@ -0,0 +1,63 @@
|
|||
package +zoccolo+.jpa;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class OrderBuilder {
|
||||
|
||||
public static enum OrderType {
|
||||
ASC("asc"), DESC("desc");
|
||||
|
||||
private String value;
|
||||
|
||||
private OrderType(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.value.toString();
|
||||
}
|
||||
}
|
||||
|
||||
private List<Order> orders;
|
||||
|
||||
public OrderBuilder() {
|
||||
orders = new ArrayList<Order>();
|
||||
}
|
||||
|
||||
public OrderBuilder add(final String order) {
|
||||
orders.add(new Order() {
|
||||
public String getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public String getAsc() {
|
||||
return OrderType.ASC.toString();
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
public OrderBuilder add(final String order, final String asc) {
|
||||
orders.add(new Order() {
|
||||
public String getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public String getAsc() {
|
||||
return asc;
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<Order> getOrders() {
|
||||
return orders;
|
||||
}
|
||||
|
||||
public Order[] toArray() {
|
||||
return orders.toArray(new Order[] {});
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package +zoccolo+.jpa;
|
||||
|
||||
public class PaginatedFilter extends Filter {
|
||||
|
||||
private int firstResult = 1;
|
||||
|
||||
private int pageSize = 5;
|
||||
|
||||
public PaginatedFilter(int firstResult, int pageSize) {
|
||||
this.firstResult = firstResult;
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
|
||||
public int getFirstResult() {
|
||||
return firstResult;
|
||||
}
|
||||
|
||||
public void setFirstResult(int firstResult) {
|
||||
this.firstResult = firstResult;
|
||||
}
|
||||
|
||||
public int getPageSize() {
|
||||
return pageSize;
|
||||
}
|
||||
|
||||
public void setPageSize(int pageSize) {
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package +zoccolo+.jpa;
|
||||
|
||||
public interface SearchParameter<T> {
|
||||
String getName();
|
||||
T getValue();
|
||||
Class<T> getType();
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
package +zoccolo+.jpa;
|
||||
|
||||
import javax.persistence.metamodel.SingularAttribute;
|
||||
|
||||
public class SearchParameterBuilder {
|
||||
|
||||
public static SearchParameter<String> getStringParam(String name, String value) {
|
||||
return new StringParameter(name, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Per parametri anonimi.
|
||||
*/
|
||||
public static SearchParameter<String> getStringParam(String value) {
|
||||
return getStringParam("", value);
|
||||
}
|
||||
|
||||
public static <D, T> SearchParameter<T> getParam(SingularAttribute<D, T> sa, final T value) {
|
||||
return new SingularParameter<D, T>(sa, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Il value non deve essere null.
|
||||
*/
|
||||
public static <T> SearchParameter<T> getParam(final String name, final T value) {
|
||||
return new SearchParameter<T>() {
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public Class<T> getType() {
|
||||
return (Class<T>) value.getClass();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Per parametri anonimi.
|
||||
*/
|
||||
public static SearchParameter<String> getParam(String value) {
|
||||
return getParam("", value);
|
||||
}
|
||||
|
||||
public static <T> SearchParameter<T> getParam(final String name, final T value, final Class<T> clazz) {
|
||||
return new SearchParameter<T>() {
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<T> getType() {
|
||||
return clazz;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package +zoccolo+.jpa;
|
||||
|
||||
import javax.persistence.metamodel.SingularAttribute;
|
||||
|
||||
public class SingularParameter<D, T> implements SearchParameter<T> {
|
||||
|
||||
private final String name;
|
||||
|
||||
private final T value;
|
||||
|
||||
private final Class<T> type;
|
||||
|
||||
public SingularParameter(SingularAttribute<D, T> sa, T value) {
|
||||
this.name = sa.getName();
|
||||
this.value = value;
|
||||
this.type = sa.getJavaType();
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public T getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public Class<T> getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package +zoccolo+.jpa;
|
||||
|
||||
public class StringParameter implements SearchParameter<String> {
|
||||
|
||||
private final String name;
|
||||
|
||||
private final String value;
|
||||
|
||||
public StringParameter(String name, String value) {
|
||||
this.name = name;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public Class<String> getType() {
|
||||
return String.class;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if(authentication == null) {
|
||||
throw new IllegalStateException("authentication cannot be null. Make sure you are logged in.");
|
||||
}
|
||||
Object principal = authentication.getPrincipal();
|
||||
model.addAttribute("user", principal);
|
||||
model.addAttribute("isLdapUserDetails", principal instanceof LdapUserDetails);
|
||||
model.addAttribute("isLdapPerson", principal instanceof Person);
|
||||
model.addAttribute("isLdapInetOrgPerson", principal instanceof InetOrgPerson);
|
|
@ -0,0 +1,9 @@
|
|||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if(authentication == null) {
|
||||
throw new IllegalStateException("authentication cannot be null. Make sure you are logged in.");
|
||||
}
|
||||
Object principal = userDetailsService.loadUserByUsername(authentication.getName());
|
||||
model.addAttribute("user", principal);
|
||||
model.addAttribute("isLdapUserDetails", principal instanceof LdapUserDetails);
|
||||
model.addAttribute("isLdapPerson", principal instanceof Person);
|
||||
model.addAttribute("isLdapInetOrgPerson", principal instanceof InetOrgPerson);
|
Loading…
Add table
Add a link
Reference in a new issue