dissabte, 26 de setembre del 2020

s2i with docker to test images locally

this document explain how to create docker imges to redhad openshift and test images locally whith only docker

Install docker and configure docker for snap.

you need install docker. I have used snap docker for ubuntu20 but each docker daemaon and client shudl be ok

to work with images stream you need to have it in your dockerd and it is necessary have the capacity to pull images from redhad

create user docker and add your user if you want to avoid sudo docker.

docker login registry.redhat.io

this create a file with credentials tokens from user and pwd this file shud be accesible in ~/.docker In case of snapcraft this file is located inside of snap and you shuld copy it

cp /home/jordi/snap/docker/471/.docker/config.json /home/jordi/.docker/config.json

install s2i

only download from gith and set the executable in the path

create image from git

it is possible and easyest way to create image

 s2i  build  https://github.com/jordiesc/java-springboot-basic registry.redhat.io/redhat-openjdk-18/openjdk18-openshift jordi:v2
INFO Performing Maven build in /tmp/src
INFO Using MAVEN_OPTS -XX:+UseParallelOldGC -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=20 -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -XX:MaxMetaspaceSize=100m -XX:+ExitOnOutOfMemoryError
INFO Using Apache Maven 3.6.1 (Red Hat 3.6.1-6.3)
Maven home: /opt/rh/rh-maven36/root/usr/share/maven
Java version: 1.8.0_262, vendor: Oracle Corporation, runtime: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.262.b10-0.el7_8.x86_64/jre
Default locale: en_US, platform encoding: ANSI_X3.4-1968
OS name: "linux", version: "5.4.0-48-generic", arch: "amd64", family: "unix"
INFO Running 'mvn -e -Popenshift -DskipTests -Dcom.redhat.xpaas.repo.redhatga -Dfabric8.skip=true --batch-mode -Djava.net.preferIPv4Stack=true -s /tmp/artifacts/configuration/settings.xml -Dmaven.repo.local=/tmp/artifacts/m2  package'
[INFO] Error stacktraces are turned on.
[INFO] Scanning for projects...

to run the container

❯ docker run -p 8080:8080  jordi:v1
Starting the Java application using /opt/jboss/container/java/run/run-java.sh ...
INFO exec  java -javaagent:/opt/jboss/container/jolokia/jolokia.jar=config=/opt/jboss/container/jolokia/etc/jolokia.properties -XX:+UseParallelOldGC -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=20 -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -XX:MaxMetaspaceSize=100m -XX:+ExitOnOutOfMemoryError -cp "." -jar /deployments/rest-service-0.0.1-SNAPSHOT.jar
I> No access restrictor found, access to any MBean is allowed
Jolokia: Agent started with URL https://172.17.0.2:8778/jolokia/

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.2.RELEASE)

create from source with maven or from binary

you can build from binary o from source code. you must to specify a folder in both cases

❯ cd java-springboot-basic
❯ ll
total 36K
-rwxrwxr-x 1 jordi jordi 9,9K sep 26 11:22 mvnw
-rw-rw-r-- 1 jordi jordi 6,5K sep 26 11:22 mvnw.cmd
-rw-rw-r-- 1 jordi jordi 1,4K sep 26 10:13 pom.xml
-rw-rw-r-- 1 jordi jordi  406 sep 26 11:34 README.md
drwxrwxr-x 4 jordi jordi 4,0K sep 26 10:14 src
drwxrwxr-x 9 jordi jordi 4,0K sep 26 11:09 target
❯ s2i build target  registry.redhat.io/redhat-openjdk-18/openjdk18-openshift jordi:v6
INFO S2I source build with plain binaries detected
INFO Copying binaries from /tmp/src to /deployments ...
rest-service-0.0.1-SNAPSHOT.jar
rest-service-0.0.1-SNAPSHOT.jar.original
classes/
classes/com/
classes/com/example/
classes/com/example/restservice/
classes/com/example/restservice/Greeting.class
classes/com/example/restservice/GreetingController.class
classes/com/example/restservice/Headers.class
classes/com/example/restservice/RestServiceApplication.class
generated-sources/
generated-sources/annotations/
generated-test-sources/
generated-test-sources/test-annotations/
maven-archiver/
maven-archiver/pom.properties
maven-status/
maven-status/maven-compiler-plugin/
maven-status/maven-compiler-plugin/compile/
maven-status/maven-compiler-plugin/compile/default-compile/
maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst
maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst
maven-status/maven-compiler-plugin/testCompile/
maven-status/maven-compiler-plugin/testCompile/default-testCompile/
maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst
maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst
surefire-reports/
surefire-reports/TEST-com.example.restservice.GreetingControllerTests.xml
surefire-reports/com.example.restservice.GreetingControllerTests.txt
test-classes/
test-classes/com/
test-classes/com/example/
test-classes/com/example/restservice/
test-classes/com/example/restservice/GreetingControllerTests.class
Build completed successfully

alternatively

<LeftMouse>❯ cd java-springboot-basic
❯ ll
total 36K
-rwxrwxr-x 1 jordi jordi 9,9K sep 26 11:22 mvnw
-rw-rw-r-- 1 jordi jordi 6,5K sep 26 11:22 mvnw.cmd
-rw-rw-r-- 1 jordi jordi 1,4K sep 26 10:13 pom.xml
-rw-rw-r-- 1 jordi jordi  406 sep 26 11:34 README.md
drwxrwxr-x 4 jordi jordi 4,0K sep 26 10:14 src
drwxrwxr-x 9 jordi jordi 4,0K sep 26 11:09 target
❯ cd ..
❯ s2i build java-springboot-basic  registry.redhat.io/redhat-openjdk-18/openjdk18-openshift jordi:v5

from Docker file

export a docker file

s2i generate registry.redhat.io/redhat-openjdk-18/openjdk18-openshift Dockerfile.jordi

create a folder and move the Dockerfile.jordi to this folder and rename it to Dockerfile

below a sampel with the only the jar, this docker file also work with source code with maven

❯ cd s2idocker
❯ tree
.
├── Dockerfile
├── s3i.adoc
└── target
    └── rest-service-0.0.1-SNAPSHOT.jar

here the docker file

❯ cat Dockerfile
FROM registry.redhat.io/redhat-openjdk-18/openjdk18-openshift
LABEL "io.openshift.s2i.build.image"="registry.redhat.io/redhat-openjdk-18/openjdk18-openshift" \
      "io.openshift.s2i.scripts-url"="image:///usr/local/s2i" \
      "io.openshift.s2i.destination"="/tmp"

USER root
# Copying in source code
COPY ./target /tmp/src
#COPY /home/jordi/jordi/repositorios/github/sprign-securty-saml/target /tmp/src
# Change file ownership to the assemble user. Builder image must support chown command.
RUN chown -R 1001:0 /tmp/src
USER 1001
# Assemble script sourced from builder image based on user input or image metadata.
# If this file does not exist in the image, the build will fail.
RUN /usr/local/s2i/assemble
# Run script sourced from builder image based on user input or image metadata.
# If this file does not exist in the image, the build will fail.
CMD /usr/local/s2i/run

build the docker file

docker build . -t jordi:v4

test and run image

❯ docker images
REPOSITORY                                                 TAG                 IMAGE ID            CREATED             SIZE
jordi                                                      v4                  3f13a7f2bbfc        2 minutes ago       539MB
jordi                                                      v3                  1dbdc19facc1        33 minutes ago      506MB
jordi                                                      v2                  3d9fbf5de1db        2 hours ago         555MB
<none>                                                     <none>              1e244fb4b7a1        2 hours ago         555MB
jordi                                                      v1                  dd78eb8ca2c9        2 hours ago         555MB
jordi                                                      latest              a1064a60f7e6        2 hours ago         555MB
registry.redhat.io/redhat-openjdk-18/openjdk18-openshift   latest              46b0b4cf8a00        2 months ago        473MB
hello-world                                                latest              bf756fb1ae65        8 months ago        13.3kB

❯ docker run -p 8080:8080  -itd  jordi:v4
27e11949e11f9ed432a53804f1ef4ec44dcdd39cc03d0ffcba791a3e508f278f
❯ curl -H "name1: value1" -H "name2: value2" http://localhost:8080/headers
{"host":"localhost:8080","name2":"value2","name1":"value1","user-agent":"curl/7.68.0","accept":"*/*"}%

later

divendres, 6 de desembre del 2019

SAML MELLON POC

Introduction

the Poc consist on VM installed used Vagrant.Git with the scripts and the configuration. Apache httpd , mellon and Tomcat with small application.

Vagrant

The installation has been done by vagrant in Centos7

you can do it without vagrant but it is needed to has NAT ports forward enables 8888 and 8180.

Port 80 is not recomended because Windows use ti internally.

Once the vagrant is done go to git and clone the

repository.

Install begin

execute ./installbegin.sh. This install basic softwarebase along sets up the heroes.org in the hosts file.

It also disable SELinux and reboot.

Install Mellon and Apahce httpd

execute ./installmellon.sh

it will copy the heroes.org.conf virtual host apache and create mellon section and it crate the XML SP metadata.

Listen 8888
<VirtualHost *:8888>
    ServerName heroes.org
    ServerAlias heroes.org
    DocumentRoot /var/www/heroes.org/public_html

<Location / >
    AuthType Mellon
    MellonEnable auth
    Require valid-user
    MellonEndpointPath /mellon/
    MellonSPMetadataFile /etc/httpd/saml2/http_heroes.org_8888.xml
    MellonSPPrivateKeyFile /etc/httpd/saml2/http_heroes.org_8888.key
    MellonSPCertFile /etc/httpd/saml2/http_heroes.org_8888.cert
    MellonIdPMetadataFile /etc/httpd/saml2/meta_idp.xml

    MellonUser "NAME_ID"
    MellonSetEnv "display_name" "displayName"
    MellonSamlResponseDump On
    ProxyPassInterpolateEnv On
 RequestHeader set X-WEBAUTH-USER "%{MELLON_NAME_ID}e"
 #RequestHeader set X-WEBAUTH-DUMP "%{MELLON_SAML_RESPONSE}e"


</Location>

   #Pass most connections to backend app, once it has been secured.
    ProxyPass / http://localhost:8080/mellon
    ProxyPassReverse / http://localhost:8080/mellon

</VirtualHost>

Install keyclaock

execute ./installkeycloack the web administration console is there.

you later must to create a realm called heroes, create a client impoting the SP.xml file configuration create by mellon http_heroes.org_8888.xml

you can log into http://heroes.org:8180/auth/ with user admin and pwd admin

Once imported go to the heroes client configuration is useful to disable encryption fo the saml assertion and pass the username as user Id.

  • Encrypt Assertions Off

  • Name ID Format username

the realm is exported as realm-export.json althought it has not been tested the import

Create a user and its pwd in the Users section.

Once the client and user is done you must to install metadata in mellon

ssh into the guest and execute

curl http://localhost:8180/auth/realms/heroes/protocol/saml/descriptor > meta-idp.xml

sudo cp meta_idp.xml /etc/httpd/saml2

Install Tomcat and small end point appliation

execute install_app_tomcat.sh thies goes to saml2/mellon and execute

mvn package

This install mvn tomcat and build a deploy small application into locally in the guest.

TEST

execute

it willl forward to keycloack IDP put user jordi and pwd jordi and you will see a output like this

Hola Mundo (1)
host=localhost:8080
user-agent=Mozilla/5.0 (Windows NT 10.0; WOW64; rv:60.0) Gecko/20100101 Firefox/60.0
accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language=es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3
accept-encoding=gzip, deflate
referer=http://heroes.org:8180/
cookie=mellon-cookie=6e83894907480c27921539d940ba6f74
dnt=1
upgrade-insecure-requests=1
x-webauth-user=jordi (2)
1 Servlet System.out
2 User Id.

the User Id comes in the SAML assertion in the subcject element of the XML. if you want a code like jordi is when you must to change Idp Client configuration .

Below de default Id, to change it go to keycloack and change the Name Id format.

<saml:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient">G-e535ce9b-5b55-4896-92a6-0e7777f9aa5c</saml:NameID>

TroubleShooting

SELinux enable or disable.

SELinux /etc/selinus/config to enable or disable SElinux

Apache

The logs are in /etc/httpd/logs Check status $httpd -d Check config $httpd -t

Dump SAML assertion in header

Tomcat Logs $journalctl -u tomcat

increase headers in /etc/tomcat/server.xml

In heroes.org.conf enable the dump to header #RequestHeader set X-WEBAUTH-DUMP "%{MELLON_SAML_RESPONSE}e"

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
maxHttpHeaderSize="65536"
redirectPort="8443" />

Others

Install Spring sample

Follow

jordi@LAPTOP-ELFAQNCG MINGW64 /c/Program Files/Java/jdk1.8.0_181/bin
$ jrunscript.exe -e 'print (javax.crypto.Cipher.getMaxAllowedKeyLength("RC5") >= 256);'
true

SAML certificates vorkflow

  • Create a new key pair for signing and/or encryption together with the respective X.509 certificate

  • Configure your SP to support the new key pair

  • Add a new KeyDescriptor to your SAML metadata

  • Support decrypting SAML messages using your new key

  • Send your metadata (or just the X.509 certificate) to the IdP(s). They must:

  • Switch the encryption certificate to the new one

  • Trust in your new signing certificate, without stop trusting in the old one

  • Wait for the IdP(s) to update its configurations

  • Do not start to use the new key for signing your messages until the IdP(s) confirm they are supporting your new certificate

  • Configure your SP to start using the new key for signing messages

  • The old keys may be completely removed

  • The IdP(s) can now untrust your old signing certificat

dimarts, 6 d’agost del 2019

Repository Spring

The use of @JPARepository or @CrudRepository is very handy, developers can do basic operations with no SQL operations. However it also hide the transaccion managemetn. By default every method has a transacciton scope. I have seen so many developers forget the use of @Transactional scope in their services. Hibernate and JPA force to you to create a Transaccion but with the use of frameworks it is deep hide and frecuantly ommited, skipped or simplely unknown by mediocre developers

Behaviour without Transaction management

the service produces different output depending of use of Transaccional scope

    @Transactional
    public void getGetOlder(int age, int plus) {

        List<User> listUsers = repoUser.findByAgeGreaterThan(age);
        for (User user : listUsers) {
            user.setAge(user.getAge() + plus);
            repoUser.save(user);
        }
    }

This give you a log with only one transaccion

2019-08-06 11:42:19,731 DEBUG [main] o.h.e.t.i.TransactionImpl [TransactionImpl.java:101] committing
2019-08-06 11:42:19,731 DEBUG [main] o.h.e.i.AbstractFlushingEventListener [AbstractFlushingEventListener.java:141] Processing flush-time cascades
2019-08-06 11:42:19,731 DEBUG [main] o.h.e.i.AbstractFlushingEventListener [AbstractFlushingEventListener.java:193] Dirty checking collections
2019-08-06 11:42:19,733 DEBUG [main] o.h.e.i.AbstractFlushingEventListener [AbstractFlushingEventListener.java:115] Flushed: 0 insertions, 2 updates, 0 deletions to 2 objects
2019-08-06 11:42:19,733 DEBUG [main] o.h.e.i.AbstractFlushingEventListener [AbstractFlushingEventListener.java:122] Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
2019-08-06 11:42:19,734 DEBUG [main] o.h.i.u.EntityPrinter [EntityPrinter.java:110] Listing entities:
2019-08-06 11:42:19,734 DEBUG [main] o.h.i.u.EntityPrinter [EntityPrinter.java:117] org.jordi.h2db.springboot.models.User{firstName=Joana, lastName=Fernandez, id=2, age=11}
2019-08-06 11:42:19,734 DEBUG [main] o.h.i.u.EntityPrinter [EntityPrinter.java:117] org.jordi.h2db.springboot.models.User{firstName=Rachel, lastName=Fernandez, id=1, age=11}
2019-08-06 11:42:19,735 DEBUG [main] o.h.SQL [SqlStatementLogger.java:94] update users set age=?, first_name=?, last_name=? where id=?
2019-08-06 11:42:19,739 DEBUG [main] o.h.SQL [SqlStatementLogger.java:94] update users set age=?, first_name=?, last_name=? where id=?
2019-08-06 11:42:19,759 DEBUG [Thread-3] o.h.i.SessionFactoryImpl [SessionFactoryImpl.java:792] HHH000031: Closing

whereras if you ommit the transaccion you will the below where you can see two commits instead of one.:

2019-08-06 12:00:19,763 DEBUG [main] o.h.e.t.i.TransactionImpl [TransactionImpl.java:101] committing
2019-08-06 12:00:19,764 DEBUG [main] o.h.e.i.AbstractFlushingEventListener [AbstractFlushingEventListener.java:141] Processing flush-time cascades
2019-08-06 12:00:19,765 DEBUG [main] o.h.e.i.AbstractFlushingEventListener [AbstractFlushingEventListener.java:193] Dirty checking collections
2019-08-06 12:00:19,766 DEBUG [main] o.h.e.i.AbstractFlushingEventListener [AbstractFlushingEventListener.java:115] Flushed: 0 insertions, 1 updates, 0 deletions to 1 objects
2019-08-06 12:00:19,767 DEBUG [main] o.h.e.i.AbstractFlushingEventListener [AbstractFlushingEventListener.java:122] Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
2019-08-06 12:00:19,767 DEBUG [main] o.h.i.u.EntityPrinter [EntityPrinter.java:110] Listing entities:
2019-08-06 12:00:19,768 DEBUG [main] o.h.i.u.EntityPrinter [EntityPrinter.java:117] org.jordi.h2db.springboot.models.User{firstName=Rachel, lastName=Fernandez, id=1, age=11}
2019-08-06 12:00:19,769 DEBUG [main] o.h.SQL [SqlStatementLogger.java:94] update users set age=?, first_name=?, last_name=? where id=?
2019-08-06 12:00:19,774 DEBUG [main] o.h.e.t.i.TransactionImpl [TransactionImpl.java:56] On TransactionImpl creation, JpaCompliance#isJpaTransactionComplianceEnabled == false
2019-08-06 12:00:19,775 DEBUG [main] o.h.e.t.i.TransactionImpl [TransactionImpl.java:84] begin
2019-08-06 12:00:19,776 DEBUG [main] o.h.l.Loader [Loader.java:2269] Loading entity: [org.jordi.h2db.springboot.models.User#2]
2019-08-06 12:00:19,777 DEBUG [main] o.h.SQL [SqlStatementLogger.java:94] select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.first_name as first_na3_0_0_, user0_.last_name as last_nam4_0_0_ from users user0_ where user0_.id=?
2019-08-06 12:00:19,780 DEBUG [main] o.h.l.Loader [DelegatingBasicLogger.java:384] Result set row: 0
2019-08-06 12:00:19,781 DEBUG [main] o.h.l.Loader [Loader.java:1532] Result row: EntityKey[org.jordi.h2db.springboot.models.User#2]
2019-08-06 12:00:19,784 DEBUG [main] o.h.e.i.TwoPhaseLoad [TwoPhaseLoad.java:145] Resolving associations for [org.jordi.h2db.springboot.models.User#2]
2019-08-06 12:00:19,785 DEBUG [main] o.h.e.i.TwoPhaseLoad [TwoPhaseLoad.java:290] Done materializing entity [org.jordi.h2db.springboot.models.User#2]
2019-08-06 12:00:19,785 DEBUG [main] o.h.l.Loader [Loader.java:2298] Done entity load
2019-08-06 12:00:19,786 DEBUG [main] o.h.e.t.i.TransactionImpl [TransactionImpl.java:101] committing
2019-08-06 12:00:19,787 DEBUG [main] o.h.e.i.AbstractFlushingEventListener [AbstractFlushingEventListener.java:141] Processing flush-time cascades
2019-08-06 12:00:19,787 DEBUG [main] o.h.e.i.AbstractFlushingEventListener [AbstractFlushingEventListener.java:193] Dirty checking collections
2019-08-06 12:00:19,788 DEBUG [main] o.h.e.i.AbstractFlushingEventListener [AbstractFlushingEventListener.java:115] Flushed: 0 insertions, 1 updates, 0 deletions to 1 objects
2019-08-06 12:00:19,789 DEBUG [main] o.h.e.i.AbstractFlushingEventListener [AbstractFlushingEventListener.java:122] Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
2019-08-06 12:00:19,789 DEBUG [main] o.h.i.u.EntityPrinter [EntityPrinter.java:110] Listing entities:
2019-08-06 12:00:19,790 DEBUG [main] o.h.i.u.EntityPrinter [EntityPrinter.java:117] org.jordi.h2db.springboot.models.User{firstName=Joana, lastName=Fernandez, id=2, age=11}
2019-08-06 12:00:19,790 DEBUG [main] o.h.SQL [SqlStatementLogger.java:94] update users set age=?, first_name=?, last_name=? where id=?
2019-08-06 12:00:19,810 DEBUG [Thread-3] o.h.i.SessionFactoryImpl [SessionFactoryImpl.java:792] HHH000031: Closing

diumenge, 9 de juny del 2019

VAGRANT W10


It took me a lot of time to get over the below problem Raw-mode is unavailable courtesy of Hyper-V. (VERR_SUPDRV_NO_RAW_MODE_HYPER_V_ROOT).

to fix it   HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity\Enabled set to 0

dissabte, 23 de febrer del 2019

CDI in JEE-Jakarta EE part I

Dependence injection commontly CI or CD/CI or CDI is the framework for JEE for dependence injection. Very similar to Spring. It also was know as IoC or inversion of control. the point is that de dependeces are injected instead of created by new…​ Injected means that the container created and pass the reference…​. thats all…​.

Specification

In case of OpenLiberty is based in JBooss implementation http://weld.cdi-spec.org/

Features

Instalation

In CDI 1.0 was necessary a file META-INF/beans.xml but not in later version. This file also can be located in anohter places.

Scopes

CDI is based in a concept of container which is actually a on memory key-value data object database. this container or database is partitionated in scopes so a bean only can see its neigbourds in its scope. the scope come from applications scope

  • @RequestScoped

  • @SessionScoped

  • @ApplicationScoped

  • @ConversationScoped. This is similar to transacctional in jpa…​.

Names

El Names or @Name("myname") is a name to be referenced either JSP or JSF

Creation

The below sample create a Bean of type String…​ how does it solve conflicts?

    @Produces
    @Property("")
    String  valueofProperty(InjectionPoint injectionPoint){
        Property property = injectionPoint.getAnnotated().getAnnotation(Property.class);
        return "clave mas "+ property.value();
           }

Ambiguity.

if CDI is actually a key-value. how does it look up objects?. by the type. and the ambibuguity is solved with custom anotations or called @Qualifier.

@Qualifier
@Target({ ElementType.FIELD,ElementType.METHOD, ElementType.TYPE,ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface Property {
    @Nonbinding
    String value() default "";

Use

The most commotn is by @Inject similar to @Autowired in Spring}

dilluns, 22 d’octubre del 2018

Instalation

browsesync is based on node/js platform so npm install -g browser-sync

Default running

browser-sync start --server

in my case to go fast i got an alias in my bashrc

alias bserve='browser-sync start --server' then to run for me is

$ bserve --file * -w

diumenge, 14 d’octubre del 2018

GIT most used comands

GIT log and info

set alias into .bashrc vimlog

alias gitlog='git log --all --oneline --graph'

to see diferences betwen branches write .. betwen branches

git diff branch_a..branch_b

GIT Commit

when I sure git commit -m -a "message" when not it allows check the diferences git add -p

GIT branch

create a branch called features git checkout -b features merge into branch into master git checkout master to go to master and the git merge features. if there is confilcs resolve or file to file editing one by one or use git mergetool it opens a nice tool based in vimlo git checkout --theirs or git checkout --ours in case you wan take iether feture or master

GIT rebase

Use rebase when you want get all the master o shared repo to you personal branch

dilluns, 13 d’agost del 2018

Testing With Gradle

Gradle has Junit out of the box, the reporting is not still so fancy as maven but it has the same functionality

Gradle JUnit 5

testCompile('org.junit.jupiter:junit-jupiter-api:5.2.0')
testCompile('org.junit.jupiter:junit-jupiter-params:5.2.0')
testRuntime('org.junit.jupiter:junit-jupiter-engine:5.2.0')

to run the test just execute gradle test but if you wish and specific test ie the whole class is still posssible with gradle test --tests org.jordiesc.BlogTest

dimecres, 4 de juliol del 2018

Update Ubuntu certificates

  • create a directory into /usr/local/share/ca-certificates mkdir new directory

  • copy the certificate directory file *.crt give permsissions and chmod 644 for the files

  • sudo update-ca-certificates

Get the certificates chain from the server

openssl s_client -connect HOST:PORTNUMBER -showcerts save the files as crt.

dilluns, 26 de febrer del 2018

Threading in Python

Very very similar to Java but with less code. 

import threading
import datetime
import time

DELAY = 10

def hacertrabajo():
timeinit = datetime.datetime.now()
print("se inicia "+str(timeinit))
time.sleep(10)
print("se finaliza "+ str(datetime.datetime.now()) + "en "+str(datetime.datetime.now()-timeinit))

th1 = threading.Thread(target=hacertrabajo,name="th-1")
th2 = threading.Thread(target=hacertrabajo,name="th-2")

th1.start()
th2.start()


print("no se espera")

if you execute the prgoram you will see that the output "no se espear" is writtein even without having finisthed both threads.

PS C:\Users\jordi\Documents\python\multithread> python multi.py
se inicia 2018-02-26 22:02:26.326352
start th1
se inicia 2018-02-26 22:02:26.328306
start th2
no se espera
se finaliza 2018-02-26 22:02:36.328301en 0:00:10.001949
se finaliza 2018-02-26 22:02:36.330257en 0:00:10.001951

to wait implement the call join(seconds) where seconds are the timeout , the time point the time when the control will arive to point join

import threading
import datetime
import time

DELAY = 10

def hacertrabajo():
timeinit = datetime.datetime.now()
print("se inicia "+str(timeinit))
time.sleep(10)
print("se finaliza "+ str(datetime.datetime.now()) + "en "+str(datetime.datetime.now()-timeinit))

th1 = threading.Thread(target=hacertrabajo,name="th-1")
th2 = threading.Thread(target=hacertrabajo,name="th-2")

th1.start()
th2.start()
timeinit = datetime.datetime.now()
th1.join(5)
print("se finaliza th1 "+ str(datetime.datetime.now()) + "en "+str(datetime.datetime.now()-timeinit))
th2.join(11)
print("se finaliza th2"+ str(datetime.datetime.now()) + "en "+str(datetime.datetime.now()-timeinit))

Da el resultado siguiente.

PS C:\Users\jordi\Documents\python\multithread> python multi.py
se inicia 2018-02-26 22:22:31.651966
se inicia 2018-02-26 22:22:31.652945
se finaliza th1 2018-02-26 22:22:36.653236en 0:00:05.000291
se finaliza 2018-02-26 22:22:41.653288en 0:00:10.001322
se finaliza 2018-02-26 22:22:41.654265en 0:00:10.001320
se finaliza th22018-02-26 22:22:41.655247en 0:00:10.002302
PS C:\Users\jordi\Documents\python\multithread>

Tal y como indica la documentacion lo normal de join() seria despues hacer algo con el thread como

dissabte, 17 de febrer del 2018



PlyGround with Python 1

how easy is python and sqlite3

import sqlite3
import datetime

def createDataBase():
conn = sqlite3.connect('control.db')
c = conn.cursor()
c.execute('create table control( nombre TEXT, fechaini timestamp, fechafin timestamp)')
c.close()

def pupulateDataBase():
conn = sqlite3.connect('control.db')
c = conn.cursor()
c.execute('insert into control values (?,?,?)',('registro 1',datetime.datetime.now(),datetime.datetime.now()))
conn.commit()
conn.close()

def pupulateDataBaseWhitNull():
conn = sqlite3.connect('control.db')
c = conn.cursor()
c.execute('insert into control values (?,?,?)',('registro 1',datetime.datetime.now(),None))
conn.commit()
conn.close()
def fetchDataBase():
conn = sqlite3.connect('control.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM control'):
print(row)


createDataBase()
pupulateDataBase()
pupulateDataBaseWhitNull()
fetchDataBase()


(test) C:\Users\jordi\jordi\workspaces\python\test>python testsqlite.py
('registro 1', '2018-02-17 10:48:47.235088', '2018-02-17 10:48:47.235088')
('registro 1', '2018-02-17 10:48:47.354523', None)


LightWeight Python Envirotment with Visual Studio 

Create a virtualenv with virtualenv and later activate it running the activate script.

Open the VSC and creaate a fill called .env with the variable PYTHONPATH pointing to the site-packages where the virualenv located all the libraries already download by PIP.

PYTHONPATH=C:\Users\jordi\jordi\workspaces\python\test\Lib\site-packages




diumenge, 11 de febrer del 2018



Little’s law

number of threads = (Requests/sec) X (ResponseTime in secs)

dissabte, 3 de febrer del 2018

ssh keys


From my laptop I will create the keys and I will expose this key to the server I want to connect using keys. Additionally we get rid of passwords , even for my user as sudo user.

jordi@LAPTOP-ELFAQNCG MINGW64 ~/.ssh
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/jordi/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Users/jordi/.ssh/id_rsa.
Your public key has been saved in /c/Users/jordi/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:ljvEge2a/MwKp8OK73ai27v7zRFiPyPmMxJCpw0nJLU jordi@LAPTOP-ELFAQNCG
The key's randomart image is:
+---[RSA 2048]----+
| ..              |
|.. .   o         |
|o E   . o        |
| + o   o o       |
|. B o . S        |
|...o + * .       |
| . o+ X o        |
| o+o*B B .       |
|+*OX+++.+        |
+----[SHA256]-----+

jordi@LAPTOP-ELFAQNCG MINGW64 ~/.ssh
$ ssh-copy-id jordi@localhost
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/c/Users/jordi/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
no such identity: /c/Users/jordi/.ssh/keys/id_rsa.pub: No such file or directory
jordi@localhost's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'jordi@localhost'"
and check to make sure that only the key(s) you wanted were added

jordi@LAPTOP-ELFAQNCG MINGW64 ~/.ssh
$ cat config
Host localhost
 Hostname localhost
 IdentityFile ~/.ssh/id_rsa
.

jordi@LAPTOP-ELFAQNCG MINGW64 ~/.ssh
$ ssh localhost
Last login: Sat Feb  3 17:27:47 2018 from gateway
[jordi@localhost ~]$

At centos to avoid password for instance to avoid pas to do sudo

/etc/ssh/sshd_config
PasswordAuthentication no

addl to the bototn
 sudo visudo
jordi ALL=(ALL) NOPASSWD: ALL

dilluns, 1 de gener del 2018

RAD in java


Some tools to rapidly create a java/groovy application  or RAD applications 

Jeddict

Grails

Spring Roo

JHipster

dissabte, 9 de desembre del 2017


Configuration of the CentOS 7 to be accesible the deamon from outside

Stop Docker

[root@localhost jordi]# systemctl stop docker

[root@localhost jordi]# cat /lib/systemd/system/docker.service

look at the

ExecStart=/usr/bin/dockerd

It is risky touch direcly the file direcly there is a edit utility in linux services

systemctl edit docker

[Service]
ExecStart=
 ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock

 finally start docker

[root@localhost jordi]# systemctl start docker
[root@localhost jordi]# systemctl restart docker
[root@localhost jordi]# curl http://localhost:2375 {"message":"page not found"}
[root@localhost jordi]# docker run ubuntu echo "helo world" helo world


Remember set up the firewall, A rapid to way this issue around is disable it

[root@localhost jordi]# systemctl disable firewalld

dimecres, 6 de desembre del 2017

Tomcat embed with anotated Servlet

Recently I have playing in with the Tomcat embed version. Currently Spring Boot gives a fancy, easy and rapid creation of the Main class invoking a instanting a Tomcat server. However there is a lack of official information that it makes me doubt about of readiness for production. I belive that the classic war and deployment it is going to be safer in the future and it of course much more portable . But an embeded version can have a futture for testin. I will chose war solution for cloud PaaS envirotments or container solutions such us Cloud Foundry unless Apache will decide to publich formal and clear documentation. Spring give us a OSGI version which wrap tomcat, this seeems be valid for production but Spring is Spring and I personally hate it because they reinvent the heel constantly, I lke JEE a littel bit more but my feeling is that you will never be safe either Spring nor JEE.

It is my intention to do the same test but in a JEE cointainer like Payara or Payara-micro which give us much better documentation.

Having said that. Here is the issues or poblems that I found. My goal was instanciate a Tomcat with a anotated Servlet with no web.xml and no adding explicti Servlet at all. Remember Servlet 3.0 support is a must and tomcat +7 is necessary.

I built the solution using gradle but only with java plugin, the first issue was find out the exacly dependences.

The dependeces list are in the build.gradle but is intersted notice that not all the tomcat versions worked. Also be carefull in that you maven or gradle include the anotations solution for Tomcat otherwise you can face issues.


    compile  "org.apache.tomcat:tomcat-catalina:$tomcatVersion"
    compile  "org.apache.tomcat:tomcat-util:$tomcatVersion"
    compile  "org.apache.tomcat:tomcat-jasper:$tomcatVersion"
    compile  "org.apache.tomcat:tomcat-jasper-el:$tomcatVersion" 
    compile  "org.apache.tomcat:tomcat-jsp-api:$tomcatVersion"
    compile  "org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion"
    compile  "org.apache.tomcat.embed:tomcat-embed-logging-juli:$tomcatVersion"
    compile  "org.apache.tomcat.embed:tomcat-embed-jasper:$tomcatVersion"

To be the Servlet reconzied your tomcat classpath must have the class but also the context must have the access to the servlet.class file. The easy and standart way to achieve this is include the class inside of jar file and execute it using java -jar my.jar along with all the dependences uncompress in the same jar file.

To achieve this in gradle I used the shadow gradle plugin, in Maven you can achieve the same with the maven-assembly-plugin

to run the sample the sources are in  https://github.com/jordiesc/java/tree/master/embedtomcat/JavaTomcatEmbed

$ gradle build shadowJar
$ cd build/libs
$ java -jar GroovyTomcatEmbed-all.jar

https://github.com/jordiesc/java/tree/master/embedtomcat/GroovyTomcatEmbed

Moreover you will see two versions of the project. they are almost identical apart form some details. The most important is the groovy incompatibility with Java annotations. where you must to turn curly bracktest {} into [] otherwishe the compiler will interpret a Groovy Clousre

The Java way

@WebServlet(
    name = "dataServlet",
    urlPatterns = {"/datajava"}
)

The Groovy way

@WebServlet(
    name = "dataServlet",
    urlPatterns = ["/datagroovy"]
)

just run http://localhost:8080/datajava or http://localhost:8080/datagroovy

diumenge, 12 de novembre del 2017

CSS POSITON.

STATIC. es el posicionamiento por defecto del navegador poniendo los elementos segun aparecen en el html, dom. es como si no hubiera posicionamiento. si se pone static el navegador no hace caso de los left,right,top, botton.

RELATIVE el navegador conserva el espacio que habia despues de moverlo. los porcentages solo funcionan si esta el heigh del padre. Es inportante saber que el espacio dejado despues de desplazarse continuara reservado
ABSOLUTE. los elemenos se posicionan en base a su inmediato padre , posicionado, o sea que tiene posiciones relative,absolute o fixed. El espacio no es reservado.
El ancho de un elemento absolute depende de su contenido.

FIXED. como absoluta no reserva la posicion, se ajusta al contenido las cordenatdas se calculan segun el navegador o ventana asi que  nunca se escrolla. los elementos fixed quedan fijos pero se salen del flujo de colocacion.

Posicionamiento por ejes

Siempre son posiciones desplazadas desde el margen hacia adentro. Por ejemplo top 2px moviera el elemento desde el top hacia el centro o sea hacia abajo

Solo puede haber un posicionamiento vertical y uno horizonal, css solo toma uno si hay varios.

Horizontal left, right
Vertical -> top, botton

3 dimension- z-index

MARGIN collapse.

Los top and bootion margin colapsan. con elementos posicionados absoluto no colapsan https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

dilluns, 6 de novembre del 2017


Groovy con Gradle

Hay una manera facil de ejecutar Groovy scripts sin llegar a instalar Groovy si se tiee Gradle

$ gradle init

Genera un proyecto gradle. El fichero build.gradle

task inicio{}

println "hola mundo"
h

con el comando gradle inicio. se vera la siguiente salida

$ gradle inicio
hola mundo
:inicio UP-TO-DATE

BUILD SUCCESSFUL in 1s


task inicio{}

def lista = ["uno","dos",3]

lista.forEach {
println it
}
produce

$ gradle inicio
uno
dis
3
:inicio UP-TO-DATE

BUILD SUCCESSFUL in 1s

divendres, 1 de setembre del 2017


Los webcomponents son la base de los ultimos frameworks aparecidos como Angular 2 o 4, Polymer, Aurelia, X-tag e incluso React tiene una aire.

Todos hacen lo mismo encapsulan html modularmente y bindean objetos de datos.

Vanilla ES6 permite escribir web compoents NATIVOS, esto quiere decir mas rapidos en ejecucion y mas entendibles pq no hay magia. Por contra habra que hacer un poquito mas de codigo para el binding de datos pero con ES6 las arrows y typescript tampoco es que sea muy dificil.

Como son NATIVOS se pueden incorporar en todos los frameworks, y como son NATIVOS van a durar mucho mas que no los frameworks q tienen un ciclo de vida de 2 añitos.Y nos olvidaremos de migraciones

Para los navegadores que no soportan WC nativos ya hay polyfills. Es mas todos los frameworks anteriores o incorporan el mismo polyfill o lo has de poner.

La especificación de webcomponents y en concreto los Custom Elements se puede ver en los enlaces de abajo

https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elementss

y un fantastico enlace en castellano

https://developers.google.com/web/fundamentals/getting-started/primers/customelements

Los custom elements llevan el gion normalmentepor ejemplo <my-app></my-app>. Eso es parte de la especificacion.

Lo basico es crear una clase que extienda de HtmlElement o del element que sea HtmlButton... y implementar algunas de las funciones para interctuar con el DOM.

Para poner atributtos en el htmlelement se deben de declarar con get y set.

get attributename()
set attributename()

Si ademas queremos que esos atribures notifiquen a nuestra clase cuando se cambian hay que declarar el array

static get observableattributes y despues el metodo attributeChangedCallback

Mi personal test con custom elelments v1 que incluye dos custom tags y con sus porpios eventos

https://github.com/jordiesc/webcomponents