Archivos properties con Producer

A veces podemos crear @Producer para obtener los valores del archivo de propiedades

crear el archivo en /src/main/resources

Leer el archivo

 InputStream inputStream = getClass()
                        .getClassLoader().getResourceAsStream("connection.properties");
                Properties prop = new Properties();

                if (inputStream != null) {

                    prop.load(inputStream);
                    String ip = prop.getProperty("ip");
                    Integer port = Integer.parseInt(prop.getProperty("port"));
                    String user = prop.getProperty("user");
                    String password = prop.getProperty("password");

Clase SQLServerProducer.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.avbravo.fiscalserver.producer;

import com.avbravo.jmoordbutils.JsfUtil;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.faces.context.FacesContext;
import javax.inject.Singleton;

/**
 *
 * @author avbravo
 */
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class SQLServerProducer {

    Connection connectionClient = null;
    Connection connectionClientJSD = null;

    @Produces
    @ApplicationScoped
    public Connection connection() {

        try {
            if (connectionClient == null) {

                InputStream inputStream = getClass()
                        .getClassLoader().getResourceAsStream("connection.properties");
                Properties prop = new Properties();

                if (inputStream != null) {

                    prop.load(inputStream);
                    String ip = prop.getProperty("ip");
                    Integer port = Integer.parseInt(prop.getProperty("port"));
                    String user = prop.getProperty("user");
                    String password = prop.getProperty("password");

                    Class.forName("net.sourceforge.jtds.jdbc.Driver");
//                connectionClient = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/GRUPOMORENO;instance=SQLEXPRESS;", "sa", "denver16$");
                    connectionClient = DriverManager.getConnection("jdbc:jtds:sqlserver://" + ip + ":" + port + "/GRUPOMORENO;instance=SQLEXPRESS;", user, password);
                } else {
                    System.out.println("No se puede cargar el archivo connection.properties");
                }

            }
        } catch (Exception e) {
            JsfUtil.errorMessage("conecction() " + e.getLocalizedMessage());
        }
        return connectionClient;
    }

}

Last updated