/org.itbelts.domain/src/main/java/org/itbelts/dao/mongolab/AbstractMongoLabDAO.java
Java | 204 lines | 103 code | 33 blank | 68 comment | 14 complexity | 0c2adea3d0826bf48e0b0eaa51cad2dd MD5 | raw file
- package org.itbelts.dao.mongolab;
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.lang.reflect.Type;
- import java.net.HttpURLConnection;
- import java.net.ProtocolException;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.logging.Logger;
- import org.itbelts.exception.ITBeltsInternalException;
- import com.google.gson.Gson;
- import com.google.gson.GsonBuilder;
- /**
- * Base class for anything that needs to access our MongoDB. <br>
- * <br>
- * <u><i>Version History</i></u>
- *
- * <pre>
- * v2013.10.0 19-okt.-2013 - DKBR813 - initial release
- *
- * </pre>
- *
- * @version v2013.10.0 19-okt.-2013
- * @author <a href="mailto:koenbruyndonckx@gmail.com"> Koen Bruyndonckx </a>
- */
- public abstract class AbstractMongoLabDAO {
- private static final Logger LOGGER = Logger.getLogger( AbstractMongoLabDAO.class.getName() );
- /**
- * constant that defines the base URL pointing towards the ITBelts Mongolab DB
- */
- private static String DB_URL;
- /**
- * constant that defines the MongoDB api key (for ITBelts) parameter for the rest API
- */
- private static final String API_KEY = "apiKey=aVabHKBbju53FvUBR-dRW7zsSBagCndc";
- // Check if we are running in a production environment
- static {
- if ( System.getProperty( "com.google.appengine.runtime.environment" ) != null &&
- System.getProperty( "com.google.appengine.runtime.environment" ).equals( "Production" ) ) {
- DB_URL = "https://api.mongolab.com/api/1/databases/itbelts/";
- } else {
- DB_URL = "https://api.mongolab.com/api/1/databases/itbelts-test/";
- }
- }
-
- /**
- * Compose an URL from the given path
- *
- * @param aPath
- * @return URL
- */
- protected URL buildUrl( String aPath ) {
- try {
- if ( aPath.indexOf( "?" ) > 0 ) {
- return new URL( DB_URL + aPath + "&" + API_KEY );
- }
- return new URL( DB_URL + aPath + "?" + API_KEY );
- } catch ( Exception e ) {
- throw new ITBeltsInternalException( "URL could not be composed for path " + aPath, e );
- }
- }
- /**
- * Compose an URL from the given path
- *
- * @param aPath
- * @param aParamList
- * @return URL
- */
- protected URL buildUrl( String aPath, String... aParamList ) {
- try {
- StringBuilder theUrl = new StringBuilder( DB_URL + aPath + "?" );
- for ( int i = 0 ; i < aParamList.length ; i++ ) {
- String theQuery = URLEncoder.encode( aParamList[i], "UTF-8" ).replace( "%3D", "=" );
- if ( i > 0 ) {
- theUrl.append( "&" );
- }
- theUrl.append( theQuery );
- }
- return new URL( theUrl + "&" + API_KEY );
- } catch ( Exception e ) {
- throw new ITBeltsInternalException( "URL could not be composed for path " + aPath, e );
- }
- }
- /**
- * Basic list retrieval using HTTP GET.
- *
- * @param url
- * The URL to connect to
- * @param aType
- * The Type of the List
- * @return <T> The list of the given type
- */
- protected <T> T readFrom( URL url, Type aType ) {
- try {
- LOGGER.info( "Reading from " + url );
- HttpURLConnection con = connectTo( url );
-
- BufferedReader reader = new BufferedReader( new InputStreamReader( con.getInputStream() ) );
- if ( con.getResponseCode() != HttpURLConnection.HTTP_OK ) {
- throw new ITBeltsInternalException( "Failed : HTTP error code : " + con.getResponseCode() );
- }
- T theList = new Gson().fromJson( reader, aType );
- con.disconnect();
- return theList;
- } catch ( Exception e ) {
- throw new ITBeltsInternalException( "Problem reading from URL " + url, e );
- }
- }
- /**
- * Connect to the given URL. using a proxy or not. Just uncomment what you need.
- * @param url
- * @return
- */
- private HttpURLConnection connectTo( URL url ) {
-
- try {
- return (HttpURLConnection) url.openConnection();
-
- // This is the code we need when running this from behind a proxy
- // Proxy proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress( "iproxy.axa.be", 8080 ) );
- // Authenticator authenticator = new Authenticator() {
- // public PasswordAuthentication getPasswordAuthentication() {
- // return ( new PasswordAuthentication( "myUser", "myPassword".toCharArray() ) );
- // }
- // };
- // Authenticator.setDefault( authenticator );
- // return (HttpURLConnection) url.openConnection( proxy );
- } catch ( IOException e ) {
- throw new ITBeltsInternalException( "Problem connecting to URL " + url, e );
- }
- }
- /**
- * POST an object to the given URL.
- *
- * @param url
- * @param o
- */
- protected void sendTo( URL url, Object o ) {
- try {
- LOGGER.info( "Posting to " + url + " --> object " + o );
- HttpURLConnection con = (HttpURLConnection) url.openConnection();
- // add request header
- con.setRequestMethod( "POST" );
- con.setRequestProperty( "Content-Type", "application/json;charset=utf-8" );
- con.setDoOutput( true );
- DataOutputStream wr = new DataOutputStream( con.getOutputStream() );
- String json = new GsonBuilder().disableHtmlEscaping().create().toJson( o );
- LOGGER.info( json );
- wr.writeBytes( json );
- wr.flush();
- wr.close();
- if ( con.getResponseCode() != HttpURLConnection.HTTP_CREATED && con.getResponseCode() != HttpURLConnection.HTTP_OK ) {
- throw new ITBeltsInternalException( "Failed : HTTP error code : " + con.getResponseCode() );
- }
- BufferedReader br = new BufferedReader( new InputStreamReader( ( con.getInputStream() ) ) );
- String output;
- LOGGER.info( "Output from Server ...." );
- while ( ( output = br.readLine() ) != null ) {
- LOGGER.info( output );
- }
- con.disconnect();
- } catch ( ProtocolException e ) {
- throw new ITBeltsInternalException( "Problem with URL when writing to MongoDB at " + url, e );
- } catch ( IOException e ) {
- throw new ITBeltsInternalException( "Problem writing to MongoDB at " + url, e );
- }
- }
- // public static void main( String[] args ) throws Exception {
- // Date d = new GregorianCalendar().getTime();
- //
- // System.out.println( String.format( "%1$tY-%1$tm-%1$td %1$tT", d ) );
- // }
- }