This is an handy tutorial to show how to scaffold a REST application based on an Entity object using JBoss Forge. ScreenCast included!

Pre-requisites: You need JBoss Forge and WildFly application server.

You can download Forge using:

wget http://downloads.jboss.org/forge/releases/3.9.0.Final/forge-distribution-3.9.0.Final-offline.zip

You can download WildFly using:

wget http://download.jboss.org/wildfly/12.0.0.Final/wildfly-12.0.0.Final.zip

Now move into the bin folder of your forge-distribution and launch forge:

$ forge

As first step we will create a new Project named "demo-rest" which uses JAVA EE 7 stack

project-new  --named demo-rest --type war --stack JAVA_EE_7

We will then add an Entity object named Customer

jpa-new-entity --named Customer

jpa-new-field --named firstname
jpa-new-field --named surname
jpa-new-field --named email

Now we move to the top of our project and we generate the REST Endpoints to CRUD our Entities:

cd ~~
rest-generate-endpoints-from-entities --targets org.demo.rest.model.Customer 

As you can see, the following EJB Rest Resource has been created:

@Stateless
@Path("/customers")
public class CustomerEndpoint {
	@PersistenceContext(unitName = "demo-rest-persistence-unit")
	private EntityManager em;

	@POST
	@Consumes("application/json")
	public Response create(Customer entity) {
		em.persist(entity);
		return Response.created(
				UriBuilder.fromResource(CustomerEndpoint.class)
						.path(String.valueOf(entity.getId())).build()).build();
	}

	@DELETE
	@Path("/{id:[0-9][0-9]*}")
	public Response deleteById(@PathParam("id") Long id) {
		Customer entity = em.find(Customer.class, id);
		if (entity == null) {
			return Response.status(Status.NOT_FOUND).build();
		}
		em.remove(entity);
		return Response.noContent().build();
	}

	@GET
	@Path("/{id:[0-9][0-9]*}")
	@Produces("application/json")
	public Response findById(@PathParam("id") Long id) {
		TypedQuery<Customer> findByIdQuery = em
				.createQuery(
						"SELECT DISTINCT c FROM Customer c WHERE c.id = :entityId ORDER BY c.id",
						Customer.class);
		findByIdQuery.setParameter("entityId", id);
		Customer entity;
		try {
			entity = findByIdQuery.getSingleResult();
		} catch (NoResultException nre) {
			entity = null;
		}
		if (entity == null) {
			return Response.status(Status.NOT_FOUND).build();
		}
		return Response.ok(entity).build();
	}

	@GET
	@Produces("application/json")
	public List<Customer> listAll(@QueryParam("start") Integer startPosition,
			@QueryParam("max") Integer maxResult) {
		TypedQuery<Customer> findAllQuery = em.createQuery(
				"SELECT DISTINCT c FROM Customer c ORDER BY c.id",
				Customer.class);
		if (startPosition != null) {
			findAllQuery.setFirstResult(startPosition);
		}
		if (maxResult != null) {
			findAllQuery.setMaxResults(maxResult);
		}
		final List<Customer> results = findAllQuery.getResultList();
		return results;
	}

	@PUT
	@Path("/{id:[0-9][0-9]*}")
	@Consumes("application/json")
	public Response update(@PathParam("id") Long id, Customer entity) {
		if (entity == null) {
			return Response.status(Status.BAD_REQUEST).build();
		}
		if (id == null) {
			return Response.status(Status.BAD_REQUEST).build();
		}
		if (!id.equals(entity.getId())) {
			return Response.status(Status.CONFLICT).entity(entity).build();
		}
		if (em.find(Customer.class, id) == null) {
			return Response.status(Status.NOT_FOUND).build();
		}
		try {
			entity = em.merge(entity);
		} catch (OptimisticLockException e) {
			return Response.status(Response.Status.CONFLICT)
					.entity(e.getEntity()).build();
		}

		return Response.noContent().build();
	}
}

Now our Forge project is complete. We will add to the pom.xml the WildFly plugin so that we can deploy using our Maven project:

<plugins>
	<plugin>
	        <groupId>org.wildfly.plugins</groupId>
	        <artifactId>wildfly-maven-plugin</artifactId>
	        <version>1.0.2.Final</version>
	        <configuration>
	            <filename>${project.build.finalName}.war</filename>
	        </configuration>
	</plugin>
</plugins>

That's all. Build and deploy with:

mvn wildfly:deploy

Testing the REST Application

In order to test our application, we will use the cURL utility to send JSON content type. This is needed to create new Entities:

curl -d '{  "firstname": "john",  "surname": "doe",  "email": "johndoeEgmail.com"}' -H "Content-Type: application/json" -X POST http://localhost:8080/demo-rest/rest/customers

curl -d '{  "firstname": "uncle",  "surname": "tom",  "email": "uncletomEgmail.com"}' -H "Content-Type: application/json" -X POST http://localhost:8080/demo-rest/rest/customers

You can check the list of Customers or individual Customers with:

curl http://localhost:8080/demo-rest/rest/customers/

curl http://localhost:8080/demo-rest/rest/customers/1

Finally, you can delete one Customer using:

curl -X DELETE http://localhost:8080/demo-rest/rest/customers/2

That's all! Enjoy the screencast of it!

0
0
0
s2smodern