1
\$\begingroup\$

I have this working code, but I wonder how I can make it better.

  @Path("/legalProcess")
  public class LegalProcessService {
private static org.apache.log4j.Logger logger = org.apache.log4j.Logger
        .getLogger(LegalProcessService.class.getName());

private static final com.squareup.okhttp.MediaType JSON = com.squareup.okhttp.MediaType
        .parse("application/json; charset=utf-8");

@PermitAll
@GET
@Path("/list")
@Produces(MediaType.APPLICATION_JSON)
public String legalProcGet(@Context final HttpServletRequest request, @Context final HttpServletResponse response) {

    OkHttpClient client = new OkHttpClient();

    String webServiceUrl = "https://wu:18001/infringements/wegalProcessList";
    String ipAddress = ServiceHelper.getIpAddress(request);
    String userId = ServiceHelper.getUserId(request);

    com.squareup.okhttp.Response restResponse;

    ObjectMapper requestMapper = new ObjectMapper();
    ObjectNode objectNodeRequest = requestMapper.createObjectNode();
    objectNodeRequest.put("pdaipaddress", ipAddress);
    objectNodeRequest.put("pdauserid", userId);
    objectNodeRequest.put("pdarfa", "TEST");
    objectNodeRequest.put("pdaenviron", "TRN");
    objectNodeRequest.put("pdamessagerefnum", "1");
    objectNodeRequest.put("pdacentralnamesrefnum", "779112806");
    objectNodeRequest.put("pdacount", "");

    RequestBody body = RequestBody.create(JSON, objectNodeRequest.toString());

    try {

        Request restRequest = new Request.Builder().header("Content-Type", "application/json").url(webServiceUrl)
                .post(body).build();

        restResponse = client.newCall(restRequest).execute();

        String jsonResponse = restResponse.body().string();

        ObjectMapper mapper = new ObjectMapper();

        List<Map<String, String>> fg = new ArrayList<Map<String, String>>();

        try {
            LegalProcessResponseParsed legalProcessResponseParsed = mapper.readValue(jsonResponse,
                    LegalProcessResponseParsed.class);

            mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
            jsonResponse = mapper.writeValueAsString(legalProcessResponseParsed);

            for (int i = 0; i < legalProcessResponseParsed.getPdaincidentcategory().size(); i++) {
                String incidentcategory = legalProcessResponseParsed.getPdaincidentcategory().get(i);
                String incidentstartdt = legalProcessResponseParsed.getPdaincidentstartdt().get(i);
                String noticetype = legalProcessResponseParsed.getPdanoticetype().get(i);
                String infringementnum = legalProcessResponseParsed.getPdainfringementnum().get(i);
                String pdalegalprocessrefnum = legalProcessResponseParsed.getPdalegalprocessrefnum().get(i);

                Map<String, String> map_incident = new HashMap<String, String>();
                map_incident.put("incidentcategory", incidentcategory);
                map_incident.put("incidentdate", incidentstartdt);
                map_incident.put("noticetype", noticetype);
                map_incident.put("infringementnum", infringementnum);
                map_incident.put("legalprocessrefnum", pdalegalprocessrefnum);

                fg.add(map_incident);
            }
            System.out.println("fg :" + fg);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ObjectMapper mapperObj = new ObjectMapper();

        try {
            String jsonStr = mapperObj.writeValueAsString(fg);
            System.out.println(jsonStr);

            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
        }

    } catch (IOException e) {
        logger.error("\n ** could not      ", e);
    }

    return "{\"k\":\"default\"}";
}

// detail
@PermitAll
@GET
@Path("/detail/{refnum}")
@Produces(MediaType.APPLICATION_JSON)
public String legalProcDetailGet(@Context final HttpServletRequest request,
        @Context final HttpServletResponse response, @PathParam("refnum") String refnum) {

    OkHttpClient client = new OkHttpClient();

    String webServiceUrl = "https://wu:18001/infringements/wegalProcessView";
    String ipAddress = ServiceHelper.getIpAddress(request);
    String userId = ServiceHelper.getUserId(request);

    com.squareup.okhttp.Response restResponse;

    ObjectMapper requestMapper = new ObjectMapper();
    ObjectNode objectNodeRequest = requestMapper.createObjectNode();
    objectNodeRequest.put("pdaipaddress", ipAddress);
    objectNodeRequest.put("pdauserid", userId);
    objectNodeRequest.put("pdarfa", "TEST");
    objectNodeRequest.put("pdaenviron", "TRN");
    objectNodeRequest.put("pdamessagerefnum", "1");
    objectNodeRequest.put("pdacentralnamesrefnum", "779112806");
    objectNodeRequest.put("pdacount", "");
    objectNodeRequest.put("pdalegalprocessrefnum", refnum);

    RequestBody body = RequestBody.create(JSON, objectNodeRequest.toString());

    try {

        Request restRequest = new Request.Builder().header("Content-Type", "application/json").url(webServiceUrl)
                .post(body).build();

        restResponse = client.newCall(restRequest).execute();

        String jsonResponse = restResponse.body().string();
        ObjectMapper mapper = new ObjectMapper();

        Map<String, Object> map_incident = new HashMap<String, Object>();

        try {
            LegalProcessDetailResponseParsed legalProcessDetailResponseParsed = mapper.readValue(jsonResponse,
                    LegalProcessDetailResponseParsed.class);

            System.out.println("student :" + legalProcessDetailResponseParsed);
            mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
            jsonResponse = mapper.writeValueAsString(legalProcessDetailResponseParsed);

            // map_incident.put("messagerefnum",
            // legalProcessDetailResponseParsed.getPdamessagerefnum());
            map_incident.put("legalprocessrefnum", legalProcessDetailResponseParsed.getPdalegalprocessrefnum());
            map_incident.put("eventtype", legalProcessDetailResponseParsed.getPdaeventtype());
            map_incident.put("eventtrefnum", legalProcessDetailResponseParsed.getPdaeventtrefnum());
            map_incident.put("noticestatus", legalProcessDetailResponseParsed.getPdanoticestatus());

            for (int i = 0; i < legalProcessDetailResponseParsed.getPdaoffencecode().size(); i++) {

                List<Map<String, String>> composedArraya = new ArrayList<Map<String, String>>();

                String pdaoffencecode = legalProcessDetailResponseParsed.getPdaoffencecode().get(i);
                String pdaipbcode = legalProcessDetailResponseParsed.getPdaipbcode().get(i);
                String pdaoffencetitledesc = legalProcessDetailResponseParsed.getPdaoffencetitledesc().get(i);
                String pdaoutcomecode = legalProcessDetailResponseParsed.getPdaoutcomecode().get(i);
                String pdaoutcomedate = legalProcessDetailResponseParsed.getPdaoutcomedate().get(i);

                Map<String, String> map_incidentcategory = new HashMap<String, String>();
                map_incidentcategory.put("offencecode", pdaoffencecode);
                map_incidentcategory.put("ipbcode", pdaipbcode);
                map_incidentcategory.put("offencetitledesc", pdaoffencetitledesc);
                map_incidentcategory.put("outcomecode", pdaoutcomecode);
                map_incidentcategory.put("outcomedate", pdaoutcomedate);
                composedArraya.add(map_incidentcategory);

                map_incident.put("offence", composedArraya);

            }

            System.out.println("fg :" + map_incident);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ObjectMapper mapperObj = new ObjectMapper();

        try {
            String jsonStr = mapperObj.writeValueAsString(map_incident);
            System.out.println(jsonStr);

            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
        }

        logger.debug("\n **received response mako: " + jsonResponse);

        return jsonResponse;

    } catch (IOException e) {
        logger.error("\n ** could not      ", e);
    }

    return "{\"k\":\"default\"}";
}
}
\$\endgroup\$
4
  • 2
    \$\begingroup\$ Don't manually create json with string concatenation. Use jackson or some other library. You also need to apply some architecture to your code and separate out the view representation from the business logic. At the moment everything is just in there in the request handling functions. Lean on the framework more. If you are returning strings, you are likely forsaking a lot of the error handling and consistency the framework would otherwise give you and instead you have potentially buggy boilerplate \$\endgroup\$ Oct 4 '17 at 3:47
  • 2
    \$\begingroup\$ this comment above is actually an answer... \$\endgroup\$ Oct 4 '17 at 6:27
  • \$\begingroup\$ yes thanks @PaulRooney json is no longer string concatenation. Now I need to separate view from business logic, and returns. Thanks! \$\endgroup\$ Oct 4 '17 at 6:28
  • \$\begingroup\$ I see a few System.out.println in your code despite the fact you're also using log4j. I would suggest replacing sysout with log4j. \$\endgroup\$
    – D.B.
    Oct 5 '17 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.