Sunday 10 December 2017

REST API endpoints with Firestore

Firestore is the new database cloud service from Google to support web/mobile development. It was launched in October this year.

If you have google account you can create your own database for your applications.

One interesting thing you can do it is to have endpoints to access to your firestore collections (tables) using REST API.

I will summarize how you can have the endpoints for a CRUD application using one collection in firestore.

First step is to create a collection in firestore that I will call 'tasks'
This collection will have 2 fields: title and description.




Get list of records:
GET
https://firestore.googleapis.com/v1beta1/projects/YOUR_PROJECT_ID/databases/(default)/documents/COLLECTION_NAME
Example:
GET
https://firestore.googleapis.com/v1beta1/projects/myproject/databases/(default)/documents/tasks

The response will have this format:
{
    "documents": [
        {
            "name": "projects/angular-task-e7f39/databases/(default)/documents/tasks/Cw36XeLhvf9widHiatQG",
            "fields": {
                "description": {
                    "stringValue": "Task1"
                },
                "title": {
                    "stringValue": "My first task"
                }
            },
            "createTime": "2017-12-04T23:04:03.933099Z",
            "updateTime": "2017-12-04T23:04:03.933099Z"
        }
   ]
}

Get one record by Id:
GET

https://firestore.googleapis.com/v1beta1/projects/YOUR_PROJECT_ID/databases/(default)/documents/COLLECTION_NAME/ID

Example:
GET
https://firestore.googleapis.com/v1beta1/projects/myproject/databases/(default)/documents/tasks/ Cw36XeLhvf9widHiatQG


The response will have this format:

{
    "name": "projects/angular-task-e7f39/databases/(default)/documents/tasks/Cw36XeLhvf9widHiatQG",
    "fields": {
        "title": {
            "stringValue": "Task1"
        },
        "description": {
            "stringValue": "My first task"
        }
    },
    "createTime": "2017-12-04T23:04:03.933099Z",
    "updateTime": "2017-12-04T23:04:03.933099Z"
}


Create a new record:
POST
https://firestore.googleapis.com/v1beta1/projects/YOUR_PROJECT_ID/databases/(default)/documents/COLLECTION_NAME
Example:
POST
https://firestore.googleapis.com/v1beta1/projects/myproject/databases/(default)/documents/tasks

Request body:
{  
   "fields":{  
      "title":{  
         "stringValue":"task2"
      },
      "description":{  
         "stringValue":"My second task"
      }
   }
}

Delete one record by Id:

DELETE
https://firestore.googleapis.com/v1beta1/projects/YOUR_PROJECT_ID/databases/(default)/documents/COLLECTION_NAME/ID

Example:
DELETE
https://firestore.googleapis.com/v1beta1/projects/myproject/databases/(default)/documents/tasks/Cw36XeLhvf9widHiatQG


Thursday 22 June 2017

Java 8 certification - upgrade

It is only 34 days until the Java 9 is released. To be updated about this you can check this countdown.

That is why I will include in the blog new entries to cover the new topics included in Java 8 certification because I think it would be high time to upgrade the java knowledge. Java 8 first released appeared on March 2014, and the first beta certification exam was available one year after, so it is likely to happen the same with the next version.

Java 8 it has supposed a big jump from previous version java 7 introducing Lambdas, streams and functional programming. 

There are several ways to obtain Java8 certification:

- If you do not have any previous Java certification. The steps to be Java SE 8 Professional certified would be to pass this 2 exams:

  • 1Z0-808 Java SE8 Programmer I
  • 1Z0-809 Java SE8 Programmer II

- If you are certified in Java 7 you can take a unique exam to upgrade the certification.
  • 1Z0-810 Upgrade Java SE 7 to Java SE 8 OCP Programmer

- If you are certified in Java 6 or any other previous version you can upgrade to Java 8 with only one exam that will include the same topics as the the previous but also including additional topics included in Java 7 as language enhancements, NIO2, concurrency and localization.
  • 1z0-813 Upgrade to Java SE 8 OCP ( Java SE 6 and all prior versions)

Java 8 certification - upgrade from Java7

150 min

60 questions
65 % passing score


1. Lambda Expressions
1.1. Describe and develop code that uses Java inner classes, including nested class, static class, local class, and anonymous classes
1.2. Describe and write functional interfaces
1.3. Describe a lambda expression; refactor the code that uses an anonymous inner class to use a lambda expression; describe type inference and target typing
2. Using Built-in Lambda Types
2.1. Describe the interfaces of the java.util.function package
2.2. Develop code that uses the Function interface
2.3. Develop code that uses the Consumer interface
2.4. Develop code that uses the Supplier interface
2.5. Develop code that uses the UnaryOperator interface
2.6. Develop code that uses the Predicate interface
2.7. Develop code that uses the primitive and binary variations of the base interfaces of the java.util.function package
2.8. Develop code that uses a method reference, including refactoring a lambda expression to a method reference
3. Java Collections and Streams with Lambdas
3.1. Develop code that iterates a collection by using the forEach() method and method chaining
3.2. Describe the Stream interface and pipelines
3.3. Filter a collection by using lambda expressions
3.4. Identify the operations, on stream, that are lazy
4 Collection Operations with Lambda

4.1. Develop code to extract data from an object by using the map() method
4.2. Search for data by using methods such as findFirst(), findAny(), anyMatch(), allMatch(), and noneMatch()
4.3. Describe the unique characteristics of the Optional class
4.4. Perform calculations by using Java Stream methods, such as count(), max(), min(), average(), and sum()
4.5. Sort a collection by using lambda expressions
4.6. Develop code that uses the Stream.collect() method and Collectors class methods, such as averagingDouble(), groupingBy(), joining(), and partitioningBy()
5. Parallel Streams
5.1. Develop code that uses parallel streams
5.2. Implement decomposition and reduction in streams
6. Lambda Cookbook
6.1. Develop code that uses Java SE 8 collection improvements, including Collection.removeIf(), List.replaceAll(), Map.computeIfAbsent(), and Map.computeIfPresent() methods
6.2. Develop code that uses Java SE 8 I/O improvements, including Files.find(), Files.walk(), and lines() methods
6.3. Use flatMap() methods in the Stream API
6.4. Develop code that creates a stream by using the Arrays.stream() and IntStream.range() methods
7. Method Enhancements
7.1. Add static methods to interfaces
7.2. Define and use a default method of an interface and describe the inheritance rules for the default method
8. Use Java SE 8 Date/Time API
8.1. Create and manage date- and time-based events, including a combination of date and time in a single object, by using LocalDate, LocalTime, LocalDateTime, Instant, Period, and Duration
8.2. Work with dates and times across time zones and manage changes resulting from daylight savings, including Format date and times values
8.3. Define, create, and manage date- and time-based events using Instant, Period, Duration, and TemporalUnit

9. Javascript on Java with Nashorn
9.1. Develop Javascript code that creates and uses Java members such as Java objects, methods, JavaBeans, Arrays, Collections, Interfaces.
9.2. Develop code that evaluates Javascript in java, passes java object to Javascript, invokes Javascript function and call methods on javascript objects.
* Note these are the topics to upgrade your certification from Java 7. In case you are java certified in Java 6 or previous versions there are extra topics included in the exam: Language enhancements, concurrency, localization, NIO.2.

OCEJBCD - Resources to study JavaBeans cert

OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification


This is a summary of available resources that I used to prepare the Oracle JavaEE6 Java beans certification.
  • Oracle JavaEE6 tutorial This tutorial is essential to me for every JavaEE certification. It contains all the topics, examples and it is one of the resources I most usually query.
  • JavaRanch links JavaBeans section This a section for the java beans certifications in the well known site for java programmers javaRanch. In this links section you have all the information regarding the certification. Also it links to 2 free guides (I used the first one). 
  • Enthuware This is another essential resource to prepare the exam. The books/tutorials and guides are important for the studying but when you are preparing the exam you need to complement with mock exams. I bought the web version (you have access during 6 months).
  • O'Reilly Enterprise JavaBeans 3.1. This is the book I bought in paper format. It is a book I recommend because it covers most of the certification topics and has plenty of examples. Not all the chapters are needed in the certification, it has several sections dedicated to JPA which is not applicable to the exam.
OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

Sunday 30 October 2016

OCEJBCD - Package and Deploy EJB applications

OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

Package and Deploy EJB applications

EJB3 bean classes are packaged in regular JAR files.

The javabeans configuration can be defined with annotations or using a deployment descriptor ejb-jar that will be located under META-INF folder:
  • META-INF
    • ejb-jar.xml
    The configuration specified in the descriptor will override the configuration specified by annotations.


    The JAR generated will be placed under lib folder in the WAR generated for the application.

    • WAR
      • WEB-INF
        • lib
          • ejbModule.jar



      Example of deploying an EJB project in a Glassfish server using Eclipse in this post .


      OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

      Sunday 23 October 2016

      OCEJBCD - Perform EJB Exception Handling

      OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

      EJB container considers two exception types:

      • System Exceptions
      • Application Exceptions


      System Exceptions .- internal errors

      • EJBException is a subclass of java.lang.RuntimeException
      • They always cause a rollback in transactions.
      • Runtime exceptions are unchecked exceptions, so they are thrown from the method (not need to throws or try/catch clauses)
      • Way the container hands system exceptions:
        • Roll back transaction
        • Log exception
        • Discard EJB instance
      • The EJB wraps the exception into RemoteException and throws it to the client.
      • If the client started the application and it was propagated to the EJB, the system exception will be rethrown as EJBTransactionRolledbackException

      Application Exceptions.- errors in the business logic

      • The do not cause a rollback by default. To rollback the transaction automatically it can be used the annotation @ApplicationException(rollback=true), or doing it explicity with a call the method setRollbackOnly()
      • They are sent to the client directly. The container does not wrap the exception.

      OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

      Sunday 9 October 2016

      OCEJBCD -11. Implementing Security

      OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

      11.1. Understand the JavaEE security architecture

      -Declarative security (using deployment description and annotations)
      -Programmatic security

      More details in securing java beans section from javaEE tutorial. 


      11.2. Authenticate the caller 

      Authenticate on a remote EJB can be done by JNDI:

      properties.put(Context.SECURITY_PRINCIPAL, "usename");
      properties.put(Context.SECURITY_CREDENTIALS, "password");

      Context jndiContext =  new InitialContext(properties);
      Object ref = jndiContext.lookup("SecureBean/remoteObject");

      11.3. Examine JavaEE authorization strategies

      Details about web application security can be review here.

      • Basic Authentication

      Data is encoded in base64 (not encrypted).


      • Form-based authentication

      Creating a custom login form.
      data are sent in http request with no encryption.

      In the Form authentication type the loginPage should be defined (using these three fields: j_security_check, j_username, j_password

      <form method="POST" action="j_security_check">
        <input type="text" name="j_username">
        <input type="password" name="j_password">
        <input type="submit" value="Enter">
      </form>



      • Digest authentication

      Data is encrypted (not SSL) but not all JEE containers support it.


      • Client authentication

      Using Publick Key Certificates
      Clients need to have a certificate to use it.


      • Mutual authentication
      The server and client authenticate each other. It can be certificate based or user/password based.

      11.4. Use declarative authorization

      Annotations:

      @DeclareRoles (class level)
      @RolesAllowed (class or method level)
      @PermitAll(class or method level)
      @DenyAll (class or method level)

      These annotations can be used at class or method level. At class level means that those roles will be applied to all the method in the class. The annotation at method level will override the class annotation.



      Java Security identity between the client and EJBcontainer is the identity of the caller.

      Propagating security between EJB containers by default will be the identity of the caller, but also can be specified configuring the bean with annotation(@RunAs("nameOfTheRole"))

      Message-driven beans have only @Run As as identity, they are not allowed to use method permissions or execute under caller identity.

      11.5. Use programmatic authorization 

      Methods from javax.ejb.EJBContext

      -getCallerPrincipal()

      -isCallerInRole("role")

      11.6. Examine the responsibilities of the deployer

      To override security annotations at deployment time it can be used security elements in the deployment descriptor.

      The deployer customises an EJB for a specific operational environment and deploy it into the server.
      Interprets the deployment descriptor from the application assembler and the bean provider and knows the security roles and users for this system.


      OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

      Sunday 2 October 2016

      OCEJBCD -10. Implementing transactions

      OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

      10.1. Describe transaction demarcation management

      JTA (Java Transaction API).

      Transaction demarcation involves indicating when a transaction begin and ends.

      There are three kind of demarcation management:

      • Bean managed
      • Container managed (by default)
      • Client managed

      10.2. Implement CMT

      CMT (Container Managed transaction)

      Transaction attributes

      Transactions attributes can be used at class or method level.

      • Required
      @TransactionAttribute(REQUIRED)
      Start transaction or continue with client transaction.
      • RequiresNew
      @TransactionAttribute(REQUIRES_NEW)
      Start new transaction (stop client and resume later).


      • Mandatory
      @TransactionAttribute(MANDATORY)
      Always with client transaction, if not throws an exception


      • Not supported
      @TransactionAttribute(NOT_SUPPORTED)
      No transaction (if client running within trans stop and resume later)


      • Supports
      @TransactionAttribute(SUPPORTS)
      Bean runs within client transaction if related only.


      • Never
      @TransactionAttribute(NEVER)



      10.3. Interact programmatically with an ongoing CMT transaction

      A transaction will rollback automatically in CMT when a system exception ocurrs. It can be invoked by setRollbackOnly() method.

      Methods not allowed in CMT are ( commit, rollback, getUserTransaction...)

      10.4. Implement BMT Apply transactions to messaging

      @TransactionManagement(BEAN)

      Use of commit, rollback, getUserTransaction(setTransactionTimeout..etc)
      Not allowed get/setRollbackOnly()

      OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification