Ex. 5: HOLLEDController.java

1   
2   package org.sunspotworld.demo;
3   
4   import com.sun.spot.resources.Resources;
5   import com.sun.spot.resources.transducers.ITriColorLEDArray;
6   import com.sun.squawk.util.StringTokenizer;
7   import java.io.IOException;
8   import com.sun.spot.wot.WebApplication;
9   import com.sun.spot.wot.http.HttpResponse;
10  import com.sun.spot.wot.http.HttpRequest;
11  import com.sun.spot.wot.utils.Base64;
12  
13  /**
14   *
15   * @author vgupta
16   */
17  public class HOLLEDController extends WebApplication {
18      private ITriColorLEDArray myLEDs = (ITriColorLEDArray)
19              Resources.lookup(ITriColorLEDArray.class);
20  
21      public void init() {
22          if (myLEDs == null) {
23              myLEDs = (ITriColorLEDArray) Resources.lookup(ITriColorLEDArray.class);
24          }
25          for (int i = 0; i < myLEDs.size(); i++) {
26              myLEDs.getLED(i).setRGB(0,0,0);
27              myLEDs.getLED(i).setOff();                // turn off all LEDs
28          }
29      }
30  
31      public HOLLEDController(String str) {
32          super(str);
33      }
34  
35      public HttpResponse processRequest(HttpRequest request) throws IOException {
36          String respStr = "[]";
37          HttpResponse response = new HttpResponse();
38  
39          // We assume all LEDs are the same color, we look at LED 4 ...
40          if (request.getMethod().equalsIgnoreCase("GET")) {
41              /*
42               * Send a JSON string with timestamp and r, g, b values in
43               * response to a GET.
44               */
45              respStr = "[" + myLEDs.getLED(4).getRed() + "," +
46                          myLEDs.getLED(4).getGreen() + "," +
47                          myLEDs.getLED(4).getBlue() + "]\n";
48  
49              response.setStatus(HttpResponse.SC_OK);
50              response.setHeader("Content-Type", "text/plain");
51              // Note: Allow this to be cached for 20 sec to reduce gateway load
52              response.setHeader("Cache-Control", "max-age=20");
53              response.setBody(respStr.getBytes());
54              return response;
55          } else if (request.getMethod().equalsIgnoreCase("PUT")) {
56              int rgb[] = new int[3]; // integers are automatically initialized to 0
57              String val = "";
58  
59              try {
60                  // We expect the POSTed data to be in the format [r,g,b]
61                  // We first remove the square brackets and then split the rgb
62                  // string using coma as separator. We check for three integers,
63                  // each in the range 0-255. Otherwise, we complain.
64                  String rgbStr = new String(request.getBody());
65                  System.out.println("Received rgb string: " + rgbStr);
66                  // The next two lines remove the leading [ and trailing ] if present
67                  if (rgbStr.startsWith("[")) rgbStr = rgbStr.substring(1);
68                  if (rgbStr.endsWith("]")) rgbStr = rgbStr.substring(0, rgbStr.length() - 1);
69                  System.out.println("New rgb string: " + rgbStr);
70                  StringTokenizer st = new StringTokenizer(rgbStr, ",");
71                  if (st.countTokens() != 3) {
72                      throw new IOException("Incorrect number of integers.");
73                  }
74  
75                  for (int i = 0; i < 3; i++) {
76                      val = st.nextToken();
77                      rgb[i] = Integer.parseInt(val);
78                      if (rgb[i] < 0 || rgb[i] > 255) {
79                          throw new IOException("Incorrect integer range.");
80                      }
81                  }
82              } catch (Exception e) {
83                  response.setStatus(HttpResponse.SC_BAD_REQUEST);
84                  response.setBody(("Error: Need input in " +
85                          "form [r,g,b] each 0-255").getBytes());
86                  return response;
87              }
88  
89              // We use validated r,g,b values to set the color of all the LEDs
90              for (int i = 0; i < myLEDs.size(); i++) {
91                  myLEDs.getLED(i).setRGB(rgb[0], rgb[1], rgb[2]);
92                  myLEDs.getLED(i).setOn();
93              }
94             
95              response.setStatus(HttpResponse.SC_OK);
96              return response;
97          }
98  
99          // We return an error for HTTP methods other than GET, PUT
100         response.setStatus(HttpResponse.SC_METHOD_NOT_ALLOWED);
101         response.setHeader("Allow", "GET,PUT");
102 
103         return response;
104     }
105 
106     /*
107      * We only support HTTP Basic authentication which
108      * sends a Base-64 encoding of "username:password" in the
109      * "Authorization" header.
110      *
111      * General form:
112      * Authorization: <authType> <authToken>
113      *
114      * Example:
115      * Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
116      * ...
117      */
118     public boolean isAuthorized(HttpRequest req) {
119         /* XXX Uncomment the following lines to authenticate PUTs.
120          * Replace "Ali Baba" with the authorized username and
121          * "open sesame" with the authorized password.
122          */
123 //        String authorizedUser = "Ali Baba";
124 //        String authorizedPassword = "open sesame";
125 //
126 //        if (req.getMethod().equalsIgnoreCase("PUT")) {
127 //            String auth = req.getHeader("Authorization");
128 //
129 //            return ((auth != null) &&
130 //                    auth.equalsIgnoreCase("Basic " +
131 //                    Base64.encode(authorizedUser + ":" + authorizedPassword)));
132 //        }
133 
134         return true; // GETs should still succeed
135     }
136 }
137 
138