// Path: dashboard/src/ch/icclab/cyclops/dashboard/builder/KeystoneRequestBuilder.java
// public class KeystoneRequestBuilder {
// 
//     /**
//      * This method builds the correct JSON object for a keystone authentication request
//      *
//      * @param username  The keystone username
//      * @param pwd  The keystone password
//      * @param domainName  The keystone domain
//      * @return  A JSON representation
//      */
//     public static JsonRepresentation buildKeystoneAuthRequestBody(String username, String pwd, String domainName) throws JSONException {
//         JSONObject wrapper = new JSONObject();
//         JSONObject domain = new JSONObject();
//         domain.put("name", domainName);
//         JSONArray methods = new JSONArray();
//         methods.put("password");
//         JSONObject user = new JSONObject();
//         user.put("domain", domain);
//         user.put("name", username);
//         user.put("password", pwd);
//         JSONObject password = new JSONObject();
//         password.put("user", user);
//         JSONObject identity = new JSONObject();
//         identity.put("methods", methods);
//         identity.put("password", password);
//         JSONObject auth = new JSONObject();
//         auth.put("identity", identity);
//         wrapper.put("auth", auth);
// 
//         return new JsonRepresentation(wrapper);
//     }
// }
// 
// Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
//     private static final String EXCHANGE_NAME = "cyclops";
// 
//     public static void reportException(Exception ex) {
//         if(isExceptionReportingEnabled()) {
//             try {
//                 Connection conn = getConnection();
//                 Channel channel = conn.createChannel();
//                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                 ex.printStackTrace(new PrintStream(baos));
//                 channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
//                 channel.close();
// 
//             } catch (IOException e) {
//                 System.err.println("Failed to open connection for error reporting: " + e.getMessage());
//             }
//         }
//     }
// 
//     public static boolean isExceptionReportingEnabled() {
//         String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
//         return enabled.equals("true");
//     }
// 
//     private static Connection getConnection() throws IOException {
//         ConnectionFactory factory = new ConnectionFactory();
//         factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
//         factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
//         factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
//         factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
//         factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
//         return factory.newConnection();
//     }
// }
// 
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
// 
//     //Instantiating the Instance variable for saving the config details
//     public static HashMap<String,String> configuration;
// 
//     /**
//      * Loads the configuration file
//      *
//      * Pseudo Code
//      * 1. Create an instance of the ServletContext
//      * 2. Get the relative path of the configuration.txt file
//      * 3. Load the file and save the values into a static HashMap
//      *
//      * @param context
//      * @throws IOException
//      */
//     public void run(Context context) throws IOException {
//         configuration = new HashMap<String,String>();
//         String nextLine;
// 
//         // Extract the ServletContext from the attributes of RestletContext
//         ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
//         System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
//         // Get the path of the config file relative to the WAR
//         String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
// 
//         //Add WEB-INF path to access local images etc.
//         String webInfPath = servlet.getRealPath("/WEB-INF");
//         configuration.put("WEB-INF", webInfPath);
// 
//         Path path = Paths.get(rootPath);
//         File configFile = new File(path.toString());
//         FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
// 
//         // Read the values from the config file
//         try {
//             BufferedReader reader = new BufferedReader(file.getReader());
//             while((nextLine = reader.readLine()) != null ) {
//                 String[] str = nextLine.split("==");
//                 configuration.put(str[0],str[1]);
//             }
//         } catch (IOException e) {
//             System.out.println("Failed to load the Config file");
//             e.printStackTrace();
//         }
//     }
// }


import ch.icclab.cyclops.dashboard.builder.KeystoneRequestBuilder;
import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Header;
import org.restlet.data.MediaType;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.*;
import org.restlet.util.Series;
import java.io.IOException;
                headers = new Series<Header>(Header.class);
                res.getRequestAttributes().put("org.restlet.http.headers", headers);
            }

            headers.set("iPlanetDirectoryPro", sessionId);

            JSONObject data = new JSONObject();
            data.put("keystoneid", keystoneId);
            return res.put(new JsonRepresentation(data), MediaType.APPLICATION_JSON);
        }
        catch (Exception e) {
            ErrorReporter.reportException(e);
            throw new ResourceException(500);
        }
    }

    private Representation findUserId(Representation rep) throws JSONException, IOException {
        JSONObject response = new JSONObject();
        JsonRepresentation jsonRep = new JsonRepresentation(rep);
        JSONObject wrapper = jsonRep.getJsonObject();
        String id = wrapper
                .getJSONObject("token")
                .getJSONObject("user")
                .getString("id");

        response.put("keystoneId", id);
        return new JsonRepresentation(response);
    }

    private Representation sendRequest(String username, String pwd) throws JSONException, IOException {
// Path: dashboard/src/ch/icclab/cyclops/dashboard/builder/KeystoneRequestBuilder.java
// public class KeystoneRequestBuilder {
// 
//     /**
//      * This method builds the correct JSON object for a keystone authentication request
//      *
//      * @param username  The keystone username
//      * @param pwd  The keystone password
//      * @param domainName  The keystone domain
//      * @return  A JSON representation
//      */
//     public static JsonRepresentation buildKeystoneAuthRequestBody(String username, String pwd, String domainName) throws JSONException {
//         JSONObject wrapper = new JSONObject();
//         JSONObject domain = new JSONObject();
//         domain.put("name", domainName);
//         JSONArray methods = new JSONArray();
//         methods.put("password");
//         JSONObject user = new JSONObject();
//         user.put("domain", domain);
//         user.put("name", username);
//         user.put("password", pwd);
//         JSONObject password = new JSONObject();
//         password.put("user", user);
//         JSONObject identity = new JSONObject();
//         identity.put("methods", methods);
//         identity.put("password", password);
//         JSONObject auth = new JSONObject();
//         auth.put("identity", identity);
//         wrapper.put("auth", auth);
// 
//         return new JsonRepresentation(wrapper);
//     }
// }
// 
// Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
//     private static final String EXCHANGE_NAME = "cyclops";
// 
//     public static void reportException(Exception ex) {
//         if(isExceptionReportingEnabled()) {
//             try {
//                 Connection conn = getConnection();
//                 Channel channel = conn.createChannel();
//                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                 ex.printStackTrace(new PrintStream(baos));
//                 channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
//                 channel.close();
// 
//             } catch (IOException e) {
//                 System.err.println("Failed to open connection for error reporting: " + e.getMessage());
//             }
//         }
//     }
// 
//     public static boolean isExceptionReportingEnabled() {
//         String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
//         return enabled.equals("true");
//     }
// 
//     private static Connection getConnection() throws IOException {
//         ConnectionFactory factory = new ConnectionFactory();
//         factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
//         factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
//         factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
//         factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
//         factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
//         return factory.newConnection();
//     }
// }
// 
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
// 
//     //Instantiating the Instance variable for saving the config details
//     public static HashMap<String,String> configuration;
// 
//     /**
//      * Loads the configuration file
//      *
//      * Pseudo Code
//      * 1. Create an instance of the ServletContext
//      * 2. Get the relative path of the configuration.txt file
//      * 3. Load the file and save the values into a static HashMap
//      *
//      * @param context
//      * @throws IOException
//      */
//     public void run(Context context) throws IOException {
//         configuration = new HashMap<String,String>();
//         String nextLine;
// 
//         // Extract the ServletContext from the attributes of RestletContext
//         ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
//         System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
//         // Get the path of the config file relative to the WAR
//         String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
// 
//         //Add WEB-INF path to access local images etc.
//         String webInfPath = servlet.getRealPath("/WEB-INF");
//         configuration.put("WEB-INF", webInfPath);
// 
//         Path path = Paths.get(rootPath);
//         File configFile = new File(path.toString());
//         FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
// 
//         // Read the values from the config file
//         try {
//             BufferedReader reader = new BufferedReader(file.getReader());
//             while((nextLine = reader.readLine()) != null ) {
//                 String[] str = nextLine.split("==");
//                 configuration.put(str[0],str[1]);
//             }
//         } catch (IOException e) {
//             System.out.println("Failed to load the Config file");
//             e.printStackTrace();
//         }
//     }
// }


// Path: dashboard/src/ch/icclab/cyclops/dashboard/keystone/KeystoneAssociation.java
import ch.icclab.cyclops.dashboard.builder.KeystoneRequestBuilder;
import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Header;
import org.restlet.data.MediaType;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.*;
import org.restlet.util.Series;
import java.io.IOException;

                headers = new Series<Header>(Header.class);
                res.getRequestAttributes().put("org.restlet.http.headers", headers);
            }

            headers.set("iPlanetDirectoryPro", sessionId);

            JSONObject data = new JSONObject();
            data.put("keystoneid", keystoneId);
            return res.put(new JsonRepresentation(data), MediaType.APPLICATION_JSON);
        }
        catch (Exception e) {
            ErrorReporter.reportException(e);
            throw new ResourceException(500);
        }
    }

    private Representation findUserId(Representation rep) throws JSONException, IOException {
        JSONObject response = new JSONObject();
        JsonRepresentation jsonRep = new JsonRepresentation(rep);
        JSONObject wrapper = jsonRep.getJsonObject();
        String id = wrapper
                .getJSONObject("token")
                .getJSONObject("user")
                .getString("id");

        response.put("keystoneId", id);
        return new JsonRepresentation(response);
    }

    private Representation sendRequest(String username, String pwd) throws JSONException, IOException {
        JsonRepresentation body = KeystoneRequestBuilder.buildKeystoneAuthRequestBody(username, pwd, "default");