lunes, 21 de agosto de 2017

Spring AppContext Beans (Xml y Anotaciones)

Spring AppContext Beans (Xml y Anotaciones)


  Prototipo básico de Spring por AppContext beans Core por xml

https://github.com/jalbertomr/jalbertomr-springAppContextBeans/commit/167618cb7557c6970c3e86127ebe095e73ff1937


Se modifica la configuración de xml a Anotaciones.
   Se crea una clase con nombre AppConfig, que puede tener otro nombre ya que se referencia en la class main por
ApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.class);

Se anota la Clase AppConfig con @Configuration

@Configuration
public class AppConfig {

    @Bean
    public ClaseParaBean cpb() {
        return new ClaseParaBean();
    }
   
    @Bean
    public Tierra tierra() {
        return new Tierra();
    }
   
    @Bean(name = "beanMarte")
    public Marte marte() {
        return new Marte();
    }
}


En la Clase Main

public static void main(String[] args) {
        System.out.println("Iniciado...");
       
       
        /* Metodo Beans */
        ApplicationContext appContext = 

        new AnnotationConfigApplicationContext(AppConfig.class);
        //ClaseParaBean cpb = (ClaseParaBean) appContext.getBean("claseBean");
        ClaseParaBean cpb = (ClaseParaBean)    appContext.getBean(ClaseParaBean.class);
        System.out.println("ClaseParaBean.getPropiedadDeClaseMensaje:" + cpb.getPropiedadDeClaseMensaje());
       
        Tierra tierra = (Tierra) appContext.getBean(Tierra.class);
        System.out.println("Tierra color:" + tierra.getColor() );
        System.out.println("Tierra diametro:" + tierra.getDiametro().toString());
       
        Marte marte = (Marte) appContext.getBean("beanMarte");
        System.out.println("Marte color:" + marte.getColor());
        System.out.println("Marte diametro:" + marte.getDiametro().toString());
       
        ((ConfigurableApplicationContext)appContext).close();
    }


  Se modifica la AppConfig por anotaciones para tener otra AppConfig2, y se modifica la clase main en la parte de AnnotationConfigApplicationContext(..)

AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext();
        appContext.register(AppConfig.class);
        appContext.register(AppConfig2.class);
        appContext.refresh();


La clase Tierra inicializa sus valores con la anotacion @Value en sus propiedades

public class Tierra {
    @Value("AZUL")
    private String Color;
    @Value("12742")
    private BigInteger diametro;

    public String getColor() {    return Color;     }
    public void setColor(String color) { Color = color;    }

    public BigInteger getDiametro() { return diametro; }
    public void setDiametro(BigInteger diametro) { this.diametro = diametro; }
}



 https://github.com/jalbertomr/jalbertomr-springAppContextBeans/commit/3202f72a3e757b986ad19fa953e0819056095bc0

Inyección por Constructor


   Creamos una clase Persona, y la declaramos en el beans.xml

Clase Persona
public class Persona {
    private int id;
    private String nombre;
    private String telefono;
   
    public Persona(int id, String nombre, String telefono) {
        this.id = id;
        this.nombre = nombre;
        this.telefono = telefono;
    }


    public Persona(int id) {
        this.id = id;
    }

    public Persona(String telefono) {
        this.telefono = telefono;
    }


En bean.xml declaramos el bean de Persona y las propiedades las inicializamos con constructor

beans.xml
...
<bean id="persona" class="com.bext.beans.Persona">
   <constructor-arg value="1"></constructor-arg>
   <constructor-arg value="Alberto"></constructor-arg>
   <constructor-arg value="4325235244"></constructor-arg>
</bean>

...

Al ejecutar la app tenemos
App.java
...
Persona per = (Persona) appContext.getBean("persona");
        System.out.println(per.getId() + " " + per.getNombre() +" "+per.getTelefono());

...

Iniciado...
1 Alberto 4325235244


Si solo inicializamos en el constructor con value="1" y ejecutamos la App tenemos

<bean id="persona" class="com.bext.beans.Persona">
   <constructor-arg value="1"></constructor-arg>
</bean>


Iniciado...
0 null 1


Observamos que con un solo valor en este caso "1" lo toma como String, o sea toma el constructor con un solo parametro de tipo String, pero este corresponde al Telefono. para que tome el int, hay que especificar el type="int" 

<bean id="persona" class="com.bext.beans.Persona">
   <constructor-arg type="int" value="1"></constructor-arg>
</bean>


Iniciado...
1 null null


Si especificamos el type="String" tomará el constructor con parámetro type String que corresponde al Telefono.

<bean id="persona" class="com.bext.beans.Persona">
   <constructor-arg type="String" value="1234567"></constructor-arg>
</bean>


Iniciado...
0 null 1234567


Podemos indicar la posición del parametro del constructor a inicializar

...
<bean id="persona" class="com.bext.beans.Persona">
   <constructor-arg index="2" value="1234567"></constructor-arg>
   <constructor-arg index="0" value="1"></constructor-arg>
   <constructor-arg index="1" value="Alberto"></constructor-arg>
</bean>

...

Iniciado...
1 Alberto 1234567


Inyección de Objectos

  A la Clase Persona le agregamos la Clase Pais.

Pais.java
public class Pais {
    private String nombre;

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
}


 
Persona.java
public class Persona {
    private int id;
    private String nombre;
    private String telefono;
    private Pais pais;
   
    public int getId() { return id; }
    public void setId(int id) {    this.id = id; }

    public String getNombre() {    return nombre;}
    public void setNombre(String nombre) { this.nombre = nombre;}

    public String getTelefono() { return telefono; }
    public void setTelefono(String telefono) { this.telefono = telefono; }

    public Pais getPais() {    return pais;}
    public void setPais(Pais pais) {this.pais = pais;}
}

App.java
public class App {

    public static void main(String[] args) {
        System.out.println("Iniciado...");
       
        /* Metodo Beans */
        ApplicationContext appContext = new ClassPathXmlApplicationContext("com/bext/xml/beans.xml");
        //AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext();
        //appContext.register(AppConfig.class);
        //appContext.register(AppConfig2.class);
        //appContext.refresh();
       
        Persona per = (Persona) appContext.getBean("persona");
        System.out.println(per.getId() + " " + per.getNombre() +" "+per.getTelefono() + " "+ per.getPais().getNombre());
       
        ((ConfigurableApplicationContext)appContext).close();
    }
}



beans.xml
...
<bean id="persona" class="com.bext.beans.Persona">
   <property name="pais" ref="pais"></property>
   <property name="id" value="1"></property>
   <property name="nombre" value="Alberto"></property>
   <property name="telefono" value="1234567"></property>
</bean>

<bean id="pais" class="com.bext.beans.Pais">
    <property name="nombre" value="Mexico"></property>
</bean>
...


Ejecución

Iniciado...
1 Alberto 1234567 Mexico


Inyección de sub-Objeto


Ahora agregamos otra clase a la de Pais, será Ciudad.

Ciudad.java
public class Ciudad {
    private String nombre;

    public String getNombre() {    return nombre;}
    public void setNombre(String nombre) {this.nombre = nombre;}
}


Pais.java
public class Pais {
    private String nombre;
    private Ciudad ciudad;

    public String getNombre() {    return nombre;    }
    public void setNombre(String nombre) {    this.nombre = nombre;    }

    public Ciudad getCiudad() {    return ciudad;    }
    public void setCiudad(Ciudad ciudad) {    this.ciudad = ciudad;}
}


beans.xml
...
<bean id="persona" class="com.bext.beans.Persona">
   <property name="pais" ref="pais"></property>
   <property name="id" value="1"></property>
   <property name="nombre" value="Alberto"></property>
   <property name="telefono" value="1234567"></property>
</bean>

<bean id="pais" class="com.bext.beans.Pais">
    <property name="nombre" value="Mexico"></property>
    <property name="ciudad" ref="ciudad"></property>
</bean>

<bean id="ciudad" class="com.bext.beans.Ciudad">
    <property name="nombre" value="CDMX"></property>
</bean>

...

App.java
...
        Persona per = (Persona) appContext.getBean("persona");
        System.out.println(per.getId() + " " + per.getNombre() +" "+per.getTelefono() + " "+ per.getPais().getNombre() + " "+per.getPais().getCiudad().getNombre());
...

Ejecución
Iniciado...
1 Alberto 1234567 Mexico CDMX


https://github.com/jalbertomr/jalbertomr-springAppContextBeans/commit/aa26774b29d7c021faf11faa7fdc67eaa47813de

Anidando Beans

Integramos Ciudad dentro de Pais
    <bean id="persona" class="com.bext.beans.Persona">
        <property name="pais" ref="pais"></property>
        <property name="id" value="1"></property>
        <property name="nombre" value="Alberto"></property>
        <property name="telefono" value="1234567"></property>
    </bean>

    <bean id="pais" class="com.bext.beans.Pais">
        <property name="nombre" value="Mexico"></property>
        <property name="ciudad">
            <bean id="ciudad" class="com.bext.beans.Ciudad">
                <property name="nombre" value="CDMX"></property>
            </bean>
        </property>
    </bean>


Ahora Integramos Ciudad dentro de Persona

    <bean id="persona" class="com.bext.beans.Persona">
        <property name="pais">
            <bean id="pais" class="com.bext.beans.Pais">
                <property name="nombre" value="Mexico"></property>
                <property name="ciudad">
                    <bean id="ciudad" class="com.bext.beans.Ciudad">
                        <property name="nombre" value="CDMX"></property>
                    </bean>
                </property>
            </bean>
        </property>
        <property name="id" value="1"></property>
        <property name="nombre" value="Alberto"></property>
        <property name="telefono" value="1234567"></property>
    </bean>


https://github.com/jalbertomr/jalbertomr-springAppContextBeans/commit/2817c32acb881ab56797c8cae565cee9e5317970


Referenciando Beans (Alias)


Creamos un alias en beans.xml para Persona

<alias name="persona" alias="personaAlias"></alias>

Y se llama este alias desde App.java

Persona per = (Persona) appContext.getBean("personaAlias");

Tambien podemos poner el nombre de alias en la definición del bean de Persona con nombre="personaAlias2"

<bean id="persona" class="com.bext.beans.Persona" name="personaAlias2">
        <property name="pais" ref="pais"></property>
        <property name="id" value="1"></property>
        <property name="nombre" value="Alberto"></property>
        <property name="telefono" value="1234567"></property>

</bean>

https://github.com/jalbertomr/jalbertomr-springAppContextBeans/commit/3dfbd46fb0850f4ba00a228dd72ac700682ab9ba


Colecciones (Lista) Beans

  Vamos a definir valores para las ciudades del pais por medio de inicialización por xml.

beans.xml
...
    <bean id="persona" class="com.bext.beans.Persona" name="personaAlias2">
        <property name="pais" ref="pais"></property>
        <property name="id" value="1"></property>
        <property name="nombre" value="Alberto"></property>
        <property name="telefono" value="1234567"></property>
    </bean>

    <bean id="pais" class="com.bext.beans.Pais">
        <property name="nombre" value="Mexico"></property>
        <property name="ciudades">
            <list>
               <ref bean="ciudad1"></ref>
               <ref bean="ciudad2"></ref>
               <ref bean="ciudad3"></ref>
            </list>

        </property>
    </bean>

    <bean id="ciudad1" class="com.bext.beans.Ciudad">
        <property name="nombre" value="CDMX"></property>
    </bean>
    <bean id="ciudad2" class="com.bext.beans.Ciudad">
        <property name="nombre" value="Tepatitlan"></property>
    </bean>
    <bean id="ciudad3" class="com.bext.beans.Ciudad">
        <property name="nombre" value="Guadalajara"></property>
    </bean>

...

La App.java la modificamos para que podamos desplegar la lista
...
Persona per = (Persona) appContext.getBean("personaAlias2");
        System.out.println(per.getId() + " " + per.getNombre() +" "+per.getTelefono() + " "+ per.getPais().getNombre());

        for (Ciudad ciudad:  per.getPais().getCiudades()) {
            System.out.println(ciudad.getNombre());
        }

...

Ejecución

Iniciado...
1 Alberto 1234567 Mexico
CDMX
Tepatitlan
Guadalajara


https://github.com/jalbertomr/jalbertomr-springAppContextBeans/commit/ff559934528cd433081c8d3caf9347f897e9364b


AutoWire

   Modificamos a Pais para que no tenga la propiedad Ciudad, se traslada esta propiedad a Persona.

  En beans.xml borramos las propiedades que asignaban a Pais y Ciudad, estos valores se tomaran con autowire la cual las asociará por nombre. 

beans.xml
...
<bean id="persona" class="com.bext.beans.Persona" autowire="byName">
        <property name="id" value="1"></property>
        <property name="nombre" value="Alberto"></property>
        <property name="telefono" value="1234567"></property>
    </bean>

    <bean id="pais" class="com.bext.beans.Pais">
        <property name="nombre" value="Mexico"></property>
    </bean>

    <bean id="ciudad" class="com.bext.beans.Ciudad">
        <property name="nombre" value="CDMX"></property>
    </bean>

...

Persona.java

public class Persona {
    private int id;
    private String nombre;
    private String telefono;
    private Pais pais;
    private Ciudad ciudad;

...

Ejecutando

Iniciado...
1 Alberto 1234567 Mexico CDMX


   El autowire puede hacerse tambien por type "byType", así asignará las propiedades de personas comparadas por tipo, pero si hay dos o más tipos no  sabrá a que bean asignar la propiedad. Tambien esta autowire por constructor.

Scope (Singleton, Prototype)

Prototype genera instancias diferentes por bean

...
<bean id="persona" class="com.bext.beans.Persona" autowire="byName" scope="prototype">
        <property name="id" value="1"></property>
        <property name="nombre" value="Alberto"></property>
        <property name="telefono" value="1234567"></property>
</bean>

...

Ejecución
Iniciado...
1 Alberto 1234567 Mexico CDMX
com.bext.beans.Persona@6fc6f14e
com.bext.beans.Persona@56235b8e


Singleton genera una sola instancia por cada bean que se cree.

...<bean id="persona" class="com.bext.beans.Persona" autowire="byName" scope="singleton">
        <property name="id" value="1"></property>
        <property name="nombre" value="Alberto"></property>
        <property name="telefono" value="1234567"></property>
    </bean>

...

Ejecución
Iniciado...
1 Alberto 1234567 Mexico CDMX
com.bext.beans.Persona@6fc6f14e
com.bext.beans.Persona@6fc6f14e


https://github.com/jalbertomr/jalbertomr-springAppContextBeans/commit/21d6eb30019cf7785188e7af715203808d58b6c0

eot

sábado, 19 de agosto de 2017

Heroku Lab Run Non-web Java Dynos


El laboratorio esta hecho para corren con maven, en netbeans por default usa ant, aunque tiene algunos arquetipos de maven que se pueden usar. En este caso el arquetivo es diferente a los incluidos en netbeans, así que usaremos un projecto default de maven, para despues modificar el archivo de control maven pom.xml.

se usan dos archivos java
src/main/java/OneOffProcess.java
public class OneOffProcess
{
    public static void main(String[] args)
    {
        System.out.println("OneOffProcess executed.");
    }
} 
 
src/main/java/WorkerProcess.java
public class WorkerProcess
{
    public static void main(String[] args)
    {
        while(true) {
            try {
                Thread.sleep(1000);
            } catch(InterruptedException e) {}

            System.out.println("Worker process woke up");
        }
    }
}
 
El pom default generado por netbeans es remplaado por 
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.bext</groupId>
    <artifactId>RunNonWebJavaHeroku</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>appassembler-maven-plugin</artifactId>
                <version>1.1.1</version>
                <configuration>
                    <assembleDirectory>target</assembleDirectory>
                    <programs>
                        <program>
                            <mainClass>WorkerProcess</mainClass>
                            <name>worker</name>
                        </program>
                        <program>
                            <mainClass>OneOffProcess</mainClass>
                            <name>oneoff</name>
                        </program>
                    </programs>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>assemble</goal>
                        </goals>
                    </execution>
                </executions>            
            </plugin>
        </plugins>
    </build>
</project>


 Desde el IDE o la consola de comandos construimos la aplicacion
C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building RunNonWebJavaHeroku 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ RunNonWebJavaHeroku ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ RunNonWebJavaHeroku ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ RunNonWebJavaHeroku ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ RunNonWebJavaHeroku ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ RunNonWebJavaHeroku ---
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ RunNonWebJavaHeroku ---
[INFO] Building jar: C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku\target\RunNonWebJavaHeroku-1.0-SNAPSHOT.jar
[INFO]
[INFO] --- appassembler-maven-plugin:1.1.1:assemble (default) @ RunNonWebJavaHeroku ---
[INFO] Installing C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku\target\RunNonWebJavaHeroku-1.0-SNAPSHOT.jar to C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku\target\repo\org\bext\RunNonWebJavaHeroku\1.0-SNAPSHOT\RunNonWebJavaHeroku-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 05:44 min
[INFO] Finished at: 2017-08-17T13:59:14-05:00
[INFO] Final Memory: 8M/126M
[INFO] ------------------------------------------------------------------------

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>

Corremos la aplicación localmente

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>target\bin\worker
Worker Process woke up
Worker Process woke up
Worker Process woke up
Worker Process woke up
Worker Process woke up
...

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>target\bin\oneoff
OneOffPrecess Executed.!

Deployamos a Heroku

  commiteamos los cambios de git, desde el IDE o linea de comandos.

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>git init
Reinitialized existing Git repository in C:/Users/Bext/Documents/NetBeansProjects/exercise/RunNonWebJavaHeroku/.git/

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>git add .
warning: LF will be replaced by CRLF in target/bin/oneoff.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in target/bin/worker.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in target/repo/org/bext/RunNonWebJavaHeroku/1.0-SNAPSHOT/maven-metadata-appassembler.xml.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in target/repo/org/bext/RunNonWebJavaHeroku/maven-metadata-appassembler.xml.
The file will have its original line endings in your working directory.

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>git commit -m "Listo para Deployar"
[master warning: LF will be replaced by CRLF in target/repo/org/bext/RunNonWebJavaHeroku/1.0-SNAPSHOT/maven-metadata-appassembler.xml.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in target/repo/org/bext/RunNonWebJavaHeroku/maven-metadata-appassembler.xml.
The file will have its original line endings in your working directory.
fd6a9dc] Listo para Deployar
warning: LF will be replaced by CRLF in target/repo/org/bext/RunNonWebJavaHeroku/1.0-SNAPSHOT/maven-metadata-appassembler.xml.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in target/repo/org/bext/RunNonWebJavaHeroku/maven-metadata-appassembler.xml.
The file will have its original line endings in your working directory.
 4 files changed, 3 insertions(+), 3 deletions(-)
 rewrite target/RunNonWebJavaHeroku-1.0-SNAPSHOT.jar (64%)
 rewrite target/repo/org/bext/RunNonWebJavaHeroku/1.0-SNAPSHOT/RunNonWebJavaHeroku-1.0-SNAPSHOT.jar (64%)

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>

Creamos la aplicación en heroku (remoto)

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>heroku create
Creating app... done, floating-eyrie-93131
https://floating-eyrie-93131.herokuapp.com/ | https://git.heroku.com/floating-eyrie-93131.git

Deployamos el codigo


C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>git remote -v
heroku  https://git.heroku.com/immense-castle-67621.git (fetch)
heroku  https://git.heroku.com/immense-castle-67621.git (push)

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>heroku git:remote -a floating-eyrie-93131
set git remote heroku to https://git.heroku.com/floating-eyrie-93131.git

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>git remote -v
heroku  https://git.heroku.com/floating-eyrie-93131.git (fetch)
heroku  https://git.heroku.com/floating-eyrie-93131.git (push)


C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>git push heroku master
Counting objects: 69, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (49/49), done.
Writing objects: 100% (69/69), 13.01 KiB | 0 bytes/s, done.
Total 69 (delta 18), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Java app detected
remote: -----> Installing OpenJDK 1.8... done
remote: -----> Installing Maven 3.3.9... done
....

Scaling Worker Processes

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>heroku ps:scale worker=1
Scaling dynos... done, now running worker at 1:Free

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>heroku logs --tail
2017-08-18T00:38:37.659743+00:00 app[worker.1]: Worker Process woke up
2017-08-18T00:38:38.659965+00:00 app[worker.1]: Worker Process woke up
2017-08-18T00:38:39.660199+00:00 app[worker.1]: Worker Process woke up
2017-08-18T00:38:40.660405+00:00 app[worker.1]: Worker Process woke up
2017-08-18T00:38:41.660590+00:00 app[worker.1]: Worker Process woke up
2017-08-18T00:38:42.660820+00:00 app[worker.1]: Worker Process woke up
2017-08-18T00:38:43.661039+00:00 app[worker.1]: Worker Process woke up

One-off Dynos


C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>heroku run "sh target/bin/oneoff"
Running sh target/bin/oneoff on floating-eyrie-93131... up, run.1450 (Free)
OneOffPrecess Executed.!

C:\Users\Bext\Documents\NetBeansProjects\exercise\RunNonWebJavaHeroku>

domingo, 13 de agosto de 2017

Docker Fundamentls Lab inicial test


Se instala inicialmente la herramienta que permitira interactuar con Docker

https://www.docker.com/products/docker-toolbox

Esta herramienta me desplegara una consola.


                        ##         .
                  ## ## ##        ==
               ## ## ## ## ##    ===
           /"""""""""""""""""\___/ ===
      ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
           \______ o           __/
             \    \         __/
              \____\_______/

docker is configured to use the default machine with IP 192.168.99.100
For help getting started, check out the docs at https://docs.docker.com

Start interactive shell

Instalar en ubuntu  wget -q0- https://get.docker.com/ | sh

to use as a non root user
 sudo usermod -aG docker beto
 exit


Bext@android-ae23f0022eea MINGW64 ~
$ docker run hello-world

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://cloud.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/engine/userguide/

$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
hello-world         latest              1815c82652c0        2 months ago        1.84kB


Bext@android-ae23f0022eea MINGW64 ~
$ docker run ubuntu:14.04 echo "hello World!"
hello World!

Bext@android-ae23f0022eea MINGW64 ~
$ docker run ubuntu:14.04 ps ax
  PID TTY      STAT   TIME COMMAND
    1 ?        Rs     0:00 ps ax

Bext@android-ae23f0022eea MINGW64 ~
$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              14.04               c69811d4e993        3 days ago          188MB
hello-world         latest              1815c82652c0        2 months ago        1.84kB

Bext@android-ae23f0022eea MINGW64 ~
$ docker run -i -t ubuntu:14.04 /bin/bash
root@f291a23dcabe:/# adduser beto
Adding user `beto' ...
Adding new group `beto' (1000) ...
Adding new user `beto' (1000) with group `beto' ...
Creating home directory `/home/beto' ...
Copying files from `/etc/skel' ...
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
ChangingFull Name []: rmation for beto
Enter thRoom Number []: press ENTER for the default
        Home Phone []:
        Other []:
Is the information correct? [Y/n] Y
root@f291a23dcabe:/# adduser beto sudo
Adding user `beto' to group `sudo' ...
Adding user beto to group sudo
Done.
root@f291a23dcabe:/# su beto

beto@f291a23dcabe:/$ sudo apt-get install vim
[sudo] password for beto:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package vim is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'vim' has no installation candidate
beto@f291a23dcabe:/$
beto@f291a23dcabe:/$ sudo apt-get update
Get:1 http://security.ubuntu.com trusty-security InRelease [65.9 kB]
Ign http://archive.ubuntu.com trusty InRelease
Get:2 http://archive.ubuntu.com trusty-updates InRelease [65.9 kB]
Get:3 http://archive.ubuntu.com trusty-backports InRelease [65.9 kB]
Get:4 http://archive.ubuntu.com trusty Release.gpg [933 B]
Get:5 http://archive.ubuntu.com trusty Release [58.5 kB]
Get:6 http://security.ubuntu.com trusty-security/universe Sources [73.1 kB]
Get:7 http://archive.ubuntu.com trusty-updates/universe Sources [236 kB]
Get:8 http://security.ubuntu.com trusty-security/main amd64 Packages [809 kB]
Get:9 http://archive.ubuntu.com trusty-updates/main amd64 Packages [1258 kB]
Get:10 http://security.ubuntu.com trusty-security/restricted amd64 Packages [17.9 kB]
Get:11 http://security.ubuntu.com trusty-security/universe amd64 Packages [229 kB]
Get:12 http://archive.ubuntu.com trusty-updates/restricted amd64 Packages [21.2 kB]
Get:13 http://archive.ubuntu.com trusty-updates/universe amd64 Packages [542 kB]
Get:14 http://security.ubuntu.com trusty-security/multiverse amd64 Packages [4016 B]
Get:15 http://archive.ubuntu.com trusty-updates/multiverse amd64 Packages [15.6 kB]
Get:16 http://archive.ubuntu.com trusty-backports/main amd64 Packages [14.8 kB]
Get:17 http://archive.ubuntu.com trusty-backports/restricted amd64 Packages [40 B]
Get:18 http://archive.ubuntu.com trusty-backports/universe amd64 Packages [52.6 kB]
Get:19 http://archive.ubuntu.com trusty-backports/multiverse amd64 Packages [1396 B]
Get:20 http://archive.ubuntu.com trusty/universe Sources [7926 kB]
Get:21 http://archive.ubuntu.com trusty/main amd64 Packages [1743 kB]
Get:22 http://archive.ubuntu.com trusty/restricted amd64 Packages [16.0 kB]
Get:23 http://archive.ubuntu.com trusty/universe amd64 Packages [7589 kB]
Get:24 http://archive.ubuntu.com trusty/multiverse amd64 Packages [169 kB]
Fetched 21.0 MB in 33s (622 kB/s)
Reading package lists... Done

beto@f291a23dcabe:/$ sudo apt-get install vim
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
  libgpm2 libpython2.7 libpython2.7-minimal libpython2.7-stdlib vim-runtime
Suggested packages:
  gpm ctags vim-doc vim-scripts
The following NEW packages will be installed:
  libgpm2 libpython2.7 libpython2.7-minimal libpython2.7-stdlib vim
  vim-runtime
0 upgraded, 6 newly installed, 0 to remove and 0 not upgraded.
Need to get 9074 kB of archives.
After this operation, 42.9 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://archive.ubuntu.com/ubuntu/ trusty/main libgpm2 amd64 1.20.4-6.1 [16.5 kB]
Get:2 http://archive.ubuntu.com/ubuntu/ trusty-updates/main libpython2.7-minimal amd64 2.7.6-8ubuntu0.3 [307 kB]
Get:3 http://archive.ubuntu.com/ubuntu/ trusty-updates/main libpython2.7-stdlib amd64 2.7.6-8ubuntu0.3 [1873 kB]
Get:4 http://archive.ubuntu.com/ubuntu/ trusty-updates/main libpython2.7 amd64 2.7.6-8ubuntu0.3 [1039 kB]
Get:5 http://archive.ubuntu.com/ubuntu/ trusty-updates/main vim-runtime all 2:7.4.052-1ubuntu3.1 [4882 kB]
Get:6 http://archive.ubuntu.com/ubuntu/ trusty-updates/main vim amd64 2:7.4.052-1ubuntu3.1 [955 kB]
Fetched 9074 kB in 22s (412 kB/s)
Selecting previously unselected package libgpm2:amd64.
(Reading database ... 11569 files and directories currently installed.)
Preparing to unpack .../libgpm2_1.20.4-6.1_amd64.deb ...
Unpacking libgpm2:amd64 (1.20.4-6.1) ...
Selecting previously unselected package libpython2.7-minimal:amd64.
Preparing to unpack .../libpython2.7-minimal_2.7.6-8ubuntu0.3_amd64.deb ...
Unpacking libpython2.7-minimal:amd64 (2.7.6-8ubuntu0.3) ...
Selecting previously unselected package libpython2.7-stdlib:amd64.
Preparing to unpack .../libpython2.7-stdlib_2.7.6-8ubuntu0.3_amd64.deb ...
Unpacking libpython2.7-stdlib:amd64 (2.7.6-8ubuntu0.3) ...
Selecting previously unselected package libpython2.7:amd64.
Preparing to unpack .../libpython2.7_2.7.6-8ubuntu0.3_amd64.deb ...
Unpacking libpython2.7:amd64 (2.7.6-8ubuntu0.3) ...
Selecting previously unselected package vim-runtime.
Preparing to unpack .../vim-runtime_2%3a7.4.052-1ubuntu3.1_all.deb ...
Adding 'diversion of /usr/share/vim/vim74/doc/help.txt to /usr/share/vim/vim74/doc/help.txt.vim-tiny by vim-runtime'
Adding 'diversion of /usr/share/vim/vim74/doc/tags to /usr/share/vim/vim74/doc/tags.vim-tiny by vim-runtime'
Unpacking vim-runtime (2:7.4.052-1ubuntu3.1) ...
Selecting previously unselected package vim.
Preparing to unpack .../vim_2%3a7.4.052-1ubuntu3.1_amd64.deb ...
Unpacking vim (2:7.4.052-1ubuntu3.1) ...
Setting up libgpm2:amd64 (1.20.4-6.1) ...
Setting up libpython2.7-minimal:amd64 (2.7.6-8ubuntu0.3) ...
Setting up libpython2.7-stdlib:amd64 (2.7.6-8ubuntu0.3) ...
Setting up libpython2.7:amd64 (2.7.6-8ubuntu0.3) ...
Setting up vim-runtime (2:7.4.052-1ubuntu3.1) ...
Processing /usr/share/vim/addons/doc
Setting up vim (2:7.4.052-1ubuntu3.1) ...
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/vim (vim) in auto mode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/vimdiff (vimdiff) in auto mode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/rvim (rvim) in auto mode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/rview (rview) in auto mode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/vi (vi) in auto mode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/view (view) in auto mode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/ex (ex) in auto mode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/editor (editor) in auto mode
Processing triggers for libc-bin (2.19-0ubuntu6.13) ...

beto@f291a23dcabe:/$ ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

beto@f291a23dcabe:/$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
libuuid:x:100:101::/var/lib/libuuid:
syslog:x:101:104::/home/syslog:/bin/false
beto:x:1000:1000:,,,:/home/beto:/bin/bash

beto@f291a23dcabe:/$ sudo vim miArchivo.txt
~
~
"miArchivo.txt" [New] 1L, 17C written
beto@f291a23dcabe:/$ ls
bin  boot  dev  etc  home  lib  lib64  media  miArchivo.txt  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

beto@f291a23dcabe:/$ exit 
exit
root@f291a23dcabe:/# exit
exit

Bext@android-ae23f0022eea MINGW64 ~
Bext@android-ae23f0022eea MINGW64 ~
$ docker run -i -t ubuntu:14.04 /bin/bash
root@9c86cbb9f33f:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@9c86cbb9f33f:/# su beto
No passwd entry for user 'beto'

En esta instancia de ubuntu se puede ver que no hay archivo creado anteriormente (miArchivo.txt) y tampoco el usuario beto.


Bext@android-ae23f0022eea MINGW64 ~
$ docker run -it ubuntu:14.04 bash
root@70a3b5c4ef14:/# ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  4 00:09 pts/0    00:00:00 bash
root        14     1  0 00:09 pts/0    00:00:00 ps -ef
root@70a3b5c4ef14:/#

Stoping the container CTRL+P+Q

Bext@android-ae23f0022eea MINGW64 ~
docker ps     [list containers]
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
70a3b5c4ef14        ubuntu:14.04        "bash"              4 minutes ago       Up 4 minutes                            angry_shockley
31a35ff59ee7        ubuntu:14.04        "bash"              7 minutes ago       Up 7 minutes                            focused_ptolemy

$ docker run -it ubuntu:14.04 bashroot@8d141d7b24b5:/#   [Stoping the container CTRL+P+Q]
Bext@android-ae23f0022eea MINGW64 ~
$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
8d141d7b24b5        ubuntu:14.04        "bash"              6 seconds ago       Up 6 seconds                            confident_ardinghelli
70a3b5c4ef14        ubuntu:14.04        "bash"              5 minutes ago       Up 5 minutes                            angry_shockley
31a35ff59ee7        ubuntu:14.04        "bash"              8 minutes ago       Up 8 minutes                            focused_ptolemy


Bext@android-ae23f0022eea MINGW64 ~
$ docker ps -a      [all containers, includes containers that are stopped]
CONTAINER ID        IMAGE               COMMAND                 CREATED             STATUS                           PORTS               NAMES
8d141d7b24b5        ubuntu:14.04        "bash"                  2 minutes ago       Up 2 minutes                                         confident_ardinghelli
70a3b5c4ef14        ubuntu:14.04        "bash"                  8 minutes ago       Up 8 minutes                                         angry_shockley
9e0932a2eca8        ubuntu:14.04        "bash"                  9 minutes ago       Exited (0) 9 minutes ago                             peaceful_snyder
31a35ff59ee7        ubuntu:14.04        "bash"                  11 minutes ago      Up 11 minutes                                        focused_ptolemy
9169e0e72524        ubuntu:14.04        "bash"                  11 minutes ago      Exited (0) 11 minutes ago                            romantic_brattain
9c86cbb9f33f        ubuntu:14.04        "/bin/bash"             21 minutes ago      Exited (0) 19 minutes ago                            unruffled_babbage
f291a23dcabe        ubuntu:14.04        "/bin/bash"             36 minutes ago      Exited (0) 23 minutes ago                            adoring_brattain
3af9453da329        ubuntu:14.04        "ps ax"                 39 minutes ago      Exited (0) 39 minutes ago                            compassionate_davinci
26035831c5c9        ubuntu:14.04        "echo 'hello World!'"   41 minutes ago      Exited (0) 41 minutes ago                            affectionate_lichterman
3518cf4ae416        hello-world         "/hello"                44 minutes ago      Exited (0) 44 minutes ago                            determined_wiles
d4dbdf9d6e76        ubuntu:14.04        "/bin/bash"             About an hour ago   Exited (0) About an hour ago                         compassionate_kilby
04b19b386271        ubuntu:14.04        "/bin/bash"             About an hour ago   Exited (127) About an hour ago                       ecstatic_cray
0e2c51111982        ubuntu:14.04        "/bin/bash"             About an hour ago   Exited (0) About an hour ago                         quizzical_nobel
1d24858fc730        ubuntu:14.04        "ps ax"                 About an hour ago   Exited (0) About an hour ago                         unruffled_knuth
57158675caea        ubuntu:14.04        "echo 'Hello World!'"   About an hour ago   Exited (0) About an hour ago                         thirsty_dubinsky
c04d284278b5        hello-world         "/hello"                2 hours ago         Exited (0) 2 hours ago                               agitated_keller

Bext@android-ae23f0022eea MINGW64 ~

Running in Detached Mode
- Conocida como background o demon
- se usa -d
- Para observar la salida usamos docker logs [contianer id]

Creamos un centos container y corremos el comando ping  al ping container a mi mismo 50 veces
docker run -d centos:7 ping 127.0.0.1 -c 50

Bext@android-ae23f0022eea MINGW64 ~
$ docker run -d centos:7 ping 127.0.0.1 -c 50
Unable to find image 'centos:7' locally
7: Pulling from library/centos
74f0853ba93b: Pull complete
Digest: sha256:26f74cefad82967f97f3eeeef88c1b6262f9b42bc96f2ad61d6f3fdf544759b8
Status: Downloaded newer image for centos:7
ecc4a028333a8a4f899f7cb7d5cddd0810d55014d798b25f5dec3a25e599b41c

Bext@android-ae23f0022eea MINGW64 ~
$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
ecc4a028333a        centos:7            "ping 127.0.0.1 -c 50"   6 seconds ago       Up 6 seconds                            elastic_ptolemy
8d141d7b24b5        ubuntu:14.04        "bash"                   12 minutes ago      Up 12 minutes                           confident_ardinghelli
70a3b5c4ef14        ubuntu:14.04        "bash"                   18 minutes ago      Up 18 minutes                           angry_shockley
31a35ff59ee7        ubuntu:14.04        "bash"                   21 minutes ago      Up 21 minutes                           focused_ptolemy

Bext@android-ae23f0022eea MINGW64 ~
$ docker logs ecc4a028333a

PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.076 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.061 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.060 ms
64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.068 ms
64 bytes from 127.0.0.1: icmp_seq=5 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=6 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=7 ttl=64 time=0.065 ms
64 bytes from 127.0.0.1: icmp_seq=8 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=9 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=10 ttl=64 time=0.061 ms
64 bytes from 127.0.0.1: icmp_seq=11 ttl=64 time=0.060 ms
64 bytes from 127.0.0.1: icmp_seq=12 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=13 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=14 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=15 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=16 ttl=64 time=0.060 ms
64 bytes from 127.0.0.1: icmp_seq=17 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=18 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=19 ttl=64 time=0.061 ms
64 bytes from 127.0.0.1: icmp_seq=20 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=21 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=22 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=23 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=24 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=25 ttl=64 time=0.062 ms
64 bytes from 127.0.0.1: icmp_seq=26 ttl=64 time=0.062 ms
64 bytes from 127.0.0.1: icmp_seq=27 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=28 ttl=64 time=0.062 ms
64 bytes from 127.0.0.1: icmp_seq=29 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=30 ttl=64 time=0.083 ms
64 bytes from 127.0.0.1: icmp_seq=31 ttl=64 time=0.060 ms
64 bytes from 127.0.0.1: icmp_seq=32 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=33 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=34 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=35 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=36 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=37 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=38 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=39 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=40 ttl=64 time=0.061 ms
64 bytes from 127.0.0.1: icmp_seq=41 ttl=64 time=0.060 ms
64 bytes from 127.0.0.1: icmp_seq=42 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=43 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=44 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=45 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=46 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=47 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=48 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=49 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=50 ttl=64 time=0.066 ms

--- 127.0.0.1 ping statistics ---
50 packets transmitted, 50 received, 0% packet loss, time 48996ms
rtt min/avg/max/mdev = 0.060/0.065/0.083/0.010 ms

Bext@android-ae23f0022eea MINGW64 ~


A More Practical Example
- run a Web application in a container
- the -P flag to map container ports to host ports
 Create a container usint the tomcat image, run in detached mode and map the tomcat ports to
the host ports.
docker run -d -P tomcat:7

Bext@android-ae23f0022eea MINGW64 ~
$ docker run -d -P tomcat:7
Unable to find image 'tomcat:7' locally
7: Pulling from library/tomcat
ad74af05f5a2: Pull complete
2b032b8bbe8b: Pull complete
99a5213ead46: Pull complete
7de34ca31efd: Pull complete
9b22e57d98bb: Pull complete
12cd7a66c3fd: Pull complete
880bb942de44: Pull complete
6ada99602995: Pull complete
90451a97de52: Pull complete
646677f3b1ed: Pull complete
1e23e3421594: Pull complete
6ea7a2fda905: Pull complete
Digest: sha256:c9fb261508e2bba25f84de653a64e98acd2ad2b42dfa4b25bf6a787ca328b7b0
Status: Downloaded newer image for tomcat:7
45f9343e257bc8492719bda15659940e3f04e48c70941f304b6ee09699034323

Bext@android-ae23f0022eea MINGW64 ~ 
 

$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                     NAMES
45f9343e257b        tomcat:7            "catalina.sh run"   34 seconds ago      Up 34 seconds       0.0.0.0:32768->8080/tcp   kind_hermann
8d141d7b24b5        ubuntu:14.04        "bash"              25 minutes ago      Up 25 minutes                                 confident_ardinghelli
70a3b5c4ef14        ubuntu:14.04        "bash"              31 minutes ago      Up 31 minutes                                 angry_shockley
31a35ff59ee7        ubuntu:14.04        "bash"              34 minutes ago      Up 34 minutes                                 focused_ptolemy

Bext@android-ae23f0022eea MINGW64 ~ 


Desde el Browser acceder al servidor tomcat...
en este caso la direccion IP es la que me dio al iniciar la terminal de docker 192.168.99.100 y el puerto 32768 como lo indica el docker ps.


Ejecutando Glassfish
Bext@android-ae23f0022eea MINGW64 ~
$ docker run -ti -p 4848:4848 -p 8080:8080 oracle/glassfish
Unable to find image 'oracle/glassfish:latest' locally
latest: Pulling from oracle/glassfish
3152c71f8d80: Already exists
903ff9bc907d: Pull complete
07f804c85584: Pull complete
Digest: sha256:4eb405471fc258d237a2c3d9f09284a6de48d9de4a3859202ae52a22ec5ad64e
Status: Downloaded newer image for oracle/glassfish:latest
##########GENERATED ADMIN PASSWORD: 79567d53  ##########
Command change-admin-password executed successfully.
Waiting for domain1 to start ..........................................
Successfully started the domain : domain1
domain  Location: /glassfish4/glassfish/domains/domain1
Log File: /glassfish4/glassfish/domains/domain1/logs/server.log
Admin Port: 4848
Command start-domain executed successfully.
You must restart all running servers for the change in secure admin to take effect.
Command enable-secure-admin executed successfully.
Waiting for the domain to stop ..
Command stop-domain executed successfully.
Aug 14, 2017 2:21:41 AM com.sun.enterprise.admin.launcher.GFLauncherLogger info
INFO: JVM invocation command line:
/usr/lib/jvm/java-openjdk/bin/java
-cp
/glassfish4/glassfish/modules/glassfish.jar
-XX:+UnlockDiagnosticVMOptions
-XX:MaxPermSize=192m
-XX:NewRatio=2
-Xmx512m
-client
-javaagent:/glassfish4/glassfish/lib/monitor/flashlight-agent.jar
-Dfelix.fileinstall.disableConfigSave=false
-Djavax.net.ssl.keyStore=/glassfish4/glassfish/domains/domain1/config/keystore.jks
-Djava.awt.headless=true
-Dcom.ctc.wstx.returnNullForDefaultNamespace=true
-Dfelix.fileinstall.poll=5000
-Djava.endorsed.dirs=/glassfish4/glassfish/modules/endorsed:/glassfish4/glassfish/lib/endorsed
-Dfelix.fileinstall.bundles.startTransient=true
-Djavax.net.ssl.trustStore=/glassfish4/glassfish/domains/domain1/config/cacerts.jks
-Djavax.xml.accessExternalSchema=all
-Dcom.sun.enterprise.security.httpsOutboundKeyAlias=s1as
-Djava.security.auth.login.config=/glassfish4/glassfish/domains/domain1/config/login.conf
-DANTLR_USE_DIRECT_CLASS_LOADING=true
-Dgosh.args=--nointeractive
-Dosgi.shell.telnet.maxconn=1
-Djdbc.drivers=org.apache.derby.jdbc.ClientDriver
-Dfelix.fileinstall.dir=/glassfish4/glassfish/modules/autostart/
-Dosgi.shell.telnet.port=6666
-Djava.security.policy=/glassfish4/glassfish/domains/domain1/config/server.policy
-Dfelix.fileinstall.log.level=2
-Dcom.sun.aas.instanceRoot=/glassfish4/glassfish/domains/domain1
-Dcom.sun.enterprise.config.config_environment_factory_class=com.sun.enterprise.config.serverbeans.AppserverConfigEnvironmentFactory
-Dosgi.shell.telnet.ip=127.0.0.1
-Dcom.sun.aas.installRoot=/glassfish4/glassfish
-Djava.ext.dirs=/usr/lib/jvm/java-openjdk/lib/ext:/usr/lib/jvm/java-openjdk/jre/lib/ext:/glassfish4/glassfish/domains/domain1/lib/ext
-Dfelix.fileinstall.bundles.new.start=true
-Dorg.glassfish.additionalOSGiBundlesToStart=org.apache.felix.shell,org.apache.felix.gogo.runtime,org.apache.felix.gogo.shell,org.apache.felix.gogo.command,org.apache.felix.shell.remote,org.apache.felix.fileinstall
-Djdk.corba.allowOutputStreamSubclass=true
-Djava.library.path=/glassfish4/glassfish/lib:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
com.sun.enterprise.glassfish.bootstrap.ASMain
-domainname
domain1
-asadmin-args
--host,,,localhost,,,--port,,,4848,,,--secure=false,,,--terse=false,,,--echo=false,,,--interactive=true,,,start-domain,,,--verbose=true,,,--watchdog=false,,,--debug=false,,,--domaindir,,,/glassfish4/glassfish/domains,,,domain1
-instancename
server
-verbose
true
-debug
false
-asadmin-classpath
/glassfish4/glassfish/lib/client/appserver-cli.jar
-asadmin-classname
com.sun.enterprise.admin.cli.AdminMain
-upgrade
false
-type
DAS
-domaindir
/glassfish4/glassfish/domains/domain1
-read-stdin
true
Launching GlassFish on Felix platform
Aug 14, 2017 2:21:50 AM com.sun.enterprise.glassfish.bootstrap.osgi.BundleProvisioner createBundleProvisioner
INFO: Create bundle provisioner class = class com.sun.enterprise.glassfish.bootstrap.osgi.BundleProvisioner.
Aug 14, 2017 2:21:50 AM com.sun.enterprise.glassfish.bootstrap.osgi.BundleProvisioner$DefaultCustomizer getLocations
WARNING: Skipping entry  because it is not an absolute URI.
Aug 14, 2017 2:21:50 AM com.sun.enterprise.glassfish.bootstrap.osgi.BundleProvisioner$DefaultCustomizer getLocations
WARNING: Skipping entry  because it is not an absolute URI.
Aug 14, 2017 2:21:51 AM com.sun.enterprise.glassfish.bootstrap.osgi.BundleProvisioner startBundles
WARNING: Can not start bundle file:/glassfish4/glassfish/modules/core.jar because it is not contained in the list of installed bundles.
Registered com.sun.enterprise.glassfish.bootstrap.osgi.EmbeddedOSGiGlassFishRuntime@ce6eb5e in service registry.



#!## LogManagerService.postConstruct : rootFolder=/glassfish4/glassfish
#!## LogManagerService.postConstruct : templateDir=/glassfish4/glassfish/lib/templates
#!## LogManagerService.postConstruct : src=/glassfish4/glassfish/lib/templates/logging.properties
#!## LogManagerService.postConstruct : dest=/glassfish4/glassfish/domains/domain1/config/logging.properties
[#|2017-08-14T02:22:09.547+0000|INFO|glassfish 4.1|javax.enterprise.logging|_ThreadID=15;_ThreadName=RunLevelControllerThread-1502677328051;_TimeMillis=1502677329547;_LevelValue=800;_MessageID=NCLS-LOGGING-00009;|
  Running GlassFish Version: GlassFish Server Open Source Edition  4.1.2  (build 1)|#]

[#|2017-08-14T02:22:09.556+0000|INFO|glassfish 4.1|javax.enterprise.logging|_ThreadID=15;_ThreadName=RunLevelControllerThread-1502677328051;_TimeMillis=1502677329556;_LevelValue=800;_MessageID=NCLS-LOGGING-00010;|
  Server log file is using Formatter class: com.sun.enterprise.server.logging.ODLLogFormatter|#]

[#|2017-08-14T02:22:12.234+0000|INFO|glassfish 4.1|org.glassfish.ha.store.spi.BackingStoreFactoryRegistry|_ThreadID=15;_ThreadName=RunLevelControllerThread-1502677328051;_TimeMillis=1502677332234;_LevelValue=800;|
  Registered org.glassfish.ha.store.adapter.cache.ShoalBackingStoreProxy for persistence-type = replicated in BackingStoreFactoryRegistry|#]

[#|2017-08-14T02:22:12.883+0000|INFO|glassfish 4.1|javax.enterprise.system.core.security|_ThreadID=16;_ThreadName=RunLevelControllerThread-1502677328097;_TimeMillis=1502677332883;_LevelValue=800;_MessageID=NCLS-SECURITY-01115;|
  Realm [admin-realm] of classtype [com.sun.enterprise.security.auth.realm.file.FileRealm] successfully created.|#]

[#|2017-08-14T02:22:12.971+0000|INFO|glassfish 4.1|javax.enterprise.system.core.security|_ThreadID=16;_ThreadName=RunLevelControllerThread-1502677328097;_TimeMillis=1502677332971;_LevelValue=800;_MessageID=NCLS-SECURITY-01115;|
  Realm [file] of classtype [com.sun.enterprise.security.auth.realm.file.FileRealm] successfully created.|#]

[#|2017-08-14T02:22:13.079+0000|INFO|glassfish 4.1|javax.enterprise.system.core.security|_ThreadID=16;_ThreadName=RunLevelControllerThread-1502677328097;_TimeMillis=1502677333079;_LevelValue=800;_MessageID=NCLS-SECURITY-01115;|
  Realm [certificate] of classtype [com.sun.enterprise.security.auth.realm.certificate.CertificateRealm] successfully created.|#]

[#|2017-08-14T02:22:13.920+0000|INFO|glassfish 4.1|javax.enterprise.security.services|_ThreadID=16;_ThreadName=RunLevelControllerThread-1502677328097;_TimeMillis=1502677333920;_LevelValue=800;_MessageID=SEC-SVCS-00100;|
  Authorization Service has successfully initialized.|#]

[#|2017-08-14T02:22:13.988+0000|WARNING|glassfish 4.1|org.glassfish.grizzly.config.Utils|_ThreadID=17;_ThreadName=RunLevelControllerThread-1502677328097;_TimeMillis=1502677333988;_LevelValue=900;|
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=http-listener-1, realClassName=org.glassfish.grizzly.http2.Http2AddOn|#]

[#|2017-08-14T02:22:14.478+0000|INFO|glassfish 4.1|javax.enterprise.system.core|_ThreadID=17;_ThreadName=RunLevelControllerThread-1502677328097;_TimeMillis=1502677334478;_LevelValue=800;_MessageID=NCLS-CORE-00087;|
  Grizzly Framework 2.3.23 started in: 182ms - bound to [/0.0.0.0:8080]|#]

[#|2017-08-14T02:22:14.668+0000|WARNING|glassfish 4.1|org.glassfish.grizzly.config.Utils|_ThreadID=17;_ThreadName=RunLevelControllerThread-1502677328097;_TimeMillis=1502677334668;_LevelValue=900;|
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=http-listener-2, realClassName=org.glassfish.grizzly.http2.Http2AddOn|#]

[#|2017-08-14T02:22:14.731+0000|INFO|glassfish 4.1|javax.enterprise.system.core|_ThreadID=17;_ThreadName=RunLevelControllerThread-1502677328097;_TimeMillis=1502677334731;_LevelValue=800;_MessageID=NCLS-CORE-00087;|
  Grizzly Framework 2.3.23 started in: 15ms - bound to [/0.0.0.0:8181]|#]

[#|2017-08-14T02:22:14.892+0000|WARNING|glassfish 4.1|org.glassfish.grizzly.config.Utils|_ThreadID=17;_ThreadName=RunLevelControllerThread-1502677328097;_TimeMillis=1502677334892;_LevelValue=900;|
  Instance could not be initialized. Class=interface org.glassfish.grizzly.http.server.AddOn, name=admin-listener, realClassName=org.glassfish.grizzly.http2.Http2AddOn|#]

[#|2017-08-14T02:22:14.999+0000|INFO|glassfish 4.1|javax.enterprise.system.core|_ThreadID=17;_ThreadName=RunLevelControllerThread-1502677328097;_TimeMillis=1502677334999;_LevelValue=800;_MessageID=NCLS-CORE-00087;|
  Grizzly Framework 2.3.23 started in: 22ms - bound to [/0.0.0.0:4848]|#]

[#|2017-08-14T02:22:15.483+0000|INFO|glassfish 4.1|javax.enterprise.system.core|_ThreadID=17;_ThreadName=RunLevelControllerThread-1502677328097;_TimeMillis=1502677335483;_LevelValue=800;_MessageID=NCLS-CORE-00087;|
  Grizzly Framework 2.3.23 started in: 1ms - bound to [/0.0.0.0:3700]|#]

[#|2017-08-14T02:22:15.488+0000|INFO|glassfish 4.1|javax.enterprise.system.core|_ThreadID=1;_ThreadName=main;_TimeMillis=1502677335488;_LevelValue=800;_MessageID=NCLS-CORE-00017;|
  GlassFish Server Open Source Edition  4.1.2  (1) startup time : Felix (24,929ms), startup services(7,479ms), total(32,408ms)|#]

[#|2017-08-14T02:22:18.481+0000|INFO|glassfish 4.1|javax.enterprise.system.jmx|_ThreadID=50;_ThreadName=Thread-13;_TimeMillis=1502677338481;_LevelValue=800;_MessageID=NCLS-JMX-00024;|
  Creating a SecureRMIServerSocketFactory @ 0.0.0.0 with ssl config = GlassFishConfigBean.org.glassfish.grizzly.config.dom.Ssl|#]

[#|2017-08-14T02:22:18.601+0000|INFO|glassfish 4.1||_ThreadID=50;_ThreadName=Thread-8;_TimeMillis=1502677338601;_LevelValue=800;|
  SSLParams =org.glassfish.admin.mbeanserver.ssl.SSLParams@633e79e7|#]

[#|2017-08-14T02:22:18.606+0000|WARNING|glassfish 4.1|javax.enterprise.system.jmx|_ThreadID=50;_ThreadName=Thread-13;_TimeMillis=1502677338606;_LevelValue=900;_MessageID=NCLS-JMX-00020;|
  All SSL cipher suites disabled for network-listener(s).  Using SSL implementation specific defaults|#]

[#|2017-08-14T02:22:18.480+0000|INFO|glassfish 4.1|javax.enterprise.system.core.transaction.com.sun.jts.CosTransactions|_ThreadID=15;_ThreadName=RunLevelControllerThread-1502677328051;_TimeMillis=1502677338480;_LevelValue=800;_MessageID=jts.startup_msg;|
  JTS5014: Recoverable JTS instance, serverId = [100]|#]

[#|2017-08-14T02:22:19.510+0000|INFO|glassfish 4.1|javax.enterprise.system.core|_ThreadID=16;_ThreadName=RunLevelControllerThread-1502677328097;_TimeMillis=1502677339510;_LevelValue=800;_MessageID=NCLS-CORE-00087;|
  Grizzly Framework 2.3.23 started in: 25ms - bound to [/0.0.0.0:7676]|#]

[#|2017-08-14T02:22:19.582+0000|INFO|glassfish 4.1|javax.enterprise.bootstrap|_ThreadID=1;_ThreadName=main;_TimeMillis=1502677339582;_LevelValue=800;_MessageID=NCLS-BOOTSTRAP-00027;|
  Registered com.sun.enterprise.glassfish.bootstrap.osgi.EmbeddedOSGiGlassFishImpl@5290e804 as OSGi service registration: org.apache.felix.framework.ServiceRegistrationImpl@5951ef0d.|#]

[#|2017-08-14T02:22:20.124+0000|INFO|glassfish 4.1||_ThreadID=50;_ThreadName=Thread-8;_TimeMillis=1502677340124;_LevelValue=800;|
  SSLParams =org.glassfish.admin.mbeanserver.ssl.SSLParams@633e79e7|#]

[#|2017-08-14T02:22:20.138+0000|WARNING|glassfish 4.1|javax.enterprise.system.jmx|_ThreadID=50;_ThreadName=Thread-13;_TimeMillis=1502677340138;_LevelValue=900;_MessageID=NCLS-JMX-00020;|
  All SSL cipher suites disabled for network-listener(s).  Using SSL implementation specific defaults|#]

[#|2017-08-14T02:22:22.858+0000|INFO|glassfish 4.1|javax.enterprise.system.jmx|_ThreadID=50;_ThreadName=Thread-13;_TimeMillis=1502677342858;_LevelValue=800;_MessageID=NCLS-JMX-00025;|
  SSLServerSocket /0.0.0.0:8686 and [SSL: ServerSocket[addr=/0.0.0.0,localport=8686]] created|#]

[#|2017-08-14T02:22:31.760+0000|INFO|glassfish 4.1|javax.enterprise.system.jmx|_ThreadID=50;_ThreadName=Thread-13;_TimeMillis=1502677351760;_LevelValue=800;_MessageID=NCLS-JMX-00005;|
  JMXStartupService has started JMXConnector on JMXService URL service:jmx:rmi://f64dacdb6127:8686/jndi/rmi://f64dacdb6127:8686/jmxrmi|#]


En este caso estaba incluido el comando asadmin start-domain

Bext@android-ae23f0022eea MINGW64 ~
$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                                      NAMES
f64dacdb6127        oracle/glassfish    "/entrypoint.sh as..."   5 minutes ago       Up 5 minutes        0.0.0.0:4848->4848/tcp, 0.0.0.0:8080->8080/tcp, 8181/tcp   youthful_lumiere

Bext@android-ae23f0022eea MINGW64 ~ 





Command References 
- docker run
  https://www.docker.com/reference/commandline/cli/#run
  https://www.docker.com/reference/run
- docker images
  https://www.docker.com/reference/commandline/cli/#images
- docker ps
  https://www.docker.com/reference/commandline/cli/#ps

domingo, 6 de agosto de 2017

SOAP Web Services con NetBeans

Antes de poner manos a la obra, conviene leer una pequeña y consisa introducción de NetBeans
sobre web services https://netbeans.org/kb/docs/websvc/intro-ws.html

Comenzando con JAX-WS Web Services, del learning trial https://netbeans.org/kb/docs/websvc/jax-ws.html. Aquí se elabora una aplicación que proporciona un Web Service de una simple calculadora utilizando la tecnología Java API for XML Web Services (JAX-WS). Tambien se muestran tres clientes que consumen el Web Service, uno en una plataforma Java SE como aplicación java. el segundo como una aplicación web con servlet, y el tercero como una aplicación web con JSP.

   Un detalle para el desarrollo de esta aplicación es que se tiene que habilitar al IDE y al Glassfish server para acceder al esquema externo para poder parsear el archivo WSDL (Web Service Description Language) del web service. algo que se describe en el documento, que en mi caso no me presento difucultades, pero sí actualize el Glassfish a la version 4.1.1, la que venia original con el IDE tenia bugs en su parte de adminstración web.

  En lo personal me agrada la facilidad de integrar los métodos del web service al cliente con solo arrastrarlo o por medio de Insertar Código..., es simplemente genial. Por el momento hacer esto de web services en el ide de Eclipse se ha visto más complicado, en cambio con netbeans es como un pan sin gluten.

  El Web Service puede ser deployado en un web container o en un EJB container. Si se Tiene un Apache Web server que solo tiene un web container, se deberá crear una aplicación web, no un EJB module.

El código en github
https://github.com/jalbertomr/startingJAX-WSWebServices.git

La estructura del conjunto de los projectos CalcularorWS y sus clientes es


Para Probar el web service creado en Netbeans click derecho en View Project -> NodoDelProjecto->WebService->CalculatorWS->Test Web Service




La corrida de la aplicación java que expota el web service nos da en la ventana output

run:
Hello Perrito!
add(3,4) Result = 7
substract(3,4) Result = -1
BUILD SUCCESSFUL (total time: 2 seconds)

La aplicación web en su modalidad servlet muestra en browser (notece se agrega al url /ClientServlet)


La aplicación web en su modalidad JSP muestra en browser


el projecto CalculatorWSAppMavenEJBModule es la versión en la modalidad de EJB Module que necesita glassfish. Los clientes tambien pueden hacer referencia a este web service con minimos cambios, solamente hay que refrescar el web service client del projecto. esto es borrar el web service y volverlo a asignar tomando como fuente el del EJB module.