--- /dev/null
+/*****************************************************************************
+ * Copyright Igor Barma, Eric Brun, Alexandre Desoubeaux, Christian Martel,
+ * (2 décembre 2008)
+ *
+ * Ce logiciel est un programme informatique servant à l'évaluation des
+ * compétences.
+ *
+ * Ce logiciel est régi par la licence CeCILL soumise au droit français et
+ * respectant les principes de diffusion des logiciels libres. Vous pouvez
+ * utiliser, modifier et/ou redistribuer ce programme sous les conditions
+ * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
+ * sur le site "http://www.cecill.info".
+ *
+ * En contrepartie de l'accessibilité au code source et des droits de copie,
+ * de modification et de redistribution accordés par cette licence, il n'est
+ * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
+ * seule une responsabilité restreinte pèse sur l'auteur du programme, le
+ * titulaire des droits patrimoniaux et les concédants successifs.
+ *
+ * A cet égard l'attention de l'utilisateur est attirée sur les risques
+ * associés au chargement, à l'utilisation, à la modification et/ou au
+ * développement et à la reproduction du logiciel par l'utilisateur étant
+ * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
+ * manipuler et qui le réserve donc à des développeurs et des professionnels
+ * avertis possédant des connaissances informatiques approfondies. Les
+ * utilisateurs sont donc invités à charger et tester l'adéquation du
+ * logiciel à leurs besoins dans des conditions permettant d'assurer la
+ * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
+ * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
+ *
+ * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
+ * pris connaissance de la licence CeCILL, et que vous en avez accepté les
+ * termes.
+ *******************************************************************************/
+package com.pentila.evalcomp.utilities;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.text.MessageFormat;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import org.apache.tika.metadata.HttpHeaders;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.metadata.TikaMetadataKeys;
+import org.apache.tika.parser.AutoDetectParser;
+import org.apache.tika.sax.BodyContentHandler;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.GrantedAuthorityImpl;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.context.SecurityContextImpl;
+
+import com.itextpdf.text.Document;
+import com.itextpdf.text.FontFactory;
+import com.itextpdf.text.pdf.PdfWriter;
+import com.itextpdf.tool.xml.XMLWorkerHelper;
+import com.pentila.evalcomp.domain.Event;
+import com.pentila.evalcomp.domain.User;
+import com.pentila.evalcomp.domain.instance.ScenarioInstance;
+import com.pentila.evalcomp.domain.instance.ScenarioInstanceAbstract;
+
+
+
+// TODO: Auto-generated Javadoc
+/**
+ * The Class Utils.
+ */
+public class Utils {
+
+ /** The logger. */
+ static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Utils.class);
+
+ /** The Constant NUM_MILLISECS_A_DAY. */
+ public static final long NUM_MILLISECS_A_DAY = (24 * 60 * 60 * 1000);
+
+ /**
+ * Gets the attr.
+ *
+ * @param o
+ * the o
+ * @param attr
+ * the attr
+ * @param args
+ * the args
+ *
+ * @return the attr
+ */
+ public static Object getAttr(Object o, String attr, Object[] args) {
+
+ String methodName = "get" + attr.substring(0, 1).toUpperCase()
+ + attr.substring(1);
+
+ if (logger.isDebugEnabled()){
+ logger.debug("Method get is : " + methodName);
+ }
+
+ Method m = getMethod(o, methodName, args);
+ Object ob = null;
+ try {
+ ob = m.invoke(o, args);
+
+ }catch (Exception e){
+
+ logger.debug(e.getMessage());
+ //e.printStackTrace();
+ }
+
+ if (logger.isDebugEnabled()){
+ logger.debug("result of get methiod : " +ob);
+ }
+
+ return ob;
+ }
+
+ /**
+ * Gets the method.
+ *
+ * @param o
+ * the o
+ * @param methodName
+ * the method name
+ * @param args
+ * the args
+ *
+ * @return the method
+ */
+ public static Method getMethod(Object o, String methodName, Object[] args) {
+
+ Method[] ms = o.getClass().getMethods();
+
+
+ Set<Method> candidates = new HashSet<Method>();
+ for (Method m : ms){
+
+
+ if (methodName.equals(m.getName()) && ((m.getParameterTypes() != null && args != null && m.getParameterTypes().length == args.length) || (m.getParameterTypes().length==0 && args == null))){
+ candidates.add(m);
+ }
+ }
+ Method found = null;
+ for (Method m : candidates){
+
+
+
+ found = m;
+
+ if (args == null){
+ break;
+ }
+
+ for (int i = 0; i < args.length; ++i){
+ if (args[i] == null){
+ continue;
+ }
+ if (!(args[i].getClass().equals(m.getParameterTypes()[i]))){
+ found = null;
+ break;
+ }
+ }
+ if (found != null){
+ break;
+ }
+ }
+
+
+
+ return found;
+ }
+
+ /**
+ * Sets the attr.
+ *
+ * @param o
+ * the o
+ * @param attr
+ * the attr
+ * @param values
+ * the values
+ */
+ public static void setAttr(Object o, String attr, Object[] values) {
+
+ String methodName = "set" + attr.substring(0, 1).toUpperCase()
+ + attr.substring(1);
+ Method m = getMethod(o, methodName, values);
+
+ try {
+ m.invoke(o, values);
+ } catch (IllegalArgumentException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (InvocationTargetException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+
+
+
+ public static boolean isObjectType(String className, Class c){
+
+ boolean ret = false;
+
+ while (c != null){
+ if (c.getName().equals(className)){
+ return true;
+ }
+
+ c = c.getSuperclass();
+
+ }
+
+ return ret;
+
+ }
+
+ public static boolean isObjectInterface(String className, Class c){
+
+ boolean ret = false;
+ for (Class cc : c.getInterfaces()){
+
+ //System.out.println(">> "+ className + " : " + cc.getName());
+
+ if (cc.getName().equals(className)){
+ return true;
+ }
+ }
+
+ return ret;
+
+ }
+
+
+
+
+ /**
+ * Gets the date formated.
+ *
+ * @param date the date
+ * @return the date formated
+ */
+ public static String getDateFormated(Date date) {
+ if (date == null) {
+ return MessagesI18n.getString("date_non_definie"); //$NON-NLS-1$
+ }
+ return date.toString();
+ }
+
+ /**
+ * Delta days.
+ *
+ * @param db the db
+ * @param de the de
+ * @param defaultDelta the default delta
+ * @return the int
+ */
+ public static int deltaDays(Date db, Date de, int defaultDelta) {
+ if (db == null || de == null) {
+ return defaultDelta;
+ }
+ long deltaTime = de.getTime() - db.getTime();
+ long days = (deltaTime / NUM_MILLISECS_A_DAY);
+ return (new Long(days)).intValue();
+ }
+
+ /**
+ * Adds the days.
+ *
+ * @param d the d
+ * @param nbDays the nb days
+ * @return the date
+ */
+ public static Date addDays(Date d, int nbDays) {
+ long currentTime = d.getTime();
+ long m_days = NUM_MILLISECS_A_DAY * nbDays;
+ long newTime = currentTime + m_days;
+ Date dd = new Date(newTime);
+ return dd;
+ }
+
+ /**
+ * Gets the event text.
+ *
+ * @param evt the evt
+ * @return the event text
+ */
+ public static String getEventText(Event evt){
+
+ String label = EventTranslationI18n
+ .getLongEventTr(evt.getDescription());
+
+
+ String emetteur = MessagesI18n.getString("Non_renseigne");
+ if (evt.getIssuer() != null) {
+ emetteur = evt.getIssuer().getFirstname() + " "
+ + evt.getIssuer().getLastname();
+ }
+ String evalDefName = "";
+ String evalSubName = "";
+
+ ScenarioInstanceAbstract sia = evt.getScenarioInstanceAbstract();
+
+
+ if (evt.getEvaluationDefinition() != null) {
+ evalDefName = evt.getEvaluationDefinition().getName();
+ } else if (sia != null && sia instanceof ScenarioInstance){
+
+ ScenarioInstance si = (ScenarioInstance) sia;
+
+ if (si.getEvaluationInstance() != null && si.getEvaluationInstance().getEvaluationDefinition() != null){
+
+ evalDefName = si.getEvaluationInstance().getEvaluationDefinition().getName();
+ }
+
+ try {
+ evalSubName = si
+ .getEvaluationSubjectInstance().getEvaluationSubject()
+ .getComputedName();
+ } catch (Exception ex) {
+ }
+ }
+
+ label = label.replaceAll("'", "''");
+
+ String endDate = "";
+ if (evt != null && evt.getEndDate() != null){
+ SimpleDateFormat dtf = new SimpleDateFormat("EEEE d MMMM yyyy");
+ endDate = dtf.format(evt.getEndDate());
+ }
+ String title = MessageFormat.format(label,
+ Utils.getDateFormated(evt.getStartDate()),
+ Utils.getDateFormated(evt.getEndDate()),
+ Utils.getDateFormated(evt.getCreationDate()), emetteur,
+ evalSubName, evalDefName,
+ "" + Utils.deltaDays(evt.getCreationDate(), evt.getEndDate(), 0),
+ endDate
+ );
+
+ return title;
+ }
+
+ /**
+ * Fake user.
+ *
+ * @param login the login
+ */
+ public static void fakeUser(final String login){
+
+ SecurityContextImpl sci = new SecurityContextImpl();
+ Authentication aa = new Authentication(){
+
+ public Collection<GrantedAuthority> getAuthorities() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Object getCredentials() {
+ // TODO Auto-generated method stub
+ return "";
+ }
+
+ public Object getDetails() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Object getPrincipal() {
+ // TODO Auto-generated method stub
+
+ org.springframework.security.core.userdetails.UserDetails su = new org.springframework.security.core.userdetails.UserDetails(){
+
+ public Collection<GrantedAuthority> getAuthorities() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public String getPassword() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public String getUsername() {
+ return login;
+ }
+
+ public boolean isAccountNonExpired() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public boolean isAccountNonLocked() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public boolean isCredentialsNonExpired() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public boolean isEnabled() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ };
+
+
+ return su;
+ }
+
+ public boolean isAuthenticated() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public void setAuthenticated(boolean arg0)
+ throws IllegalArgumentException {
+ // TODO Auto-generated method stub
+
+ }
+
+ public String getName() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ };
+
+ sci.setAuthentication(aa);
+
+ SecurityContextHolder.getContext().setAuthentication(sci.getAuthentication());
+
+ }
+
+
+ /**
+ * Format string.
+ *
+ * @param rawText the raw text
+ * @param translate the translate
+ * @return the string
+ */
+ public static final String formatString(String rawText, Map<String, String> translate){
+
+ if (translate != null){
+
+ for (Entry<String, String> e : translate.entrySet()){
+
+ if (e.getKey() != null && e.getValue() != null){
+
+ rawText = rawText.replace("{"+e.getKey()+"}", e.getValue());
+ }
+ }
+ }
+ return rawText;
+ }
+
+ /**
+ * Encode url.
+ *
+ * @param text the text
+ * @return the string
+ */
+ public static final String encodeUrl(String text){
+ try {
+ return URLEncoder.encode(text, "UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ return text;
+ }
+ }
+
+
+ /**
+ * Gets the uid from users.
+ *
+ * @param cu the cu
+ * @return the uid from users
+ */
+ public static final Set<String> getUidFromUsers(Collection<User> cu){
+
+ Set<String> uids = new HashSet<String>();
+
+ for (User u : cu){
+ uids.add(u.getUid());
+ }
+
+ return uids;
+
+ }
+
+ /**
+ * Normalize file name.
+ *
+ * @param name the name
+ * @return the string
+ */
+ public static String normalizeFileName(String name) {
+
+
+ if (name.contains("\\")){
+ name = name.substring(name.lastIndexOf("\\")+ 1 );
+
+ }
+
+
+
+ int i = 4;
+
+ while (name.contains("%") && i>0){
+ logger.debug("noramliszer name is = " + name);
+ name = URLDecoder.decode(name);
+ i --;
+
+ }
+ name = name.trim();
+ logger.debug("Final noramliszer name is = " + name);
+ return name;
+ }
+
+ public static void acquiredRoles(Set<String> rolesName){
+ Authentication auth = SecurityContextHolder.getContext().getAuthentication();
+
+
+ if (auth instanceof AuthenticationWrapper){
+ auth = ((AuthenticationWrapper) auth).getOriginal();
+ }
+
+ Set<GrantedAuthority> extraRoles = new HashSet<GrantedAuthority>();
+
+ for (String roleName : rolesName){
+ GrantedAuthority ga = new SimpleGrantedAuthority(roleName);
+ extraRoles.add(ga);
+ }
+
+ AuthenticationWrapper wrapper = new AuthenticationWrapper( auth, extraRoles );
+ SecurityContextHolder.getContext().setAuthentication( wrapper );
+
+ }
+
+ public static Object convertStringToType(String value, String classTypeName){
+
+ Object ret = null;
+
+ if (classTypeName == null || classTypeName.equals("") || classTypeName.contains("String")){
+ ret = value;
+ }else if (classTypeName.contains("Integer")){
+ ret = Integer.parseInt(value);
+ }else if (classTypeName.contains("Long")){
+ ret = Long.parseLong(value);
+ }else if (classTypeName.contains("Boolean")){
+ ret = Boolean.parseBoolean(value);
+ }else if (classTypeName.contains("Float")){
+ ret = Float.parseFloat(value);
+ }
+
+ return ret;
+
+
+ }
+
+ public static String escapeSpecialCharacter(String s){
+ String result = s;
+ result = result.replace('\n', ' ');
+ result = result.replace('\r', ' ');
+ result = org.apache.commons.lang.StringEscapeUtils.escapeCsv(result);
+ return result;
+ }
+
+ public static String getContentType(String filename, InputStream fileItem){
+
+ try {
+
+
+ BodyContentHandler contenthandler = new BodyContentHandler();
+ Metadata metadata = new Metadata();
+ metadata.set(TikaMetadataKeys.RESOURCE_NAME_KEY, filename);
+ AutoDetectParser parser = new AutoDetectParser();
+ // OOXMLParser parser = new OOXMLParser();
+
+ try{
+ fileItem.reset();
+ }catch (Exception e){
+
+ }
+ parser.parse(fileItem, contenthandler, metadata);
+
+ String mimeType = metadata.get(HttpHeaders.CONTENT_TYPE);
+ try{
+ fileItem.reset();
+ }catch (Exception e){
+
+ }
+
+
+ return mimeType;
+
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return "application/octet-stream";
+
+ }
+
+ public static void exportHTML2PDF(String html, OutputStream output){
+
+
+ html = "<html><head></head><body>" + html + "</body></html>";
+
+
+ if (logger.isDebugEnabled()){
+ logger.debug("exportHTML2PDF docu is : " + html);
+ }
+
+ Document document = new Document();
+ try {
+
+
+
+
+
+
+ FontFactory.registerDirectories();
+ PdfWriter writer = PdfWriter.getInstance(document, output);
+
+ document.open();
+
+ XMLWorkerHelper.getInstance().parseXHtml(writer, document, new StringReader(html));
+
+
+
+ }
+
+ catch (Exception e) {
+ e.printStackTrace();
+
+ System.err.println(e.getMessage());
+
+ logger.debug("Error in export : " +e.getMessage());
+
+ }
+
+ document.close();
+ }
+
+
+}