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