UaiMockServer – A lot of new Features to help you with your tests

Hello, how are you?

The newest release of uaiMockVersion has a lot of new features that will influenciate a lot the HTTP mock open sources frameworks.

The first big feature is a GUI that will allow you to edit your requests:

Index

Index

You will not need to edit those boring configuration files anymore, all you need to do is to use access the GUI through the default url: http://localhost:1234/uaiGui/index

Another feature allows you to analyse everything in your request/response, very easily. All you need to do is to go to the Log tab and fire the request:

Request Log

Request Log

And if you detail a success request you will see:

Success Request

Success Request

And if you detail a request with error:

Error Detail 01

Error Detail 01

To help you to find out what kind of error just happened, you will be able to see the server log:

Error Detail 02

Error Detail 02

The last, but not least, feature is a JUnit runner that will control the server for you:

UaiMockServer JUnit Runner

UaiMockServer JUnit Runner

Using like the sample above you will not need to start and stop the uaiMockServer manually. Using like above the uaiMockServer will search for the default file named: uaiMockServer.json

You could also set specific config file:

UaiMockServer JUnit Runner Configuration

UaiMockServer JUnit Runner Configuration

And if you are a Spring user, you could also use the Spring Runner:

UaiMockServer JUnit SpringRunner Configuration

UaiMockServer JUnit SpringRunner Configuration

The last update in this new version was to change the config file from HCON to JSON. Unfortunately you will need to change your config file from HCON to JSON, sorry for that. I could not keep using the HCON type anymore.

The config file will look like below:

New Configuration File as JSON

New Configuration File as JSON

One advantage of the config file as JSON is that any file editor will be able to give you a better support.

The project site: http://uaimockserver.com/

Source code: https://github.com/uaihebert/uaiMockServer

Standalone version and config example: https://sourceforge.net/projects/uaimockserver/

Maven import:

<dependency>
    <groupId>uaihebert.com</groupId>
    <artifactId>uaiMockServer</artifactId>
    <version>1.1.0</version>
    <scope>test</scope>
</dependency>

I hope you liked the news.

If you have any questions/doubt/suggestion just post it below.

o_

uaiMockServer – Create a Mock Rest Server with a single command line

Hello how are you?

Have you ever needed to invoke a REST service, but this service was not created yet?

Imagine that you are developing an APP that needs to invoke an inexistent REST service. You will need to create a fake code that will be replaced once that the real code is finished. No matter if you are working with Java, .NET, PHP, Ruby, Python, etc. You will always need to create a fake invocation method if the REST service is not ready yet.

When we are programming in our unitary test we face the same problem. We will need to create a Mock code that will be invoked during the tests. The problem with this approach is that the real code is never invoked.

How can we solve this problem? Is there a solution that works for delphi, .NET, PHP, Java, Android, IOS, WindowsPhone, etc?

I present to you now my most recent creation: “uaiMockServer”.

With uaiMockServer you will be create a mock server using only a JAR file and a config file. With this server you will be able to execute real HTTP requests, but using your test data.

There are two ways of using uaiMockServer: Standalone and Unit Tests

Standalone

To use the uaiMockServer as a Standalone server you will manually type the command that starts it. Run the command in a prompt:

java -jar uaiMockServer-{VERSION}.Standalone.jar

You will only need the config file, that we will talk about very soon.

In the sample config file there is a mapping using the port 1234. If you are using linux, type the command:

curl localhost:1234/uaiMockServer/

The HTTP Response will contain a JSON.

Unit Test

First step is to add the project in your pom:

<dependency>
   <groupId>uaihebert.com</groupId>
   <artifactId>uaiMockServer</artifactId>
   <version>1.0.1</version>
   <scope>test</scope>
</dependency>

Now you can create a test code like:

public class YourTest {
    private static UaiMockServer uaiMockServer;
 
    @BeforeClass
    public static void beforeClass() {
        uaiMockServer = UaiMockServer.start();
    }
 
    @AfterClass
    public static void afterClass() {
        uaiMockServer.shutdown();
    }
 
    @Test
    public void aTest() {
        final Customer customer = // invoke the URL
        assertTrue(customer != null);
    }
}

You will be able to invoke the URL using any kind of framework. Below you will see a code sample using the RestEasy framework doing a request mapped in the sample config file (that we will see soon):

@Test
public void isGetRootReturning200() {
    final String url = "http://localhost:1234/uaiMockServer/";
 
    Client client = ClientBuilder.newClient();
    Response response = client.target(url).request().get();
 
    assertEquals(200, response.getStatus());
}

What is the gain in the test? You will not need a mock code anymore. You can fire a HTTP request from your JUnit test.

Configuration

To run the project you will need a config file. A simple sample would be like below:

com.uaihebert.uaimockserver {
    port = 1234
    host = localhost
    fileLog = false
    consoleLog = true
    context = /uaiMockServer
    defaultContentTypeResponse = "text/html;charset=UTF-8"
    routes = [
        {
            request {
                path = "/"
                method = "GET"
            }
            response {
                contentType = "application/json;charset=UTF-8"
                statusCode = 200
                body = """{"mockBody":{"title":"Hello World"}}"""
            }
        }
    ]
}

The file must have the .config extension and is not in the JSON format, but has a superset format of the JSON – HCON – used in configurations files (click here for more details).

With this file you can set up the port that will be invoked, the host, header, queryParm and other several options that are described in the uaiMockServer documentation.

Notice that in the configuration was created a request and a response; with these configurations you can mock every request that you want.

If you are going to use the Standalone version the config file must be in the same directory of the JAR file. You can set a different path with the command:

java -jar uaiMockServer-{VERSION}.Standalone.jar FULL_FILE_PATH

If you will run the project in your Unit Tests (like JUnit) you must put the config file in the “src/test/resources” maven folder. Or you can pass the full path like:

uaiMockServer = UaiMockServer.start(FULL_FILE_PATH);

It is free?

Yes, it is. Use it at your will.

Is open source? Yes: https://github.com/uaihebert/uaiMockServer

Where is the documentation? http://uaimockserver.com/

Where can I find the Standalone and the sample Config file: http://sourceforge.net/projects/uaimockserver/files/

It has any automated test? Yes, we have a lot of tests and we got 100% code coverage.

What about performance?

In the GIT there is a test that executes 300 requests in less than 2s.

Thanks to:

Be a Developer, not a Blender

Hello, how are you?

We live in a “frameworks that are easy to use” age that helps us to create our projects. One thing that a lot of teachers say is: “Just use this annotation and it will be ok”.

Annotations have the objective of making frameworks easier to use and identify their behavior, but some developers get lost with this feature and and they forget about some of the OO basics.

CRUD, JMS queues, Beans, transaction controls can be created in minutes, but what about the Object Orientation? What happened with the good practices that took a long time to be correctly forged? Why are they being abandoned?

Mixing Concepts

To understand better what I am trying to say, let us see below some code snippets  that we find in development sites. In the first sample we can see a code with JPA and JSON mixed:

@Entity
@XmlRootElement
@JsonAutoDetect
@DiscriminatorColumn(name = "animal_type")
@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = Dog.class, name = "dog"),
        @JsonSubTypes.Type(value = Cat.class, name = "cat"),
        @JsonSubTypes.Type(value = Bird.class, name = "bird")
})
public class Animal {
 
    @Id
    private int id;
 
    @JsonSerialize(using = JsonDateSerializer.class)
    private Date birthday;
 
    @JsonView(ToothView.class)
    @OneToMany(mappedBy = "animal")
    private List<Tooth> teethList;
 
    // other stuff
}
 
@Entity
@JsonRootName(value = "Dog")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Dog extends Animal {
 
    @JsonProperty
    private String name;
 
    @Convert(converter = JsonAttributeConverter.class)
    private Double weight;
 
    @JsonIgnore
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "dog", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Bone> boneList;
 
    public Dog() {
    }
}

What is the problem with the code above? Why would someone mix JSON annotations (VIEW) with JPA annotations (MODEL)? If we need to edit an attribute only to display it in a different way in a VIEW, this update will affect the same class that is used to persist the data. We will increase the risk to input a bug when persisting the data.

No Respect for the Layers

Let us see another example:

@ViewScoped
@ManagedBean
@TransactionManagement(TransactionManagementType.BEAN)
public class ManagedBeanOne extends SuperManagedBean implements Serializable {
     // attributes
    public String doSomething() {
        try{
            transaction.begin();
            // do something
            transaction.commit();
        }
        catch(Exception ex){
            transaction.rollback();
        }
    }
}
 
 
@ManagedBean
@WebService
@ViewScoped
public class ManagedBeanTwo implements Serializable{}

Should the class be defined as a JSF ManagedBean and an EJB? The worst part of this code is: Why is a JSF class managing a transaction? What do we gain by giving this ManagedBean so many responsibilities?

Huge Code Blocks Do Not Help

A code that I could not post here is a class with more than 1k lines. The worst part of a huge class is that the some developers start to make jokes about it, or sometimes the class is considered to be a huge bad monster that should never be touched because any update would break the code.

How long will developers keep adding just one if statement to this kind of classes without doing small refactorings?

Exception that Dictate the Rules

A terrible practice is using an Exception to handle the request flow. Take a look below:

try{
    myObject.doSomething();
} catch(MyExceptionOne one){
    sendErrorSmsToCustomer();
    defineOldPlanToCustomer();
    sentToScreenOne();
} catch(MyExceptionTwo two){
    sendErrorEmailToCustomer();
    defineNewPlanToCustomer();
    sentToScreenTwo();
}

What would happen with the database data if an error is thrown at the first line of the exception block? What would happen if a developer invokes “myObject.doSomething()” in another class but without the correct catch code like above? What if the line code that handles the user plan is not executed?

What comes next?

It is an easy task to say if code looks good or bad, but I believe that one thing that is needed is to always to show a solution. What we will see in the pages to come is not something created by me, but are good practices and design patterns that you will find in several development books.

What we will see:

  • Page 2: Do not Pass Over the Layers
    • Pay Attention to the Packages
  • Page 3: Increase your Cohesion
  • Page 4: Loose Coupling
    • Facade is a Good Call
  • Page 5: Let us Return to the DTOs World
    • How can I easily pass the Entity data to a DTO?
  • Page 6: Small Classes and Methods
  • Page 7: How can we use Exceptions Correctly?
  • Page 8: The Broken Window Theory
    • Keep your build working
    • Do not leave your tests breaking
    • Do not comment/ignore your tests
  • Page 9: Good practices that helps
    • KISS
    • DRY
  • Page 10: It does not matter if you have a huge amount of tests without quality
    • Use Test Tools
    • Did you find a bug? Create a test for it
  • Page 11: Conclusion

I hope that this posts helps you. (:

I am really thankful for the Rodrigo Sasaki’s (http://cv.rodrigosasaki.com) help, this guy rocks!

EasyCriteria has evolved to uaiCriteria. New name and more features

Hello, how are you?

I am very happy to announce the release of the uaiCriteria, the EasyCriteria evolution.

Was it really needed to change the framework name? Yes, sadly it was. I found another framework with the same name, that is why I decided to change the name (I do not want any kind of legal problems). The difference of the framework is that the other framework works with MetaModel, and uaiCriteria works with strings as parameters.

About the framework name change:

  • Your code will work with this new version without a problem, the code is retro compatible
  • All EasyCriteria classes are annotated with @Deprecated and will be removed in the next version
  • The new classes has all the methods of the old version. If you want to change for the new code just “replace” the text EasyCriteria for UaiCriteria in your code
  • Again, I did not want to change the framework name but I do not want legal problems

The framework now has a mascot:

mascot

mascot

The new version has a lot of new stuff. Let us talk first about the structural changes:

  • The site has changed, now is http://uaicriteria.com
  • The repository has changed, now is on GIT (requested by a lot of develpers) https://github.com/uaihebert/uaicriteria
  • The SONAR plug-in was added to the pom.xml to help with code the code coverage and static analysis:

    uaicriteria cobertura

    uaicriteria cobertura

  • The old site will be deactivated, but all the old documentation was migrated.
  • The current API has some criteria limitations, using HAVING in the criteria is something that is not possible. We will create a new Interface/API to use with complex criteria – I am looking for a new name for the new Interface, could you suggest me one? (:

Let us talk about the new features:

Welcome to Batoo

Batoo is a JPA provider like EclipseLink or Hibernate. In this new version we got a good number of methods tested with Batoo.

Notice that I talked about “a good number of methods” but not most of the methods. Unfortunately Batoo has several problems with JPQL and Criterias, and I could not cover most of the methods with it.

uaiCriteria framework support almost all methods with EclipseLink, Hibernate and OpenJPA.

MultiSelect

It is possible to choose which attributes will be returned:

select
    p.name,
    p.age
from 
    Person p

If we transform the JPQL above in Criteria:

finalUaiCriteria<Person> uaicriteria =
    UaiCriteriaFactory.UaiCriteriaFactory.createMultiSelectCriteria(entityManager, Person.class);

uaiCriteria.addMultiSelectAttribute("name")
           .addMultiSelectAttribute("age");

finalList multiselectList = uaiCriteria.getMultiSelectResult();

Some considerations about the code above:

  • Object will be returned if you select only one attribute
  • Object[] will be returned if you select more than one attribute
  • The JPA provider may return Vector instead of Object[] (with my tests EclipseLink was returning a Vector)

SubQuery

Now it is possible to do a subQuery like below:

select p from Person p 
where p.id in
        (select dog.person.id from Dog dog where dog.cute = true)

I will not talk about the several lines of native JPA criteria needed to do the JPQL above, but with UaiCriteria is very easy to do:

final UaiCriteria<Person> uaiCriteria = UaiCriteriaFactory.createQueryCriteria(Person.class);
 
final UaiCriteria<Dog> subQuery = uaiCriteria.subQuery("person.id", Dog.class); // dog.person.id
 
subQuery.andEquals("cute", true);
 
uaiCriteria.andAttributeIn("id", subQuery); //person.id

All you need to do is to create a subQuery informing its return; then call the method attributeIn of the root criteria.

MapIsEmpty [NOT]

The isEmpty method can be used with maps:

uaiCriteria.andCollectionIsEmpty("ENTITY_MAP");

AttributeIn [NOT]

If you want to validate if a value is inside a list like the JPQL:

select p
from Payment p
where
    p.statusEnum in :enumList

You can create the JPQL above like:

final UaiCriteria<Payment> uaiCriteria = 
    UaiCriteriaFactory.createQueryCriteria(Payment.class);
 
uaiCriteria.andAttributeIn("statusEnum", 
                           Arrays.asList(StatusEnum.VALUE_01, StatusEnum.VALUE_02));

The attribute could be a enum, integer, String, etc.

MemberOf [NOT]

The query below:

select d
from Departament d
where :person member of d.employeeList

Could be created like:

final UaiCriteria<Departament> uaiCriteria = 
    UaiCriteriaFactory.createQueryCriteria(Departament.class);
 
uaiCriteria.andIsMemberOf(person, "employeeList");

Count and CountRegularCriteria

Now it is possible to do a count with a MultiSelect criteria. The count method was renamed to countRegularCriteria(). It works like the older version, just the name was refactored to make things more distinct.

CountAttribute

Sometimes you need to count an attribute instead of an entity:

select count(p.id)
from Person p

You can run the JPQL above like:

final UaiCriteria<Person> uaiCriteria = 
    UaiCriteriaFactory.createMultiSelectCriteria(Person.class);
 
uaiCriteria.countAttribute("id");
 
final List result = uaiCriteria.getMultiSelectResult();

GroupBy and Aggregate Functions

Now it is possible to do a GroupBy with aggregate functions: sum, diff, divide, module,  etc.

select sum(p.value), p.status
from Payment p
group by p.status

Could be executed like:

final UaiCriteria<Payment> uaiCriteria = 
    UaiCriteriaFactory.createMultiSelectCriteria(Payment.class);
 
uaiCriteria.sum("id").groupBy("status");
 
final List result = uaiCriteria.getMultiSelectResult();

New Maven Import

If you want to use the new version, just add the xml below to your pom.xml:

<dependency>
    <groupId>uaihebert.com</groupId>
    <artifactId>uaiCriteria</artifactId>
    <version>4.0.0</version>
</dependency>

I hope you liked the news.

Do not forget to visit the new site ———–> http://uaicriteria.com

If you have any doubts, questions or suggestions just post it.

See you soon. o_

JPA Hibernate Alternatives. What can I use if JPA or Hibernate is not good enough for my project?

Hello, how are you?

Today we will talk about situations that the use of the JPA/Hibernate is not recommended. Which alternatives do we have outside the JPA world?

What we will talk about:

  • JPA/Hibernate problems

  • Solutions to some of the JPA/Hibernate problems

  • Criteria for choosing the frameworks described here

  • Spring JDBC Template

  • MyBatis

  • Sormula

  • sql2o

  • Take a look at: jOOQ and Avaje

  • Is a raw JDBC approach worth it?

  • How can I choose the right framework?

  • Final thoughts

I have created 4 CRUDs in my github using the frameworks mentioned in this post, you will find the URL at the beginning of each page.

I am not a radical that thinks that JPA is worthless, but I do believe that we need to choose the right framework for the each situation. If you do not know I wrote a JPA book (in Portuguese only) and I do not think that JPA is the silver bullet that will solve all the problems.

I hope you like the post. [=

Last day to by one and get other book for free!

Hello, how are you?

The people from Packt Publishing asked me to announce:

 

Packt Publishing celebrates their 2000th title with an exclusive offer – We’ve got IT covered!

Known for their extensive range of pragmatic IT ebooks, Packt Publishing are celebrating their 2000th book title `Learning Dart’– they want their customers to celebrate too.

To mark this milestone Packt Publishing will launch a ‘Buy One Get One Free’ offer across all eBooks on March 18th – for a limited period only.

Packt is one of the most prolific and fast-growing tech book publishers in the world. Originally focused on open source software, Packt contributes back into the community paying a royalty on relevant books directly to open source projects. These projects have received over $400,000 as part of Packt’s Open Source Royalty Scheme to date.

Their books focus on practicality, recognising that readers are ultimately concerned with getting the job done. Packt’s digitally-focused business model allows them to quickly publish up-to-date books in very specific areas across a range of key categories – web development, game development, big data, application development, and more. Their commitment to providing a comprehensive range of titles has seen Packt publish 1054% more titles in 2013 than in 2006.

Here are some of the best titles across Packt’s main categories – but Buy One, Get One Free will apply across all 2000 titles:

Protecting your Project – Mini Book

Hello, how are you?

This post is to celebrate the mark of 1 million views that the blog reached in the last month. Below you will find a free mini book about project security.

We are very excited to celebrate this milestone, all the 300+ post writers of the  blog(cof cof cof) cannot wait for the party:

happy

Ok… We will do the celebration in another day.

Today we will talk about security. Not only environment security, but how can we create a secure code. This post is what I call of: “Mini Book”. This post will not be published as a book, but it does not have a few pages like other posts.

It is easy to hear about a hacker attack in the news, but we do not take a time to think about security measures to our systems.

A project that has a code with good security practices and a production environment that is safe and fast to respond a hacker attack should be a requirement for every project. We need to be sure that our code is following good security practices; it is fundamental that our production environment is protected and ready to react when a hacker attacks our project.

PS.: I will not create a PDF version of this post. I have invested several hours planning, writing, formatting and translating this post. I do not have enough time to create a PDF or any other file format version of this post. This Mini Book will be available on-line only.

What you will see here:

  • Page 02: What are the foundations of security?
  • Page 03: Who will access our project?
  • Page 04: A good hacker always will have time
    • Watch out for the returned information
    • Watch out for the size of the returned message
    • Firewall/SSL does no magic
  • Page 05: Attack types and suggestion prevent/handle them
    • SQL Injection
    • JPQL Injection and HQL Injection
    • Cross-site scripting (XSS)
    • Brute Force Attack
    • Man in the middle
    • XPath Injection
    • LDAP Injection
    • DoS or DDoS
    • Slow DoS
  • Page 06: Protect your data
    • Protecting the incoming data
    • Protecting the outgoing data
  • Page 07: The “Client Side”
    • URL tips
    • Technical Tests
  • Page 08: Validation
    • Data validation
    • Be careful with uploaded files
  • Page 09: Always start with the lowest privilege
  • Page 10: Handle all project exceptions
  • Page 11: Watch out for third party libraries
  • Page 12: System versions
  • Page 13: Pay attention to the log
  • Page 14: Add layers to your project
  • Page 15: Comments in code are not always healthy
  • Page 16: Always do a Code Validation
  • Page 17: Create a Checklist
  • Page 18: IT Staff
    • Data leaking
    • Be careful with your code
    • Fired Employee
    • Code Review / Pair Programming
    • Defining a terminology
  • Page 19: Handle the passwords correctly
  • Page 20: Good practices to handle user requests
    • Hide the buttons/links, but protect the code
    • Know your user needs
    • Always hide
  • Page 21: Security Policies
  • Page 22: Be careful with errors in the code/frameworks
    • Do not expose the technologies
    • Do not mix the types
    • Use brackets in the Ifs
    • Integer and Floating
    • Defensive programming

I am not an expert in the security subject; I am sharing what I learned by reading books or in the places that I have worked.

Let us begin.

Book Review: Developing RESTful Services

Hello, how are you?

I was invited by Packt publisher to do a review of the book: Developing RESTful Services with JAX-RS 2.0, WebSockets, and JSON.

It is a small and versatile book. It not goes deep in the Webservices subject, but it talks about all needed knowledge to start a Webservice project.

The chapter that I liked most is the chapter two that talks about pooling. It talked a lot about it and got deep in the pooling subject.

At the end of the book it is possible to find two projects with different Webservices approaches.

It is a good book to those that wants to know quickly about the basic Webservices concepts.

See you later! o_

My new Book – Effective JPA is out! (portuguese only)

Hello, how are you?

I am very happy to announce that my new book was published today, and it can be found in here: http://www.casadocodigo.com.br/products/livro-jpa-eficaz

JPA-Eficaz-ebook_large

It talks about JPA spec and good practices, BUT Portuguese only. [=

I wish that, before the end of this year, I will be able to write a new post. It is about a subject that was not talked about so detailed in this blog. I hope you guys like it! ;)

See you guys soon! o_