Advertisement
Guest User

Untitled

a guest
Aug 18th, 2016
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.36 KB | None | 0 0
  1. package net.gommehd.gonet.sailor.handler;
  2.  
  3. import com.eclipsesource.json.Json;
  4. import com.eclipsesource.json.JsonObject;
  5. import net.gommehd.gonet.sailor.FailureDescription;
  6. import net.gommehd.gonet.sailor.FailureHandler;
  7.  
  8. import java.io.BufferedReader;
  9. import java.io.IOException;
  10. import java.io.InputStreamReader;
  11. import java.io.OutputStreamWriter;
  12. import java.net.HttpURLConnection;
  13. import java.net.URL;
  14. import java.util.Base64;
  15. import java.util.HashMap;
  16. import java.util.Map;
  17.  
  18. /**
  19.  * @author Fabian
  20.  * @version 1.0
  21.  */
  22. public class WebAPIHandler implements FailureHandler {
  23.     private static final String API_HOST = "api.xsrv.eu";
  24.     private static final String API_USER = "GoNetSailor";
  25.     private static final String API_PASS = "uIF52Wu2nTVLqOIbUBKg";
  26.  
  27.     private String sessionID;
  28.  
  29.     public WebAPIHandler() {
  30.         this.login();
  31.     }
  32.  
  33.     private void login() {
  34.         if ( sessionID == null || sessionID.isEmpty() ) {
  35.             // Generate Basic auth
  36.             byte[] encodedBytes = Base64.getEncoder().encode( ( API_USER + ":" + API_PASS ).getBytes() );
  37.             String authorization = "Basic " + new String( encodedBytes );
  38.  
  39.             // Request and parse
  40.             JsonObject result = request( "/v1/authorization/login", null, new HashMap<String, String>(){{
  41.                 put( "Authorization", authorization );
  42.             }} );
  43.  
  44.             // Read the session ID on success
  45.             if ( result.getBoolean( "success", false ) ) {
  46.                 this.sessionID = result.get( "result" ).asObject().getString( "sessionID", "" );
  47.             } else {
  48.                 System.out.println( "Sailor API did return error: " + result.get( "errors" ).asArray().get( 0 ).asObject().getString( "errorMessage", "none" ) );
  49.             }
  50.         } else {
  51.             this.logout();
  52.         }
  53.     }
  54.  
  55.     private void logout() {
  56.         request( "/v1/authorization/logout", null, null );
  57.         sessionID = null;
  58.     }
  59.  
  60.     private JsonObject request( String fileOnHost, String body, Map<String, String> header ) {
  61.         String response = "{}";
  62.  
  63.         try {
  64.             URL url = new URL( "http", API_HOST, 80, fileOnHost );
  65.  
  66.             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  67.             connection.setRequestMethod( "POST" );
  68.             connection.setDoInput( true );
  69.             connection.setDoOutput( true );
  70.             connection.setUseCaches( false );
  71.             connection.setRequestProperty( "Content-Type", "application/json" );
  72.  
  73.             // Overtake header
  74.             if ( header != null ) {
  75.                 for ( Map.Entry<String, String> stringStringEntry : header.entrySet() ) {
  76.                     connection.setRequestProperty( stringStringEntry.getKey(), stringStringEntry.getValue() );
  77.                 }
  78.             }
  79.  
  80.             // Append SessionID to Header
  81.             if ( this.sessionID != null && !this.sessionID.isEmpty() ) {
  82.                 connection.setRequestProperty( "X-ApiSessionID", this.sessionID );
  83.             }
  84.  
  85.             OutputStreamWriter writer = null;
  86.             if ( body != null && !body.isEmpty() ) {
  87.                 connection.setRequestProperty( "Content-Length", String.valueOf( body.length() ) );
  88.  
  89.                 writer = new OutputStreamWriter( connection.getOutputStream() );
  90.                 writer.write( body );
  91.                 writer.flush();
  92.             } else {
  93.                 connection.setRequestProperty( "Content-Length", "0" );
  94.             }
  95.  
  96.  
  97.             BufferedReader reader = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
  98.  
  99.             response = "";
  100.             for ( String line; ( line = reader.readLine() ) != null; ) {
  101.                 response += line + "\n";
  102.             }
  103.  
  104.             if ( writer != null ) {
  105.                 writer.close();
  106.             }
  107.  
  108.             reader.close();
  109.         } catch ( IOException e ) {
  110.             e.printStackTrace();
  111.         }
  112.  
  113.         return Json.parse( response ).asObject();
  114.     }
  115.  
  116.     @Override
  117.     public void handleFailure( FailureDescription description ) {
  118.         String jsonBody = writeJSON( description );
  119.  
  120.         JsonObject result = request( "/v1/sailor", jsonBody, null );
  121.         if ( !result.getBoolean( "success", false ) ) {
  122.             int errorCode = result.get( "errors" ).asArray().get( 0 ).asObject().getInt( "errorCode", 0 );
  123.  
  124.             if ( errorCode == 101 ) {
  125.                 this.login();
  126.                 handleFailure( description );
  127.                 return;
  128.             }
  129.  
  130.             System.out.println( "Sailor API did return error: " + result.get( "errors" ).asArray().get( 0 ).asObject().getString( "errorMessage", "none" ) );
  131.         }
  132.     }
  133.  
  134.     private String writeJSON( FailureDescription failureDescription ) {
  135.         JsonObject jsonObject = Json.object();
  136.         jsonObject.set( "errorIdentifier", failureDescription.getErrorIdentifier() );
  137.         jsonObject.set( "priority", failureDescription.getPriority().name() );
  138.  
  139.         JsonObject metaData = Json.object();
  140.         for ( String metaKey : failureDescription.getMetaKeys() ) {
  141.             metaData.set( metaKey, failureDescription.getMetaEntry( metaKey ) );
  142.         }
  143.  
  144.         jsonObject.set( "metadata", metaData );
  145.         jsonObject.set( "timestamp", System.currentTimeMillis() );
  146.  
  147.         return jsonObject.toString();
  148.     }
  149. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement