lunes, 13 de noviembre de 2017

How to Configure Actuator in Spring Boot

Hi,

Today I'm going to explain the steps for configuring Actuator in a Rest Service Spring Boot Application.

It's very easy, only two steps and you have it!

First you have to add the dependency to the pom.xml file:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
</dependency>

The second step is the disable security to the services offers by actuator.

You have to edit the application.properties file and add:

management.security.enabled=false

With this to step, you can run your appication and can call the next services:

http://localhost:8080/health for know the State of your App.

http://localhost:8080/mappings for view your Rest Services published

And you have more services, you can see in your log of your App when you run it.

Try it and have fun!

viernes, 20 de octubre de 2017

What to do for Convert your App into a Progressive Web App

Hi,

I'm going to explain what to do for Converting your App into a Progressive Web App. Or what's the same, for using Service Workers.

Here you can see the demo of a Progressive Web App with Service Workers.

It's very easy.

You have to use Angular/Cli in your Angular App and do the next three steps:

- First, you have to change your Angular/Cli config file and add the next line:

{
"apps": [
{ "serviceWorker": true } ]
}


- Second, you have to install the Service Workers dependency:

npm i @angular/service-worker --S

- And finally, you have to add the external links from your index.html for use the cache on them, modifying the generated file ngsw-manifest.json:

"external": {
"urls": [
{"url": "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"},
{"url": "https://cdn.rawgit.com/konpa/devicon/4f6a4b08efdad6bb29f9cc801f5c07e263b39907/devicon.min.css"},
{"url": "https://fonts.googleapis.com/icon?family=Material+Icons"},
{"url": "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"}
]
},


And that's all!

Try it and have fun!

lunes, 16 de octubre de 2017

How to define repository ownership in JPA with Spring Security?

Hi, everybody!

Today I'm going to explain how to define repository ownership in JPA with Spring Security.

First of all, we are going to explain what is a repository: is an interface of JPA that provide the access to a database table modeled with hibernate.

In this interface, you can define any JPA or native query and you can change the behaivour of any call.

For example, you can have this:

@Repository
public interface MyHibernateModelClassRepository extends JpaRepository<MyHibernateModelClass, Long> {

}


With this implementation, you can call any CRUD method.

Now, I'm going to explain how to define ownership of this JPA interface:

With the same example, you can have this:

@Repository
public interface MyHibernateModelClassRepository extends JpaRepository<MyHibernateModelClass, Long> {

    @PreAuthorize("#entity == null || #entity.id == principal.id")
    @Override
    <S extends MyHibernateModelClass> S save(S entity);

    @PreFilter("filterObject == null || filterObject.id== principal.id")

    @Override
    <S extends MyHibernateModelClass> List<S> save(Iterable<S> entities);

    @PostAuthorize("returnObject.id == principal.id")

    @Override
    MyHibernateModelClass findOne(Long integer);

    @PostFilter("filterObject.id == principal.id")

    @Override
    List<MyHibernateModelClass> findAll();
    
}

With this call, you implemented a JPA interface with ownership, where the CRUD calls can only be used by the user logged in the application is the same of the attribute id in the database table modeled with Hibernate MyHibernateModelClass.

I'm going to provide another example, which use a method of the hibernate entity that response with a boolean if the CRUD method can be use by this user.

Here is the next example:

(hibernate entity have this method):
...
public boolean hasMetadadaWithId(Long id) {
return (metadades.getId().equals(id));
}
...

And the JPA repository shows like this:

@Repository
public interface MyHibernateModelClassRepository extends JpaRepository<MyHibernateModelClass, Long> {

@PreAuthorize("#entity == null || #entity.hasMetadadaWithId(principal.id)")
    @Override
    <S extends MyHibernateModelClass> S save(S entity);

    @PreFilter("filterObject == null || filterObject.hasMetadadaWithId(principal.id)")

    @Override
    <S extends MyHibernateModelClass> List<S> save(Iterable<S> entities);
    
    @PostAuthorize("returnObject.hasMetadadaWithId(principal.id)")
    @Override
    MyHibernateModelClassfindOne(Long integer);

    @PostFilter("filterObject.hasMetadadaWithId(principal.id)")

    @Override
    List<MyHibernateModelClass> findAll();
    
}

And that's all!

For any question, ask me!

Try it and have fun!

martes, 10 de octubre de 2017

How to configure an unic properties file for Spring 4.3.3 application

Here you are!

Today I'm going to explain how to configure one or more properties files for Spring 4.3.3 application, with active profiles of Spring cofigured in the server on the run call.

You have to create a file, I named properties-context.xml with the next content:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<beans profile="DES">
    <bean id="props" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="location" value="classpath:properties/file-DES.properties"/>
    </bean>
</beans>

<beans profile="INT">
    <bean id="props" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="location" value="classpath:properties/file-INT.properties"/>
    </bean>
</beans>

<beans profile="PRO">
    <bean id="props" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="location" value="classpath:properties/file-PRO.properties"/>
    </bean>
</beans>

</beans>

In this file, you can see that we use three profiles={DES,INT,PRO}

This configuration will use the last Spring configuration and will be always on the last version.

The, you have to import this file to the root-context.xml file or the main configuration file of Spring.

The line you have to add id this:

<!-- properties context -->
<import resource="properties-context.xml" />

Then, for load the diferents profiles, you have to call the server with the parameter: -Dspring.profiles.active=DES.

In this call, you can use more than one active profile and will load any profiles defined in the call.

For use more than one profile you can call them like this:
-Dspring.profiles.active=DES,OTHER_PROFILE.

Also, you can load any amount of properties files changing the value of the location parameter, like this:

<property name="location" value="classpath:properties/file-DES.properties,classpath:properties/other_file-DES.properties"/>

This is the way for load properties files in Spring 4.3.3.

Try it and have fun!

miércoles, 28 de junio de 2017

How to configure Reactive Forms in your Angular Application?

Hey people!

Today I'm going to explain how to configure your Angular application to use Reactive Forms and how to implements your first form.

First of all, you have to install the forms module in your project:

npm install @angular/forms --save

Then, you have to modify your app.module.ts adding:

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
imports: [ BrowserModule, ReactiveFormsModule ], 
declarations: [ AppComponent ], 
bootstrap: [ AppComponent ]
})

On this point, your project is prepared for using Reactive Forms.

The you have to modify the form component you want to use:
<div class="container">
  <h1>Add user</h1>
  <form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value, myForm.valid)">
    <div class="form-group">
      <label for="">Name</label>
      <input type="text" class="form-control" formControlName="name">
      <small [hidden]="myForm.controls.name.valid || (myForm.controls.name.pristine && !submitted)" class="text-danger">
            Name is required (minimum 5 characters).
          </small>
      <!--<pre class="margin-20">{{ myForm.controls.name.errors | json }}</pre>-->
    </div>
    <div class="form-group" formGroupName="address">
      <label for="">Address</label>
      <input type="text" class="form-control" formControlName="street">
      <small [hidden]="myForm.controls.address.controls.street.valid || (myForm.controls.address.controls.street.pristine && !submitted)" class="text-danger">
            Street required
          </small>
    </div>
    <div class="form-group" formGroupName="address">
      <label for="">Postcode</label>
      <input type="text" class="form-control" formControlName="postcode">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
    <div class="margin-20">
      <div>myForm details:-</div>
      <pre>Is myForm valid?: <br>{{myForm.valid | json}}</pre>
      <pre>Is myForm submitted?: <br>{{submitted | json}}</pre>
      <pre>myForm value: <br>{{myForm.value | json}}</pre>
    </div>
    <div class="margin-20">
      Form changes:
    </div>
    <div *ngFor="let event of events" class="margin-20">
      <pre> {{ event | json }} </pre>
    </div>
  </form>
</div>
With the typescript file of the component with the changes:

public myForm: FormGroup;
public submitted: boolean;
...

constructor(private _fb: FormBuilder) { }

...

ngOnInit() {

        // the short way
        this.myForm = this._fb.group({
            name: ['', [<any>Validators.required, <any>Validators.minLength(5)]],
            address: this._fb.group({
                street: ['', <any>Validators.required],
                postcode: ['8000']
            })
        });

}

...

save(model: User, isValid: boolean) {
        this.submitted = true;
        console.log(model, isValid);
}

You can develop your forms in many way.
Use which is more easy for you.

Try it and have fun!

miércoles, 24 de mayo de 2017

The way to implements Unit Tests in Spring Boot

For doing Tests in Spring Boot you have to know the next things:

- You need a java test and resources test directories in your project. In the resources directory you put the files for the src/test/java and the src/test/resources directory the test you want to pass when you do the maven build.
- You need am application-TEST.yml file in your resources directory for configure the test calls.
- When you implements a Test you have to use the next anotations before the class name:

@org.junit.runner.RunWith(SpringJUnit4ClassRunner.class)
@org.springframework.boot.test.SpringApplicationConfiguration(classes = ClassName.class)
@org.springframework.test.context.ActiveProfiles(value = "TEST")

- For test a Service implemented in you src/main/java directory you have to indicate this way:

@org.springframework.beans.factory.annotation.Autowired
MyService service;

- At last, you need to indicate the method that test one call like:

@org.junit.Test
public void test() {
    ... do the test and finally verify the result of the test
    assertThat(result).isEqualTo("OK");
}

Here you have implemented your first test.

For call it, you have to run the maven test option.

For skip one test, you can indicate @org.junit.Ignore and the test don't will be executed.

For skip all test, you can indicate to maven that don't want to execute test this way:

Go to run configuration and check the option skip tests.

Any question of this tip, don't doubt ask me!

Try it and have fun!

miércoles, 10 de mayo de 2017

The Electronic Signatures Types: XAdES, PAdES and CAdES

Hi everyone,

I'm currently working on Pompeu Fabra University in the Electronic Administration Department.

I'm doing a Signature Project that signs, completes and validates in XAdES, PAdES and CAdES signature types.

Now I want to explain what consists my project, the troubles I had to resolve and the conclusions.

First of all, I want to explain the signature types:

XAdES: XML Advanced Electronic Signature

This signature can sign BINARI or XML files and the way for complete and validate is different. The XAdES Signature Type generates a XML Signature file. For a correct validation, the generated signature must have a correctly hash document code. So the libraries used are important, because differents libraries generates differents XML files.

There are three Signature Types: Detached (the signature don't includes the file signed), Atached Enveloped (when the signature comprises a part of the document containing the signed data) and Atached Enveloping (when the signature contains the signed data withing itself).

PAdES: PDF Advanced Electronic Signature

This signature only can sign BINARI files. The PAdES Signature Type generate a PDF Signature file that is the result of sign or complete the PDF file we want to sign. So the PAdES Signature only exists in Atached way.

CAdES: CMS Advanced Electronic Signature

This signature only can sign BINARI files. The CAdES Signature Type generate a p7b Signature file that is a binary file. There are Atached or Detached Signature Types, but don't exists the Enveloped or Enveloping concept.

Now I'm going to explain how to implements a Sign Service:

For implements a WebService I use Spring Boot and Java 8.

First of all, you have to find the Service you want to use, in my case I choose DSS (Digital Signature Service): here is the git repository.

Take a look to the repository and, when you are ready, make the next steps:

- Add the necessaries maven dependencies.
- Find the Cookbook example and try to understand how it goes and reply the example to your code.

Is very easy to integrate the DSS Sign Service.

In a week I've integrated a PAdES Enveloped, XAdES Detached and CAdES Detached Sign Service with an indicated Certificate.

And finally, I'm going to explain how I've done a Complete and Validation Signature Service:

For implements a WebService I use Spring Boot and Java 8.

First of all, you have to find the Service you want to use. In my case, I choose Psis Client from AOC: here you have the explanations in his web.

Here AOC offers some example codes and calls for integrate his Service in your Application.

Now you are in the moment to play and improve your code.

After over 3 months you will have your Complete and Validation Signature Service, but, what it's more important, You are going to learn a lot.

I've done a Complete and Validation PAdES Enveloped, XAdES Detached and CAdES Detached Signature Service three months ago.

If you are interested in more details, contact me and we could collaborate together in your project.

miércoles, 26 de abril de 2017

How to configure MongoDB with Spring Boot in Windows 7

Hi, everyone!

Today we are going to show the steps for configuring MongoDB 3.3.4 with Spring Boot 1.5 in Windows 7.

First you have to download the MongoDB:

Here you have the official link: https://docs.mongodb.com/manual/installation/

Now here is the most important think, that don't tells the manual of mongodb:

You have to download the Windows parche: Windows6.1-KB2999226-x64.msu and it will add a dll file that is necessary for running MongoDB.

Then, you have to create the directory C:/db/data.

Then, when MongoDB is installed and you have create the directory, you have to run the file C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe.

This file will open the MongoDB connection.

Here you have MongoDB running!

For the other side, you have to configure your mongoDB database connectio and driver in Spring Boot configuration.

You have to create a file named application-{environment}.yml with the next content:

spring:
    datasource:
        url: jdbc:oracle:thin:@//localhost:27017/howdyl
        driver-class-name: mongodb.jdbc.MongoDriver
    jpa:
        show-sql: true            
hibernate:
    showSql: true
    dialect: org.hibernate.dialect.Oracle10gDialect

And the magic, you run your application a mongoDB is running.

For any question, ask me!

Try it and have fun!

martes, 18 de abril de 2017

Keys for configure Bootstrap 3 in Angular 4 Project!

Hi,

Today, I'm going to explain the steps for configure Bootstrap in an Angular application.

First of all, we have to add Bootstrap in our application with:

 > npm install --save ngx-bootstrap@latest  

Then, we have to open the index.html file and add:


<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />


Then, we have all we need for use Bootstrap 3 in Angular 4.

Now, we have to configure all the html files following the structure:

<div class="row">
<div class="col-xs-12 col-sm-6 col-lg-3">
...
</div>
... (any repeations you need)
</div>

You have to know that any div with class col-**-** need a parent div with class row.
Also, you have to know that col-xs is for mobiles dispositive, col-sm for tablets dispositives and col-lg for computer dispositive.

Here you have the documentation of the Bootstrap 3 style; All you need is here:


When you domain all this css styles, you can improve new approach for your develops.

Try it and have fun!

lunes, 10 de abril de 2017

How to migrate an Angular 2 Project to Angular 4?

Hi people,

Angular is growing ;) and now we have to migrate it to be updated!

The steps to upgrade to angular 4 are as follows:

First of all verify the Node Version:
> node -v
To actualice the version download it from: https://nodejs.org/en/download/

Then, we are going to actualice angular/cli:

First, we have to remove the actuals possibles versions:
> npm uninstall -g @angular/cli
> npm uninstall -g @angular-cli
Then, we are going to install it again:
> npm install -g @angular/cli
Then, verify the versions installed:
> ng -v
It must shows something like this:
    _                      _                 ____ _     ___ 
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | | 
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | | 
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/                                        
@angular/cli: 1.0.0                                  
node: 6.10.2                                              
os: win32 x64 
Then, goes to the Project directory and actualice the @angular version:

In Windows PC:
npm install @angular/common@next @angular/compiler@next @angular/compiler-cli@next @angular/core@next @angular/forms@next @angular/http@next @angular/platform-browser@next @angular/platform-browser-dynamic@next @angular/platform-server@next @angular/router@next @angular/animations@next --save
In Mac PC:
npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@next --save
In last, actualice typescript version:
> npm install typescript@2.2.1 --save
And finally, start the project:
> ng serve

viernes, 31 de marzo de 2017

How to generate a Method with Generic Classes in Java?

Wellcome again,

Today I'm going to explain how to generate methods with generic classes in the call in Java.

First of all, I'm going to show you an example:

        public <T> T convertirDesdeXml(Class<T> c, byte[] xml) {
XStream xStream = new XStream();
xStream.alias(c.getSimpleName(), c);
T objecte = (T)xStream.fromXML(new String(xml));
return objecte;
}

This example converts an xml in byte[] format to a generic object.

We have to use a placeholder that is presented with <T> syntax. A placeholder is a String name that represents any object type that you will use in the context (the class, a method, an static call, etc.).

The placeholder <T> indicates that you can use the class T like a generic type in the method.

You can complicate the call like <T extends java.util,Map>. This new example indicates that the placeholder T extends the interface Map or, what is the same, the operator instanceof returns true.

You can complicate the call like <T, K>. In this example you use two placeholder and you can you the number of placeholder you want.

With the placeholder you have your first generic method with generic classes.

Thanks for the read!

Try it and have fun!

miércoles, 8 de febrero de 2017

How to obtain the language in the browser and externalice with it in Angular 2?

Hi everybody!

Here we comes with another question.

Today the theme is Angular 2, Javascript and the navigator class.

With this code we will obtain the language from the browser:

loadLanguage() {
  let idioma = navigator.language;
  if(idioma === 'ca' || idioma == 'es' || idioma == 'gl' || idioma == 'va' || idioma == 'eu' || idioma == 'en' || idioma == 'fr') {
    this.idioma = idioma;
  } else {
    this.idioma = "en";
  }
}


Navigator is a Javascript class that returns the language and other interesting things.

Show the nagivator object with console.log(navigator); to see what are you interested in.

Another question related with this theme is to externalice the content of your web in Angular2.

For do that I pass you my example code:

This method loads the dictionary with all the traductions and the possible languages:

loadDictionary() {
  this.dictionary = { titol: {ca: 'El Temps a Espanya!', es: '¡El Tiempo en España!', en: 'The Weather in Spain!', fr: 'String1InSpanish', gl: 'O tempo en España!', va: 'El Temps a Espanya!', eu: 'Eguraldia Espainian!'}, descripcio: { ca: 'Troba les prediccions meteorològiques de tots els municipis espanyols durant els propers quatre dies.', es: 'Encuentra las prediciones meteorológicas de todos los municipios españoles durante los próximos cuatro días.', en: 'Find weather forecasts for all Spanish municipalities over the next four days.', fr: 'Trouvez les prévisions météo pour toutes les municipalités espagnoles au cours des quatre prochains jours.', gl: 'Atopar as previsións do tempo para todos os municipios españois durante os próximos catro días.', va: 'Troba les prediccions meteorològiques de tots els municipis espanyols durant els propers quatre dies.', eu: 'Aurki eguraldi Espainiako udalerri guztietako iragarpenak hurrengo lau egunetan zehar.'} };
}


This method obtaions the translation of a key string in a language:

getTranslation(inStringId: string, inLanguageId: string) {
  let labelTexts = this.dictionary[inStringId];
  let translation;
  if (labelTexts) { translation = labelTexts[inLanguageId]; }
  if (translation == null) {
    translation = inStringId;
    console.error(inStringId + ' has no defined text for language ' + inLanguageId);
  }
  return translation;
}


And this method loads the texts you need in your web:

loadTexts() {
  this.titol = this.getTranslation("titol", this.idioma);
  this.descripcio = this.getTranslation("descripcio", this.idioma);
}

This is my way! There are another possibilities! For any questio, don't doubt ask me!

Try it and have fun!

lunes, 30 de enero de 2017

Use cases of this.http.get in Angular 2

Hi everybody!!!

Here we comes with news explanations! Today the theme is how to use the sentence this.http.get! When use on one way or another? And why?

The question you have to do is... do you want a Sincron or Asincron call?

A Sincron call is when you want that the process occurs in the main thread. On this way, the sequence of the next process don't occurs until the call finish.

For do a Sincron call, you have to do the call like this:

this.http.get(url).map( data => data.json() )


This sentence will return a json data file. If you want to return a content file (binary or others types) you have to change data.json() call by data.text().

An Asincron call is when you want to create a new thread from the main thread. On this way, the senquence of the next process will continue and our thread will continue on parallel.

For do an Asincron call, you have to do the call like this:

this.http.get(url)

.subscribe( 

  data => this.data = data.json(),

  err => this.handleError,

  () => {console.log('complete call') /*do something when finish*/}

);

This sentence will process an Asincron call and you can do want you want with the data json file obtained on the complete pass. This call is used in the onInit of the component normally and usually loads a data json file necessary for something on the application (a data project information, a data language properties or what you need or want).

I hope you have found interesting this article.

You can ask me any question or doubt!!! And you are free for share them with your friends!!!

Try it and have fun!