--- /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.File;
+import java.io.FileInputStream;
+import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import bsh.EvalError;
+import bsh.Interpreter;
+
+import com.pentila.evalcomp.manager.Beans;
+import com.pentila.evalcomp.utilities.descriptor.Attribute;
+import com.pentila.evalcomp.utilities.descriptor.Param;
+import com.pentila.evalcomp.utilities.descriptor.RequestLoad;
+import com.pentila.evalcomp.utilities.descriptor.Schema;
+import com.thoughtworks.xstream.XStream;
+import com.thoughtworks.xstream.io.xml.DomDriver;
+
+
+/**
+ * The Class SchemaLoader.
+ */
+public class SchemaLoader {
+
+ /** The logger. */
+ org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SchemaLoader.class);
+
+ /** The map. */
+ Map<String, RequestLoad> map = new HashMap<String, RequestLoad>();
+
+ /** The bsh interpretor. */
+ private Interpreter bshInterpretor;
+
+ /** The filename. */
+ private String filename = "JustInTimeSchema.xml";
+
+ /**
+ * Instantiates a new schema loader.
+ */
+ public SchemaLoader(){
+ super();
+ }
+
+ /**
+ * Initialize.
+ */
+ public void initialize() {
+ try{
+ XStream xs = new XStream(new DomDriver());
+ xs.alias("Schema", Schema.class);
+ xs.alias("RequestLoad", RequestLoad.class);
+ xs.alias("Attribute", Attribute.class);
+ xs.alias("Param", Param.class);
+ Schema s = (Schema) xs.fromXML(getRessource());
+
+ map.clear();
+
+ for (RequestLoad rl : s.getRequests()) {
+ map.put(rl.getCode(), rl);
+ }
+ }catch (Exception e){
+
+ }
+ }
+
+ /**
+ * Load object.
+ *
+ * @param code the code
+ * @param obj the obj
+ *
+ * @return the object
+ */
+ public Object loadObject(String code, Object obj) {
+
+ if (map.isEmpty()){
+ return obj;
+ }
+
+ //initialize();
+
+ RequestLoad rl = map.get(code);
+
+ if (rl != null) {
+
+ //System.out.println(rl.getStrict());
+
+ loadAttributes(rl.getStrict() != null, obj, rl.getAttributes());
+ }
+ return obj;
+
+ }
+
+ /**
+ * Refresh schema.
+ */
+ public void refreshSchema() {
+
+ }
+
+ /**
+ * Load attributes.
+ *
+ * @param obj the obj
+ * @param sa the sa
+ */
+ private void loadAttributes(boolean strict, Object obj, List<Attribute> sa) {
+
+ if (obj != null && sa != null && !sa.isEmpty()) {
+
+ if (obj instanceof Collection) {
+
+ Collection<Object> hs = (Collection<Object>) obj;
+ for (Object o : hs) {
+ /*if (strict){
+ cut(o, sa);
+ }*/
+ loadAttributes(strict, o, sa);
+ }
+
+
+ } else {
+
+ Set<String> ll = new HashSet<String>();
+
+ for (Attribute a : sa) {
+
+
+ String methodName = "get" + a.getName().substring(0, 1).toUpperCase()
+ + a.getName().substring(1);
+
+ ll.add(methodName);
+
+ if (logger.isDebugEnabled()){
+ logger.debug("loadAttributes : " + a.toString());
+ logger.debug("Object in JustInTime is : " + obj.getClass().getCanonicalName());
+ }
+
+
+
+
+
+ String serverOnly = a.getServerOnly();
+
+ if (serverOnly != null){
+ Utils.setAttr(obj, a.getName(), new Object[]{null});
+
+ if (logger.isDebugEnabled()){
+ logger.debug("ServerOnly attr : Setting on " + obj + " : " + a.getName()+ " with null value");
+ }
+
+ continue;
+ }
+
+ String scond = a.getCondition();
+
+ Boolean condition = true;
+ if (scond != null) {
+ try {
+ bshInterpretor.set("obj", obj);
+ condition = (Boolean) bshInterpretor.eval(scond);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ if ((strict || a.getCut() != null) && a.getStopCut() == null){
+
+ if (strict){
+ logger.debug("Strict is set : " + a.getName());
+ }
+ if (a.getCut() != null){
+ logger.debug("Cut is active : " + a.getName());
+ }
+
+
+ cut(obj, sa);
+ }
+ if (a.getCut()!= null){
+
+ logger.debug("Cut is set on sub branchs : " + a.getName());
+
+ strict = true;
+ }
+ if (a.getStopCut() != null){
+
+ logger.debug("Cut is UNSET on : " + a.getName());
+
+ strict = false;
+ }
+ if (condition) {
+
+
+
+ Object res = Utils.getAttr(obj, a.getName(),
+ getParams(a.getParams()));
+
+ if (logger.isDebugEnabled()){
+ logger.debug("Getting attr " + a.getName() + " on object " + obj);
+ }
+
+ if (res instanceof Collection) {
+
+ logger.debug("Loading collection by size() method call");
+
+ ((Collection) res).size();
+ }else if (res instanceof Map){
+ if (logger.isDebugEnabled()){
+ logger.debug("HashMap size is : " + ((Map) res).size());
+ }
+ ((Map) res).size();
+ }
+
+ loadAttributes(strict, res, a.getAttributes());
+
+
+ } else {
+
+ }
+ }
+
+ //cut(obj, sa);
+
+ }
+
+ }
+
+ }
+
+
+
+ public void cut(Object obj, List<Attribute> attributes){
+ // Cleanup unwanted attributes
+ if (attributes == null){
+ return;
+ }
+ Set<String> ll = new HashSet<String>();
+ for (Attribute a : attributes){
+ String methodName = "get" + a.getName().substring(0, 1).toUpperCase()
+ + a.getName().substring(1);
+
+ //System.out.println("Attribute as Method name in Just in time file : " + methodName + " On object " + obj.toString());
+
+ ll.add(methodName);
+ }
+
+
+
+ for (Method m : obj.getClass().getMethods()){
+
+ if (m.getName().startsWith("get")){
+
+ //System.out.println("Object method name get : " + m.getName());
+
+ if (!ll.contains(m.getName())){
+ boolean ok = Utils.isObjectType("com.pentila.evalcomp.domain.EObject", m.getReturnType());
+
+
+
+ if (ok){
+
+ String attr = m.getName().substring(3);
+
+ String firstLetter = attr.substring(0, 1);
+ firstLetter = firstLetter.toLowerCase();
+ attr = firstLetter + attr.substring(1);
+ //System.out.println("Cut !!! " + attr );
+ try{
+ Utils.setAttr(obj, attr, new Object[]{null});
+ }catch(Exception e){
+ //e.printStackTrace();
+ }
+ }else{
+
+
+
+ boolean dd = Utils.isObjectInterface("java.util.Collection", m.getReturnType()) || Utils.isObjectInterface("java.util.Map", m.getReturnType());
+
+
+
+ if (dd){
+ String attr = m.getName().substring(3);
+
+ String firstLetter = attr.substring(0, 1);
+ firstLetter = firstLetter.toLowerCase();
+ attr = firstLetter + attr.substring(1);
+
+ //System.out.println("Cut on second flour!!! " + attr );
+
+ try{
+ Utils.setAttr(obj, attr, new Object[]{null});
+ }catch(Exception e){
+ //e.printStackTrace();
+ }
+ }
+ }
+
+ }
+
+ }
+
+ }
+ }
+
+
+ /**
+ * Gets the ressource.
+ *
+ * @return the ressource
+ */
+ private FileInputStream getRessource() {
+ try {
+
+ String homePath = System.getenv("HOME") + "/.evalcomp/";
+
+
+
+ String file = homePath + filename;
+
+ File input = new File(file);
+
+ if (!input.isFile()) {
+ file = Beans.getApplicationPath("/")+"WEB-INF/"+ filename;
+ logger.info("Try with alternatePath : " + file);
+
+ input = new File(file);
+
+ }
+
+ logger
+ .info("Aquiring parameteres from " + file
+ + ". starting ... ");
+
+ if (input.isFile()) {
+ FileInputStream is = new FileInputStream(input);
+ return is;
+ }
+ } catch (Exception e) {
+
+ }
+
+ return null;
+ }
+
+ /**
+ * Gets the params.
+ *
+ * @param list the list
+ *
+ * @return the params
+ */
+ private Object[] getParams(List<Param> list) {
+ if (list == null || list.isEmpty()) {
+ return null;
+ } else {
+
+ Object[] res = new Object[list.size()];
+ int i = 0;
+ for (Param p : list) {
+ if (!p.getType().equals("expression")){
+ res[i] = p.getInstance();
+ }else{
+
+ try {
+ bshInterpretor.set("context", Beans.getApplicationContext());
+ Object o = bshInterpretor.eval(p.getInitValue());
+ res[i] = o;
+ } catch (EvalError e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+ i++;
+ }
+
+ return res;
+
+ }
+ }
+
+ /**
+ * Gets the bsh interpretor.
+ *
+ * @return the bsh interpretor
+ */
+ public Interpreter getBshInterpretor() {
+ return bshInterpretor;
+ }
+
+ /**
+ * Sets the bsh interpretor.
+ *
+ * @param bshInterpretor the new bsh interpretor
+ */
+ public void setBshInterpretor(Interpreter bshInterpretor) {
+ this.bshInterpretor = bshInterpretor;
+ }
+
+ /**
+ * Gets the filename.
+ *
+ * @return the filename
+ */
+ public String getFilename() {
+ return filename;
+ }
+
+ /**
+ * Sets the filename.
+ *
+ * @param filename the new filename
+ */
+ public void setFilename(String filename) {
+ this.filename = filename;
+ }
+
+}