// 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.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.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.*;
import org.restlet.util.Series;
import java.io.IOException;
/*
 * Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
 *  All Rights Reserved.
 *
 *     Licensed under the Apache License, Version 2.0 (the "License"); you may
 *     not use this file except in compliance with the License. You may obtain
 *     a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *     WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *     License for the specific language governing permissions and limitations
 *     under the License.
 */

package ch.icclab.cyclops.dashboard.login;



/**
 * This class is responsible for requests that handle OpenAM Sessions
 */
public class Session extends ServerResource{

    /**
     * This method requests an OpenAM session ID to later make OpenAM API calls
     * <p>
     * The method receives the user credentials from the dashboard frontend. Username and password are then used
     * to build a new request with X-OpenAM-Username and X-OpenAM-Password headers.
     * That request is then sent the appropriate OpenAM endpoint configured in OPENAM_AUTH_URL.
     * Finally, the response will then be sent to the frontend without modification.
     *
     * @param   entity   The incoming request from the dashboard frontend containing username and password
     * @return  A representation of the untouched response
     */
    @Post("json")
    public Representation login(Representation entity) {
        try {
            JsonRepresentation represent = new JsonRepresentation(entity);
            JSONObject json = represent.getJsonObject();
            String user = json.getString("username");
            String pass = json.getString("password");
            return sendRequest(user, pass);
        }
        catch (Exception e) {
            ErrorReporter.reportException(e);
            throw new ResourceException(500);
        }
    }

    private Representation sendRequest(String username, String password) {
// 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/login/Session.java
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.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.*;
import org.restlet.util.Series;
import java.io.IOException;

/*
 * Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
 *  All Rights Reserved.
 *
 *     Licensed under the Apache License, Version 2.0 (the "License"); you may
 *     not use this file except in compliance with the License. You may obtain
 *     a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *     WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *     License for the specific language governing permissions and limitations
 *     under the License.
 */

package ch.icclab.cyclops.dashboard.login;



/**
 * This class is responsible for requests that handle OpenAM Sessions
 */
public class Session extends ServerResource{

    /**
     * This method requests an OpenAM session ID to later make OpenAM API calls
     * <p>
     * The method receives the user credentials from the dashboard frontend. Username and password are then used
     * to build a new request with X-OpenAM-Username and X-OpenAM-Password headers.
     * That request is then sent the appropriate OpenAM endpoint configured in OPENAM_AUTH_URL.
     * Finally, the response will then be sent to the frontend without modification.
     *
     * @param   entity   The incoming request from the dashboard frontend containing username and password
     * @return  A representation of the untouched response
     */
    @Post("json")
    public Representation login(Representation entity) {
        try {
            JsonRepresentation represent = new JsonRepresentation(entity);
            JSONObject json = represent.getJsonObject();
            String user = json.getString("username");
            String pass = json.getString("password");
            return sendRequest(user, pass);
        }
        catch (Exception e) {
            ErrorReporter.reportException(e);
            throw new ResourceException(500);
        }
    }

    private Representation sendRequest(String username, String password) {
        ClientResource res = new ClientResource(LoadConfiguration.configuration.get("OPENAM_AUTH_URL"));