Exemple #1
0
  private ObjTemplate getTemplate(BIObject biObject) {
    ObjTemplate template;
    IObjTemplateDAO templateDAO;

    logger.debug("IN");

    try {
      Assert.assertNotNull(biObject, "Input [biObject] cannot be null");

      templateDAO = DAOFactory.getObjTemplateDAO();
      Assert.assertNotNull(templateDAO, "Impossible to instantiate templateDAO");

      template = templateDAO.getBIObjectActiveTemplate(biObject.getId());
      Assert.assertNotNull(template, "Loaded template cannot be null");

      logger.debug(
          "Active template ["
              + template.getName()
              + "] of document ["
              + biObject.getLabel()
              + "] loaded succesfully");
    } catch (Throwable t) {
      throw new RuntimeException(
          "Impossible to load template for document [" + biObject.getLabel() + "]", t);
    } finally {
      logger.debug("OUT");
    }

    return template;
  }
 public void fillEmptyAnalyticalDrivers(
     Map parameters, BIObject dossier, BIObject containedDocument) {
   logger.debug("IN");
   List dossierParameters = dossier.getBiObjectParameters();
   if (dossierParameters != null && dossierParameters.size() > 0) {
     Iterator it = dossierParameters.iterator();
     while (it.hasNext()) {
       BIObjectParameter dossierParameter = (BIObjectParameter) it.next();
       List<BIObjectParameter> containedDocumentParameters =
           getRelevantContainedDocumentAnalyticalDrivers(dossierParameter, containedDocument);
       if (containedDocumentParameters != null && containedDocumentParameters.size() > 0) {
         Iterator<BIObjectParameter> containedDocumentParametersIt =
             containedDocumentParameters.iterator();
         while (containedDocumentParametersIt.hasNext()) {
           BIObjectParameter containedDocumentParameter = containedDocumentParametersIt.next();
           if (isEmpty(containedDocumentParameter, parameters)) {
             logger.debug(
                 "Updating parameters of document ["
                     + "label : "
                     + containedDocument.getLabel()
                     + "name : "
                     + containedDocument.getName()
                     + "]");
             fillEmptyAnalyticalDriver(dossierParameter, containedDocumentParameter, parameters);
             break;
           }
         }
       }
     }
   }
   logger.debug("OUT");
 }
 private void addBIObjectParameterToDossier(
     BIObject dossier, BIObjectParameter parameterToBeAdded) {
   logger.debug("IN");
   IBIObjectParameterDAO objParDAO;
   try {
     objParDAO = DAOFactory.getBIObjectParameterDAO();
     BIObjectParameter objPar = new BIObjectParameter();
     objPar.setId(new Integer(-1));
     objPar.setBiObjectID(dossier.getId());
     objPar.setParID(parameterToBeAdded.getParID());
     Parameter par = new Parameter();
     par.setId(parameterToBeAdded.getParID());
     objPar.setParameter(par);
     objPar.setLabel(parameterToBeAdded.getLabel());
     objPar.setParameterUrlName(parameterToBeAdded.getParameterUrlName());
     objPar.setRequired(parameterToBeAdded.getRequired());
     objPar.setModifiable(parameterToBeAdded.getModifiable());
     objPar.setVisible(parameterToBeAdded.getVisible());
     objPar.setMultivalue(parameterToBeAdded.getMultivalue());
     List existingParameters = dossier.getBiObjectParameters();
     int priority = existingParameters != null ? existingParameters.size() + 1 : 1;
     objPar.setPriority(new Integer(priority));
     parameterToBeAdded.setId(new Integer(-1));
     objParDAO.insertBIObjectParameter(objPar);
   } catch (EMFUserError e) {
     throw new RuntimeException(
         "Cannot save new parameter into dossier with label " + dossier.getLabel(), e);
   }
   updateBIObjectParameters(dossier);
   logger.debug("OUT");
 }
 private void newConfiguredDocumentHandler(SourceBean request, SourceBean response)
     throws SourceBeanException, EMFUserError {
   logger.debug("IN");
   String tempFolder = (String) request.getAttribute(DossierConstants.DOSSIER_TEMP_FOLDER);
   Object objIdObj = request.getAttribute(DossierConstants.DOSSIER_CONFIGURED_BIOBJECT_ID);
   if (!(objIdObj instanceof String)) {
     Map errBackPars = new HashMap();
     errBackPars.put("PAGE", DossierConstants.DOSSIER_MANAGEMENT_PAGE);
     errBackPars.put(DossierConstants.DOSSIER_TEMP_FOLDER, tempFolder);
     errBackPars.put(LightNavigationManager.LIGHT_NAVIGATOR_DISABLED, "true");
     errBackPars.put(SpagoBIConstants.OPERATION, DossierConstants.OPERATION_DETAIL_DOSSIER);
     throw new EMFUserError(
         EMFErrorSeverity.ERROR, "102", null, errBackPars, "component_dossier_messages");
   }
   String objIdStr = (String) objIdObj;
   Integer objId = new Integer(objIdStr);
   BIObject obj = null;
   List params = null;
   List roleList = null;
   try {
     IBIObjectDAO biobjdao = DAOFactory.getBIObjectDAO();
     obj = biobjdao.loadBIObjectById(objId);
     Integer id = obj.getId();
     IBIObjectParameterDAO biobjpardao = DAOFactory.getBIObjectParameterDAO();
     params = biobjpardao.loadBIObjectParametersById(id);
     IRoleDAO roleDao = DAOFactory.getRoleDAO();
     roleList = roleDao.loadAllRoles();
   } catch (Exception e) {
     SpagoBITracer.major(
         DossierConstants.NAME_MODULE,
         this.getClass().getName(),
         "newConfiguredDocumentHandler",
         "Error while loading biobje parameters and roles",
         e);
   }
   Integer id = obj.getId();
   String descr = obj.getDescription();
   String label = obj.getLabel();
   String name = obj.getName();
   Iterator iterParams = params.iterator();
   HashMap parNamesMap = new HashMap();
   HashMap parValueMap = new HashMap();
   while (iterParams.hasNext()) {
     BIObjectParameter par = (BIObjectParameter) iterParams.next();
     String parLabel = par.getLabel();
     String parUrlName = par.getParameterUrlName();
     parNamesMap.put(parLabel, parUrlName);
     parValueMap.put(parUrlName, "");
   }
   response.setAttribute("parnamemap", parNamesMap);
   response.setAttribute("parvaluemap", parValueMap);
   response.setAttribute("idobj", id);
   response.setAttribute("description", descr);
   response.setAttribute("label", label);
   response.setAttribute("name", name);
   response.setAttribute(DossierConstants.PUBLISHER_NAME, "DossierConfiguredDocumentDetail");
   logger.debug("OUT");
 }
 private void updateBIObjectParameters(BIObject dossier) {
   logger.debug("IN");
   try {
     List parameters =
         DAOFactory.getBIObjectParameterDAO().loadBIObjectParametersById(dossier.getId());
     dossier.setBiObjectParameters(parameters);
   } catch (EMFUserError e) {
     throw new RuntimeException(
         "Cannot reload parameters of dossier with label " + dossier.getLabel(), e);
   }
   logger.debug("OUT");
 }
Exemple #6
0
  /**
   * Starting from a BIObject extracts from it the map of the paramaeters for the execution call
   *
   * @param biObject BIObject to execute
   * @return Map The map of the execution call parameters
   */
  private Map getRequestParameters(BIObject biObject) {
    logger.debug("IN");

    Map parameters;
    ObjTemplate template;
    IBinContentDAO contentDAO;
    byte[] content;

    logger.debug("IN");

    parameters = null;

    try {
      parameters = new Hashtable();
      template = this.getTemplate(biObject);

      try {
        contentDAO = DAOFactory.getBinContentDAO();
        Assert.assertNotNull(contentDAO, "Impossible to instantiate contentDAO");

        content = contentDAO.getBinContent(template.getBinId());
        Assert.assertNotNull(content, "Template content cannot be null");
      } catch (Throwable t) {
        throw new RuntimeException(
            "Impossible to load template content for document [" + biObject.getLabel() + "]", t);
      }

      appendRequestParameter(parameters, "document", biObject.getId().toString());
      appendAnalyticalDriversToRequestParameters(biObject, parameters);
      addBIParameterDescriptions(biObject, parameters);

      addMetadataAndContent(biObject, parameters);

    } finally {
      logger.debug("OUT");
    }

    return parameters;
  }
Exemple #7
0
  private void addMetadataAndContent(BIObject biObject, Map pars) {
    logger.debug("IN");
    try {
      if (biObject.getObjMetaDataAndContents() != null) {
        MetadataJSONSerializer jsonSerializer = new MetadataJSONSerializer();
        JSONArray metaArray = new JSONArray();
        Locale locale = getLocale();

        Domain typeDom = DAOFactory.getDomainDAO().loadDomainById(biObject.getBiObjectTypeID());
        MessageBuilder msgBuild = new MessageBuilder();
        // fill thecnical metadata

        JSONObject labelJSON = new JSONObject();
        String label = msgBuild.getMessage(GetMetadataAction.LABEL, locale);
        labelJSON.put("meta_name", label);
        labelJSON.put("meta_content", biObject.getLabel());
        labelJSON.put("meta_type", "GENERAL_META");

        JSONObject nameJSON = new JSONObject();
        String name = msgBuild.getMessage(GetMetadataAction.NAME, locale);
        nameJSON.put("meta_name", name);
        nameJSON.put("meta_content", biObject.getName());
        nameJSON.put("meta_type", "GENERAL_META");

        JSONObject typeJSON = new JSONObject();
        String typeL = msgBuild.getMessage(GetMetadataAction.TYPE, locale);
        String valueType = msgBuild.getMessage(typeDom.getValueName(), locale);
        typeJSON.put("meta_name", typeL);
        typeJSON.put("meta_content", valueType);
        typeJSON.put("meta_type", "GENERAL_META");

        JSONObject engineJSON = new JSONObject();
        String engine = msgBuild.getMessage(GetMetadataAction.ENG_NAME, locale);
        engineJSON.put("meta_name", engine);
        engineJSON.put("meta_content", biObject.getEngine().getName());
        engineJSON.put("meta_type", "GENERAL_META");

        metaArray.put(labelJSON);
        metaArray.put(nameJSON);
        metaArray.put(typeJSON);
        metaArray.put(engineJSON);

        for (Iterator iterator = biObject.getObjMetaDataAndContents().iterator();
            iterator.hasNext(); ) {
          DocumentMetadataProperty type = (DocumentMetadataProperty) iterator.next();
          Object o = jsonSerializer.serialize(type, locale);
          metaArray.put(o);
          logger.debug("Metadata serialzied " + o);
        }
        logger.debug("Metadata array serialzied " + metaArray);
        pars.put(METADATA_AND_METACONTENT, metaArray);
      } else {
        logger.debug("no meta and metacontent defined");
      }

    } catch (Exception e) {
      logger.error(
          "Impossibile to serialize metadata and metacontent for object with label "
              + biObject.getLabel(),
          e);
      throw new RuntimeException(
          "Impossibile to serialize metadata and metacontent for object with label "
              + biObject.getLabel(),
          e);
    }

    logger.debug("OUT");
  }
  private void saveConfiguredDocumentHandler(SourceBean request, SourceBean response)
      throws Exception {
    logger.debug("IN");
    String tempFolder = (String) request.getAttribute(DossierConstants.DOSSIER_TEMP_FOLDER);
    String label = (String) request.getAttribute("biobject_label");
    // get logical name assigned to the configured document
    String logicalName = (String) request.getAttribute("logicalname");
    if ((logicalName == null) || logicalName.trim().equalsIgnoreCase("")) {
      logicalName = "";
      // throw new EMFUserError(EMFErrorSeverity.ERROR, 103, "component_dossier_messages");
    }
    // load biobject using label
    //		Integer id = new Integer(idobj);
    IBIObjectDAO biobjdao = DAOFactory.getBIObjectDAO();
    BIObject obj = biobjdao.loadBIObjectByLabel(label);
    IBIObjectParameterDAO biobjpardao = DAOFactory.getBIObjectParameterDAO();
    // gets parameters of the biobject
    List params = biobjpardao.loadBIObjectParametersById(obj.getId());
    Iterator iterParams = params.iterator();
    // get map of the param url name and value assigned
    boolean findOutFormat = false;
    Map paramValueMap = new HashMap();
    Map paramNameMap = new HashMap();
    while (iterParams.hasNext()) {
      BIObjectParameter par = (BIObjectParameter) iterParams.next();
      String parUrlName = par.getParameterUrlName();
      if (parUrlName.equalsIgnoreCase("outputType")) findOutFormat = true;
      String value = (String) request.getAttribute(parUrlName);
      paramValueMap.put(parUrlName, value);
      paramNameMap.put(par.getLabel(), par.getParameterUrlName());
    }
    if (!findOutFormat) {
      paramValueMap.put("outputType", "JPGBASE64");
    }
    // fill a configured document bo with data retrived
    ConfiguredBIDocument confDoc = new ConfiguredBIDocument();
    confDoc.setDescription(obj.getDescription());
    //		confDoc.setId(obj.getId());
    confDoc.setLabel(obj.getLabel());
    confDoc.setParameters(paramValueMap);
    confDoc.setName(obj.getName());
    confDoc.setLogicalName(logicalName);

    // check if the error handler contains validation errors
    EMFErrorHandler errorHandler = getResponseContainer().getErrorHandler();
    if (errorHandler.isOKByCategory(EMFErrorCategory.VALIDATION_ERROR)) {
      // store the configured document
      IDossierDAO dossierDao = new DossierDAOHibImpl();
      dossierDao.addConfiguredDocument(confDoc, tempFolder);
      response.setAttribute(DossierConstants.PUBLISHER_NAME, "DossierLoopbackDossierDetail");
    } else {
      // set attribute into response
      response.setAttribute("parnamemap", paramNameMap);
      response.setAttribute("parvaluemap", paramValueMap);
      //			response.setAttribute("idobj", confDoc.getId());
      response.setAttribute("description", confDoc.getDescription());
      response.setAttribute("label", confDoc.getLabel());
      response.setAttribute("name", confDoc.getName());
      response.setAttribute("logicalname", confDoc.getLogicalName());
      response.setAttribute(DossierConstants.PUBLISHER_NAME, "DossierConfiguredDocumentDetail");
    }
    logger.debug("OUT");
  }
  private void documentRating(SourceBean request, String mod, SourceBean response)
      throws EMFUserError, SourceBeanException {

    String objId = "";
    String rating = "";
    RequestContainer requestContainer = this.getRequestContainer();
    SessionContainer session = requestContainer.getSessionContainer();
    SessionContainer permanentSession = session.getPermanentContainer();
    UserProfile profile =
        (UserProfile) permanentSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
    IEngUserProfile profile2 =
        (IEngUserProfile) permanentSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
    String userId =
        (profile.getUserUniqueIdentifier() != null
            ? profile.getUserUniqueIdentifier().toString()
            : "");
    List params = request.getContainedAttributes();
    ListIterator it = params.listIterator();

    while (it.hasNext()) {

      Object par = it.next();
      SourceBeanAttribute p = (SourceBeanAttribute) par;
      String parName = (String) p.getKey();
      logger.debug("got parName=" + parName);
      if (parName.equals("OBJECT_ID")) {
        objId = (String) request.getAttribute("OBJECT_ID");
        logger.debug("got OBJECT_ID from Request=" + objId);
      } else if (parName.equals("RATING")) {
        rating = (String) request.getAttribute("RATING");
      }
    }
    boolean canSee = false;

    BIObject obj = DAOFactory.getBIObjectDAO().loadBIObjectById(new Integer(objId));
    try {
      canSee = ObjectsAccessVerifier.canSee(obj, profile);
    } catch (EMFInternalError e1) {
      e1.printStackTrace();
    }
    if (!canSee) {
      logger.error("Object with label = '" + obj.getLabel() + "' cannot be executed by the user!!");
      Vector v = new Vector();
      v.add(obj.getLabel());
      throw new EMFUserError(EMFErrorSeverity.ERROR, "1075", v, null);
    }
    // get all correct execution roles
    List correctRoles = new ArrayList();
    try {
      correctRoles =
          DAOFactory.getBIObjectDAO().getCorrectRolesForExecution(new Integer(objId), profile2);
    } catch (NumberFormatException e2) {
      e2.printStackTrace();
    }
    if (correctRoles == null || correctRoles.size() == 0) {
      logger.warn("Object cannot be executed by no role of the user");
      throw new EMFUserError(EMFErrorSeverity.ERROR, 1006);
    }

    if (objId != null && !objId.equals("")) {
      if (rating != null && !rating.equals("")) {
        // VOTE!
        DAOFactory.getBIObjectRatingDAO().voteBIObject(obj, userId, rating);
      }
    }

    response.setAttribute("MESSAGEDET", mod);
    response.setAttribute(SpagoBIConstants.PUBLISHER_NAME, "ratingBIObjectPubJ");
    response.setAttribute("OBJECT_ID", objId);
  }
  public void doService() {
    ExecutionInstance instance;

    Integer documentId;
    String documentLabel;
    Integer documentVersion;
    String executionRole;
    String userProvidedParametersStr;

    BIObject obj;
    IEngUserProfile profile;
    List roles;

    logger.debug("IN");

    try {

      profile = getUserProfile();
      documentId =
          requestContainsAttribute(DOCUMENT_ID) ? getAttributeAsInteger(DOCUMENT_ID) : null;
      documentVersion =
          requestContainsAttribute(DOCUMENT_VERSION)
              ? getAttributeAsInteger(DOCUMENT_VERSION)
              : null;
      documentLabel = getAttributeAsString(DOCUMENT_LABEL);
      executionRole = getAttributeAsString(EXECUTION_ROLE);
      userProvidedParametersStr = getAttributeAsString(ObjectsTreeConstants.PARAMETERS);

      logger.debug("Parameter [" + DOCUMENT_ID + "] is equals to [" + documentId + "]");
      logger.debug("Parameter [" + DOCUMENT_LABEL + "] is equals to [" + documentLabel + "]");
      logger.debug("Parameter [" + DOCUMENT_VERSION + "] is equals to [" + documentVersion + "]");
      logger.debug("Parameter [" + EXECUTION_ROLE + "] is equals to [" + executionRole + "]");

      Assert.assertTrue(
          !StringUtilities.isEmpty(documentLabel) || documentId != null,
          "At least one between ["
              + DOCUMENT_ID
              + "] and ["
              + DOCUMENT_LABEL
              + "] parameter must be specified on request");

      Assert.assertTrue(
          !StringUtilities.isEmpty(executionRole),
          "Parameter [" + EXECUTION_ROLE + "] cannot be null");

      // load object to chek if it exists
      obj = null;
      if (!StringUtilities.isEmpty(documentLabel)) {
        logger.debug("Loading document with label = [" + documentLabel + "] ...");
        try {
          obj = DAOFactory.getBIObjectDAO().loadBIObjectByLabel(documentLabel);
        } catch (EMFUserError error) {
          logger.error("Object with label equals to [" + documentLabel + "] not found");
          throw new SpagoBIServiceException(
              SERVICE_NAME, "Object with label equals to [" + documentId + "] not found", error);
        }
      } else if (documentId != null) {
        logger.info("Loading biobject with id = [" + documentId + "] ...");
        try {
          obj = DAOFactory.getBIObjectDAO().loadBIObjectById(documentId);
        } catch (EMFUserError error) {
          logger.error("Object with id equals to [" + documentId + "] not found");
          throw new SpagoBIServiceException(
              SERVICE_NAME, "Object with id equals to [" + documentId + "] not found", error);
        }
      } else {
        Assert.assertUnreachable(
            "At least one between ["
                + DOCUMENT_ID
                + "] and ["
                + DOCUMENT_LABEL
                + "] parameter must be specified on request");
      }
      Assert.assertNotNull(obj, "Impossible to load document");
      logger.debug("... docuemnt loaded succesfully");
      // if into the request is specified a version of the template to use it's signed into the
      // object.
      if (documentVersion != null) obj.setDocVersion(documentVersion);

      // retrive roles for execution
      try {
        roles = ObjectsAccessVerifier.getCorrectRolesForExecution(obj.getId(), profile);
      } catch (Throwable t) {
        throw new SpagoBIServiceException(SERVICE_NAME, t);
      }

      if (roles != null && !roles.contains(executionRole)) {
        logger.error(
            "Document [id: "
                + obj.getId()
                + "; label: "
                + obj.getLabel()
                + " ] cannot be executed by any role of the user ["
                + profile.getUserUniqueIdentifier()
                + "]");
        throw new SpagoBIServiceException(
            SERVICE_NAME,
            "Document [id: "
                + obj.getId()
                + "; label: "
                + obj.getLabel()
                + " ] cannot be executed by any role of the user ["
                + profile.getUserUniqueIdentifier()
                + "]");
      }

      // so far so good: everything has been validated successfully. Let's create a new
      // ExecutionInstance.
      // instance = createExecutionInstance(obj.getId(), executionRole);

      UUIDGenerator uuidGen = UUIDGenerator.getInstance();
      UUID uuidObj = uuidGen.generateTimeBasedUUID();
      String executionContextId = uuidObj.toString();
      executionContextId = executionContextId.replaceAll("-", "");

      CoreContextManager ccm = createContext(executionContextId);
      // so far so good: everything has been validated successfully. Let's create a new
      // ExecutionInstance.
      instance =
          createExecutionInstance(
              obj.getId(), obj.getDocVersion(), executionRole, executionContextId, getLocale());

      createContext(executionContextId).set(ExecutionInstance.class.getName(), instance);

      // instance.refreshParametersValues(getSpagoBIRequestContainer().getRequest(), true);
      // instance.setParameterValues(userProvidedParametersStr, true);

      // refresh obj variable because createExecutionInstance load the BIObject in a different way
      // obj = instance.getBIObject();

      // ExecutionInstance has been created it's time to prepare the response with the instance
      // unique id and flush it to the client
      JSONObject responseJSON = null;
      responseJSON = new JSONObject();
      try {
        responseJSON.put("execContextId", executionContextId);
      } catch (JSONException e) {
        throw new SpagoBIServiceException("Impossible to serialize response", e);
      }

      try {
        writeBackToClient(new JSONSuccess(responseJSON));
      } catch (IOException e) {
        throw new SpagoBIServiceException("Impossible to write back the responce to the client", e);
      }

    } finally {
      logger.debug("OUT");
    }
  }
  public void doService() {
    logger.debug("IN");
    try {
      // retrieving execution instance from session, no need to check if user is able to execute the
      // current document
      ExecutionInstance executionInstance =
          getContext().getExecutionInstance(ExecutionInstance.class.getName());
      BIObject obj = executionInstance.getBIObject();
      BIObjectNotesManager objectNManager = new BIObjectNotesManager();
      String execIdentifier = objectNManager.getExecutionIdentifier(obj);

      String previousNotes = this.getAttributeAsString("PREVIOUS_NOTES");
      logger.debug("Parameter [" + PREVIOUS_NOTES + "] is equal to [" + previousNotes + "]");

      String notes = this.getAttributeAsString("NOTES");
      logger.debug("Parameter [" + NOTES + "] is equal to [" + notes + "]");

      String message = this.getAttributeAsString(MESSAGE);
      logger.debug("Parameter [" + MESSAGE + "] is equal to [" + message + "]");

      String visibility = this.getAttributeAsString(VISIBILITY);
      logger.debug("Parameter [" + VISIBILITY + "] is equal to [" + visibility + "]");

      String resultStr = null;

      ObjNote objnote = null;

      SessionContainer sessCont = getSessionContainer();
      SessionContainer permCont = sessCont.getPermanentContainer();
      IEngUserProfile profile =
          (IEngUserProfile) permCont.getAttribute(IEngUserProfile.ENG_USER_PROFILE);

      String owner = (String) ((UserProfile) profile).getUserId();
      try {
        objnote =
            DAOFactory.getObjNoteDAO().getExecutionNotesByOwner(obj.getId(), execIdentifier, owner);
      } catch (Exception e) {
        logger.error(
            "Cannot load notes for document [id: "
                + obj.getId()
                + ", label: "
                + obj.getLabel()
                + ", name: "
                + obj.getName()
                + "]",
            e);
        throw new SpagoBIServiceException(SERVICE_NAME, "Cannot load notes", e);
      }
      String currentNotes = "";
      if (objnote != null) {
        logger.debug("Existing notes found with the same execution identifier");
        byte[] content = objnote.getContent();
        currentNotes = new String(content);
      }
      if (!"INSERT_NOTE".equalsIgnoreCase(MESSAGE) && !currentNotes.equals(previousNotes)) {
        logger.debug("Notes have been created by another user");
        resultStr = "conflict";
      } else {
        logger.debug("Saving notes...");
        try {
          saveNotes(execIdentifier, obj.getId(), notes, objnote, owner, visibility, profile);
          logger.debug("Notes saved");
          resultStr = "ok";
        } catch (Exception e) {
          throw new SpagoBIServiceException(SERVICE_NAME, "Error while saving notes", e);
        }
      }

      try {
        JSONObject result = new JSONObject();
        result.put("result", resultStr);
        writeBackToClient(new JSONSuccess(result));
      } catch (IOException e) {
        throw new SpagoBIServiceException(
            SERVICE_NAME, "Impossible to write back the responce to the client", e);
      } catch (JSONException e) {
        throw new SpagoBIServiceException(
            SERVICE_NAME, "Cannot serialize objects into a JSON object", e);
      }
    } finally {
      logger.debug("OUT");
    }
  }
  /**
   * Returns an url for execute the document with the engine associated. It calls relative driver.
   *
   * @param objLabel the logical label of the document (gets from the template file)
   * @param sessionContainer session object
   * @param requestSB request object
   * @return String the complete url. It use this format: <code_error>|<url>. If there is an error
   *     during the execution <code_error> is valorized and url is null, else it is null and the url
   *     is complete.
   */
  public static String getExecutionUrl(
      String objLabel, SessionContainer sessionContainer, SourceBean requestSB) {
    logger.debug("IN");

    Monitor monitor =
        MonitorFactory.start("spagobi.engines.DocumentCompositionUtils.getExecutionUrl");

    String baseUrlReturn = "";
    String urlReturn = "";

    if (objLabel == null || objLabel.equals("")) {
      logger.error("Object Label is null: cannot get engine's url.");
      return "1008|";
    }

    try {
      // get the user profile from session
      SessionContainer permSession = sessionContainer.getPermanentContainer();
      IEngUserProfile profile =
          (IEngUserProfile) permSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
      // get the execution role
      CoreContextManager contextManager =
          new CoreContextManager(
              new SpagoBISessionContainer(sessionContainer),
              new LightNavigatorContextRetrieverStrategy(requestSB));
      ExecutionInstance instance =
          contextManager.getExecutionInstance(ExecutionInstance.class.getName());
      String executionRole = instance.getExecutionRole();
      Integer objId = DAOFactory.getBIObjectDAO().loadBIObjectByLabel(objLabel).getId();
      BIObject obj =
          DAOFactory.getBIObjectDAO().loadBIObjectForExecutionByIdAndRole(objId, executionRole);
      //			BIObject obj =
      // DAOFactory.getBIObjectDAO().loadBIObjectForExecutionByLabelAndRole(objLabel,
      // executionRole);
      //			BIObject obj = DAOFactory.getBIObjectDAO().loadBIObjectByLabel(objLabel);
      if (obj == null) {
        logger.error(
            "Cannot obtain engine url. Document with label "
                + objLabel
                + " doesn't exist into database.");
        List l = new ArrayList();
        l.add(objLabel);
        throw new EMFUserError(EMFErrorSeverity.ERROR, "1005", l, messageBundle);
      }
      //			Engine engine = obj.getEngine();

      /*ALL CONTROLS OF COMPATIBILITY ARE REMANDED TO THE SINGLE ENGINE CALLED
      // GET THE TYPE OF ENGINE (INTERNAL / EXTERNAL) AND THE SUITABLE BIOBJECT TYPES
      Domain engineType = null;
      Domain compatibleBiobjType = null;
      try {
      	engineType = DAOFactory.getDomainDAO().loadDomainById(engine.getEngineTypeId());
      	compatibleBiobjType = DAOFactory.getDomainDAO().loadDomainById(engine.getBiobjTypeId());
      } catch (EMFUserError error) {
      	logger.error("Error retrieving document's engine information", error);
      	return "1009|";
      } catch (Exception error) {
      	logger.error("Error retrieving document's engine information", error);
      	return "1009|";
      }

      String compatibleBiobjTypeCd = compatibleBiobjType.getValueCd();
      String biobjTypeCd = obj.getBiObjectTypeCode();

      // CHECK IF THE BIOBJECT IS COMPATIBLE WITH THE TYPES SUITABLE FOR THE ENGINE

      if (!compatibleBiobjTypeCd.equalsIgnoreCase(biobjTypeCd)) {
      	// the engine document type and the biobject type are not compatible
      	logger.error("Engine cannot execute input document type: " +
      			"the engine " + engine.getName() + " can execute '" + compatibleBiobjTypeCd + "' type documents " +
      			"while the input document is a '" + biobjTypeCd + "'.");
      	Vector params = new Vector();
      	params.add(engine.getName());
      	params.add(compatibleBiobjTypeCd);
      	params.add(biobjTypeCd);
      	//errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, 2002, params));
      	return "2002|";
      }
       */
      // IF USER CAN'T EXECUTE THE OBJECT RETURN
      // if (!ObjectsAccessVerifier.canSee(obj, profile)) return "1010|";

      // get object configuration
      DocumentCompositionConfiguration docConfig = null;
      docConfig = (DocumentCompositionConfiguration) contextManager.get("docConfig");

      Document document = null;
      // get correct document configuration
      List lstDoc = docConfig.getLabelsArray();
      boolean foundDoc = false;
      for (int i = 0; i < lstDoc.size(); i++) {
        document = (Document) docConfig.getDocument((String) lstDoc.get(i));
        if (document != null) {
          if (!obj.getLabel().equalsIgnoreCase(document.getSbiObjLabel())) continue;
          else {
            foundDoc = true;
            break;
          }
        }
      }
      if (!foundDoc) {
        List l = new ArrayList();
        l.add(obj.getLabel());
        EMFUserError userError = new EMFUserError(EMFErrorSeverity.ERROR, 1079, l);
        logger.error(
            "The object with label " + obj.getLabel() + " hasn't got a document into template");
        return "1002|";
      }

      String className = obj.getEngine().getClassName();
      if ((className == null || className.trim().equals(""))
          && (document.getSnapshot() == null || !document.getSnapshot())) {
        // external engine
        // baseUrlReturn = obj.getEngine().getUrl() + "?";
        baseUrlReturn = obj.getEngine().getUrl();
        if (baseUrlReturn.indexOf("?") < 0) baseUrlReturn += "?";
        String driverClassName = obj.getEngine().getDriverName();
        IEngineDriver aEngineDriver = (IEngineDriver) Class.forName(driverClassName).newInstance();
        Map mapPars = aEngineDriver.getParameterMap(obj, profile, executionRole);
        String id = (String) requestSB.getAttribute("vpId");
        if (id != null) {
          IViewpointDAO VPDAO = DAOFactory.getViewpointDAO();
          Viewpoint vp = VPDAO.loadViewpointByID(new Integer(id));
          String[] vpParameters = vp.getVpValueParams().split("%26");
          if (vpParameters != null) {
            for (int i = 0; i < vpParameters.length; i++) {
              String param = (String) vpParameters[i];
              String name = param.substring(0, param.indexOf("%3D"));
              String value = param.substring(param.indexOf("%3D") + 3);
              if (mapPars.get(name) != null) {
                mapPars.remove(name);
                mapPars.put(name, value);
              } else mapPars.put(name, value);
            }
          }
        }
        mapPars.put(SpagoBIConstants.SBI_CONTEXT, GeneralUtilities.getSpagoBiContext());
        mapPars.put(SpagoBIConstants.SBI_HOST, GeneralUtilities.getSpagoBiHost());
        UUIDGenerator uuidGen = UUIDGenerator.getInstance();
        UUID uuidObj = uuidGen.generateRandomBasedUUID();
        String executionId = uuidObj.toString();
        executionId = executionId.replaceAll("-", "");
        mapPars.put("SBI_EXECUTION_ID", executionId);
        mapPars.put("EXECUTION_CONTEXT", "DOCUMENT_COMPOSITION");
        // Auditing
        AuditManager auditManager = AuditManager.getInstance();
        Integer executionAuditId =
            auditManager.insertAudit(
                instance.getBIObject(),
                null,
                profile,
                executionRole,
                instance.getExecutionModality());

        // adding parameters for AUDIT updating
        if (executionAuditId != null) {
          mapPars.put(AuditManager.AUDIT_ID, executionAuditId.toString());
        }

        Set parKeys = mapPars.keySet();
        Iterator parKeysIter = parKeys.iterator();
        do {
          if (!parKeysIter.hasNext()) {
            break;
          }
          String parkey = parKeysIter.next().toString();
          String parvalue = mapPars.get(parkey).toString();
          urlReturn =
              (new StringBuilder())
                  .append(urlReturn)
                  .append("&")
                  .append(parkey)
                  .append("=")
                  .append(parvalue)
                  .toString();
        } while (true);

      } else {

        // internal engine
        baseUrlReturn =
            GeneralUtilities.getSpagoBIProfileBaseUrl(profile.getUserUniqueIdentifier().toString());
        urlReturn = "&" + ObjectsTreeConstants.OBJECT_LABEL + "=" + objLabel;
        // identity string for context
        UUIDGenerator uuidGen = UUIDGenerator.getInstance();
        UUID uuid = uuidGen.generateRandomBasedUUID();
        urlReturn += "&" + LightNavigationManager.LIGHT_NAVIGATOR_ID + "=" + uuid.toString();
        if (document.getSnapshot() != null && document.getSnapshot()) {
          Snapshot snap = DAOFactory.getSnapshotDAO().getLastSnapshot(objId);
          if (snap != null) {
            urlReturn += "&SNAPSHOT_ID=" + snap.getId();
          }
          urlReturn += "&OBJECT_ID=" + objId;
          urlReturn += "&ACTION_NAME=GET_SNAPSHOT_CONTENT";
        } else {
          urlReturn +=
              "&PAGE=ExecuteBIObjectPage&"
                  + SpagoBIConstants.IGNORE_SUBOBJECTS_VIEWPOINTS_SNAPSHOTS
                  + "=true";
          urlReturn +=
              "&" + ObjectsTreeConstants.MODALITY + "=" + SpagoBIConstants.DOCUMENT_COMPOSITION;
        }
      }

      // I add passing of SBI_LANGUAGE and SBI_COUNTRY
      // on session container they are called AF_COUNTRY and AF_LANGUAGE
      SessionContainer sContainer = sessionContainer.getPermanentContainer();
      if (sContainer != null) {
        Object language = sContainer.getAttribute("AF_LANGUAGE");
        Object country = sContainer.getAttribute("AF_COUNTRY");
        if (language == null) {
          language = sContainer.getAttribute("SBI_LANGUAGE");
        }
        if (country == null) {
          country = sContainer.getAttribute("SBI_COUNTRY");
        }
        if (language != null && country != null) {
          urlReturn +=
              "&"
                  + SpagoBIConstants.SBI_LANGUAGE
                  + "="
                  + language
                  + "&"
                  + SpagoBIConstants.SBI_COUNTRY
                  + "="
                  + country;
        }
      }

      urlReturn += "&" + SpagoBIConstants.ROLE + "=" + executionRole;
      urlReturn += getParametersUrl(obj, document, requestSB, instance);
      // adds '|' char for management error into jsp if is necessary.

      urlReturn = baseUrlReturn + urlReturn;

      logger.debug("urlReturn: " + "|" + urlReturn);
    } catch (Exception ex) {
      logger.error("Error while getting execution url: " + ex);
      return null;
    } finally {
      monitor.stop();
    }

    logger.debug("OUT");

    return "|" + urlReturn;
  }
  /**
   * Return a string representative an url with all parameters set with a request value (if it is
   * present) or with the default's value.
   *
   * @param doc the document object that is managed
   * @param document the document configurator
   * @param requestSB the request object
   * @return a string with the url completed
   */
  private static String getParametersUrl(
      BIObject obj, Document document, SourceBean requestSB, ExecutionInstance instance) {
    logger.debug("IN");
    String paramUrl = "";
    // set others parameters value
    Properties lstParams = document.getParams();
    String key = "";
    List values = new ArrayList();
    String singleValue = "";
    int cont = 0;

    try {
      if (lstParams != null) {
        ParameterValuesEncoder encoderUtility = new ParameterValuesEncoder();
        // while(enParams.hasMoreElements()) {
        for (int i = 0; i < lstParams.size(); i++) {
          String typeParam =
              lstParams.getProperty("type_par_" + document.getNumOrder() + "_" + cont);
          // only for parameter in input to the document managed (type equal 'IN')
          if (typeParam != null && typeParam.indexOf("IN") >= 0) {
            String tmpKey = "sbi_par_label_param_" + document.getNumOrder() + "_" + cont;
            key = lstParams.getProperty(tmpKey);
            if (key == null && !document.getTypeCross().equalsIgnoreCase(Constants.CROSS_EXTERNAL))
              break;

            values = (List) requestSB.getAttributeAsList(key);
            // if value isn't defined, check if there is a value into the instance(there is when a
            // document is called from a refresh o viewpoint mode)
            if (values == null || values.size() == 0 || ((String) values.get(0)).equals("")) {
              List instanceValue = getInstanceValue(key, instance);
              if (instanceValue != null
                  && instanceValue.size() > 0
                  && !instanceValue.get(0).equals("")) values = instanceValue;
            }
            // if value isn't defined, gets the default value from the template
            if (values == null || values.size() == 0 || ((String) values.get(0)).equals("")) {
              values.add(
                  lstParams.getProperty(
                      ("default_value_param_" + document.getNumOrder() + "_" + cont)));
            }
            logger.debug("Values to pass : "******"")) {
              // EXTERNAL ENGINES
              BIObjectParameter par = getBIObjectParameter(obj, key);
              par.setParameterValues(values);
              Parameter tmpPar = par.getParameter();
              logger.debug("Manage parameter : " + tmpPar.getLabel() + "...");
              if (tmpPar != null
                  && values.size() > 1
                  && tmpPar.getModalityValue() != null
                  && ((!(par).isMultivalue())
                      || tmpPar
                          .getModalityValue()
                          .getITypeCd()
                          .equalsIgnoreCase(SpagoBIConstants.INPUT_TYPE_MAN_IN_CODE))) {
                logger.debug("Force the multivalue modality for parameter " + tmpPar.getLabel());
                // force the multivalue management if the parameter has defined as MANUAL INPUT and
                // the values is multiple.
                tmpPar.getModalityValue().setMultivalue(true);
                tmpPar.getModalityValue().setITypeCd(SpagoBIConstants.INPUT_TYPE_QUERY_CODE);
                par.setParameter(tmpPar);
              }
              String parsValue = encoderUtility.encode(par);
              // conversion in UTF-8 of the par
              Map parsMap = new HashMap();
              parsMap.put(key, parsValue);
              String tmpUrl = GeneralUtilities.getUrl("", parsMap);
              logger.debug("tmpUrl for " + obj.getLabel() + ": " + tmpUrl);
              paramUrl += "&" + tmpUrl.substring(tmpUrl.indexOf("?") + 1);

              // paramUrl += "&" + key + "=" + tmpUrl;
            } else {
              // INTERNAL ENGINES
              for (int j = 0; j < values.size(); j++) {
                singleValue = (String) values.get(j);
                if (singleValue.equals("%")) singleValue = "%25";
                // setting an url likes &key=val1;val2;valn
                if (j == 0) {
                  paramUrl += "&" + key + "=" + singleValue;
                } else {
                  paramUrl += ";" + singleValue;
                }
              }
            }

            cont++;
          }
        }
      }
    } catch (Exception ex) {
      logger.error(
          "Error while getting parameter's document "
              + document.getSbiObjLabel()
              + " param: "
              + key
              + ": "
              + ex);
      return null;
    }

    /*
    if (forInternalEngine)
    	paramUrl = paramUrl.substring(0, paramUrl.length()-3);
    else
    	paramUrl = paramUrl.substring(0, paramUrl.length()-5);
     */
    logger.debug("paramUrl: " + paramUrl);
    logger.debug("OUT");
    return paramUrl;
  }