Monday, November 30, 2015

How to deploy a .ear in WILDFLY - como realizar deploy de nuestros .ear exportados

Cuando necesitamos desplegar nuestros aplicativos desde consola ya sin el asistente de eclipse o netbeans, primero corremos el servidor wildfly como servicio como lo explicamos el post http://javaeefuncional.blogspot.com.co/2015/11/configurar-wilf-fly-en-linux-ubuntu.html

como servicio seria sino colocar service wildfly start en una terminal linux como root y de esta manera ya tendriamos wildfly corriendo, si aun no hemos hecho puesto wildfly como servicio nos dirigimos donde tengamos el wildfly y nos dirijimos a la carpeta bin alli, colocamos ./standalone.sh

Luego en otra pestania abierta nos dirigimos a la misma carpeta donde tengamos el wildfly ingresamos al bin y luego ejecutamos ./jboss-cli.sh luego de alli colocamos el comando connect

luego movemos nuestros archivo .EAR dentro de la carpeta wildfly/standalone/deployments/Cmall.ear  y colocamos nuestro arhcivo .ear alli,

luego desde esta consola lanzamos  deploy /opt/wildfly/standalone/deployments/Cmall.ear

y de esta manera quedaria el .ear deplegado, si el wildfly esta como servicio cada vez que se inicie el sistema automaticamente cuando se inicie el wildly se hace un deploy de los paquetes que fueron corridos previamente, si queremos desmontar el paque seria el mismo solo que reemplazando deploy por undeploy asi:

 undeploy /opt/wildfly/standalone/deployments/Cmall.ear

Schedule background jobs on application start from EJB - Correr funciones automaticas al inicio de una aplicacion desde un EJB Singleton

Para correr un metodo automaticamente cuando se inicia la aplicacion, por ejemplo estar ejecutando una funcion cada X cantidad de minutos, segundos, horas, etc, nos srive para realizar backups, copiar, eliminar X determinada tipo de informacion, en fin ya es a la creatividad y de la necesidad que se tenga que realizar, en j2SE se manejavan los Threads para hacer este tipo de operaciones aca, en JAVA EE, necesitamos crear un EJB de tipo Singleton asi:
 
 
@Singleton
public class BackgroundJobManager {

    @Schedule(hour="0", minute="0", second="0", persistent=false)
    public void someDailyJob() {
        // ... (runs every start of day)
    }

    @Schedule(hour="*/1", minute="0", second="0", persistent=false)
    public void someHourlyJob() {
        // ... (runs every hour of day)
    }

    @Schedule(hour="*", minute="*/15", second="0", persistent=false)
    public void someQuarterlyJob() {
        // ... (runs every 15th minute of hour)
    }

    @Schedule(hour="*", minute="*", second="*/30", persistent=false)
    public void someHalfminutelyJob() {
        // ... (runs every 30th second of minute)
    }

}



@Singleton
public class HiloSingleton implements HiloSingletonRemote {


 @PostConstruct
    @Schedule(hour="*", minute="*/1", second="0", persistent=false)
    @Override
    public void corre() {

                //IMpementar logica del meodo, este metodo corre cada Minuto, aun despues de cerrar la aplicacion, el metodo cesa cuando se realiza un undeploy de la aplicacion .ear o cuando se apaga el servidor wildfly
          
    }

}

JPA select query with timestamp and date fields fail to retrieve results

Cuando necesitemos hacer consultas con dates, tipo date, y timestamp se hace asi:


 
Date and Calendar parameter values require special methods in order to specify what they represent, such as a pure date, a pure time or a combination of date and time, as explained in detail in the Date and Time (Temporal) Types section

For example, the following invocation passes a Date object as a pure date (no time):

Query query = em.createQuery("Select f From usuarios f where f.fecha=:date");

query.setParameter("date", new java.util.Date(), TemporalType.DATE);


and timestamp

query.setParameter("date", new java.util.Date(), TemporalType.TIMESTAMP);

JSF How to redirect from backing bean to a URL dynamically constructed in the backing bean - Redirijir Url desde Mangedbean a otra pagina web

Cuando necesitamos redirigir dedesde MangedBean hacia cualquier otra pagina web hacemos lo siguiente

ExternalContext context2 = FacesContext.getCurrentInstance().getExternalContext();
                try {
                    context2.redirect(context2.getRequestContextPath() +"http://www.google.com");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

Wildfly Conectividad con MYSQL DRIVER

Cuando se necesite cargar driver MYSQL con wildfly creamos una carpeta dentro de wildfly-9.0.1.Final/modules/system/layers/base/com

la carpeta que creemos alli la nombramos mysql y dentro otra carpeta llamada main, dentro de main creamos un archivo .xml y dentro de este archivo colocamos

<module xmlns="urn:jboss:module:1.1" name="com.mysql">

    <resources>
        <resource-root path="mysql-connector-java-5.1.23-bin.jar"/>
    </resources>
    <dependencies>
        <module name="javax.api"/>
        <module name="javax.transaction.api"/>
        <module name="javax.servlet.api" optional="true"/>
    </dependencies>
</module>

descargamos el jar mysql-connector-java-5.1.23-bin.jar o la version actual que este en el momento y la dejamos en esa carpeta asi:




Luego nos dirijimos a wildfly-9.0.1.Final/standalone/configuration/ y abrimos el archivo standalone.xml y dentro del bloque driver que aparace asi

<drivers>
<driver name="h2" module="com.h2database.h2">
                        <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
                    </driver>             

</drivers>

vamos a dejarlo asi:


    <drivers>
                    <driver name="h2" module="com.h2database.h2">
                        <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
                    </driver>

                    <driver name="mysqlDriver" module="com.mysql">
                        <xa-datasource-class>com.mysql.jdbc.Driver</xa-datasource-class>
                    </driver>
                </drivers>



Reiniciamos servidor Jboss wildfly y ya estamos listos para agregar datasources de mysql al servidor por medio de jndi



Web Access WildFly

SI necesitamos tener acceso libre de la red hacia wildfly

By default, you will be able to access Wildfly via web only on your local system, by browsing to:
http://localhost:8090 [or any port that you have previously configured]
If you need access from outside, you must locate the following in standalone.xml:


1
2
3
4
5
6
<interface name="management">
    <inet-address value="${jboss.bind.address.management:127.0.0.1}"/>
</interface>
<interface name="public">
    <inet-address value="${jboss.bind.address:127.0.0.1}"/>
</interface>
 
 
And change that to:

1
2
3
4
5
6
<interface name="management">
    <any-address/>
</interface>
<interface name="public">
    <any-address/>
</interface>

Configurar Wilf Fly en Linux UBUNTU como servicio

Cando se necesita configurar wildfly como servidor y como servicio para que inicie automaticamente la app, se realizan los siguientes pasos:

1: Aderir usuario wildfly
2: Aderir grupo wildfly

copiar el archivo wildlfly-xxx.zip a /opt, descomprimir alli, renombrar la carpeta como wildfly
3: darle propiedad al usuario wildfly y grupo wildfly a la carpeta wildlfy asi:

chown -R wildfly:wildlfy /opt/wildfly

To run Wildfly you can simply execute the standalone.sh script located at:
1
[WILDFLY_INSTALLATION_DIRECTORY]/bin/standalone.sh
 
This is a pretty straightforward approach and it does not require any configuration.
If you need Wildfly to run in the background (and maybe at system startup), you must install Wildfly as a service:

Copy wildfly.conf to /etc/default/ and change the name to wildfly

cp [WILDFLY_INSTALLATION_DIRECTORY]/bin/init.d/wildfly.conf /etc/default/wildfly
Edit this file to set your own configurations, they will be discarded by default because of the #.

You need to set some values, for example, JAVA_HOME must be set to where you have Java installed, JBOSS_USER (default: wildfly) must be set to the user who will be running Wildfly and who owns the main directory, JBOSS_HOME (default: /opt/widlfly) is the main directory where you have placed the installation files, JBOSS_CONSOLE_LOG is where logs will be stored (make sure the user have write access to this file).
Now you need to copy the wildfly-init-debian.sh to /etc/init.d and rename it to wildfly.


cp [WILDFLY_INSTALLATION_DIRECTORY]/bin/init.d/wildfly-init-debian.sh /etc/init.d/wildfly
And this is enough to install Wildfly as a service, to run the service, simply execute:


service wildfly start
 
 
Hasta este punto ya debemos de tener el servicio de wildfly corriendo, ahora para poder hacer que 
autoinicie cada vez que el servidor se encienda se debe de correr: 
update-rc.d wildfly defaults 
y con esto ya tendriamos Wildfly rodando cada vez que el servidor se reinicie

Para remover el Servicio de autoestarte se coloca update-rc.d -f wildfly remove



 
 
 
 

Sunday, November 29, 2015

7-Zip command to create and extract a password-protected ZIP file on Linux

Cuando necesitemos de comprimir archivos protegidos usando zip

zip -P password -r encrypted.zip folderIWantToZip
 
para descomprimir
 
unzip -P password encrypted.zip
 
Para descomprimir usando 7z usamos
 
 
7z a secure.7z * -pSECRET

Donde  
 
7z:      name and path of 7-Zip executable
a:        add to archive
secure.7z:    name of destination archive
*:    add all files from current directory to destination archive
-pSECRET: specify the password "SECRET" 

How to get current timestamp in java - Obtener Timestamp tiempo actual en JAVA

La forma de convertir la fecha actual a timestamp es la siguiente


 Date date= new Date();
         //getTime() returns current time in milliseconds
  long time = date.getTime();
         //Passed the milliseconds to constructor of Timestamp class 
  Timestamp ts = new Timestamp(time);
  System.out.println("Current Time Stamp: "+ts);

Comparando fechas JAVA

Con los metodos .before y .after podemos realizar comparaciones de fechas interesantes incluso con fechas tipo Timestamp
 
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class HashtableDemo {
    public static void main(String args[]) throws AssertionError, ParseException {
        DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        //comparing date using compareTo method in Java
        System.out.println("Comparing two Date in Java using CompareTo method");
        compareDatesByCompareTo(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
        compareDatesByCompareTo(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
        compareDatesByCompareTo(df, df.parse("02-03-2012"), df.parse("01-02-2012"));
        //comparing dates in java using Date.before, Date.after and Date.equals
        System.out.println("Comparing two Date in Java using Date's before, after and equals method");
        compareDatesByDateMethods(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
        compareDatesByDateMethods(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
        compareDatesByDateMethods(df, df.parse("02-03-2012"), df.parse("01-02-2012"));
        //comparing dates in java using Calendar.before(), Calendar.after and Calendar.equals()
        System.out.println("Comparing two Date in Java using Calendar's before, after and equals method");
        compareDatesByCalendarMethods(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
        compareDatesByCalendarMethods(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
        compareDatesByCalendarMethods(df, df.parse("02-03-2012"), df.parse("01-02-2012"));
    }
    public static void compareDatesByCompareTo(DateFormat df, Date oldDate, Date newDate) {
        //how to check if date1 is equal to date2
        if (oldDate.compareTo(newDate) == 0) {
            System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
        }
        //checking if date1 is less than date 2
        if (oldDate.compareTo(newDate) < 0) {
            System.out.println(df.format(oldDate) + " is less than " + df.format(newDate));
        }
        //how to check if date1 is greater than date2 in java
        if (oldDate.compareTo(newDate) > 0) {
            System.out.println(df.format(oldDate) + " is greater than " + df.format(newDate));
        }
    }
    public static void compareDatesByDateMethods(DateFormat df, Date oldDate, Date newDate) {
        //how to check if two dates are equals in java
        if (oldDate.equals(newDate)) {
            System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
        }
        //checking if date1 comes before date2
        if (oldDate.before(newDate)) {
            System.out.println(df.format(oldDate) + " comes before " + df.format(newDate));
        }
        //checking if date1 comes after date2
        if (oldDate.after(newDate)) {
            System.out.println(df.format(oldDate) + " comes after " + df.format(newDate));
        }
    }
    public static void compareDatesByCalendarMethods(DateFormat df, Date oldDate, Date newDate) {
        //creating calendar instances for date comparision
        Calendar oldCal = Calendar.getInstance();
        Calendar newCal = Calendar.getInstance();
        oldCal.setTime(oldDate);
        newCal.setTime(newDate);
        //how to check if two dates are equals in java using Calendar
        if (oldCal.equals(newCal)) {
            System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
        }
        //how to check if one date comes before another using Calendar
        if (oldCal.before(newCal)) {
            System.out.println(df.format(oldDate) + " comes before " + df.format(newDate));
        }
        //how to check if one date comes after another using Calendar
        if (oldCal.after(newCal)) {
            System.out.println(df.format(oldDate) + " comes after " + df.format(newDate));
        }
    }
}
Output:
Comparing two Date in Java using CompareTo method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 is less than 04-05-2012
02-03-2012 is greater than 01-02-2012
Comparing two Date in Java using Date's before, after and equals method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 comes before 04-05-2012
02-03-2012 comes after 01-02-2012
Comparing two Date in Java using Calendar's before, after and equals method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 comes before 04-05-2012
02-03-2012 comes after 01-02-2012