// public SessionFactory newSessionFactory(Configuration config) throws HibernateException {
  public Configuration newConfiguration() throws HibernateException {
    Configuration config = super.newConfiguration();

    log.debug("Configuring hibernate sessionFactory properties");

    Properties moduleProperties = Context.getConfigProperties();

    // override or initialize config properties with module-provided ones
    for (Object key : moduleProperties.keySet()) {
      String prop = (String) key;
      String value = (String) moduleProperties.get(key);
      log.trace("Setting module property: " + prop + ":" + value);
      config.setProperty(prop, value);
      if (!prop.startsWith("hibernate")) config.setProperty("hibernate." + prop, value);
    }

    Properties properties = Context.getRuntimeProperties();

    // loop over runtime properties and override each in the configuration
    for (Object key : properties.keySet()) {
      String prop = (String) key;
      String value = (String) properties.get(key);
      log.trace("Setting property: " + prop + ":" + value);
      config.setProperty(prop, value);
      if (!prop.startsWith("hibernate")) config.setProperty("hibernate." + prop, value);
    }

    // load in the default hibernate properties
    try {
      InputStream propertyStream =
          ConfigHelper.getResourceAsStream("/hibernate.default.properties");
      Properties props = new Properties();
      OpenmrsUtil.loadProperties(props, propertyStream);
      propertyStream.close();

      // Only load in the default properties if they don't exist
      config.mergeProperties(props);
    } catch (IOException e) {
      log.fatal("Unable to load default hibernate properties", e);
    }

    log.debug(
        "Setting global Hibernate Session Interceptor for SessionFactory, Interceptor: "
            + chainingInterceptor);

    // make sure all autowired interceptors are put onto our chaining interceptor
    // sort on the keys so that the devs/modules have some sort of control over the order of the
    // interceptors
    List<String> keys = new ArrayList<String>(interceptors.keySet());
    Collections.sort(keys);
    for (String key : keys) {
      chainingInterceptor.addInterceptor(interceptors.get(key));
    }

    config.setInterceptor(chainingInterceptor);

    return config;
  }
예제 #2
0
  /**
   * @return true/false whether the 'allow upload' or 'allow web admin' property has been turned on
   */
  public static Boolean allowAdmin() {

    Properties properties = Context.getRuntimeProperties();
    String prop = properties.getProperty(ModuleConstants.RUNTIMEPROPERTY_ALLOW_UPLOAD, null);
    if (prop == null)
      prop = properties.getProperty(ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN, "false");

    return "true".equals(prop);
  }
예제 #3
0
  /** @see {@link org.openmrs.module.ModuleUtil#checkOpenmrsCoreModulesStarted()} */
  @Test(expected = OpenmrsCoreModuleException.class)
  @Verifies(
      value = "should throw ModuleException if a core module is not started",
      method = "checkOpenmrsCoreModulesStarted()")
  public void checkMandatoryModulesStarted_shouldThrowModuleExceptionIfACoreModuleIsNotStarted()
      throws Exception {
    // given
    assertThat(ModuleFactory.getStartedModules(), empty());
    assertThat(ModuleConstants.CORE_MODULES.keySet(), contains("logic"));

    initialRuntimeProperties = new Properties(Context.getRuntimeProperties());
    Properties runtimeProperties = Context.getRuntimeProperties();
    runtimeProperties.setProperty(ModuleConstants.IGNORE_CORE_MODULES_PROPERTY, "false");
    Context.setRuntimeProperties(runtimeProperties);

    // when
    ModuleUtil.checkOpenmrsCoreModulesStarted();

    // then exception
  }
  private static Connection connect(String url) throws SQLException {
    // Step 1: Load the JDBC driver.
    try {
      DatabaseUtil.loadDatabaseDriver(url);
    } catch (ClassNotFoundException e) {
      log.error("Could not find JDBC driver class.", e);
      throw (SQLException) e.fillInStackTrace();
    }

    // Step 2: Establish the connection to the database.
    String username = Context.getRuntimeProperties().getProperty("connection.username");
    String password = Context.getRuntimeProperties().getProperty("connection.password");
    log.debug(
        "connecting to DATABASE: "
            + OpenmrsConstants.DATABASE_NAME
            + " USERNAME: "******" URL: "
            + url);
    return DriverManager.getConnection(url, username, password);
  }
예제 #5
0
  /**
   * Does the work of adding UUIDs to all rows.
   *
   * @see liquibase.change.custom.CustomTaskChange#execute(liquibase.database.Database)
   */
  @Override
  public void execute(Database database) throws CustomChangeException {

    // if we're in a "generate sql file" mode, quit early
    if (Context.getRuntimeProperties().size() == 0) return;

    if (tableNamesArray == null || tableNamesArray.length == 0)
      throw new CustomChangeException(
          "At least one table name in the 'tableNames' parameter is required", null);

    JdbcConnection connection = (JdbcConnection) database.getConnection();

    // loop over all tables
    for (String tableName : tableNamesArray) {
      try {
        Statement idStatement = null;
        PreparedStatement updateStatement = null;
        try {
          String idSql = genericIdSql.replaceAll("tablename", tableName);
          String updateSql = genericUpdateSql.replaceAll("tablename", tableName);

          // hacky way to deal with tables that don't follow the tableNam_id convention
          for (Map.Entry<String, String> idException : idExceptionsMap.entrySet()) {
            idSql = idSql.replaceFirst(idException.getKey(), idException.getValue());
            updateSql = updateSql.replaceFirst(idException.getKey(), idException.getValue());
          }
          idStatement = connection.createStatement();
          updateStatement = connection.prepareStatement(updateSql);

          // Map<Integer, UUID> uuids = new HashMap<Integer, UUID>();

          ResultSet ids = idStatement.executeQuery(idSql);
          while (ids.next()) {
            updateStatement.setObject(2, ids.getObject(1)); // set the primary key number
            updateStatement.setString(1, UUID.randomUUID().toString()); // set the uuid for this row
            updateStatement.executeUpdate();
          }
        } finally {
          if (idStatement != null) idStatement.close();
          if (updateStatement != null) updateStatement.close();
        }

      } catch (DatabaseException e) {
        throw new CustomChangeException("Unable to set uuid on table: " + tableName, e);
      } catch (SQLException e) {
        throw new CustomChangeException("Unable to set uuid on table: " + tableName, e);
      }
    }
  }
예제 #6
0
  /**
   * Gets the folder where modules are stored. ModuleExceptions are thrown on errors
   *
   * @return folder containing modules
   * @should use the runtime property as the first choice if specified
   * @should return the correct file if the runtime property is an absolute path
   */
  public static File getModuleRepository() {

    String folderName =
        Context.getRuntimeProperties()
            .getProperty(ModuleConstants.REPOSITORY_FOLDER_RUNTIME_PROPERTY);
    if (StringUtils.isBlank(folderName)) {
      AdministrationService as = Context.getAdministrationService();
      folderName =
          as.getGlobalProperty(
              ModuleConstants.REPOSITORY_FOLDER_PROPERTY,
              ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT);
    }
    // try to load the repository folder straight away.
    File folder = new File(folderName);

    // if the property wasn't a full path already, assume it was intended to be a folder in the
    // application directory
    if (!folder.exists()) {
      folder = new File(OpenmrsUtil.getApplicationDataDirectory(), folderName);
    }

    // now create the modules folder if it doesn't exist
    if (!folder.exists()) {
      log.warn(
          "Module repository "
              + folder.getAbsolutePath()
              + " doesn't exist.  Creating directories now.");
      folder.mkdirs();
    }

    if (!folder.isDirectory())
      throw new ModuleException(
          "Module repository is not a directory at: " + folder.getAbsolutePath());

    return folder;
  }
  public static File generate(HrReport report, String outputFormat, String jrxmlUrl)
      throws IOException {

    String url = Context.getRuntimeProperties().getProperty("connection.url", null);
    Connection conn;
    try {
      conn = connect(url);
    } catch (SQLException e) {
      log.error("Error connecting to DB.", e);
      return null;
    }
    Map<String, Object> map = new HashMap<String, Object>();
    for (HrReportParameter reportParameter : report.getParameters()) {
      if (reportParameter != null)
        if (reportParameter.getName() != null)
          map.put(reportParameter.getName(), reportParameter.getValue());
    }
    log.debug("Report parameter map: " + map);
    String exportPath = OpenmrsUtil.getApplicationDataDirectory();
    URL resourceUrl = new URL(jrxmlUrl);
    InputStream is = resourceUrl.openStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    FileWriter appDirJrxml = new FileWriter(new File(exportPath + report.getFileName()));
    BufferedWriter bw = new BufferedWriter(appDirJrxml);
    String line;
    while ((line = br.readLine()) != null) {
      bw.write(line);
      bw.write("\n");
    }
    bw.flush();
    bw.close();
    JasperPrint jasperPrint = null;
    try {
      JasperDesign jasperDesign = JRXmlLoader.load(exportPath + report.getFileName());
      JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
      jasperPrint = JasperFillManager.fillReport(jasperReport, map, conn);
      if (outputFormat.equals("PDF")) {
        File pdfFile =
            new File(
                exportPath
                    + report.getName()
                    + new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss").format(new Date())
                    + ".pdf");
        JasperExportManager.exportReportToPdfFile(jasperPrint, pdfFile.getAbsolutePath());
        return pdfFile;
      } else if (outputFormat.equals("Excel")) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        File outputfile =
            new File(
                exportPath
                    + report.getName()
                    + new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss").format(new Date())
                    + ".xls");
        OutputStream outputfileStream = new FileOutputStream(outputfile);
        JRXlsExporter exporterXLS = new JRXlsExporter();
        exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
        exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, output);
        exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
        exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
        exporterXLS.setParameter(
            JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
        exporterXLS.exportReport();
        outputfileStream.write(output.toByteArray());
        outputfileStream.flush();
        outputfileStream.close();
        return outputfile;
      }
    } catch (JRException e) {
      log.error("Error generating report", e);
    } finally {
      try {
        if (!conn.isClosed()) {
          conn.close();
        }
      } catch (SQLException e) {
        log.error("Exception closing report connection.", e);
      }
    }
    return null;
  }
예제 #8
0
 /**
  * Uses the runtime properties to determine if the core modules should be enforced or not.
  *
  * @return true if the core modules list can be ignored.
  */
 public static boolean ignoreCoreModules() {
   String ignoreCoreModules =
       Context.getRuntimeProperties()
           .getProperty(ModuleConstants.IGNORE_CORE_MODULES_PROPERTY, "false");
   return Boolean.parseBoolean(ignoreCoreModules);
 }