@Bean
  LocalContainerEntityManagerFactoryBean entityManagerFactory(
      DataSource dataSource, Environment env) {

    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean =
        new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource(dataSource);
    entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    entityManagerFactoryBean.setPackagesToScan("es.udc.lbd.rie");

    Properties jpaProperties = new Properties();

    // Configures the used database dialect. This allows Hibernate to create SQL
    // that is optimized for the used database.
    jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));

    // Configures the naming strategy that is used when Hibernate creates
    // new database objects and schema elements
    jpaProperties.put(
        "hibernate.ejb.naming_strategy", env.getRequiredProperty("hibernate.ejb.naming_strategy"));

    // If the value of this property is true, Hibernate writes all SQL
    // statements to the console.
    jpaProperties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));

    // If the value of this property is true, Hibernate will format the SQL
    // that is written to the console.
    jpaProperties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));

    entityManagerFactoryBean.setJpaProperties(jpaProperties);

    return entityManagerFactoryBean;
  }
Esempio n. 2
1
  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
      throws ClassNotFoundException {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean =
        new LocalContainerEntityManagerFactoryBean();

    entityManagerFactoryBean.setDataSource(dataSource());
    entityManagerFactoryBean.setPackagesToScan(
        environment.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
    entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);

    Properties jpaProterties = new Properties();
    jpaProterties.put(
        PROPERTY_NAME_HIBERNATE_DIALECT,
        environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
    jpaProterties.put(
        PROPERTY_NAME_HIBERNATE_FORMAT_SQL,
        environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
    jpaProterties.put(
        PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY,
        environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
    jpaProterties.put(
        PROPERTY_NAME_HIBERNATE_SHOW_SQL,
        environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

    entityManagerFactoryBean.setJpaProperties(jpaProterties);

    return entityManagerFactoryBean;
  }
  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean =
        new LocalContainerEntityManagerFactoryBean();

    entityManagerFactoryBean.setDataSource(dataSource());
    entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);

    Properties jpaProperties = new Properties();

    jpaProperties.put(
        PROPERTY_NAME_HIBERNATE_DIALECT,
        environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
    jpaProperties.put(
        PROPERTY_NAME_HIBERNATE_FORMAT_SQL,
        environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
    jpaProperties.put(
        PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO,
        environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
    jpaProperties.put(
        PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY,
        environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
    jpaProperties.put(
        PROPERTY_NAME_HIBERNATE_SHOW_SQL,
        environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

    entityManagerFactoryBean.setJpaProperties(jpaProperties);

    return entityManagerFactoryBean;
  }
 private static String getMessage(
     EmbeddedDatabaseConnection connection, Environment environment, String property) {
   StringBuilder message = new StringBuilder();
   message.append(
       "Cannot determine embedded database "
           + property
           + " for database type "
           + connection
           + ". ");
   message.append(
       "If you want an embedded database please put a supported " + "one on the classpath. ");
   message.append(
       "If you have database settings to be loaded from a "
           + "particular profile you may need to active it");
   if (environment != null) {
     String[] profiles = environment.getActiveProfiles();
     if (ObjectUtils.isEmpty(profiles)) {
       message.append(" (no profiles are currently active)");
     } else {
       message.append(
           " (the profiles \""
               + StringUtils.arrayToCommaDelimitedString(environment.getActiveProfiles())
               + "\" are currently active)");
     }
   }
   message.append(".");
   return message.toString();
 }
  @Bean
  public CacheManager cacheManager() {
    log.debug("Starting Ehcache");
    cacheManager = net.sf.ehcache.CacheManager.create();
    cacheManager
        .getConfiguration()
        .setMaxBytesLocalHeap(
            env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
    log.debug("Registering Ehcache Metrics gauges");
    Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
    for (EntityType<?> entity : entities) {

      String name = entity.getName();
      if (name == null || entity.getJavaType() != null) {
        name = entity.getJavaType().getName();
      }
      Assert.notNull(name, "entity cannot exist without a identifier");

      net.sf.ehcache.Cache cache = cacheManager.getCache(name);
      if (cache != null) {
        cache
            .getCacheConfiguration()
            .setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
        net.sf.ehcache.Ehcache decoratedCache =
            InstrumentedEhcache.instrument(metricRegistry, cache);
        cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
      }
    }
    EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
    ehCacheManager.setCacheManager(cacheManager);
    return ehCacheManager;
  }
 @PostConstruct
 private void initialise() {
   port = environment.getProperty("bookService.port", Integer.class);
   host = environment.getProperty("bookService.host", "localhost");
   objectMapper = createObjectMapper();
   httpClient = createHttpClient();
 }
 private Properties hibernateProperties() {
   Properties properties = new Properties();
   properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
   properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
   properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
   return properties;
 }
Esempio n. 8
0
  @Bean
  public BoneCPDataSource dataSource() {

    BoneCPDataSource dataSource = new BoneCPDataSource();

    dataSource.setDriverClass(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
    dataSource.setJdbcUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
    dataSource.setUsername(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
    dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));

    // https://github.com/wwadge/bonecp/blob/master/bonecp/src/main/resources/bonecp-default-config.xml
    dataSource.setConnectionTestStatement("SELECT 1 FROM DUAL");
    dataSource.setMinConnectionsPerPartition(0);
    dataSource.setMaxConnectionsPerPartition(10);
    dataSource.setMaxConnectionAge(0, TimeUnit.SECONDS);
    dataSource.setConnectionTimeout(5, TimeUnit.SECONDS);
    dataSource.setIdleMaxAge(60, TimeUnit.MINUTES);
    dataSource.setAcquireIncrement(1);
    dataSource.setPartitionCount(1);
    dataSource.setIdleConnectionTestPeriod(240, TimeUnit.MINUTES);
    dataSource.setStatementsCacheSize(500);
    dataSource.setCloseConnectionWatch(false);
    dataSource.setAcquireRetryDelay(7000, TimeUnit.MILLISECONDS);
    dataSource.setAcquireRetryAttempts(5);
    dataSource.setQueryExecuteTimeLimit(1, TimeUnit.MILLISECONDS);
    dataSource.setLazyInit(false);
    dataSource.setLogStatementsEnabled(true);

    return dataSource;
  }
  @Bean(name = "mainDataSource")
  public DataSource dataSource() {

    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    try {
      dataSource.setDriverClass(env.getProperty("jdbc.driverClassName"));
    } catch (PropertyVetoException e) {
      // TODO Auto-generated catch block
      logger.info("PropertyVetoException : {}", e.getMessage());
    }
    dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
    dataSource.setUser(env.getProperty("jdbc.username"));
    dataSource.setPassword(env.getProperty("jdbc.password"));
    dataSource.setAcquireIncrement(20);
    dataSource.setAcquireRetryAttempts(30);
    dataSource.setAcquireRetryDelay(1000);
    dataSource.setAutoCommitOnClose(false);
    dataSource.setDebugUnreturnedConnectionStackTraces(true);
    dataSource.setIdleConnectionTestPeriod(100);
    dataSource.setInitialPoolSize(10);
    dataSource.setMaxConnectionAge(1000);
    dataSource.setMaxIdleTime(200);
    dataSource.setMaxIdleTimeExcessConnections(3600);
    dataSource.setMaxPoolSize(10);
    dataSource.setMinPoolSize(2);
    dataSource.setPreferredTestQuery("select 1");
    dataSource.setTestConnectionOnCheckin(false);
    dataSource.setUnreturnedConnectionTimeout(1000);
    return dataSource;
  }
Esempio n. 10
0
  /**
   * Initializes swank.
   *
   * <p>Spring profiles can be configured with a program arguments
   * --spring.profiles.active=your-active-profile
   *
   * <p>
   *
   * <p>You can find more information on how profiles work with JHipster on <a
   * href="http://jhipster.github.io/profiles.html">http://jhipster.github.io/profiles.html</a>.
   */
  @PostConstruct
  public void initApplication() throws IOException {

    /*        System.out.printf("This is the classpath: %s %n",
        System.getProperty("java.class.path"));
    Set<String> propNames = new TreeSet<String>(System.getProperties().stringPropertyNames());
    for (String propertyName : propNames) {
        System.out.printf("%s is %s %n",
            propertyName,
            System.getProperty(propertyName));
    }*/

    if (env.getActiveProfiles().length == 0) {
      log.warn("No Spring profile configured, running with default configuration");
    } else {
      log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
      Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
      if (activeProfiles.contains("dev") && activeProfiles.contains("prod")) {
        log.error(
            "You have misconfigured your application! "
                + "It should not run with both the 'dev' and 'prod' profiles at the same time.");
      }
      if (activeProfiles.contains("prod") && activeProfiles.contains("fast")) {
        log.error(
            "You have misconfigured your application! "
                + "It should not run with both the 'prod' and 'fast' profiles at the same time.");
      }
      if (activeProfiles.contains("dev") && activeProfiles.contains("cloud")) {
        log.error(
            "You have misconfigured your application! "
                + "It should not run with both the 'dev' and 'cloud' profiles at the same time.");
      }
    }
  }
  /**
   * Get the user preferences from the GPII
   *
   * @param user
   * @return
   * @throws Exception
   */
  private String getPreferencesFromServer(EasitAccount user) throws Exception {

    HttpClient client = new DefaultHttpClient();
    HttpGet request =
        new HttpGet(
            environment.getProperty("flowManager.url")
                + environment.getProperty("flowManager.preferences"));

    // add the access token to the request header
    request.addHeader("Authorization", "Bearer " + user.getAccessToken());
    HttpResponse response = client.execute(request);

    // NOT Correct answer
    if (response.getStatusLine().getStatusCode() != 200) {
      throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

    // Correct answer
    BufferedReader rd =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
      result.append(line);
    }

    logger.info("User preferences:" + result);
    return result.toString();
  }
Esempio n. 12
0
  @Bean
  public BasicDataSource dataSource() {
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(environment.getProperty("jdbc.driverClassName"));
    basicDataSource.setUrl(environment.getProperty("jdbc.url"));
    basicDataSource.setUsername(environment.getProperty("jdbc.username"));
    basicDataSource.setPassword(environment.getProperty("jdbc.password"));

    // properties below are to improve performance
    basicDataSource.setTestWhileIdle(true);
    basicDataSource.setTestOnBorrow(true);
    basicDataSource.setTestOnReturn(false);
    basicDataSource.setValidationQuery(environment.getProperty("jdbc.validationQuery"));
    basicDataSource.setTimeBetweenEvictionRunsMillis(30000);
    basicDataSource.setMaxActive(100);
    basicDataSource.setMinIdle(10);
    basicDataSource.setMaxWait(10000);
    basicDataSource.setInitialSize(10);
    basicDataSource.setRemoveAbandonedTimeout(60);
    basicDataSource.setRemoveAbandoned(true);
    basicDataSource.setLogAbandoned(true);
    basicDataSource.setMinEvictableIdleTimeMillis(30000);

    // create scheme
    if (!"false".equals(System.getProperty("create_scheme"))) {
      JdbcTestUtils.executeSqlScript(
          new JdbcTemplate(basicDataSource),
          new ClassPathResource("/sql/create_scheme.sql"),
          false);
    }
    return basicDataSource;
  }
  @PreAuthorize("hasRole('AUTH')")
  @RequestMapping(value = "/admin/configuration/email.html", method = RequestMethod.GET)
  public String displayEmailSettings(
      Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    setEmailConfigurationMenu(model, request);
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);
    EmailConfig emailConfig = emailService.getEmailConfiguration(store);
    if (emailConfig == null) {
      emailConfig = new EmailConfig();
      // TODO: Need to check below properties. When there are no record available in
      // MerchantConfguration table with EMAIL_CONFIG key,
      // instead of showing blank fields in setup screen, show default configured values from
      // email.properties
      emailConfig.setProtocol(env.getProperty("mailSender.protocol"));
      emailConfig.setHost(env.getProperty("mailSender.host"));
      emailConfig.setPort(env.getProperty("mailSender.port}"));
      emailConfig.setUsername(env.getProperty("mailSender.username"));
      emailConfig.setPassword(env.getProperty("mailSender.password"));
      emailConfig.setSmtpAuth(Boolean.parseBoolean(env.getProperty("mailSender.mail.smtp.auth")));
      emailConfig.setStarttls(Boolean.parseBoolean(env.getProperty("mail.smtp.starttls.enable")));
    }

    model.addAttribute("configuration", emailConfig);
    return ControllerConstants.Tiles.Configuration.email;
  }
  @PostConstruct
  public void initClients() {
    final String targetEndpoint = env.getProperty(Config.EnvKey.CF_ENDPOINT);
    final boolean skipSslValidation =
        Boolean.parseBoolean(env.getProperty(Config.EnvKey.CF_SKIP_SSL_VALIDATION, "false"));
    final String username = env.getProperty(Config.EnvKey.CF_USERNAME);
    final String password = env.getProperty(Config.EnvKey.CF_PASSWORD);
    final String clientId = env.getProperty(Config.EnvKey.CF_CLIENT_ID, "cf");
    final String clientSecret = env.getProperty(Config.EnvKey.CF_CLIENT_SECRET, "");
    try {

      log.debug("buildClient - targetEndpoint={}", targetEndpoint);
      log.debug("buildClient - skipSslValidation={}", skipSslValidation);
      log.debug("buildClient - username={}", username);
      cfClient =
          SpringCloudFoundryClient.builder()
              .host(targetEndpoint)
              .clientId(clientId)
              .clientSecret(clientSecret)
              .skipSslValidation(skipSslValidation)
              .username(username)
              .password(password)
              .build();

      logClient = SpringLoggingClient.builder().cloudFoundryClient(cfClient).build();
    } catch (RuntimeException r) {
      log.error("CloudFoundryApi - failure while login", r);
    }
  }
  @Override
  public void insertOrUpdatePreferences(EasitApplicationPreferences preferences, EasitAccount user)
      throws Exception {

    // Convert the prefs to
    String strPrefs = localPrefsToServerPrefs(preferences);

    // Prepare request and send it
    DefaultHttpClient client = new DefaultHttpClient();
    StringEntity input = new StringEntity(strPrefs);
    input.setContentEncoding("UTF8");
    input.setContentType("application/json");

    HttpPost postRequest =
        new HttpPost(
            environment.getProperty("flowManager.url") + "/oldpreferences/" + user.getUserToken());
    postRequest.setEntity(input);
    HttpResponse response = client.execute(postRequest);

    // NOT Correct answer
    if (response.getStatusLine().getStatusCode() != 200) {
      logger.info("ERROR:");
      logger.info(
          "URL target"
              + environment.getProperty("flowManager.url")
              + "/oldpreferences/"
              + user.getUserToken());
      throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

    // Clear connection
    client.getConnectionManager().shutdown();
  }
Esempio n. 16
0
 private Properties hibProperties() {
   Properties properties = new Properties();
   properties.put(DIALECT, env.getRequiredProperty(DIALECT));
   properties.put(SHOW_SQL, env.getRequiredProperty(SHOW_SQL));
   properties.put(HBM2DDL_AUTO, env.getRequiredProperty(HBM2DDL_AUTO));
   return properties;
 }
  @Bean(name = "entityManagerFactory", destroyMethod = "destroy")
  LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
      DataSource dataSource, Environment env) {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean =
        new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource(dataSource);
    entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    entityManagerFactoryBean.setPackagesToScan("com.test.mmm.entity");
    // added for scanning hbm files
    ClasspathScanningPersistenceUnitPostProcessor classpathScanningPersistenceUnitPostProcessor =
        new ClasspathScanningPersistenceUnitPostProcessor("com.test.mmm.entity");
    classpathScanningPersistenceUnitPostProcessor.setMappingFileNamePattern("*.hbm.xml");
    entityManagerFactoryBean.setPersistenceUnitPostProcessors(
        classpathScanningPersistenceUnitPostProcessor);

    Properties properties = new Properties();
    properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
    properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));

    entityManagerFactoryBean.setJpaProperties(properties);

    return entityManagerFactoryBean;
  }
  @Bean(name = "entityManagerFactory")
  public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
    LocalContainerEntityManagerFactoryBean factoryBean =
        new LocalContainerEntityManagerFactoryBean();
    factoryBean.setDataSource(dataSource());
    factoryBean.setPersistenceUnitName("a1ecommerceEntityManager");
    factoryBean.setPackagesToScan(new String[] {"com.a1electronics.ecommerce.dbo"});
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    factoryBean.setJpaVendorAdapter(vendorAdapter);
    Properties jpaProperties = new Properties();

    // Configures the used database dialect. This allows Hibernate to create
    // SQL
    // that is optimized for the used database.
    jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));

    // If the value of this property is true, Hibernate writes all SQL
    // statements to the console.
    jpaProperties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));

    // If the value of this property is true, Hibernate will format the SQL
    // that is written to the console.
    jpaProperties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));
    // jpaProperties.put("hibernate.hbm2ddl.auto",env.getRequiredProperty("hibernate.hbm2ddl.auto"));
    // To fix the followinf issue
    // HHH000424: Disabling contextual LOB creation as createClob() method threw error :
    // java.lang.reflect.InvocationTargetException
    jpaProperties.put("hibernate.temp.use_jdbc_metadata_defaults", false);

    factoryBean.setJpaProperties(jpaProperties);
    factoryBean.afterPropertiesSet();
    factoryBean.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
    //		factoryBean.setPersistenceUnitName(env.getRequiredProperty("persistence.unitName"));
    return factoryBean;
  }
Esempio n. 19
0
 /**
  * Initializes gestionDemandes.
  *
  * <p>Spring profiles can be configured with a program arguments
  * --spring.profiles.active=your-active-profile
  *
  * <p>
  *
  * <p>You can find more information on how profiles work with JHipster on <a
  * href="http://jhipster.github.io/profiles.html">http://jhipster.github.io/profiles.html</a>.
  */
 @PostConstruct
 public void initApplication() throws IOException {
   if (env.getActiveProfiles().length == 0) {
     log.warn("No Spring profile configured, running with default configuration");
   } else {
     log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
     Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
     if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT)
         && activeProfiles.contains(Constants.SPRING_PROFILE_PRODUCTION)) {
       log.error(
           "You have misconfigured your application! "
               + "It should not run with both the 'dev' and 'prod' profiles at the same time.");
     }
     if (activeProfiles.contains(Constants.SPRING_PROFILE_PRODUCTION)
         && activeProfiles.contains(Constants.SPRING_PROFILE_FAST)) {
       log.error(
           "You have misconfigured your application! "
               + "It should not run with both the 'prod' and 'fast' profiles at the same time.");
     }
     if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT)
         && activeProfiles.contains(Constants.SPRING_PROFILE_CLOUD)) {
       log.error(
           "You have misconfigured your application! "
               + "It should not run with both the 'dev' and 'cloud' profiles at the same time.");
     }
   }
 }
Esempio n. 20
0
  @Bean
  public EntityManagerFactory entityManagerFactory() {

    Properties jpaProterties = new Properties();
    jpaProterties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    jpaProterties.put(
        "hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
    jpaProterties.put(
        "hibernate.ejb.naming_strategy",
        environment.getRequiredProperty("hibernate.ejb.naming_strategy"));
    jpaProterties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
    jpaProterties.put(
        "hibernate.generate_statistics",
        environment.getRequiredProperty("hibernate.generate_statistics"));

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(false);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("br.com.uol.cubus.support.domain");
    factory.setDataSource(dataSource());
    factory.setJpaProperties(jpaProterties);
    factory.afterPropertiesSet();

    return factory.getObject();
  }
 @Bean
 public CassandraClusterFactoryBean cluster() {
   CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
   cluster.setContactPoints(environment.getProperty("cassandra.contactpoints"));
   cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port")));
   return cluster;
 }
  @Override
  public void loadData(String fileName, String sheetName) throws RestLoaderException, IOException {

    // Initialize
    init();

    // Read
    log.info("Reading data from the file..");
    List<FileData<PatientVisitDTO>> patientVisits = excelFileReader.readData(fileName, sheetName);
    log.info("Data read complete..");

    // Transform
    log.info("Transforming the data read..");
    patientVisits = patientVisitDataTransformer.populateModelList(patientVisits);
    log.info("Data transformation complete..");

    // Load
    log.info("Loading the data into PIM..");
    List<FileData<PatientVisitDTO>> post =
        patientVisits
            .stream()
            .filter(
                data ->
                    DataLoaderConstants.POST_OPERATION.equalsIgnoreCase(data.getOperationType()))
            .collect(Collectors.toCollection(ArrayList::new));

    List<FileData<PatientVisitDTO>> put =
        patientVisits
            .stream()
            .filter(
                data -> DataLoaderConstants.PUT_OPERATION.equalsIgnoreCase(data.getOperationType()))
            .collect(Collectors.toCollection(ArrayList::new));

    Map<String, List<FileData<PatientVisitDTO>>> groupedPostData = convertToMap(post);
    post = doPost(groupedPostData);

    List<FileData<PatientVisitDTO>> putList = new ArrayList<>();
    put.forEach(
        dataSheet -> {
          try {
            addPathParam(
                env.getProperty(DataLoaderConstants.PATIENT_ID_KEY),
                dataSheet.getEntity().getPatientNumber());
            addPathParam(
                env.getProperty(DataLoaderConstants.PATIENT_VISIT_ID_KEY),
                dataSheet.getEntity().getId());
            putList.add(doPut(dataSheet));
          } catch (RestLoaderException e) {
          }
        });

    patientVisits = Stream.concat(post.stream(), putList.stream()).collect(Collectors.toList());
    log.info("Data loading complete..");

    // Write
    log.info("Writing the results back to the file..");
    excelFileWriter.writeResult(fileName, patientVisits, sheetName);
    log.info("Writing results complete..");
  }
Esempio n. 23
0
 final Properties additionalProperties() {
   final Properties hibernateProperties = new Properties();
   hibernateProperties.setProperty(
       "hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
   hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
   // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
   return hibernateProperties;
 }
 final Properties additionalProperties() {
   final Properties hibernateProperties = new Properties();
   hibernateProperties.setProperty(
       "hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
   hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
   hibernateProperties.setProperty("hibernate.show_sql", "true");
   return hibernateProperties;
 }
Esempio n. 25
0
 @Autowired
 private void setEnv(Environment env) {
   this.serverUri =
       env.getProperty("micromall.resourcesUri", "http://pmd_manager.51flashmall.com/resource");
   this.resourceHome =
       env.getProperty(
           "micromall.resourcesHome", "D:/website/pdmall_test/res.chinaswt.cn/resource");
 }
Esempio n. 26
0
 @Override
 public DeploymentSettings deploymentSettings() {
   DeploymentSettings settings = super.deploymentSettings();
   settings.setDeploymentContext(env.getProperty("site.deploymentContext"), servletContext);
   settings.setHTTPPort(env.getRequiredProperty("site.httpPort", int.class));
   settings.setHTTPSPort(env.getRequiredProperty("site.httpsPort", int.class));
   return settings;
 }
 @PostConstruct
 public void initApplication() throws IOException {
   if (env.getActiveProfiles().length == 0) {
     LOGGER.warn("No Spring profile configured, running with default configuration");
   } else {
     LOGGER.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
   }
 }
Esempio n. 28
0
 @Bean
 public Cloudinary cloudinary() {
   return new Cloudinary(
       ObjectUtils.asMap(
           "cloud_name", env.getProperty("cloud_name"),
           "api_key", env.getProperty("api_key"),
           "api_secret", env.getProperty("api_secret")));
 }
Esempio n. 29
0
  @Test
  public void testValueAnnotation() {
    assertThat(config.getRandonNum(), notNullValue());
    assertThat((String) getField(config, "serviceBroke"), equalTo("tcp://192.168.1.188"));

    assertThat(environment.getProperty("mail.none"), nullValue());
    assertThat(environment.getRequiredProperty("mail.from"), equalTo("*****@*****.**"));
  }
  private Properties getDefaultProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
    properties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
    properties.setProperty("hibernate.format", env.getProperty("hibernate.format"));

    return properties;
  }