terça-feira, 30 de outubro de 2018

JSP hot-deploy in Jboss / Wildfly


To enable hot-deploy of JSPs in Wildfly, i.e. to automatically publish any changes to JSPs in ${WILDFLY_ROOT}/standalone/tmp/vfs/temp/tempxxxxxxx/content-xxxxxxx without requiring redeployment of war, set the development attribute of jsp-config within undertow subsystem to true as below:
<subsystem xmlns=”urn:jboss:domain:undertow:3.0″>
<servlet-container name=”default” default-encoding=”UTF-8″>
        <jsp-config development=”true” tag-pooling=”false”/>        <websockets/>
</servlet-container>

Ref: https://ohioedge.com/2018/01/31/jsp-hot-deploy-in-wildfly/

sexta-feira, 26 de outubro de 2018

Recursively display all 'csv' files in a list of directories


private static final String CONST_SUFFIX = "csv";
....
//method
for (String directoryPath : folders) {
if (Paths.get(directoryPath).toFile().isDirectory()) {
Files.list(Paths.get(directoryPath)).filter(Files::isRegularFile).forEach(path -> {
if(path.endsWith(CONST_SUFFIX) || path.toString().toLowerCase().endsWith(CONST_SUFFIX)){
System.out.println(path.getFileName());
}
});
}
}

segunda-feira, 22 de outubro de 2018

How to call the same methods from difference classes

public class Teste1 {

public String valor1;

public String getValor1() {
return valor1;
}

public void setValor1(String valor1) {
this.valor1 = valor1;
}
}
#########################################################################
public class Teste2 {

public String valor1;

public String getValor1() {
return valor1;
}

public void setValor1(String valor1) {
this.valor1 = valor1;
}

}

#########################################################################


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class GenericTest {

public static void main(String[] args) {

Teste1 t1 = new Teste1();
t1.setValor1("valor1");

Teste2 t2 = new Teste2();
t2.setValor1("valor2");

System.out.println(testeMetodo(t1, Teste1.class));
System.out.println(testeMetodo(t2, Teste2.class));
}
public static String testeMetodo(Object objecInstance, Class<?> clazz) {
String retorno = "";
try {
Method metodo = clazz.getMethod("getValor1");
retorno = (String) metodo.invoke(objecInstance, null);

} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retorno;
}

}

sábado, 20 de outubro de 2018

how to check if attribute has '@notNull' annotation dynamic

This solution was used in a java project with String jdbcTemplate following the idea of @NotNull JPA Annotation to check ScreenMapper from Controller and @All attributes need to have the same name column in Database.


public Boolean validationRequiredFieldsInMapper(Class<?> clazz, final Map<String, Object> screenFieldMap) {
Boolean isError = false;

Object objValue = null;
Field field = null;
String strValue = "";
for (String column : screenFieldMap.keySet()) {
field = clazz.getDeclaredField(column);
if (field != null) {
if (field.isAnnotationPresent(NotNull.class)) {
objValue = screenFieldMap.get(column);
strValue = (String) objValue;
if (StringUtils.isBlank(strValue)) {
isError = true;
break;
}
}
}
}
}

Class:

@NotNull
private Integer sap;
@NotNull
private String address;
@NotNull
private Date dateRegister;

Map: 

@RequestMapping(value="examplecontroller", method=RequestMethod.POST)
public @ResponseBody ReturnObject setData(
@RequestParam(value="sap",required= true ) String sap,
@RequestParam(value="address", required= true) String address,
@RequestParam(value="dateRegister", required= true) String dateRegister,

Map<String,Object> screenFieldMap = new HashMap<String,Object>();
screenFieldMap.put("sap",sap);
screenFieldMap.put("address",address);
screenFieldMap.put("dateRegister",dateRegister);




sexta-feira, 28 de setembro de 2018

Return Generic Type with jdbcTemplate.queryForObject - Generic Dao with jdbcTemplate


public Class TestClass  implements Serializable{
private int id;
private Usuario usuario;
private Date      data_hora;
private Fila id_fila;
private Integer sap;
...
 //omitted getter and setters  }

##################################################################

Method getObjectByID:

public <T> T getObjectByID(Class<? extends T> classe, String tableName, Integer id){

Object response= null;

try{
StringBuffer sql = new StringBuffer();
                        sql.append("SELECT * FROM );
                        sql.append(tableName);
                        sql.append(" WHERE ID = ?");

                        Object[] parametros = new Object[] {id};

response= jdbcTemplate.queryForObject(sql.toString(),parametros, new GenericRowMapper(classe));

}catch(Exception ex){
LOGGER.error("Error "+ex.getMessage(), ex);
}
return (T) response;
}
}

##################################################################
Class GenericRowMapper:

public class GenericRowMapper<T> implements RowMapper<T> {

  private Class<T> mappedClass;

  public GenericRowMapper(Class<T> mappedClass) {
    this.mappedClass = mappedClass;
  }

  @Override
  public T mapRow(ResultSet rs, int rowNum) throws SQLException {

    T mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);

    bw.setAutoGrowNestedPaths(true);

    ResultSetMetaData meta_data = rs.getMetaData();
    int columnCount = meta_data.getColumnCount();

    for (int index = 1; index <= columnCount; index++) {

      try {

        String column = JdbcUtils.lookupColumnName(meta_data, index);
        Object value = JdbcUtils.getResultSetValue(rs, index, Class.forName(meta_data.getColumnClassName(index)));

        bw.setPropertyValue(column, value);

      } catch (TypeMismatchException | NotWritablePropertyException | ClassNotFoundException e) {
         // Ignore
      }
    }

    return mappedObject;
  }
}

##################################################################
search --->
TestClass  testClass  =  (TestClass ) genericDAO.getObjectByID(TestClass.class,"TableName",1);

#######################################################

Method  getListByStatus :

public <T> List<T> getListByStatus(Class<? extends T> classe, String tableName, String status) {
Object response = null;
try{
sql.append("SELECT * FROM );
                        sql.append(tableName);
                        sql.append(" WHERE status = ?");

                       response = jdbcTemplate.query(sql.toString(), new GenericRowMapper<T>((Class<T>) classe));

}catch(Exception ex){
LOGGER.error("Error "+ex.getMessage(), ex);
}
return (List<T>) response;
}

#######################################################

search:
List<TestClass> testList  =  (List<TestClass>) genericDAO.getListByStatus(TestClass.class,"TableName", StatusEnum.cancel);




quinta-feira, 13 de setembro de 2018

Validação com regular expression



import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

public class Blp01_41Validator extends AbstractValidator{


//CONSTANT for : Beginning method is validate
private static final String  C_BEGINNING_METHOD_IS_VALIDATE = "Beginning method is validate";
//CONSTANT for : Validation of the
private static final String  C_VALIDATION_OF_THE = "Validation of the ";
//CONSTANT for :  field with the RegularExpressionValidator validator.
private static final String  C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR = " field with the RegularExpressionValidator validator.";
//CONSTANT for : (null)|(\\d{0,4})
private static final String  C_NULL_D_0_4 = "(null)|(\\d{0,4})";
//CONSTANT for : [SN]
private static final String  C_SN = "[SN]";  //1 letra dentro desse conjunto
//CONSTANT for : [A-Z]{2}
private static final String  C_A_Z_2 = "[A-Z]{2}"; //2 letras de A à Z
//CONSTANT for : \\d{3,11}
private static final String  C_D_3_11 = "\\d{3,11}"; //valor decima (minimo 3 e no máx 11 digitos)
//CONSTANT for : (null)|(\\d{0,9})
private static final String  C_NULL_D_0_9 = "(null)|(\\d{0,9})"; //valor decimal não obrigatorio com no máx 9 digitos
//CONSTANT for : (null)|(\\d{2,8})
private static final String  C_NULL_D_2_8 = "(null)|(\\d{2,8})"; //valor decimal não obrigatorio com no minumo 2 e no máx 8 digitos
//CONSTANT for : (null)|(1)|(2)|(3)|(4)|(5)|(6)|(7)|(8)|(9)|(10)|(11)|(12)|(13)|(14)|(15)|(16)
private static final String  C_NULL_1_2_3_4_5_6_7_8_9_10_11_12_13_14_15_16 = "(null)|(1)|(2)|(3)|(4)|(5)|(6)|(7)|(8)|(9)|(10)|(11)|(12)|(13)|(14)|(15)|(16)"; //nao obrigatorio com um valor de 1 à 16.
//CONSTANT for : \\d{7,8}
private static final String  C_D_7_8 = "\\d{7,8}";
//CONSTANT for : [MF]
private static final String  C_MF = "[MF]"; //
//CONSTANT for : \\d{4,8}
private static final String  C_D_4_8 = "\\d{4,8}";
//CONSTANT for : (1)|(2)|(3)
private static final String  C_1_2_3 = "(1)|(2)|(3)";
//CONSTANT for : \\d{2,7}
private static final String  C_D_2_7 = "\\d{2,7}";
//CONSTANT for : \\d{1,10}
private static final String  C_D_1_10 = "\\d{1,10}";
//CONSTANT for : \\d{2,8}
private static final String  C_D_2_8 = "\\d{2,8}";
//CONSTANT for : Ending method validate the form
private static final String  C_ENDING_METHOD_VALIDATE_THE_FORM = "Ending method validate the form";

// LOGGER for the class Blp01_41Validator
private static final Logger LOGGER = Logger.getLogger( Blp01_41Validator.class);

/**
* Operation validate for Blp01_41Form
* @param obj : the current form (Blp01_41Form)
* @param errors : The spring errors to return for the form Blp01_41Form
*/
public void validate(final Object obj,final Errors errors){
if (LOGGER.isInfoEnabled()) {
// For : Blp01_41Validator
LOGGER.info(C_BEGINNING_METHOD_IS_VALIDATE);
}
Blp01_41Form cBlp01_41Form = (Blp01_41Form)obj;

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinmMunRed", "", "Municipio: NAO INFORMADO");

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinuTelDddRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuTelDddRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuTelDddRed()),C_NULL_D_0_4)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinuTelDddRed", "", "DDD: formato inválido");
}

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oTlaConfRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oTlaConfRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oTlaConfRed()),C_SN)== 0 ){
errors.rejectValue("inputScreen.pt41oTlaConfRed", "", "Confirmação: FORA DE FAIXA");
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinmSiglaUfRed", "", "UF: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqinmSiglaUfRed")== null){

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinmSiglaUfRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinmSiglaUfRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinmSiglaUfRed()),C_A_Z_2)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinmSiglaUfRed", "", "UF: FORA DE FAIXA");
}
}

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oJornadaRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oJornadaRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oJornadaRed()),C_SN)== 0 ){
errors.rejectValue("inputScreen.pt41oJornadaRed", "", "Dupla Jornada: FORA DE FAIXA");
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinmBairroRed", "", "Bairro: NAO INFORMADO");

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinuCpf1Red", "", "CPF: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqinuCpf1Red")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinuCpf1Red"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuCpf1Red())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuCpf1Red()),C_D_3_11)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinuCpf1Red", "", "CPF: formato inválido");
}
}

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinuTelRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuTelRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuTelRed()),C_NULL_D_0_9)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinuTelRed", "", "Telefone: FORMATO INVÁLIDO");
}

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqiidOlSegundaJornadaRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqiidOlSegundaJornadaRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqiidOlSegundaJornadaRed()),C_NULL_D_2_8)== 0 ){
errors.rejectValue("inputScreen.pt41oMqiidOlSegundaJornadaRed", "", "OL da Segunda Jornada: formato inválido");
}

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41onmEspecialidadeRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41onmEspecialidadeRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41onmEspecialidadeRed()),C_NULL_1_2_3_4_5_6_7_8_9_10_11_12_13_14_15_16)== 0 ){
errors.rejectValue("inputScreen.pt41onmEspecialidadeRed", "", "Especialidade: FORA DE FAIXA");
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqiteEndRed", "", "Endereco: NAO INFORMADO");

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqid2AdmissRed", "", "Data de Admissao no : NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqid2AdmissRed")== null){


if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqid2AdmissRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqid2AdmissRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqid2AdmissRed()),C_D_7_8)== 0 ){
errors.rejectValue("inputScreen.pt41oMqid2AdmissRed", "", "Data de Admissao no : formato inválido");
}
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oTipoSexoRed", "", "Sexo: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oTipoSexoRed")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oTipoSexoRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oTipoSexoRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oTipoSexoRed()),C_MF)== 0 ){
errors.rejectValue("inputScreen.pt41oTipoSexoRed", "", "Sexo: FORA DE FAIXA");
}
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinuCepRed", "", "CEP: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqinuCepRed")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinuCepRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuCepRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuCepRed()),C_D_4_8)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinuCepRed", "", "CEP: formato inválido");
}
}




if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oHomologaRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oHomologaRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oHomologaRed()),C_SN)== 0 ){
errors.rejectValue("inputScreen.pt41oHomologaRed", "", "Apto a Homologacao: FORA DE FAIXA");
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqidtNascRed", "", "Data de Nascimento: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqidtNascRed")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqidtNascRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqidtNascRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqidtNascRed()),C_D_7_8)== 0 ){
errors.rejectValue("inputScreen.pt41oMqidtNascRed", "", "Data de Nascimento: formato inválido");
}
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqicsFuncaoRed", "", "Funcao: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqicsFuncaoRed")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqicsFuncaoRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqicsFuncaoRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqicsFuncaoRed()),C_1_2_3)== 0 ){
errors.rejectValue("inputScreen.pt41oMqicsFuncaoRed", "", "Funcao: FORA DE FAIXA");
}
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinum Red", "", "Numero Matricula  : NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqinum Red")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinum Red"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinum Red())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinum Red()),C_D_2_7)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinum Red", "", "Numero Matricula  : formato inválido");
}
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinuInsCrmRed", "", "Numero ICRM: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqinuInsCrmRed")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinuInsCrmRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuInsCrmRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuInsCrmRed()),C_D_1_10)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinuInsCrmRed", "", "Numero ICRM: formato inválido");
}
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqiIdOlRed", "", "OL: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqiIdOlRed")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqiIdOlRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqiIdOlRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqiIdOlRed()),C_D_2_8)== 0 ){
errors.rejectValue("inputScreen.pt41oMqiIdOlRed", "", "OL: formato inválido");
}
}
}

}
}

quinta-feira, 26 de abril de 2018

ORACLE Backup: Utilizando Data Pump (EXPDP E IMPDP)

O banco de dados Oracle fornece uma variedade de procedimentos e opções de backup que ajudam a proteger o banco. Não adianta ter ótimas ferramentas e não implementar de maneira adequada e que possa recuperá-los facilmente, com isso, devemos sempre efetuar testes de backup e restore regularmente.
Neste poste vou falar sobre o utilitário Data Pump (impdp e expdp) que realiza backup lógico de um banco de dados que envolve a leitura de um conjunto de registros do banco de dados e a gravação destes em um arquivo. Esses registros são lidos independente das suas localizações físicas.
Você pode exportar todo o banco de dados, tablespaces, usuários específicos (schemas), espaços de tabelas ou tabelas especificas. O arquivo gravado pelo Data Pump export conterá os comandos necessários para recriar completamente todos os objetos e dados escolhidos. Depois que os dados foram exportados por meio do Data Pump Export, eles poderão ser importados por meio do utilitário Data Pump Import. O Data Pump Import lê o arquivo dump criado pelo Data Pump Export e executa os comandos localizados ali. Por exemplo, esses comandos podem incluir um comando create table, create indice e vários inserts.
Vejamos alguns exemplos de como usar o Data Pump como backup.

Criando um diretório no Sistema Operacional Linux:
mkdir /u01/backup/
Logando no Oracle com sysdba:
sqlplus / as sysdba
Criando um objeto de pasta no Oracle:
CREATE OR REPLACE DIRECTORY funcionarios AS ‘/u01/backup/’;
Directory created.
Utilizando o utilitário EXPDP
Exportando todo o banco de dados:
expdp system DIRECTORY=funcionarios DUMPFILE=funcionario.dmp FULL=y LOGFILE=expfull.log
Exportando uma tablespace:
expdp system DIRECTORY=funcionarios DUMPFILE=funcionarios_TB.dmp TABLESPACES=USERS
Exportando um schema:
expdp system DIRECTORY=funcionarios DUMPFILE=funcionarios_schema.dmp SCHEMAS=hr
Exportando uma tabela:
expdp system tables=hr.employees directory=funcionarios dumpfile=funcionario_tabela.dmp logfile=FUNCIONARIO.log

Utilizando o utilitário IMPDP
Importando o banco de dados inteiro:
impdp system DIRECTORY=funcionarios DUMPFILE=funcionario.dmp FULL=y
Importando uma tablespace:
impdp system DIRECTORY=funcionarios DUMPFILE=funcionarios_TB.dmp TABLESPACES=USERS
Importando um schema, remapeando com um novo usuario (schema), chamado amanda:
impdp system DIRECTORY=funcionarios DUMPFILE=funcionarios_schema.dmp remap_schema=hr:amanda remap_tablespace=HR:USERS
Importando uma tabela
impdp system DIRECTORY=funcionarios DUMPFILE=funcionario_tabela.dmp TABLES=amanda.employees;
Alguns parâmetros:
EXPDP: comando para exportar
IMPDP: Comando para importar
SYSTEM: usuário que estou usando para exportar e importar.
TABLES: Informa qual vai ser a tabela importada e exportada.
TABLESPACES: Informa qual vai ser a tablespace que será exportada ou importada.
DIRECTORY: nome do objeto que criamos no oracle, ele aponta para o /u01/backup
DUMPFILE: informo qual será o nome do arquivo exportado.
FULL: informo que o backup é completo
LOGFILE: Nome do arquivo de log, fica localizado na pasta do directory.
TRANSPORT_FULL_CHECK: Especifica se os espaços de tabela sendo importados devem primeiro ser verificados como conjunto contido.
FULL: Opção de Y/N, utilizado para especificar que voce quer importar o arquivo por completo
REMAP_DATAFILE: Altera o nome do arquivo de dados de origem para o arquivo de dados alvo nos comandos create tablespace, create table, etc.
REMAP_SCHEMA: Altera o nome do schema de origem para o destino, separando por dois pontos (:).
REMAP_TABLESPACE: Altera o a tablespace de origem para o destino, separando por dois pontos.
REUSE_DATAFILES: Re-utiliza os datafiles, se já existirem.

Alguns GRANTs importantes, em caso de exportar ou importar com o usuário sem perfil de dba, conceda essas permissções
GRANT READ, WRITE ON DIRECTORY funcionarios TO amanda;
GRANT READ, WRITE ON DIRECTORY funcionarios TO hr;
GRANT IMP_FULL_DATABASE to amanda;
GRANT EXP_FULL_DATABASE to hr;

ref: http://aprenderoracle.com/2011/07/05/backup-utilizando-data-pump-expdp-e-impdp/

quinta-feira, 22 de fevereiro de 2018

Relatorio jasper com multiplos dataSources JSF


Essa código faz parte de um biblioteca utilizada em uma aplicação JSF



Dependências utilizadas:

<dependencies>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>5.6.0</version>
</dependency>
<dependency>
<groupId>org.olap4j</groupId>
<artifactId>olap4j</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>


Classe:



import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JRPrintPage;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class ServicoImpressao {

private static final Logger LOGGER = Logger.getLogger(ServicoImpressao.class);

private static JasperPrint print;

public void generateReport(final Collection lista, final Map parameters, final String reporterFile) throws Exception {

try {
JRBeanCollectionDataSource source = new JRBeanCollectionDataSource(lista, false);

InputStream stream = this.getClass().getClassLoader().getResourceAsStream(reporterFile);

Map parametersLocal = parameters;
if (ServicoImpressao.print == null) {
if (parametersLocal == null) {
parametersLocal = new HashMap(1);
}
java.util.Locale locale = new Locale("pt", "BR");
parametersLocal.put(JRParameter.REPORT_LOCALE, locale);
ServicoImpressao.print = JasperFillManager.fillReport(stream, parametersLocal, source);
} else {
JasperPrint jasperPrint_next = JasperFillManager.fillReport(stream, parametersLocal, source);
List pages = jasperPrint_next.getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage) pages.get(j);
ServicoImpressao.print.addPage(object);
}
}

} catch (Exception e) {
LOGGER.error("ERRO AO GERAR RELATORIO", e);
throw e;
}
}

public void generateReport(final Map<String, Collection> map, final Map parameters, final String reporterFile) throws Exception {

try {
Map parametersLocal = parameters;

if (parametersLocal == null) {
parametersLocal = new HashMap(1);
}

InputStream stream = this.getClass().getClassLoader().getResourceAsStream(reporterFile);

JRBeanCollectionDataSource dataSourceDefault = null;
JRBeanCollectionDataSource dataSource = null;

Iterator<Entry<String, Collection>> entries = map.entrySet().iterator();

while (entries.hasNext()) {
Map.Entry<String, Collection> entry = (Map.Entry<String, Collection>) entries.next();

dataSource = new JRBeanCollectionDataSource((Collection) entry.getValue(), false);
// MAP KEY VAZIA OU DEFAULT = DATASOURCE DEFAULT
if ("".equals(entry.getKey()) || "default".equalsIgnoreCase(entry.getKey())) {
dataSourceDefault = dataSource;
} else {
dataSource = new JRBeanCollectionDataSource((Collection) entry.getValue(), false);
parametersLocal.put(entry.getKey(), dataSource);
}
}
if (ServicoImpressao.print == null) {
if (parametersLocal == null) {
parametersLocal = new HashMap(1);
}
Locale locale = new Locale("pt", "BR");
parametersLocal.put(JRParameter.REPORT_LOCALE, locale);
ServicoImpressao.print = JasperFillManager.fillReport(stream, parametersLocal, dataSourceDefault);
} else {
JasperPrint jasperPrint_next = JasperFillManager.fillReport(stream, parametersLocal, dataSourceDefault);
List pages = jasperPrint_next.getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage) pages.get(j);
ServicoImpressao.print.addPage(object);
}
}

} catch (Exception e) {
LOGGER.error("ERRO AO GERAR RELATORIO", e);
throw e;
}
}

public Integer getNumeroPaginas() {
return ServicoImpressao.print.getPages().size();
}

public void imprime() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
try {
response.reset();
response.setContentType("application/pdf");
java.io.OutputStream outputStream = null;
outputStream = response.getOutputStream();
outputStream.write(JasperExportManager.exportReportToPdf(print));
outputStream.close();
} catch (IOException | JRException e) {
e.printStackTrace();
} finally {
ServicoImpressao.print = null;
}
facesContext.responseComplete();
}
}

Chamador:

try {
Map<String,Collection> mapJasper = new HashMap<String,Collection>();

mapJasper.put("", relatorioOut.getGrupos());
mapJasper.put("SUB_REPORT", relatorioOut.getGruposReajustes());

impressao.generateReport(mapJasper, parameters, nomeJasper);
impressao.imprime();

} catch (Exception e) {
LOGGER.error(e, e);
}



terça-feira, 20 de fevereiro de 2018

How to Iterate Over a Map in Java

How to Iterate Over a Map in Java

Java
There are several ways of iterating over a Map in Java. Lets go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement Mapinterface, following techniques will work for any map implementation (HashMapTreeMapLinkedHashMapHashtable, etc.)

Method #1: Iterating over entries using For-Each loop.

This is the most common method and is preferable in most cases. Should be used if you need both map keys and values in the loop.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Note that For-Each loop was introduced in Java 5 so this method is working only in newer versions of the language. Also For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for nullreferences.

Method #2: Iterating over keys or values using For-Each loop.

If you need only keys or values from the map, you can iterate over keySet or valuesinstead of entrySet.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}
//iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}
This method gives slight performance advantage over entrySet iteration (about 10% faster) and is more clean.

Method #3: Iterating using Iterator.

Using Generics:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry<Integer, Integer> entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Without Generics:
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}
You can also use same technique to iterate over keySet or values.
This method might look redundant but it has its own advantages. First of all it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling iterator.remove(). If you try to do this during For-Each iteration you will get "unpredictable results" according to javadoc.
From performance point of view this method is equal to For-Each iteration.

Method #4: Iterating over keys and searching for values (inefficient).

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
    Integer value = map.get(key);
    System.out.println("Key = " + key + ", Value = " + value);
}
This might look like a cleaner alternative for method #1 but in practice it is pretty slow and inefficient as getting values by a key might be time consuming (this method in different Mapimplementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided.

Conclusion

If you need only keys or values from the map use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration you have to use method #3. Otherwise use method #1.

ref: http://www.sergiy.ca/how-to-iterate-over-a-map-in-java/