<commit_before>/*********************************
 *  REST Easy Ember Application  *
 * Copyright 2014 - <NAME> *
 *********************************/

// Constants
var HTTP_METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'LINK', 'UNLINK', 'OPTIONS'],
    DM_NONE = tr('request.data.type.none'),
    DM_FORM = tr('request.data.type.form'),
    DM_CUSTOM = tr('request.data.type.custom'),
    DATA_MODES = [DM_NONE, DM_FORM, DM_CUSTOM],
    FT_URLENCODED = 'application/x-www-form-urlencoded',
    FT_MULTIPART = 'multipart/form-data',
    FORM_TYPES = [FT_URLENCODED, FT_MULTIPART],
    DATABASE_KEY = 'savedRequests';

// Create the application and set the window title
window.RESTEasy = Ember.Application.create();
window.document.title = tr('application.title');


// -----------------------
// Initialize the database
var localDB = window.indexedDB.open("REST-Easy", 2);

// TODO: remove the console.logs

localDB.onerror = function(event) {
    // Do something with localDB.errorCode!
    console.log("DB: error opening the database with code " + localDB.errorCode);
};


localDB.onupgradeneeded = function(event) {
    var idb = event.target.result;
    console.log("DB: updateding the version");

    // Create an objectStore for this database
    var objectStore = idb.createObjectStore(DATABASE_KEY, { keyPath: "saveName" });
    console.log(objectStore);
};

var updateCollections = function() {
    console.log('Updating collections');
    localDB.result.transaction(DATABASE_KEY).objectStore(DATABASE_KEY).mozGetAll().onsuccess = function (event) {
      var collections =  event.target.result;
      self.set('collections', event.target.result);
      console.log('Collections are now', collections);
    };
}



// Main controller for the REST Easy application
RESTEasy.ApplicationController = Ember.Controller.extend({
    methods: HTTP_METHODS,
    dataModes: DATA_MODES,
    formTypes: FORM_TYPES,

    // Translations for attributes
    trDataType: tr('request.data.custom.type'),
    trUsername: tr('request.auth.username'),
    trPassword: tr('<PASSWORD>'),

    // Initialize the application for the first time
    init: function() {

        // REST Easy reuses a single XMLHttpRequest instead of creating a new
        // one for each request - this reduces the number of state variables
        var self = this,
            request = new XMLHttpRequest();
        request.onreadystatechange = function() {
            self.send('readyStateChange', request);
        };
        this.set('request', request);

        // Reset all values to their defaults
        this.send('reset');


    },

    // Parse a string containing response headers, returning a list of objects
    // containing a name and value property
    parseHeaders: function(headers) {
        return headers.trim().split('\n').map(function(header) {
            var i = header.indexOf(':');
            return {
                name: header.substr(0, i),
                value: header.substr(i + 1)
            };
        });
    },

    actions: {

        saveRequest: function() {
            var db = localDB.result;
            var transaction = db.transaction([DATABASE_KEY], "readwrite");
            var objectStore = transaction.objectStore(DATABASE_KEY);

            // We use url as saveName for now
            var saveName = this.get('url'); //this.get('saveName')

            var saveItem = {
                saveName: saveName,
                method: this.get('method'),
                url: this.get('url'),
                requestHeaders: this.get('requestHeaders'),
                dataMode: this.get('dataMode'),
                formType: this.get('formType'),
                formData: this.get('formData'),
                dataType: this.get('dataType'),
                dataCustom: this.get('dataCustom'),
                username: this.get('username'),
                password: this.get('password')
            };
            console.log("About to save:", saveItem);

            var request = objectStore.add(saveItem);
        },

        loadRequest: function() {
            var saveName = record.url;


            localDB.result.transaction(DATABASE_KEY).objectStore(DATABASE_KEY).get(saveName).onsuccess = function (event) {
                var record = event.target.result;

                this.set('method', HTTP_METHODS[0]);    // TODO:
                this.set('url', record.url);
                this.set('requestHeaders', record.requestHeaders);
                this.set('dataMode', DATA_MODES[0]);    // TODO:
                this.set('formType', FORM_TYPES[0]);    // TODO:
                this.set('formData', record.formData);
                this.set('dataType', record.dataType);
                this.set('dataCustom', record.dataCustom);
                this.set('username', record.username);
                this.set('password', <PASSWORD>);
                this.set('saveName', record.saveName);
            };
        },

        // Collections
        setRequestFromCollection: function(item) {
            this.set('method', item.method);    // TODO:
            this.set('url', item.url);
            /*this.set('requestHeaders', record.requestHeaders);
            this.set('dataMode', DATA_MODES[0]);    // TODO:
            this.set('formType', FORM_TYPES[0]);    // TODO:
            this.set('formData', record.formData);
            this.set('dataType', record.dataType);
            this.set('dataCustom', record.dataCustom);
            this.set('username', record.username);
            this.set('password', <PASSWORD>);
            this.set('saveName', record.saveName);*/

            console.log(this);
        },

        // Clear all values and set them to their defaults
        reset: function() {
            this.set('method', HTTP_METHODS[0]);
            this.set('url', '');
            this.set('requestHeaders', []);
            this.set('dataMode', DATA_MODES[0]);
            this.set('formType', FORM_TYPES[0]);
            this.set('formData', []);
            this.set('dataType', '');
            this.set('dataCustom', '');
            this.set('username', '');
            this.set('password', '');
            this.set('response', null);

            console.log('readyState', localDB.readyState);
            var self = this;
            localDB.onsuccess = function(event) {
                // Do something with localDB.result!
                var db = event.target.result;
                var collections = [];
                console.log('result', db);

                // Example:
                // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB#Using_a_cursor
                localDB.result.transaction(DATABASE_KEY).objectStore(DATABASE_KEY).openCursor().onsuccess = function (event) {
                    var cursor = event.target.result;
                    if(cursor) {
                        collections.push(cursor.value);
                        cursor.continue();
                    } else {
                        console.info(collections.length + " items fetched from db, setting state.");
                        self.set('collections', collections);
                    }
                };
            };
        },

        // Show and hide the about dialog
        showAbout: function() { this.set('displayAbout', true); },
        hideAbout: function() { this.set('displayAbout', false); },

        // Open a new request using the values from the UI and send it
        send: function() {
            var request  = this.get('request'),
                dataMode = this.get('dataMode'),
                username = this.get('username'),
                password = this.get('password'),
                url      = this.get('url');

            // If url does not start with http://, we help the user out and add it for them
            // Improvements and suggestions to behaviour welcome
            if (!/^(http:\/\/)/.test(url)) {
              url = 'http://' + url;
            }
            console.log(this.get('url'))
            request.open(
                this.get('method'),
                url,
                true  // async?
            );<commit_msg>Refreshes collections when a request is added<commit_after>/*********************************
 *  REST Easy Ember Application  *
 * Copyright 2014 - <NAME> *
 *********************************/

// Constants
var HTTP_METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'LINK', 'UNLINK', 'OPTIONS'],
    DM_NONE = tr('request.data.type.none'),
    DM_FORM = tr('request.data.type.form'),
    DM_CUSTOM = tr('request.data.type.custom'),
    DATA_MODES = [DM_NONE, DM_FORM, DM_CUSTOM],
    FT_URLENCODED = 'application/x-www-form-urlencoded',
    FT_MULTIPART = 'multipart/form-data',
    FORM_TYPES = [FT_URLENCODED, FT_MULTIPART],
    DATABASE_KEY = 'savedRequests';

// Create the application and set the window title
window.RESTEasy = Ember.Application.create();
window.document.title = tr('application.title');


// -----------------------
// Initialize the database
var localDB = window.indexedDB.open("REST-Easy", 2);

// TODO: remove the console.logs

localDB.onerror = function(event) {
    // Do something with localDB.errorCode!
    console.log("DB: error opening the database with code " + localDB.errorCode);
};


localDB.onupgradeneeded = function(event) {
    var idb = event.target.result;
    console.log("DB: updateding the version");

    // Create an objectStore for this database
    var objectStore = idb.createObjectStore(DATABASE_KEY, { keyPath: "saveName" });
    console.log(objectStore);
};

// Utility methods
var updateCollections = function (waitFor) {
    console.log('Running update method');

    // We also need to .call this method.. ES5 ftw
    var self = this;
    var waitFor = waitFor || localDB;
    waitFor.onsuccess = function(event) {
        var db = event.target.result;
        var collections = [];

        localDB.result.transaction(DATABASE_KEY).objectStore(DATABASE_KEY).openCursor().onsuccess = function (event) {
            var cursor = event.target.result;
            if(cursor) {
                collections.push(cursor.value);
                cursor.continue();
            } else {
                console.info(collections.length + " items fetched from db, setting state.");
                self.set('collections', collections);
            }
        };
    };
};

// Main controller for the REST Easy application
RESTEasy.ApplicationController = Ember.Controller.extend({
    methods: HTTP_METHODS,
    dataModes: DATA_MODES,
    formTypes: FORM_TYPES,

    // Translations for attributes
    trDataType: tr('request.data.custom.type'),
    trUsername: tr('request.auth.username'),
    trPassword: tr('<PASSWORD>'),

    // Initialize the application for the first time
    init: function() {

        // REST Easy reuses a single XMLHttpRequest instead of creating a new
        // one for each request - this reduces the number of state variables
        var self = this,
            request = new XMLHttpRequest();
        request.onreadystatechange = function() {
            self.send('readyStateChange', request);
        };
        this.set('request', request);

        // Reset all values to their defaults
        this.send('reset');


    },

    // Parse a string containing response headers, returning a list of objects
    // containing a name and value property
    parseHeaders: function(headers) {
        return headers.trim().split('\n').map(function(header) {
            var i = header.indexOf(':');
            return {
                name: header.substr(0, i),
                value: header.substr(i + 1)
            };
        });
    },

    actions: {
        saveRequest: function() {
            var db = localDB.result;
            var transaction = db.transaction([DATABASE_KEY], "readwrite");
            var objectStore = transaction.objectStore(DATABASE_KEY);

            // We use url as saveName for now
            var saveName = this.get('url'); //this.get('saveName')

            var saveItem = {
                saveName: saveName,
                method: this.get('method'),
                url: this.get('url'),
                requestHeaders: this.get('requestHeaders'),
                dataMode: this.get('dataMode'),
                formType: this.get('formType'),
                formData: this.get('formData'),
                dataType: this.get('dataType'),
                dataCustom: this.get('dataCustom'),
                username: this.get('username'),
                password: <PASSWORD>')
            };
            console.log("About to save:", saveItem);

            var request = objectStore.add(saveItem);

            // Update collection state from db
            updateCollections.call(this, request);
        },

        loadRequest: function() {
            var saveName = record.url;

            localDB.result.transaction(DATABASE_KEY).objectStore(DATABASE_KEY).get(saveName).onsuccess = function (event) {
                var record = event.target.result;

                this.set('method', HTTP_METHODS[0]);    // TODO:
                this.set('url', record.url);
                this.set('requestHeaders', record.requestHeaders);
                this.set('dataMode', DATA_MODES[0]);    // TODO:
                this.set('formType', FORM_TYPES[0]);    // TODO:
                this.set('formData', record.formData);
                this.set('dataType', record.dataType);
                this.set('dataCustom', record.dataCustom);
                this.set('username', record.username);
                this.set('password', record.password);
                this.set('saveName', record.saveName);
            };
        },

        // Collections
        setRequestFromCollection: function(item) {
            this.set('method', item.method);    // TODO:
            this.set('url', item.url);
            /*this.set('requestHeaders', record.requestHeaders);
            this.set('dataMode', DATA_MODES[0]);    // TODO:
            this.set('formType', FORM_TYPES[0]);    // TODO:
            this.set('formData', record.formData);
            this.set('dataType', record.dataType);
            this.set('dataCustom', record.dataCustom);
            this.set('username', record.username);
            this.set('password', <PASSWORD>);
            this.set('saveName', record.saveName);*/

            console.log(this);
        },

        // Clear all values and set them to their defaults
        reset: function() {
            this.set('method', HTTP_METHODS[0]);
            this.set('url', '');
            this.set('requestHeaders', []);
            this.set('dataMode', DATA_MODES[0]);
            this.set('formType', FORM_TYPES[0]);
            this.set('formData', []);
            this.set('dataType', '');
            this.set('dataCustom', '');
            this.set('username', '');
            this.set('password', '');
            this.set('response', null);

            // Update collection state from db
            updateCollections.call(this);
        },

        // Show and hide the about dialog
        showAbout: function() { this.set('displayAbout', true); },
        hideAbout: function() { this.set('displayAbout', false); },

        // Open a new request using the values from the UI and send it
        send: function() {
            var request  = this.get('request'),
                dataMode = this.get('dataMode'),
                username = this.get('username'),
                password = <PASSWORD>('password'),
                url      = this.get('url');

            // If url does not start with http://, we help the user out and add it for them
            // Improvements and suggestions to behaviour welcome
            if (!/^(http:\/\/)/.test(url)) {
              url = 'http://' + url;
            }
            console.log(this.get('url'))
            request.open(
                this.get('method'),
                url,
                true  // async?
            );
{'fraction_non_alphanumeric': 0.14367601246105918, 'fraction_numerical': 0.0019314641744548288, 'mean_word_length': 1.97516218721038, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 1, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '890456', 'n_tokens_mistral': 4406, 'n_tokens_neox': 4228, 'n_words': 968}