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");
 }
Exemple #3
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;
  }
Exemple #4
0
  /**
   * Add into the parameters map the BIObject's BIParameter names and values
   *
   * @param biobj BIOBject to execute
   * @param pars Map of the parameters for the execution call
   * @return Map The map of the execution call parameters
   */
  private Map appendAnalyticalDriversToRequestParameters(BIObject biobj, Map pars) {
    logger.debug("IN");

    if (biobj == null) {
      logger.warn("BIObject parameter null");
      return pars;
    }

    ParameterValuesEncoder parValuesEncoder = new ParameterValuesEncoder();
    if (biobj.getBiObjectParameters() != null) {
      BIObjectParameter biobjPar = null;
      for (Iterator it = biobj.getBiObjectParameters().iterator(); it.hasNext(); ) {
        try {
          biobjPar = (BIObjectParameter) it.next();
          String value = parValuesEncoder.encode(biobjPar);
          pars.put(biobjPar.getParameterUrlName(), value);
          logger.debug("Add parameter:" + biobjPar.getParameterUrlName() + "/" + value);
        } catch (Exception e) {
          logger.error("Error while processing a BIParameter", e);
        }
      }
    }

    logger.debug("OUT");
    return pars;
  }
 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");
 }
  /**
   * Function not implemented. Thid method should not be called
   *
   * @param biobject The BIOBject to edit
   * @param profile the profile
   * @return the edits the document template build url
   * @throws InvalidOperationRequest the invalid operation request
   */
  public EngineURL getEditDocumentTemplateBuildUrl(Object biobject, IEngUserProfile profile)
      throws InvalidOperationRequest {

    EngineURL engineURL;
    BIObject obj;
    String documentId;
    Engine engine;
    String url;
    HashMap parameters;

    logger.debug("IN");

    try {
      obj = null;
      try {
        obj = (BIObject) biobject;
      } catch (ClassCastException cce) {
        logger.error("The input object is not a BIObject type", cce);
        return null;
      }

      documentId = obj.getId().toString();
      engine = obj.getEngine();
      url = engine.getUrl();

      parameters = new HashMap();

      // getting the dataset label from template, if smart filter is based on a dataset
      ObjTemplate objectTemplate = obj.getActiveTemplate();
      byte[] content = objectTemplate.getContent();
      SourceBean sbTemplate = getTemplateAsSourceBean(content);
      if (sbTemplate.getName().equals(EngineConstants.SMART_FILTER_TAG)
          && sbTemplate.containsAttribute("DATASET")) {
        String label =
            (String) ((SourceBean) sbTemplate.getAttribute("DATASET")).getAttribute("label");
        parameters.put("dataset_label", label);
      }
      parameters.put("document", documentId);
      parameters.put(PARAM_SERVICE_NAME, "FORM_ENGINE_TEMPLATE_BUILD_ACTION");
      parameters.put(PARAM_NEW_SESSION, "TRUE");
      parameters.put(PARAM_MODALITY, "EDIT");
      applySecurity(parameters, profile);

      engineURL = new EngineURL(url, parameters);
    } catch (Throwable t) {
      throw new RuntimeException("Cannot get engine edit URL", t);
    } finally {
      logger.debug("OUT");
    }

    return engineURL;
  }
 public List<EMFValidationError> adjustRequiredAnalyticalDrivers(Integer dossierId, List docs) {
   logger.debug("IN");
   BIObject dossier = null;
   try {
     dossier = DAOFactory.getBIObjectDAO().loadBIObjectById(dossierId);
     dossier.setBiObjectParameters(DAOFactory.getBIObjectDAO().getBIObjectParameters(dossier));
   } catch (EMFUserError e) {
     throw new RuntimeException("Cannot load details of dossier with id " + dossierId, e);
   }
   List<EMFValidationError> list = removeNotEmptyAnalyticalDrivers(dossier, docs);
   addEmptyAnalyticalDrivers(dossier, docs);
   logger.debug("OUT");
   return list;
 }
 private List<EMFValidationError> removeNotEmptyAnalyticalDrivers(BIObject dossier, List docs) {
   logger.debug("IN");
   List parameters = dossier.getBiObjectParameters();
   List<BIObjectParameter> biParametersToBeRemoved = new ArrayList<BIObjectParameter>();
   if (parameters != null && parameters.size() > 0) {
     HashMap<Integer, List<BIObjectParameter>> analyticalDrivers =
         getAnalyticalDriverCount(parameters);
     Set<Entry<Integer, List<BIObjectParameter>>> entries = analyticalDrivers.entrySet();
     Iterator<Entry<Integer, List<BIObjectParameter>>> it = entries.iterator();
     while (it.hasNext()) {
       Entry<Integer, List<BIObjectParameter>> entry = it.next();
       List<BIObjectParameter> biParameters = entry.getValue();
       int occurrences = biParameters.size();
       int emptyOccurences = getMaxEmptyOccurrences(biParameters.get(0), docs);
       int difference = occurrences - emptyOccurences;
       for (int i = 1; i <= difference; i++) {
         // remove last ones
         biParametersToBeRemoved.add(biParameters.get(biParameters.size() - i));
       }
     }
   }
   Iterator<BIObjectParameter> biParametersToBeRemovedIt = biParametersToBeRemoved.iterator();
   List<EMFValidationError> toReturn = new ArrayList<EMFValidationError>();
   while (biParametersToBeRemovedIt.hasNext()) {
     BIObjectParameter aBIObjectParameter = biParametersToBeRemovedIt.next();
     EMFValidationError error = removeAnalyticalDriver(aBIObjectParameter);
     if (error != null) {
       toReturn.add(error);
     }
   }
   updateBIObjectParameters(dossier);
   logger.debug("OUT");
   return toReturn;
 }
  private Map applyService(Map parameters, BIObject biObject) {
    logger.debug("IN");

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

      ObjTemplate objectTemplate = biObject.getActiveTemplate();
      byte[] content = objectTemplate.getContent();
      SourceBean sbTemplate = getTemplateAsSourceBean(content);

      if (sbTemplate.getName().equals(EngineConstants.SMART_FILTER_TAG)) {
        parameters.put(PARAM_SERVICE_NAME, "FORM_ENGINE_FROM_DATASET_START_ACTION");
        if (sbTemplate.containsAttribute("DATASET")) {
          String label =
              (String) ((SourceBean) sbTemplate.getAttribute("DATASET")).getAttribute("label");
          parameters.put("dataset_label", label);
        }
      } else {
        parameters.put(PARAM_SERVICE_NAME, "FORM_ENGINE_START_ACTION");
      }
      parameters.put(PARAM_MODALITY, "VIEW");

      parameters.put(PARAM_NEW_SESSION, "TRUE");
    } catch (Throwable t) {
      throw new RuntimeException("Cannot apply service parameters", t);
    } finally {
      logger.debug("OUT");
    }

    return parameters;
  }
 /**
  * Adds a system parameter contaning info about document parameters (url name, label, type)
  *
  * @param biobject The BIObject under execution
  * @param map The parameters map
  * @return the modified map with the new parameter
  */
 private Map addDocumentParametersInfo(Map map, BIObject biobject) {
   logger.debug("IN");
   JSONArray parametersJSON = new JSONArray();
   try {
     Locale locale = getLocale();
     List parameters = biobject.getBiObjectParameters();
     if (parameters != null && parameters.size() > 0) {
       Iterator iter = parameters.iterator();
       while (iter.hasNext()) {
         BIObjectParameter biparam = (BIObjectParameter) iter.next();
         JSONObject jsonParam = new JSONObject();
         jsonParam.put("id", biparam.getParameterUrlName());
         IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
         // String interLabel = msgBuilder.getUserMessage(biparam.getLabel(),
         // SpagoBIConstants.DEFAULT_USER_BUNDLE, locale);
         String interLabel = msgBuilder.getI18nMessage(locale, biparam.getLabel());
         jsonParam.put("label", interLabel);
         jsonParam.put("type", biparam.getParameter().getType());
         parametersJSON.put(jsonParam);
       }
     }
   } catch (Exception e) {
     logger.error("Error while adding document parameters info", e);
   }
   map.put("SBI_DOCUMENT_PARAMETERS", parametersJSON.toString());
   logger.debug("OUT");
   return map;
 }
  /**
   * Returns an url for the test of the EXTERNAL engine.
   *
   * @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 getEngineTestUrl(
      String objLabel, SessionContainer sessionContainer, SourceBean requestSB) {
    logger.debug("IN");

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

    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();
      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);
      }

      String className = obj.getEngine().getClassName();
      if (className == null || className.trim().equals("")) {
        // external engine
        baseUrlReturn = obj.getEngine().getUrl() + "Test?";
        urlReturn = baseUrlReturn;
        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;
  }
  private static List getInstanceValue(String key, ExecutionInstance instance) {
    List retVal = new ArrayList();
    BIObject obj = instance.getBIObject();
    List objPars = obj.getBiObjectParameters();

    for (int i = 0; i < objPars.size(); i++) {
      BIObjectParameter objPar = (BIObjectParameter) objPars.get(i);
      if (objPar.getParameterUrlName().equalsIgnoreCase(key)) {
        retVal.add(
            (objPar.getParameterValues() == null)
                ? ""
                : (String) objPar.getParameterValues().get(0));
        break;
      }
    }
    return retVal;
  }
  /**
   * Method called by document composition publisher , that returns alla available exporters for a
   * single document contained in the composed one.
   *
   * @param objLabel
   * @param sessionContainer
   * @param requestSB
   * @return
   */
  public static List getAvailableExporters(
      String objLabel, SessionContainer sessionContainer, SourceBean requestSB) {
    logger.debug("IN");

    List<Exporters> exporters = null;
    List<String> exportersTypes = null;
    if (objLabel == null || objLabel.equals("")) {
      logger.error("Object Label is null: cannot get engine's url.");
      return null;
    }

    try {
      // get the user profile from session
      SessionContainer permSession = sessionContainer.getPermanentContainer();
      IEngUserProfile profile =
          (IEngUserProfile) permSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
      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();
      exporters = DAOFactory.getEngineDAO().getAssociatedExporters(engine);
      if (exporters != null) {
        exportersTypes = new ArrayList<String>();
        for (int i = 0; i < exporters.size(); i++) {
          Domain domain = DAOFactory.getDomainDAO().loadDomainById(exporters.get(i).getDomainId());
          String cd = domain.getValueCd();
          exportersTypes.add(cd);
        }
      }
    } catch (Exception e) {
      logger.error("Error while getting document's exporters for label :" + objLabel + ": " + e);
      return null;
    } finally {
      logger.debug("OUT");
    }

    return exportersTypes;
  }
 private int getMaxEmptyOccurrences(BIObjectParameter biParameter, List docs) {
   int toReturn = 0;
   logger.debug("IN");
   Iterator it = docs.iterator();
   while (it.hasNext()) {
     ConfiguredBIDocument configuredBIDocument = (ConfiguredBIDocument) it.next();
     Map parameters = configuredBIDocument.getParameters();
     BIObject configuredDocument = configuredBIDocument.loadBIObjectDetails();
     List configuredDocumentParameters = configuredDocument.getBiObjectParameters();
     int emptyOccurrences =
         getAnalyticalDriverEmptyOccurrences(
             biParameter, configuredDocumentParameters, parameters);
     if (emptyOccurrences > toReturn) {
       toReturn = emptyOccurrences;
     }
   }
   logger.debug("OUT: " + toReturn);
   return toReturn;
 }
  /**
   * Function not implemented. Thid method should not be called
   *
   * @param biobject The BIOBject to edit
   * @param profile the profile
   * @return the new document template build url
   * @throws InvalidOperationRequest the invalid operation request
   */
  public EngineURL getNewDocumentTemplateBuildUrl(Object biobject, IEngUserProfile profile)
      throws InvalidOperationRequest {

    EngineURL engineURL;
    BIObject obj;
    String documentId;
    Engine engine;
    String url;
    HashMap parameters;

    logger.debug("IN");

    try {
      obj = null;
      try {
        obj = (BIObject) biobject;
      } catch (ClassCastException cce) {
        logger.error("The input object is not a BIObject type", cce);
        return null;
      }

      documentId = obj.getId().toString();
      engine = obj.getEngine();
      url = engine.getUrl();
      // url = url.replaceFirst("/servlet/AdapterHTTP", "");
      // url += "/templateBuilder.jsp";

      parameters = new HashMap();
      parameters.put("document", documentId);
      parameters.put(PARAM_SERVICE_NAME, "FORM_ENGINE_TEMPLATE_BUILD_ACTION");
      parameters.put(PARAM_NEW_SESSION, "TRUE");
      parameters.put(PARAM_MODALITY, "NEW");
      applySecurity(parameters, profile);

      engineURL = new EngineURL(url, parameters);
    } finally {
      logger.debug("OUT");
    }

    return engineURL;
  }
  /**
   * Return the BIObjectParameter with the key passed
   *
   * @param key String with url (identifier) of parameter
   * @return BIObjectParameter
   */
  private static BIObjectParameter getBIObjectParameter(BIObject obj, String urlKey) {
    if (urlKey == null || urlKey.equals("")) return null;

    BIObjectParameter par = null;
    List objParams = obj.getBiObjectParameters();
    for (int i = 0, l = objParams.size(); i < l; i++) {
      par = (BIObjectParameter) objParams.get(i);
      if (par.getParameterUrlName().equals(urlKey)) break;
    }

    return par;
  }
Exemple #17
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;
  }
 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");
 }
 /**
  * Returns the number of occurrences of the same Analytical Driver in the document, i.e. the
  * number of BIObjectParameter that are related to the same Parameter object.
  *
  * @param dossier The dossier document
  * @param biParameter Th dossier's BIObjectParameter
  * @return the number of occurrences of the same Analytical Driver in the document
  */
 private int getAnalyticalDriverOccurrenciesInDossier(BIObject dossier, Integer parameterId) {
   int toReturn = 0;
   logger.debug("IN");
   List parameters = dossier.getBiObjectParameters();
   Iterator it = parameters.iterator();
   while (it.hasNext()) {
     BIObjectParameter aParameter = (BIObjectParameter) it.next();
     if (aParameter.getParID().equals(parameterId)) {
       toReturn++;
     }
   }
   logger.debug("OUT: returning " + toReturn);
   return toReturn;
 }
 private void addEmptyAnalyticalDrivers(
     BIObject dossier, ConfiguredBIDocument configuredBIDocument) {
   logger.debug("IN");
   Map parameters = configuredBIDocument.getParameters();
   BIObject configuredDocument = configuredBIDocument.loadBIObjectDetails();
   List configuredDocumentParameters = configuredDocument.getBiObjectParameters();
   Iterator configuredBIObjectParametersIt = configuredDocumentParameters.iterator();
   while (configuredBIObjectParametersIt.hasNext()) {
     BIObjectParameter biParameter = (BIObjectParameter) configuredBIObjectParametersIt.next();
     int emptyOccurrences =
         getAnalyticalDriverEmptyOccurrences(
             biParameter, configuredDocumentParameters, parameters);
     if (emptyOccurrences > 0) {
       int occurrenciesInDossier =
           getAnalyticalDriverOccurrenciesInDossier(dossier, biParameter.getParID());
       for (int c = occurrenciesInDossier; c < emptyOccurrences; c++) {
         BIObjectParameter parameterToBeAdded =
             getEmptyOccurrence(biParameter, configuredDocumentParameters, parameters, c);
         addBIObjectParameterToDossier(dossier, parameterToBeAdded);
       }
     }
   }
   logger.debug("OUT");
 }
 private void detailConfiguredDocumentHandler(SourceBean request, SourceBean response)
     throws Exception {
   logger.debug("IN");
   String tempFolder = (String) request.getAttribute(DossierConstants.DOSSIER_TEMP_FOLDER);
   String confDocIdent = (String) request.getAttribute("configureddocumentidentifier");
   // get configured document
   IDossierDAO dossierDao = new DossierDAOHibImpl();
   ConfiguredBIDocument confDoc = dossierDao.getConfiguredDocument(confDocIdent, tempFolder);
   // get parameter value map
   Map paramValueMap = confDoc.getParameters();
   // create parameter name map
   //		Integer idobj = confDoc.getId();
   String label = confDoc.getLabel();
   BIObject obj = DAOFactory.getBIObjectDAO().loadBIObjectByLabel(label);
   Integer idobj = obj.getId();
   IBIObjectParameterDAO biobjpardao = DAOFactory.getBIObjectParameterDAO();
   List params = biobjpardao.loadBIObjectParametersById(idobj);
   Iterator iterParams = params.iterator();
   Map paramNameMap = new HashMap();
   while (iterParams.hasNext()) {
     BIObjectParameter par = (BIObjectParameter) iterParams.next();
     String parLabel = par.getLabel();
     String parUrlName = par.getParameterUrlName();
     paramNameMap.put(parLabel, parUrlName);
   }
   // 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 List<BIObjectParameter> getRelevantContainedDocumentAnalyticalDrivers(
     BIObjectParameter dossierParameter, BIObject containedDocument) {
   List<BIObjectParameter> toReturn = new ArrayList<BIObjectParameter>();
   logger.debug("IN");
   List containedDocumentParameters = containedDocument.getBiObjectParameters();
   if (containedDocumentParameters != null && containedDocumentParameters.size() > 0) {
     Iterator it = containedDocumentParameters.iterator();
     while (it.hasNext()) {
       BIObjectParameter containedDocumentParameter = (BIObjectParameter) it.next();
       if (containedDocumentParameter.getParID().equals(dossierParameter.getParID())) {
         toReturn.add(containedDocumentParameter);
       }
     }
   }
   logger.debug("OUT");
   return toReturn;
 }
  /** This action is called by the user who wants to export the result of a Kpi in PDF */
  public void service(SourceBean serviceRequest, SourceBean serviceResponse) throws Exception {

    File tmpFile = null;
    logger.debug("IN");
    HttpServletRequest httpRequest = getHttpRequest();
    HttpSession session = httpRequest.getSession();

    this.freezeHttpResponse();

    try {
      // get KPI result
      List<KpiResourceBlock> listKpiBlocks =
          (List<KpiResourceBlock>) session.getAttribute("KPI_BLOCK");

      // List<KpiResourceBlock> listKpiBlocks=executeKpi(objectId);

      // recover BiObject Name
      Object idObject = serviceRequest.getAttribute(SpagoBIConstants.OBJECT_ID);
      if (idObject == null) {
        logger.error("Document id not found");
        return;
      }

      Integer id = Integer.valueOf(idObject.toString());
      BIObject document = DAOFactory.getBIObjectDAO().loadBIObjectById(id);
      String docName = document.getName();

      // Recover user Id
      HashedMap parameters = new HashedMap();
      String userId = null;
      Object userIdO = serviceRequest.getAttribute("user_id");
      if (userIdO != null) userId = userIdO.toString();

      it.eng.spagobi.engines.exporters.KpiExporter exporter = new KpiExporter();
      tmpFile = exporter.getKpiReportPDF(listKpiBlocks, document, userId);

      String outputType = "PDF";

      String mimeType = "application/pdf";

      logger.debug("Report exported succesfully");

      HttpServletResponse response = getHttpResponse();
      response.setContentType(mimeType);
      response.setHeader("Content-Disposition", "filename=\"report." + outputType + "\";");
      response.setContentLength((int) tmpFile.length());

      BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
      int b = -1;
      while ((b = in.read()) != -1) {
        response.getOutputStream().write(b);
      }
      response.getOutputStream().flush();
      in.close();
      logger.debug("OUT");

    } catch (Throwable e) {
      logger.error("An exception has occured", e);
      throw new Exception(e);
    } finally {

      tmpFile.delete();
    }
  }
Exemple #24
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);
  }
  @POST
  @Produces(MediaType.TEXT_HTML)
  // TODO: change produced output
  public String insertValues(@Context HttpServletRequest req) {
    try {
      IEngUserProfile profile =
          (IEngUserProfile) req.getSession().getAttribute(IEngUserProfile.ENG_USER_PROFILE);
      if (profile == null) {
        return "User must be logged in";
      }
      String userId = (String) profile.getUserUniqueIdentifier();
      IBIObjectDAO sbiObjectsDAO = DAOFactory.getBIObjectDAO();
      BIObject document = sbiObjectsDAO.loadBIObjectByLabel("EII_RPT_0015_frc"); // TODO: to change
      Integer documentId = document.getId();
      List enabledRoles = sbiObjectsDAO.getCorrectRolesForExecution(documentId, profile);
      // check if current user can see this document
      if ((enabledRoles != null) && (enabledRoles.size() > 0)) {
        // Get fixed parameters values
        String year = req.getParameter("par_year");
        String closureCode = req.getParameter("par_closure_cd");
        String businessAreaCode = req.getParameter("par_ba");
        String businessUnitCode = req.getParameter("par_bu");
        String cdc = req.getParameter("par_cdc");

        String ricavi = req.getParameter("Ricavi_resValue");
        String ricaviVarPer = req.getParameter("Ricavi_variationPerc");
        if (ricaviVarPer == null) {
          ricaviVarPer = "0";
        }
        String ricaviVarAbs = req.getParameter("Ricavi_variationAbsolute");
        if (ricaviVarAbs == null) {
          ricaviVarAbs = "0";
        }

        String primoMargine = req.getParameter("PM_resValue");
        String primoMargineVarPer = req.getParameter("PM_variationPerc");
        if (primoMargineVarPer == null) {
          primoMargineVarPer = "0";
        }
        String primoMargineVarAbs = req.getParameter("PM_variationAbsolute");
        if (primoMargineVarAbs == null) {
          primoMargineVarAbs = "0";
        }

        String margineContribuzione = req.getParameter("MC_resValue");
        String margineContribuzioneVarPer = req.getParameter("MC_variationPerc");
        if (margineContribuzioneVarPer == null) {
          margineContribuzioneVarPer = "0";
        }
        String margineContribuzioneVarAbs = req.getParameter("MC_variationAbsolute");
        if (margineContribuzioneVarAbs == null) {
          margineContribuzioneVarAbs = "0";
        }

        // ----------------------

        // 2- Insert values on database
        persistValues(
            businessUnitCode,
            businessAreaCode,
            cdc,
            year,
            closureCode,
            userId,
            ricavi,
            primoMargine,
            margineContribuzione,
            ricaviVarPer,
            ricaviVarAbs,
            primoMargineVarPer,
            primoMargineVarAbs,
            margineContribuzioneVarPer,
            margineContribuzioneVarAbs);

        return "<b>Values Updated</b>";

        // Uncomment next line for test
        // return printSubmittedValues(req);

      } else {
        // User cannot execute operation
        return "Operation forbidden";
      }

    } catch (Exception e) {
      logger.error("An unexpected error occured while executing Forecast Edit");
      throw new SpagoBIServiceException(
          "An unexpected error occured while executing Forecast Edit", e);
    }
  }
  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;
  }