1 package com.atlassian.plugins.rest.sample.entities;
2
3 import com.atlassian.sal.api.ApplicationProperties;
4 import com.atlassian.sal.api.net.*;
5
6 import javax.servlet.ServletException;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10 import javax.ws.rs.core.HttpHeaders;
11 import java.io.IOException;
12 import java.io.PrintWriter;
13
14 public class EntityClientServlet extends HttpServlet
15 {
16 private final RequestFactory restRequestFactory;
17 private final ApplicationProperties applicationProperties;
18
19 public static final String P_ORANGE = "orange";
20 public static final String P_CONTENT_TYPE = "contentType";
21 public static final String P_ACCEPT = "accept";
22
23 public EntityClientServlet(RequestFactory restRequestFactory, ApplicationProperties applicationProperties)
24 {
25 this.restRequestFactory = restRequestFactory;
26 this.applicationProperties = applicationProperties;
27 }
28
29 @Override
30 protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException
31 {
32 resp.setContentType("text/plain");
33 final PrintWriter out = resp.getWriter();
34 try
35 {
36
37 String name = req.getParameter(P_ORANGE);
38 if (name == null)
39 {
40 out.write("name is a required parameter");
41 return;
42 }
43
44 Request restRequest = restRequestFactory.createRequest(Request.MethodType.POST, applicationProperties.getBaseUrl() + "/rest/entity/1/fruit");
45
46
47 String contentType = req.getParameter(P_CONTENT_TYPE);
48 if (contentType != null)
49 {
50 restRequest.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
51 }
52 String[] accepts = req.getParameterValues(P_ACCEPT);
53 if (accepts != null)
54 {
55 for (String accept : accepts)
56 {
57 restRequest.addHeader(HttpHeaders.ACCEPT, accept);
58 }
59 }
60
61 restRequest.setEntity(new Orange(name));
62
63 restRequest.execute(new ResponseHandler<Response>()
64 {
65 public void handle(final Response restResponse) throws ResponseException
66 {
67 Apple apple = restResponse.getEntity(Apple.class);
68 out.write(apple.getName() + "\n");
69 out.write("Content-Type=" + apple.getReqContentType() + "\n");
70 out.write("Accept=" + apple.getReqAccept());
71 }
72 });
73 return;
74 }
75 catch (ResponseException e)
76 {
77 out.write(e.toString());
78 }
79 catch (RuntimeException e)
80 {
81 out.write(e.toString());
82 throw e;
83 }
84 finally
85 {
86 out.close();
87 }
88 }
89
90 }