org.rro.inventory.rest.InventoryResourceRESTService.java Source code

Java tutorial

Introduction

Here is the source code for org.rro.inventory.rest.InventoryResourceRESTService.java

Source

/*
 * JBoss, Home of Professional Open Source
 * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the @authors tag. See the copyright.txt in the
 * distribution for a full listing of individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.rro.inventory.rest;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.http.HttpStatus;
import org.rro.android.commons.models.ItemResponse;
import org.rro.android.commons.models.ItemsResponse;
import org.rro.android.commons.par.InventoryUser;
import org.rro.android.commons.par.ItemModel;
import org.rro.inventory.commons.models.Item;
import org.rro.inventory.service.InventoryServices;

import com.adp.it.common.exceptions.UserException;
import com.adp.it.common.utils.Utilities;

/**
 * JAX-RS Example
 * <p/>
 * This class produces a RESTful service to read/write the contents of the members table.
 */
@Path("/inventory")
@RequestScoped
public class InventoryResourceRESTService {
    @Inject
    private Logger log;

    @Inject
    private Validator validator;

    @Inject
    private InventoryServices services;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/recordcount")
    public Long getRecordCount(@QueryParam("entity") String entityName, @QueryParam("order") String[] orderFields)
            throws UserException {
        log.info("getRecordCount: orderFields=" + (orderFields != null ? Arrays.toString(orderFields) : "empty"));
        return services.getRecordCount(entityName);
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/listitems")
    public ItemsResponse getItems(@QueryParam("page") Integer page, @QueryParam("pagesize") Integer pagesize,
            @QueryParam("order") String[] orderFields) throws UserException {
        return services.getItems(orderFields, page, pagesize);
    }

    /**
     * 
      Query parameters are added to the url after the ? mark, while a path parameter is part of the regular URL.
      In the URL below tom could be the value of a path parameter and there is one query parameter with the name id and value 1:
      http://mydomain.com/tom?id=1
          
     * @param user
     * @param pwd
     * @return
     * @throws CloneNotSupportedException
     * @throws UserException
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/login/{usr}/{pwd}")
    public InventoryUser login(@PathParam("usr") String user, @PathParam("pwd") String pwd)
            throws CloneNotSupportedException, UserException {
        log.info("Login  usr:" + user + " pwd:" + pwd);
        InventoryUser retVal = new InventoryUser(user, "user description");
        retVal.setSuccess(true);
        return retVal;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/inventoryitems")
    public List<Item> getInventoryItems(@QueryParam("code") String supplierCode)
            throws CloneNotSupportedException, UserException {
        log.info("Loading inventory items for code:" + supplierCode);
        List<Item> sup = services.findAllItems(supplierCode);
        return sup;
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/newItem.json")
    public ItemResponse insertInventoryItem(ItemModel input) {
        log.info("Item=" + (input != null ? input.getPictureNames() : "nullo"));

        try {
            services.addItem(input);
            return new ItemResponse(true, "tutto ok", 1, 1L);
        } catch (UserException e) {
            e.printStackTrace();
            return new ItemResponse(false, e.getMessage(), 0, 0L);
        }

        //       JsonFactory jFactory = new JsonFactory();
        //       try {
        //         JsonParser jParser = jFactory.createJsonParser(input);
        //         // loop until token equal to "}"
        //         while (jParser.nextToken() != JsonToken.END_OBJECT) {
        //            
        //            
        //         }
        //      } catch (JsonParseException e) {
        //         // TODO Auto-generated catch block
        //         e.printStackTrace();
        //      } catch (IOException e) {
        //         // TODO Auto-generated catch block
        //         e.printStackTrace();
        //      }
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/deleteItem.json")
    public ItemResponse deleteInventoryItem(ItemModel input) {
        try {
            boolean status = services.deleteItem(input);
            return new ItemResponse(status, "tutto ok", 1, 1L);
        } catch (UserException e) {
            e.printStackTrace();
            return new ItemResponse(false, e.getMessage(), 0, 0L);
        }
    }

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    //   public Response uploadFile(MultipartFormDataInput input) {
    //    @Consumes(MediaType.APPLICATION_OCTET_STREAM)
    //    public Response insertInventoryItem(InputStream is) {
    public Response put(Map<String, InputStream> data) {

        String fileName = "";

        log.info("output = eccomi");
        for (String key : data.keySet()) {
            fileName += "," + key;
            log.info(key + " = " + data.get(key));
            InputStream is = data.get(key);
            ByteArrayOutputStream baos = null;
            try {
                baos = new ByteArrayOutputStream();
                Utilities.rushStreams(is, baos);
                log.info("output = " + baos.size());
                services.addPicture(key, baos.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();
                return Response.status(HttpStatus.SC_METHOD_FAILURE).entity(e.getMessage() + " " + fileName)
                        .build();
            } catch (UserException e) {
                e.printStackTrace();
                return Response.status(HttpStatus.SC_METHOD_FAILURE).entity(e.getMessage() + " " + fileName)
                        .build();
            } finally {
                if (baos != null) {
                    try {
                        baos.close();
                    } catch (IOException eIgnored) {
                    }
                }
            }

        }

        return Response.status(HttpStatus.SC_OK).entity("uploadFile is called, Uploaded file name : " + fileName)
                .build();

        //      ByteArrayOutputStream baos = null;
        //      try {
        //         baos = new ByteArrayOutputStream();
        //         Utilities.rushStreams(is, baos);
        //         String xml = new String(baos.toByteArray());
        //         log.info("output = " + xml.length());
        //      } catch (IOException e) {
        //         e.printStackTrace();
        //      } finally {
        //         if (baos != null) {
        //            try {
        //               baos.close();
        //            } catch (IOException eIgnored) {
        //            }
        //         }
        //      }

        // 
        //      Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
        //      
        //      if (uploadForm != null) {
        //         for (String partName : uploadForm.keySet()) {
        //            log.info("Upload........................ part id="+partName);
        //         }
        //      }

        //      List<InputPart> inputParts = uploadForm.get("uploadedFile");
        // 
        //      for (InputPart inputPart : inputParts) {
        // 
        //       try {
        // 
        //         MultivaluedMap<String, String> header = inputPart.getHeaders();
        //         fileName = getFileName(header);
        // 
        //         //convert the uploaded file to inputstream
        //         InputStream inputStream = inputPart.getBody(InputStream.class,null);
        // 
        //         byte [] bytes = IOUtils.toByteArray(inputStream);
        // 
        //         //constructs upload file path
        //         fileName = UPLOADED_FILE_PATH + fileName;
        // 
        //         writeFile(bytes,fileName);
        // 
        //         System.out.println("Done");
        // 
        //        } catch (IOException e) {
        //         e.printStackTrace();
        //        }
        // 
        //      }

        //      return Response.status(200)
        //          .entity("uploadFile is called, Uploaded file name : " + fileName).build();

    }

    @GET
    //    @Produces(MediaType.APPLICATION_JSON)
    @Path("/deletePicture/{fileName}")
    public Response deletePicture(@PathParam("fileName") String fileName) throws UserException {
        log.info("deletePicture  fileName:" + fileName);
        try {
            if (services.deletePicture(fileName)) {
                return Response.status(HttpStatus.SC_OK)
                        .entity("deletePicture is called, deleted file name : " + fileName).build();
            }
            return Response.status(HttpStatus.SC_METHOD_FAILURE).entity("File not deleted! " + fileName).build();
        } catch (UserException e) {
            e.printStackTrace();
            return Response.status(HttpStatus.SC_METHOD_FAILURE).entity(e.getMessage() + " " + fileName).build();
        }
    }

    /**
     * Creates a JAX-RS "Bad Request" response including a map of all violation fields, and their message. This can then be used
     * by clients to show violations.
     * 
     * @param violations A set of violations that needs to be reported
     * @return JAX-RS response containing all violations
     */
    private Response.ResponseBuilder createViolationResponse(Set<ConstraintViolation<?>> violations) {
        log.fine("Validation completed. violations found: " + violations.size());

        Map<String, String> responseObj = new HashMap<String, String>();

        for (ConstraintViolation<?> violation : violations) {
            responseObj.put(violation.getPropertyPath().toString(), violation.getMessage());
        }

        return Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
    }

}