protected Engine getEngineByDocumentType(String type) {
    Engine engine;
    List<Engine> engines;

    engine = null;
    try {
      Assert.assertNotNull(DAOFactory.getEngineDAO(), "EngineDao cannot be null");
      engines = DAOFactory.getEngineDAO().loadAllEnginesForBIObjectType(type);
      if (engines == null || engines.size() == 0) {
        throw new SpagoBIServiceException(
            SERVICE_NAME, "There are no engines for documents of type [" + type + "] available");
      } else {
        engine = engines.get(0);
        if (engines.size() > 1) {
          LogMF.warn(
              logger,
              "There are more than one engine for document of type [WORKSHEET]. We will use the one whose label is equal to [{0}]",
              engine.getLabel());
        } else {
          LogMF.debug(logger, "Using worksheet engine with label [{0}]", engine.getLabel());
        }
      }
    } catch (Throwable t) {
      throw new SpagoBIServiceException(
          SERVICE_NAME, "Impossible to load a valid engine for document of type [WORKSHEET]", t);
    } finally {
      logger.debug("OUT");
    }

    return engine;
  }
 protected void setTenant() {
   logger.debug("IN");
   try {
     IEngUserProfile profile = getUserProfile();
     Assert.assertNotNull(profile, "Input parameter [profile] cannot be null");
     UserProfile userProfile = (UserProfile) profile;
     String tenant = userProfile.getOrganization();
     LogMF.debug(logger, "Tenant: [{0}]", tenant);
     TenantManager.setTenant(new Tenant(tenant));
     LogMF.debug(logger, "Tenant [{0}] set properly", tenant);
   } catch (Throwable t) {
     logger.error("Cannot set tenant", t);
     throw new SpagoBIRuntimeException("Cannot set tenant", t);
   } finally {
     logger.debug("OUT");
   }
 }
  /**
   * Creates a table with columns got from metadata. PAY ATTENTION TO THE FACT THAT THE INPUT
   * CONNECTION WON'T BE CLOSED!!!!!
   *
   * @param conn The JDBC connection to be used
   * @param meta The metadata of the dataset to be persisted on the database
   * @param tableName The name of the table to be created
   * @param list The list of the fields of the dataset to be included on table
   * @return A DataSetTableDescriptor that contains the association between table's columns and
   *     dataset's fields.
   */
  public static DataSetTableDescriptor createTemporaryTable(
      Connection conn, IMetaData meta, String tableName, List<String> selectedFields) {
    logger.debug("IN");

    DataSetTableDescriptor dstd = null;
    Statement st = null;
    String sqlQuery = null;

    if (selectedFields == null) {
      selectedFields = new ArrayList<String>();
    }

    try {
      CreateTableCommand createTableCommand =
          new CreateTableCommand(tableName, conn.getMetaData().getDriverName());

      // run through all columns in order to build the SQL columndefinition
      int count = meta.getFieldCount();
      logger.debug("The table tableName has " + count + " columns ");
      for (int i = 0; i < count; i++) {
        IFieldMetaData fieldMeta = meta.getFieldMeta(i);
        String fieldName = fieldMeta.getName();
        if (selectedFields.isEmpty() || selectedFields.contains(fieldName)) {
          createTableCommand.addColumn(fieldMeta);
        }
      }

      // after built columns create SQL Query
      sqlQuery = createTableCommand.createSQLQuery();

      // execute
      logger.debug("Executing the query " + sqlQuery + "...");
      st = conn.createStatement();
      st.execute(sqlQuery);
      logger.debug("Query executed");
      dstd = createTableCommand.getDsTableDescriptor();
      LogMF.debug(logger, "The query descriptor is {0}", dstd);

    } catch (SQLException e) {
      logger.error("Error in excuting statement " + sqlQuery, e);
      throw new SpagoBIRuntimeException("Error creating temporary table", e);
    } finally {
      try {
        if (st != null) {
          st.close();
        }
      } catch (SQLException e) {
        logger.error("could not free resources ", e);
      }
    }
    logger.debug("OUT");
    return dstd;
  }
  @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");
    }
  }
  /**
   * Read dataset's attributes from request and save them in a bean object.
   *
   * @return GuiGenericDataSet the bean object that collect all the dataset attributes read from
   *     request.
   */
  private IDataSet getDatasetAttributesFromRequest() {

    IDataSet datasetBean;

    String label;
    String name;
    String description;
    String customData;
    String jClassName;
    String metadata;
    String parametersDefinitionJson;
    String parametersDefinitionXML;

    logger.debug("IN");

    datasetBean = null;

    try {
      logger.trace("Reading from request attributes used to build the new dataset...");

      LogMF.trace(logger, "Reading input parametr [{0}] from request...", INPUT_PARAMETER_DS_LABEL);
      label = getAttributeAsString(INPUT_PARAMETER_DS_LABEL);
      LogMF.debug(
          logger, "Input parameter [{0}] is equal to [{1}]", INPUT_PARAMETER_DS_LABEL, label);
      Assert.assertNotNull(
          label, "Input parameter [" + INPUT_PARAMETER_DS_LABEL + "] cannot be null");

      LogMF.trace(logger, "Reading input parametr [{0}] from request...", INPUT_PARAMETER_DS_NAME);
      name = getAttributeAsString(INPUT_PARAMETER_DS_NAME);
      LogMF.debug(
          logger, "Input parameter [{0}] is equal to [{1}]", INPUT_PARAMETER_DS_LABEL, name);

      LogMF.trace(
          logger, "Reading input parametr [{0}] from request...", INPUT_PARAMETER_DS_DESCRIPTION);
      description = getAttributeAsString(INPUT_PARAMETER_DS_DESCRIPTION);
      LogMF.debug(
          logger,
          "Input parameter [{0}] is equal to [{1}]",
          INPUT_PARAMETER_DS_DESCRIPTION,
          description);

      LogMF.trace(
          logger, "Reading input parametr [{0}] from request...", INPUT_PARAMETER_DS_CUSTOM_DATA);
      customData = getAttributeAsString(INPUT_PARAMETER_DS_CUSTOM_DATA);
      LogMF.debug(
          logger,
          "Input parameter [{0}] is equal to [{1}]",
          INPUT_PARAMETER_DS_CUSTOM_DATA,
          customData);

      LogMF.trace(
          logger, "Reading input parametr [{0}] from request...", INPUT_PARAMETER_DS_JCLASS_NAME);
      jClassName = getAttributeAsString(INPUT_PARAMETER_DS_JCLASS_NAME);
      LogMF.debug(
          logger,
          "Input parameter [{0}] is equal to [{1}]",
          INPUT_PARAMETER_DS_JCLASS_NAME,
          jClassName);

      LogMF.trace(
          logger, "Reading input parametr [{0}] from request...", INPUT_PARAMETER_DS_METADATA);
      metadata = getAttributeAsString(INPUT_PARAMETER_DS_METADATA);
      LogMF.debug(
          logger, "Input parameter [{0}] is equal to [{1}]", INPUT_PARAMETER_DS_METADATA, metadata);

      LogMF.trace(
          logger,
          "Reading input parametr [{0}] from request...",
          INPUT_PARAMETER_DS_PARAMETER_DEFINITION);
      parametersDefinitionJson = getAttributeAsString(INPUT_PARAMETER_DS_PARAMETER_DEFINITION);
      LogMF.debug(
          logger,
          "Input parameter [{0}] is equal to [{1}]",
          INPUT_PARAMETER_DS_METADATA,
          parametersDefinitionJson);

      parametersDefinitionXML = null;
      if (!StringUtilities.isEmpty(parametersDefinitionJson)) {
        LogMF.trace(
            logger,
            "Coverting input parameter [{0}] from JSON format to XML format ...",
            INPUT_PARAMETER_DS_PARAMETER_DEFINITION);
        parametersDefinitionXML = parametersJsonToXML(parametersDefinitionJson);
        LogMF.trace(
            logger,
            "Input parameter [{0}] succesfully converted to xml formt [{1}]",
            INPUT_PARAMETER_DS_PARAMETER_DEFINITION,
            parametersDefinitionXML);
      }

      logger.trace("Attributes used to build the new dataset succesfully read from request");

      logger.trace("Building the dataset bean...");

      datasetBean = new CustomDataSet();
      datasetBean.setLabel(label);
      datasetBean.setName(name);
      datasetBean.setDescription(description);

      ((CustomDataSet) datasetBean).setCustomData(customData);
      ((CustomDataSet) datasetBean).setJavaClassName(jClassName);
      datasetBean.setParameters(parametersDefinitionXML);
      datasetBean.setDsType(DataSetConstants.DS_CUSTOM);
      if (!StringUtilities.isEmpty(metadata)) {
        datasetBean.setDsMetadata(metadata);
      }

      try {
        JSONObject jsonConf = new JSONObject();
        jsonConf.put(CUSTOM_DATA, customData);
        jsonConf.put(JCLASS_NAME, jClassName);
        jsonConf.put(DataSetConstants.PARS, parametersDefinitionXML);
        jsonConf.put(DataSetConstants.DS_CUSTOM, DataSetConstants.DS_CUSTOM);
        jsonConf.put(DataSetConstants.DS_TYPE_CD, DataSetConstants.DS_CUSTOM);
        datasetBean.setConfiguration(jsonConf.toString());
      } catch (Exception e) {
        logger.error("Error while defining dataset configuration.  Error: " + e.getMessage());
      }

      logger.trace("Dataset bean succesfully built");

    } catch (Throwable t) {
      throw new SpagoBIServiceException(
          SERVICE_NAME,
          "Impossible to read from request all parameters required to create the new dataset",
          t);
    } finally {
      logger.debug("OUT");
    }

    return datasetBean;
  }