src/org/ohmage/service/VisualizationServices.java
public static byte[] sendVisualizationRequest(final String requestPath, 
			final String userToken, final String campaignId, final int width, 
			final int height, final Map<String, String> parameters) 
			throws ServiceException {
		
		// Build the request URL.
		StringBuilder urlBuilder = new StringBuilder();
		try {
			String serverUrl = PreferenceCache.instance().lookup(PreferenceCache.KEY_VISUALIZATION_SERVER);
			urlBuilder.append(serverUrl);
			
			if(! serverUrl.endsWith("/")) {
				urlBuilder.append("/");
			}
		}
		catch(CacheMissException e) {
			throw new ServiceException(
					"Cache doesn't know about 'known' key: " + 
						PreferenceCache.KEY_VISUALIZATION_SERVER,
					e);
		}
		urlBuilder.append(requestPath);
		
		// Generate the URL String.
		String urlString = urlBuilder.toString();
		
		// Build this server's URL.
		StringBuilder parameterBuilder = new StringBuilder();
		try {
			parameterBuilder
				.append(URLEncoder.encode(PARAMETER_KEY_TOKEN, ENCODING))
				.append("='")
				.append(URLEncoder.encode(userToken, ENCODING))
				.append("'");
	
			// Build this server's URL.
			parameterBuilder.append("&")
				.append(URLEncoder.encode(PARAMETER_KEY_SERVER, ENCODING))
				.append("='");
			
			// Get this machine's default URL.
			try {
				parameterBuilder
					.append(
						URLEncoder
							.encode(
								CookieUtils.buildServerRootUrl().toString(),
								ENCODING));
			}
			catch(DomainException e) {
				throw new ServiceException(
						"Error building the root URL.",
						e);
			}
			parameterBuilder
				.append(URLEncoder.encode(RequestBuilder.getInstance().getRoot(), ENCODING))
				.append("'");
			
			// Add the required parameters.
			parameterBuilder.append("&")
				.append(URLEncoder.encode(PARAMETER_KEY_CAMPAIGN_ID, ENCODING))
				.append("='")
				.append(URLEncoder.encode(campaignId, ENCODING))
				.append("'");
			
			parameterBuilder.append("&")
				.append(URLEncoder.encode(PARAMETER_KEY_WIDTH, ENCODING))
				.append("=")
				.append(width);
			
			parameterBuilder.append("&")
				.append(URLEncoder.encode(PARAMETER_KEY_HEIGHT, ENCODING))
				.append("=")
				.append(height);
			
			// Add all of the non-required, request-specific parameters.
			for(String key : parameters.keySet()) {
				parameterBuilder.append('&');
				
				if(PARAMETER_KEY_AGGREGATE.equals(key)) {
					parameterBuilder
						.append(URLEncoder.encode(key, ENCODING))
						.append('=')
						.append(parameters.get(key));
				}
				else {
					parameterBuilder
						.append(URLEncoder.encode(key, ENCODING))
						.append("='")
						.append(URLEncoder.encode(parameters.get(key), ENCODING))
						.append("'");
				}
			}
		}
		catch(UnsupportedEncodingException e) {
			throw new ServiceException(
					"UTF-8 encoding is unknown.",
					e);
		}
		
		try {
			// Connect to the visualization server.
			URL url = new URL(urlString);
			HttpURLConnection urlConnection = 
					(HttpURLConnection) url.openConnection();
			
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setInstanceFollowRedirects(true);
			urlConnection.setRequestMethod("POST");
			urlConnection.setRequestProperty(
					"Content-Length", 
					Integer.toString(parameterBuilder.length()));
			
			DataOutputStream output = 
					new DataOutputStream(urlConnection.getOutputStream());
			output.writeBytes(parameterBuilder.toString());
			output.flush();
			output.close();
			
			// If a non-200 response was returned, get the text from the 
			// response.
			if(urlConnection.getResponseCode() != 200) {
				// Get the error text.
				ByteArrayOutputStream errorByteStream = new ByteArrayOutputStream();
				InputStream errorStream = urlConnection.getErrorStream();
				byte[] chunk = new byte[4096];
				int amountRead;
				while((amountRead = errorStream.read(chunk)) != -1) {
					errorByteStream.write(chunk, 0, amountRead);
				}
				errorStream.close();
				
				// Echo the error.
				throw new ServiceException(
						ErrorCode.VISUALIZATION_GENERAL_ERROR,
						"There was an error. Please, try again later.",
						"The server returned the HTTP error code '" + 
							urlConnection.getResponseCode() + 
							"' with the error '" + 
							errorByteStream.toString() + 
							"': " + 
							urlString);
			}
			
			// Build the response.
			InputStream reader = urlConnection.getInputStream();
			
			// Generate the byte array.
			ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
			byte[] chunk = new byte[4096];
			int amountRead = 0;
			while((amountRead = reader.read(chunk)) != -1) {
				byteArrayStream.write(chunk, 0, amountRead);
			}
			reader.close();
			
			return byteArrayStream.toByteArray();
		}
		catch(MalformedURLException e) {
			throw new ServiceException(
					ErrorCode.VISUALIZATION_GENERAL_ERROR, 
					"Built a malformed URL: " + urlString, 
					e);
		}
		catch(IOException e) {
			throw new ServiceException(
					ErrorCode.VISUALIZATION_GENERAL_ERROR, 
					"Error while communicating with the visualization server.",
					e);
		}
	}
/**
	 * Sends a request to the visualization server and returns the image as a
	 * byte array that was returned by the visualization server.
	 * 
	 * @param requestPath The additional path beyond the base URI that is 
	 * 					  stored in the database. An example would be, if the
	 * 					  database stored the visualization server's address as
	 * 					  "https://viz.server.com/R/visualzations" then this
	 * 					  parameter could be "survey_response_count" which 
	 * 					  would result in a URL of
	 * 					  "https://viz.server/com/R/visualizations/survey_response_count?param1=...".
	 * 
	 * @param userToken The authentication token for the requesting user that
	 * 					will be passed on to the visualization server to 
	 * 					perform subsequent requests on our behalf.
	 * 
	 * @param campaignId The unique identifier for the campaign whose 
	 * 					 information will be used in conjunction with this
	 * 					 request and any subsequent parameters.
	 * 
	 * @param width The desired width of the resulting visualization.
	 * 
	 * @param height The desired height of the resulting visualization.
	 * 
	 * @param parameters Any additional parameters that should be passed to the
	 * 					 visualization server. Their key values will be used as
	 * 					 the key in the HTTP parameter and their actual value
	 * 					 will be their single-quoted HTTP parameter value.
	 * 
	 * @return Returns a byte[] representation of the visualization image.
	 * 
	 * @throws ServiceException Thrown if there is an error.
	 */
Sends a request to the visualization server and returns the image as a
byte array that was returned by the visualization server.

@param requestPath The additional path beyond the base URI that is
stored in the database.

@param userToken The authentication token for the requesting user that
will be passed on to the visualization server to
perform subsequent requests on our behalf.

@param campaignId The unique identifier for the campaign whose
information will be used in conjunction with this
request and any subsequent parameters.

@param width The desired width of the resulting visualization.

@param height The desired height of the resulting visualization.

@param parameters Any additional parameters that should be passed to the
visualization server. Their key values will be used as
the key in the HTTP parameter and their actual value
will be their single-quoted HTTP parameter value.

@return Returns a byte[] representation of the visualization image.

@throws ServiceException Thrown if there is an error.
Sends a request to the visualization server and returns the image as a byte array that was returned by the visualization server . @param requestPath The additional path beyond the base URI that is stored in the database . @param userToken The authentication token for the requesting user that will be passed on to the visualization server to perform subsequent requests on our behalf . @param campaignId The unique identifier for the campaign whose information will be used in conjunction with this request and any subsequent parameters . @param width The desired width of the resulting visualization . @param height The desired height of the resulting visualization . @param parameters Any additional parameters that should be passed to the visualization server . Their key values will be used as the key in the HTTP parameter and their actual value will be their single - quoted HTTP parameter value . @return Returns a byte [] representation of the visualization image . @throws ServiceException Thrown if there is an error .
public static byte[] sendVisualizationRequest(final String requestPath, 
			final String userToken, final String campaignId, final int width, 
			final int height, final Map<String, String> parameters) 
			throws ServiceException {
		StringBuilder urlBuilder = new StringBuilder();
		try {
			String serverUrl = PreferenceCache.instance().lookup(PreferenceCache.KEY_VISUALIZATION_SERVER);
			urlBuilder.append(serverUrl);
			if(! serverUrl.endsWith("/")) {
				urlBuilder.append("/");
			}
		}
		catch(CacheMissException e) {
			throw new ServiceException(
					"Cache doesn't know about 'known' key: " + 
						PreferenceCache.KEY_VISUALIZATION_SERVER,
					e);
		}
		urlBuilder.append(requestPath);
		String urlString = urlBuilder.toString();
		StringBuilder parameterBuilder = new StringBuilder();
		try {
			parameterBuilder
				.append(URLEncoder.encode(PARAMETER_KEY_TOKEN, ENCODING))
				.append("='")
				.append(URLEncoder.encode(userToken, ENCODING))
				.append("'");
			parameterBuilder.append("&")
				.append(URLEncoder.encode(PARAMETER_KEY_SERVER, ENCODING))
				.append("='");
			try {
				parameterBuilder
					.append(
						URLEncoder
							.encode(
								CookieUtils.buildServerRootUrl().toString(),
								ENCODING));
			}
			catch(DomainException e) {
				throw new ServiceException(
						"Error building the root URL.",
						e);
			}
			parameterBuilder
				.append(URLEncoder.encode(RequestBuilder.getInstance().getRoot(), ENCODING))
				.append("'");
			parameterBuilder.append("&")
				.append(URLEncoder.encode(PARAMETER_KEY_CAMPAIGN_ID, ENCODING))
				.append("='")
				.append(URLEncoder.encode(campaignId, ENCODING))
				.append("'");
			parameterBuilder.append("&")
				.append(URLEncoder.encode(PARAMETER_KEY_WIDTH, ENCODING))
				.append("=")
				.append(width);
			parameterBuilder.append("&")
				.append(URLEncoder.encode(PARAMETER_KEY_HEIGHT, ENCODING))
				.append("=")
				.append(height);
			for(String key : parameters.keySet()) {
				parameterBuilder.append('&');
				if(PARAMETER_KEY_AGGREGATE.equals(key)) {
					parameterBuilder
						.append(URLEncoder.encode(key, ENCODING))
						.append('=')
						.append(parameters.get(key));
				}
				else {
					parameterBuilder
						.append(URLEncoder.encode(key, ENCODING))
						.append("='")
						.append(URLEncoder.encode(parameters.get(key), ENCODING))
						.append("'");
				}
			}
		}
		catch(UnsupportedEncodingException e) {
			throw new ServiceException(
					"UTF-8 encoding is unknown.",
					e);
		}
		try {
			URL url = new URL(urlString);
			HttpURLConnection urlConnection = 
					(HttpURLConnection) url.openConnection();
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setInstanceFollowRedirects(true);
			urlConnection.setRequestMethod("POST");
			urlConnection.setRequestProperty(
					"Content-Length", 
					Integer.toString(parameterBuilder.length()));
			DataOutputStream output = 
					new DataOutputStream(urlConnection.getOutputStream());
			output.writeBytes(parameterBuilder.toString());
			output.flush();
			output.close();
			if(urlConnection.getResponseCode() != 200) {
				ByteArrayOutputStream errorByteStream = new ByteArrayOutputStream();
				InputStream errorStream = urlConnection.getErrorStream();
				byte[] chunk = new byte[4096];
				int amountRead;
				while((amountRead = errorStream.read(chunk)) != -1) {
					errorByteStream.write(chunk, 0, amountRead);
				}
				errorStream.close();
				throw new ServiceException(
						ErrorCode.VISUALIZATION_GENERAL_ERROR,
						"There was an error. Please, try again later.",
						"The server returned the HTTP error code '" + 
							urlConnection.getResponseCode() + 
							"' with the error '" + 
							errorByteStream.toString() + 
							"': " + 
							urlString);
			}
			InputStream reader = urlConnection.getInputStream();
			ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
			byte[] chunk = new byte[4096];
			int amountRead = 0;
			while((amountRead = reader.read(chunk)) != -1) {
				byteArrayStream.write(chunk, 0, amountRead);
			}
			reader.close();
			return byteArrayStream.toByteArray();
		}
		catch(MalformedURLException e) {
			throw new ServiceException(
					ErrorCode.VISUALIZATION_GENERAL_ERROR, 
					"Built a malformed URL: " + urlString, 
					e);
		}
		catch(IOException e) {
			throw new ServiceException(
					ErrorCode.VISUALIZATION_GENERAL_ERROR, 
					"Error while communicating with the visualization server.",
					e);
		}
	}
public static byte [ ] sendVisualizationRequest ( final String requestPath , final String userToken , final String campaignId , final int width , final int height , final Map < String , String > parameters ) throws ServiceException { StringBuilder urlBuilder = new StringBuilder ( ) ; try { String serverUrl = PreferenceCache . instance ( ) . lookup ( PreferenceCache . KEY_VISUALIZATION_SERVER ) ; urlBuilder . append ( serverUrl ) ; if ( ! serverUrl . endsWith ( "/" ) ) { urlBuilder . append ( "/" ) ; } } catch ( CacheMissException e ) { throw new ServiceException ( "Cache doesn't know about 'known' key: " + PreferenceCache . KEY_VISUALIZATION_SERVER , e ) ; } urlBuilder . append ( requestPath ) ; String urlString = urlBuilder . toString ( ) ; StringBuilder parameterBuilder = new StringBuilder ( ) ; try { parameterBuilder . append ( URLEncoder . encode ( PARAMETER_KEY_TOKEN , ENCODING ) ) . append ( "='" ) . append ( URLEncoder . encode ( userToken , ENCODING ) ) . append ( "'" ) ; parameterBuilder . append ( "&" ) . append ( URLEncoder . encode ( PARAMETER_KEY_SERVER , ENCODING ) ) . append ( "='" ) ; try { parameterBuilder . append ( URLEncoder . encode ( CookieUtils . buildServerRootUrl ( ) . toString ( ) , ENCODING ) ) ; } catch ( DomainException e ) { throw new ServiceException ( "Error building the root URL." , e ) ; } parameterBuilder . append ( URLEncoder . encode ( RequestBuilder . getInstance ( ) . getRoot ( ) , ENCODING ) ) . append ( "'" ) ; parameterBuilder . append ( "&" ) . append ( URLEncoder . encode ( PARAMETER_KEY_CAMPAIGN_ID , ENCODING ) ) . append ( "='" ) . append ( URLEncoder . encode ( campaignId , ENCODING ) ) . append ( "'" ) ; parameterBuilder . append ( "&" ) . append ( URLEncoder . encode ( PARAMETER_KEY_WIDTH , ENCODING ) ) . append ( "=" ) . append ( width ) ; parameterBuilder . append ( "&" ) . append ( URLEncoder . encode ( PARAMETER_KEY_HEIGHT , ENCODING ) ) . append ( "=" ) . append ( height ) ; for ( String key : parameters . keySet ( ) ) { parameterBuilder . append ( '&' ) ; if ( PARAMETER_KEY_AGGREGATE . equals ( key ) ) { parameterBuilder . append ( URLEncoder . encode ( key , ENCODING ) ) . append ( '=' ) . append ( parameters . get ( key ) ) ; } else { parameterBuilder . append ( URLEncoder . encode ( key , ENCODING ) ) . append ( "='" ) . append ( URLEncoder . encode ( parameters . get ( key ) , ENCODING ) ) . append ( "'" ) ; } } } catch ( UnsupportedEncodingException e ) { throw new ServiceException ( "UTF-8 encoding is unknown." , e ) ; } try { URL url = new URL ( urlString ) ; HttpURLConnection urlConnection = ( HttpURLConnection ) url . openConnection ( ) ; urlConnection . setDoOutput ( true ) ; urlConnection . setDoInput ( true ) ; urlConnection . setInstanceFollowRedirects ( true ) ; urlConnection . setRequestMethod ( "POST" ) ; urlConnection . setRequestProperty ( "Content-Length" , Integer . toString ( parameterBuilder . length ( ) ) ) ; DataOutputStream output = new DataOutputStream ( urlConnection . getOutputStream ( ) ) ; output . writeBytes ( parameterBuilder . toString ( ) ) ; output . flush ( ) ; output . close ( ) ; if ( urlConnection . getResponseCode ( ) != 200 ) { ByteArrayOutputStream errorByteStream = new ByteArrayOutputStream ( ) ; InputStream errorStream = urlConnection . getErrorStream ( ) ; byte [ ] chunk = new byte [ 4096 ] ; int amountRead ; while ( ( amountRead = errorStream . read ( chunk ) ) != - 1 ) { errorByteStream . write ( chunk , 0 , amountRead ) ; } errorStream . close ( ) ; throw new ServiceException ( ErrorCode . VISUALIZATION_GENERAL_ERROR , "There was an error. Please, try again later." , "The server returned the HTTP error code '" + urlConnection . getResponseCode ( ) + "' with the error '" + errorByteStream . toString ( ) + "': " + urlString ) ; } InputStream reader = urlConnection . getInputStream ( ) ; ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream ( ) ; byte [ ] chunk = new byte [ 4096 ] ; int amountRead = 0 ; while ( ( amountRead = reader . read ( chunk ) ) != - 1 ) { byteArrayStream . write ( chunk , 0 , amountRead ) ; } reader . close ( ) ; return byteArrayStream . toByteArray ( ) ; } catch ( MalformedURLException e ) { throw new ServiceException ( ErrorCode . VISUALIZATION_GENERAL_ERROR , "Built a malformed URL: " + urlString , e ) ; } catch ( IOException e ) { throw new ServiceException ( ErrorCode . VISUALIZATION_GENERAL_ERROR , "Error while communicating with the visualization server." , e ) ; } }
Sends a request to the visualization server and returns the image as a
 byte array that was returned by the visualization server.
Sends a request to the visualization server and returns the image as a byte array that was returned by the visualization server .
// Build the request URL. // Generate the URL String. // Build this server's URL. // Build this server's URL. // Get this machine's default URL. // Add the required parameters. // Add all of the non-required, request-specific parameters. // Connect to the visualization server. // If a non-200 response was returned, get the text from the  // response. // Get the error text. // Echo the error. // Build the response. // Generate the byte array.