package votorola.a.web.wap; // Copyright 2011-2012, Michael Allan. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Votorola Software"), to deal in the Votorola Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicence, and/or sell copies of the Votorola Software, and to permit persons to whom the Votorola Software is furnished to do so, subject to the following conditions: The preceding copyright notice and this permission notice shall be included in all copies or substantial portions of the Votorola Software. THE VOTOROLA SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE VOTOROLA SOFTWARE OR THE USE OR OTHER DEALINGS IN THE VOTOROLA SOFTWARE. import com.google.gson.stream.*; import java.io.*; import java.lang.reflect.*; import java.util.*; import java.util.regex.*; import javax.servlet.http.*; import votorola.g.*; import votorola.g.lang.*; import votorola.g.web.*; /** A context for responding to one or more calls. */ public @ThreadRestricted("Call constructor") final class Responding implements Requesting, ResponseConfiguration { /** Constructs a Responding. * * @see #wap() * @see #request() * @see #response() */ Responding( WAP _wap, HttpServletRequest _request, HttpServletResponse _response ) throws HTTPRequestException { request = _request; response = _response; wap = _wap; wCallback = HTTPServletRequestX.getParameterNonEmpty( "wCallback", request ); wPretty = HTTPServletRequestX.getBooleanParameter( "wPretty", request ); final String form = HTTPServletRequestX.getParameterNonEmpty( "wForm", request ); if( form != null && !"JSON".equals( form )) { throw new HTTPRequestException( /*400*/HttpServletResponse.SC_BAD_REQUEST, "unrecognized wForm value: " + form ); } final String wCall = HTTPServletRequestX.getParameterNonEmpty( "wCall", request ); if( wCall == null ) calls = Collections.emptyList(); else { calls = new ArrayList( /*initial capacity*/wCall.length() / 4 + 1 ); final Matcher m = WAP.W_CALL_PATTERN.matcher( wCall ); synchronized( wap ) // per WAP.callConstructors { for( int n = 0; m.find(); ++n ) // each entry in wCall { final String callType = m.group( 2 ); final Constructor callConstructor = wap.callConstructors().get( callType ); if( callConstructor == null ) { throw new HTTPRequestException( /*400*/HttpServletResponse.SC_BAD_REQUEST, "wCall to unknown call type: " + callType ); } final String prefix = m.group( 1 ); try { calls.add( callConstructor.newInstance( prefix, /*req*/Responding.this, /*resConfig*/Responding.this )); } catch( final InvocationTargetException xIT ) { Throwable x = xIT.getCause(); if( x instanceof HTTPRequestException ) throw (HTTPRequestException)x; if( x == null ) x = xIT; // probably never occurs else // nor probably do these: { if( x instanceof Error ) throw (Error)x; if( !( x instanceof Exception )) throw new IllegalStateException( x ); } throw VotorolaRuntimeException.castOrWrapped( (Exception)x ); } catch( Exception x ) { throw new RuntimeException( x ); } // others not much expected } } } } // -------------------------------------------------------------------------------- /** The writer for the response. The bulk of the response is likely to be written * indirectly through the tributary buffer {@linkplain #outJSON() outJSON}. In any * case, be sure to flush outJSON before writing directly to outBuf. */ public @Warning("flush outJSON") Writer outBuf() { return outBuf; } private Writer outBuf; // final after init in respond() /** A JSON writer based on {@linkplain #outBuf() outBuf}. Be sure to bracket the * response of each particular call in its assigned prefix, as shown here:
      *
      *   res.outJSON().name( {@linkplain Call#prefix() prefix}() ).beginObject();
      *   // output your response here
      *   res.outJSON().endObject();
*/ public JsonWriter outJSON() { return outJSON; } private JsonWriter outJSON; // final after init in respond() /** The indentation unit for the JSON writer (e.g. 3 or 4 spaces), or an empty string * "" if no indentation is required. */ public String outJSONIndent() { return outJSONIndent; } private String outJSONIndent; // final after init in respond() /** Responds to all calls. */ void respond() throws IOException { final String characterEncoding = "UTF-8"; response.setCharacterEncoding( characterEncoding ); try ( final Writer outBuf = new BufferedWriter( new OutputStreamWriter( response.getOutputStream(), characterEncoding )); // note that response.isCommitted() when outBuf flushes final JsonWriter outJSON = new JsonWriter( outBuf ); // grep GSONCLOSE for reason ){ Responding.this.outBuf = outBuf; Responding.this.outJSON = outJSON; if( wCallback != null ) { outBuf.append( wCallback ); outBuf.append( '(' ); } final String contentType; if( wPretty ) { contentType = "text/plain"; outJSONIndent = PRETTY_INDENT; outJSON.setIndent( outJSONIndent ); // otherwise it would be packed } else { contentType = wCallback == null? "application/json": "application/javascript"; outJSONIndent = ""; } response.setContentType( contentType ); outJSON.beginObject(); for( final Call call: calls ) call.respond( Responding.this ); outJSON.endObject(); if( wCallback != null ) { outJSON.flush(); outBuf.append( ");" ); } } } /** The HTTP response to the client. */ public HttpServletResponse response() { return response; } private final HttpServletResponse response; // - R e q u e s t i n g -------------------------------------------------------------- public HttpServletRequest request() { return request; } private final HttpServletRequest request; public WAP wap() { return wap; } private final WAP wap; public boolean wPretty() { return wPretty; } private final boolean wPretty; // - R e s p o n s e - C o n f i g u r a t i o n -------------------------------------- public void headMustRevalidate() { assert !response.isCommitted(); if( headMustRevalidate_called ) return; headMustRevalidate_called = true; response.addHeader( "Cache-Control", "must-revalidate" ); } private boolean headMustRevalidate_called; public void headNoCache() { assert !response.isCommitted(); if( headNoCache_called ) return; // cf. org.apache.wicket.request.http.WebResponse.disableCaching // http://stackoverflow.com/questions/3976624/java-servlet-how-to-disable-caching-of-page headNoCache_called = true; response.addHeader( "Cache-Control", "no-cache" ); response.addHeader( "Cache-Control", "no-store" ); // response.addHeader( "Cache-Control", "private" ); // Chrome TEST per ResponseConfiguration response.addHeader( "Pragma", "no-cache" ); // response.setDateHeader( "Expires", 0L ); // Chrome TEST per ResponseConfiguration } private boolean headNoCache_called; //// P r i v a t e /////////////////////////////////////////////////////////////////////// private final List calls; /** The indentation string for all pretty responses. */ private static final String PRETTY_INDENT = " "; private final String wCallback; }