PageRenderTime 110ms CodeModel.GetById 1ms RepoModel.GetById 1ms app.codeStats 0ms

/org.itbelts.domain/src/main/java/org/itbelts/dao/mongolab/AbstractMongoLabDAO.java

https://bitbucket.org/itbelts/itbelts
Java | 204 lines | 103 code | 33 blank | 68 comment | 14 complexity | 0c2adea3d0826bf48e0b0eaa51cad2dd MD5 | raw file
  1. package org.itbelts.dao.mongolab;
  2. import java.io.BufferedReader;
  3. import java.io.DataOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.lang.reflect.Type;
  7. import java.net.HttpURLConnection;
  8. import java.net.ProtocolException;
  9. import java.net.URL;
  10. import java.net.URLEncoder;
  11. import java.util.logging.Logger;
  12. import org.itbelts.exception.ITBeltsInternalException;
  13. import com.google.gson.Gson;
  14. import com.google.gson.GsonBuilder;
  15. /**
  16. * Base class for anything that needs to access our MongoDB. <br>
  17. * <br>
  18. * <u><i>Version History</i></u>
  19. *
  20. * <pre>
  21. * v2013.10.0 19-okt.-2013 - DKBR813 - initial release
  22. *
  23. * </pre>
  24. *
  25. * @version v2013.10.0 19-okt.-2013
  26. * @author <a href="mailto:koenbruyndonckx@gmail.com"> Koen Bruyndonckx </a>
  27. */
  28. public abstract class AbstractMongoLabDAO {
  29. private static final Logger LOGGER = Logger.getLogger( AbstractMongoLabDAO.class.getName() );
  30. /**
  31. * constant that defines the base URL pointing towards the ITBelts Mongolab DB
  32. */
  33. private static String DB_URL;
  34. /**
  35. * constant that defines the MongoDB api key (for ITBelts) parameter for the rest API
  36. */
  37. private static final String API_KEY = "apiKey=aVabHKBbju53FvUBR-dRW7zsSBagCndc";
  38. // Check if we are running in a production environment
  39. static {
  40. if ( System.getProperty( "com.google.appengine.runtime.environment" ) != null &&
  41. System.getProperty( "com.google.appengine.runtime.environment" ).equals( "Production" ) ) {
  42. DB_URL = "https://api.mongolab.com/api/1/databases/itbelts/";
  43. } else {
  44. DB_URL = "https://api.mongolab.com/api/1/databases/itbelts-test/";
  45. }
  46. }
  47. /**
  48. * Compose an URL from the given path
  49. *
  50. * @param aPath
  51. * @return URL
  52. */
  53. protected URL buildUrl( String aPath ) {
  54. try {
  55. if ( aPath.indexOf( "?" ) > 0 ) {
  56. return new URL( DB_URL + aPath + "&" + API_KEY );
  57. }
  58. return new URL( DB_URL + aPath + "?" + API_KEY );
  59. } catch ( Exception e ) {
  60. throw new ITBeltsInternalException( "URL could not be composed for path " + aPath, e );
  61. }
  62. }
  63. /**
  64. * Compose an URL from the given path
  65. *
  66. * @param aPath
  67. * @param aParamList
  68. * @return URL
  69. */
  70. protected URL buildUrl( String aPath, String... aParamList ) {
  71. try {
  72. StringBuilder theUrl = new StringBuilder( DB_URL + aPath + "?" );
  73. for ( int i = 0 ; i < aParamList.length ; i++ ) {
  74. String theQuery = URLEncoder.encode( aParamList[i], "UTF-8" ).replace( "%3D", "=" );
  75. if ( i > 0 ) {
  76. theUrl.append( "&" );
  77. }
  78. theUrl.append( theQuery );
  79. }
  80. return new URL( theUrl + "&" + API_KEY );
  81. } catch ( Exception e ) {
  82. throw new ITBeltsInternalException( "URL could not be composed for path " + aPath, e );
  83. }
  84. }
  85. /**
  86. * Basic list retrieval using HTTP GET.
  87. *
  88. * @param url
  89. * The URL to connect to
  90. * @param aType
  91. * The Type of the List
  92. * @return <T> The list of the given type
  93. */
  94. protected <T> T readFrom( URL url, Type aType ) {
  95. try {
  96. LOGGER.info( "Reading from " + url );
  97. HttpURLConnection con = connectTo( url );
  98. BufferedReader reader = new BufferedReader( new InputStreamReader( con.getInputStream() ) );
  99. if ( con.getResponseCode() != HttpURLConnection.HTTP_OK ) {
  100. throw new ITBeltsInternalException( "Failed : HTTP error code : " + con.getResponseCode() );
  101. }
  102. T theList = new Gson().fromJson( reader, aType );
  103. con.disconnect();
  104. return theList;
  105. } catch ( Exception e ) {
  106. throw new ITBeltsInternalException( "Problem reading from URL " + url, e );
  107. }
  108. }
  109. /**
  110. * Connect to the given URL. using a proxy or not. Just uncomment what you need.
  111. * @param url
  112. * @return
  113. */
  114. private HttpURLConnection connectTo( URL url ) {
  115. try {
  116. return (HttpURLConnection) url.openConnection();
  117. // This is the code we need when running this from behind a proxy
  118. // Proxy proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress( "iproxy.axa.be", 8080 ) );
  119. // Authenticator authenticator = new Authenticator() {
  120. // public PasswordAuthentication getPasswordAuthentication() {
  121. // return ( new PasswordAuthentication( "myUser", "myPassword".toCharArray() ) );
  122. // }
  123. // };
  124. // Authenticator.setDefault( authenticator );
  125. // return (HttpURLConnection) url.openConnection( proxy );
  126. } catch ( IOException e ) {
  127. throw new ITBeltsInternalException( "Problem connecting to URL " + url, e );
  128. }
  129. }
  130. /**
  131. * POST an object to the given URL.
  132. *
  133. * @param url
  134. * @param o
  135. */
  136. protected void sendTo( URL url, Object o ) {
  137. try {
  138. LOGGER.info( "Posting to " + url + " --> object " + o );
  139. HttpURLConnection con = (HttpURLConnection) url.openConnection();
  140. // add request header
  141. con.setRequestMethod( "POST" );
  142. con.setRequestProperty( "Content-Type", "application/json;charset=utf-8" );
  143. con.setDoOutput( true );
  144. DataOutputStream wr = new DataOutputStream( con.getOutputStream() );
  145. String json = new GsonBuilder().disableHtmlEscaping().create().toJson( o );
  146. LOGGER.info( json );
  147. wr.writeBytes( json );
  148. wr.flush();
  149. wr.close();
  150. if ( con.getResponseCode() != HttpURLConnection.HTTP_CREATED && con.getResponseCode() != HttpURLConnection.HTTP_OK ) {
  151. throw new ITBeltsInternalException( "Failed : HTTP error code : " + con.getResponseCode() );
  152. }
  153. BufferedReader br = new BufferedReader( new InputStreamReader( ( con.getInputStream() ) ) );
  154. String output;
  155. LOGGER.info( "Output from Server ...." );
  156. while ( ( output = br.readLine() ) != null ) {
  157. LOGGER.info( output );
  158. }
  159. con.disconnect();
  160. } catch ( ProtocolException e ) {
  161. throw new ITBeltsInternalException( "Problem with URL when writing to MongoDB at " + url, e );
  162. } catch ( IOException e ) {
  163. throw new ITBeltsInternalException( "Problem writing to MongoDB at " + url, e );
  164. }
  165. }
  166. // public static void main( String[] args ) throws Exception {
  167. // Date d = new GregorianCalendar().getTime();
  168. //
  169. // System.out.println( String.format( "%1$tY-%1$tm-%1$td %1$tT", d ) );
  170. // }
  171. }