Exemple #1
0
  private Locale getLocale() {
    logger.debug("IN");
    try {
      Locale locale = null;

      if (RequestContainer.getRequestContainer() != null) {
        RequestContainer requestContainer = RequestContainer.getRequestContainer();
        SessionContainer permanentSession =
            requestContainer.getSessionContainer().getPermanentContainer();
        String language = (String) permanentSession.getAttribute(SpagoBIConstants.AF_LANGUAGE);
        String country = (String) permanentSession.getAttribute(SpagoBIConstants.AF_COUNTRY);
        logger.debug(
            "Language retrieved: [" + language + "]; country retrieved: [" + country + "]");
        locale = new Locale(language, country);
      } else {
        locale = GeneralUtilities.getDefaultLocale();
      }
      return locale;
    } catch (Exception e) {
      logger.error("Error while getting locale; using default one", e);
      return GeneralUtilities.getDefaultLocale();
    } finally {
      logger.debug("OUT");
    }
  }
  protected Map<String, String> buildWorksheetEditServiceBaseParametersMap() {
    HashMap<String, String> parametersMap = new HashMap<String, String>();

    parametersMap.put("ACTION_NAME", WORKSHEET_EDIT_ACTION);
    parametersMap.put("NEW_SESSION", "TRUE");

    parametersMap.put(SpagoBIConstants.SBI_CONTEXT, GeneralUtilities.getSpagoBiContext());
    parametersMap.put(SpagoBIConstants.SBI_HOST, GeneralUtilities.getSpagoBiHost());

    parametersMap.put(SpagoBIConstants.SBI_LANGUAGE, getLocale().getLanguage());
    parametersMap.put(SpagoBIConstants.SBI_COUNTRY, getLocale().getCountry());

    // if (!GeneralUtilities.isSSOEnabled()) {
    UserProfile userProfile = (UserProfile) getUserProfile();
    parametersMap.put(SsoServiceInterface.USER_ID, (String) userProfile.getUserUniqueIdentifier());
    // }

    return parametersMap;
  }
  public Object serialize(Object o, Locale locale) throws SerializationException {
    JSONObject result = null;

    if (!(o instanceof Goal)) {
      throw new SerializationException(
          "GoalJSONSerializer is unable to serialize object of type: " + o.getClass().getName());
    }

    try {
      Goal goal = (Goal) o;
      result = new JSONObject();
      result.put(ID, goal.getId());
      result.put(NAME, goal.getName());
      result.put(DESCRIPTION, goal.getDescription());
      result.put(LABEL, goal.getLabel());
      String df = GeneralUtilities.getServerDateFormat();
      SimpleDateFormat dateFormat = new SimpleDateFormat();
      dateFormat.applyPattern(df);
      dateFormat.setLenient(false);
      result.put(START_DATE, dateFormat.format(goal.getStartDate()));
      result.put(END_DATE, dateFormat.format(goal.getEndDate()));

      if (goal.getGrant() != null) {

        OrganizationalUnitGrant grant =
            DAOFactory.getOrganizationalUnitDAO().getGrant(goal.getGrant());
        result.put(GRANT_ID, goal.getGrant());
        result.put(GRANT_NAME, grant.getName());
      }

    } catch (Throwable t) {
      throw new SerializationException("An error occurred while serializing object: " + o, t);
    }

    return result;
  }
  private void loadPresentationTemplateHandler(SourceBean request, SourceBean response)
      throws SourceBeanException, EMFUserError {
    logger.debug("IN");
    try {
      String tempFolder = (String) request.getAttribute(DossierConstants.DOSSIER_TEMP_FOLDER);
      IDossierDAO dossierDao = new DossierDAOHibImpl();
      FileItem upFile = (FileItem) request.getAttribute("UPLOADED_FILE");
      if (upFile != null) {
        String fileName = GeneralUtilities.getRelativeFileNames(upFile.getName());
        if (upFile.getSize() == 0) {
          EMFValidationError error =
              new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "201");
          getErrorHandler().addError(error);
          return;
        }
        int maxSize = GeneralUtilities.getTemplateMaxSize();
        if (upFile.getSize() > maxSize) {
          EMFValidationError error =
              new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "202");
          getErrorHandler().addError(error);
          return;
        }
        if (!fileName.toUpperCase().endsWith(".PPT")) {
          List params = new ArrayList();
          params.add("ppt");
          EMFUserError error =
              new EMFValidationError(
                  EMFErrorSeverity.ERROR,
                  "UPLOADED_FILE",
                  "107",
                  params,
                  null,
                  "component_dossier_messages");
          getErrorHandler().addError(error);
        } else {
          byte[] fileContent = upFile.get();
          dossierDao.storePresentationTemplateFile(fileName, fileContent, tempFolder);
        }
      } else {
        logger.warn("Upload file was null!!!");
      }

      //			UploadedFile upFile = (UploadedFile) request.getAttribute("UPLOADED_FILE");
      //			if (upFile != null) {
      //				String fileName = upFile.getFileName();
      //				if (!fileName.toUpperCase().endsWith(".PPT")) {
      //					List params = new ArrayList();
      //					params.add("ppt");
      //					EMFUserError error = new EMFValidationError(EMFErrorSeverity.ERROR, "UPLOADED_FILE",
      // "107", params, null, "component_dossier_messages");
      //					getErrorHandler().addError(error);
      //				} else {
      //					byte[] fileContent = upFile.getFileContent();
      //					dossierDao.storePresentationTemplateFile(fileName, fileContent, tempFolder);
      //				}
      //			} else {
      //				logger.warn("Upload file was null!!!");
      //			}
      response.setAttribute(DossierConstants.PUBLISHER_NAME, "DossierLoopbackDossierDetail");
    } finally {
      logger.debug("OUT");
    }
  }
  @Override
  public void doService() {

    DatasetManagementAPI creationUtilities;
    IDataSet datasetBean;

    logger.debug("IN");

    try {

      // create the input parameters to pass to the WorkSheet Edit Service
      Map worksheetEditActionParameters = buildWorksheetEditServiceBaseParametersMap();

      String executionId = ExecuteAdHocUtility.createNewExecutionId();
      worksheetEditActionParameters.put("SBI_EXECUTION_ID", executionId);

      Engine worksheetEngine = getWorksheetEngine();
      LogMF.debug(logger, "Engine label is equal to [{0}]", worksheetEngine.getLabel());

      IDataSource datasource;
      try {
        datasource = DAOFactory.getDataSourceDAO().loadDataSourceWriteDefault();
      } catch (EMFUserError e) {
        throw new SpagoBIRuntimeException("Error while loading default datasource for writing", e);
      }
      if (datasource != null) {
        LogMF.debug(logger, "Datasource label is equal to [{0}]", datasource.getLabel());
        worksheetEditActionParameters.put(
            EngineConstants.DEFAULT_DATASOURCE_FOR_WRITING_LABEL, datasource.getLabel());
      } else {
        logger.debug("There is no default datasource for writing");
      }

      datasetBean = getDatasetAttributesFromRequest();
      worksheetEditActionParameters.put("dataset_label", datasetBean.getLabel());

      Map<String, String> datasetParameterValuesMap = getDatasetParameterValuesMapFromRequest();
      worksheetEditActionParameters.putAll(datasetParameterValuesMap);

      // create the WorkSheet Edit Service's URL
      String worksheetEditActionUrl =
          GeneralUtilities.getUrl(worksheetEngine.getUrl(), worksheetEditActionParameters);
      LogMF.debug(
          logger, "Worksheet edit service invocation url is equal to [{}]", worksheetEditActionUrl);

      // create the dataset
      logger.trace("Creating the dataset...");
      Integer datasetId = null;
      try {
        creationUtilities = new DatasetManagementAPI();
        datasetId = creationUtilities.creatDataSet(datasetBean);
        Assert.assertNotNull(datasetId, "Dataset Id cannot be null");
      } catch (Throwable t) {
        throw new SpagoBIServiceException(
            SERVICE_NAME,
            "An error occurred while creating dataset from bean [" + datasetBean + "]",
            t);
      }
      LogMF.debug(logger, "Datset [{0}]succesfully created with id [{1}]", datasetBean, datasetId);

      logger.trace("Copying output parameters to response...");
      try {
        getServiceResponse().setAttribute(OUTPUT_PARAMETER_EXECUTION_ID, executionId);
        getServiceResponse()
            .setAttribute(OUTPUT_PARAMETER_WORKSHEET_EDIT_SERVICE_URL, worksheetEditActionUrl);
        getServiceResponse().setAttribute(OUTPUT_PARAMETER_DATASET_LABEL, datasetBean.getLabel());
        getServiceResponse()
            .setAttribute(OUTPUT_PARAMETER_DATASET_PARAMETERS, datasetParameterValuesMap);

        // business metadata
        JSONObject businessMetadata = getBusinessMetadataFromRequest();
        if (businessMetadata != null) {
          getServiceResponse()
              .setAttribute(OUTPUT_PARAMETER_BUSINESS_METADATA, businessMetadata.toString());
        }
      } catch (Throwable t) {
        throw new SpagoBIServiceException(
            SERVICE_NAME,
            "An error occurred while creating dataset from bean [" + datasetBean + "]",
            t);
      }
      logger.trace("Output parameter succesfully copied to response");

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