text:
/*globals require*/
/*jshint node:true, mocha:true*/
/**
 * @author ksmyth / https://github.com/ksmyth
 * @author lattmann / https://github.com/lattmann
 */

var testFixture = require('../../../_globals.js');

describe('GME authentication', function () {
    'use strict';

    var gmeConfig = testFixture.getGmeConfig(),
        GMEAuth = testFixture.GMEAuth,
        expect = testFixture.expect,
        Q = testFixture.Q,

        auth;

    before(function (done) {
        auth = new GMEAuth(null, gmeConfig);

        testFixture.clearDatabase(gmeConfig)
            .then(function () {
                return auth.connect();
            })
            .then(function () {
                return Q.allDone([
                    auth.addUser('user', 'user@example.com', 'plaintext', true, {overwrite: true}),
                    auth.addUser('adminUser2', 'user@example.com', 'plaintext', true, {overwrite: true}),
                    auth.addUser('adminUser3', 'user@example.com', 'plaintext', true, {overwrite: true}),
                    auth.addUser('adminUser4', 'user@example.com', 'plaintext', true, {overwrite: true}),
                    auth.addUser('adminUser5', 'user@example.com', 'plaintext', true, {overwrite: true})
                ]);
            })
            .then(function () {
                return auth.authorizeByUserId('user', 'project', 'create', {
                    read: true,
                    write: true,
                    delete: false
                });
            })
            .then(function () {
                return auth.authorizeByUserId('user', 'unauthorized_project', 'create', {
                    read: false,
                    write: false,
                    delete: false
                });
            })
            .nodeify(done);
    });

    after(function (done) {
        auth.unload()
            .nodeify(done);
    });

    it('adds random user without overwrite', function (done) {
        var username = 'no_overwrite_user' + (new Date()).toISOString();
        auth.addUser(username, username + '@example.com', 'plaintext', true, {overwrite: false})
            .then(function () {
                return auth.getUser(username);
            })
            .then(function (userData) {
                expect(userData._id).equal(username);
            })
            .nodeify(done);
    });

    it('adds user without overwrite', function (done) {
        auth.addUser('no_overwrite_user', 'no_overwrite_user@example.com', 'plaintext', true, {overwrite: false}, done);
    });

    it('adds a user without email address', function (done) {
        auth.addUser('user_no_email', null, 'plaintext', true, {overwrite: true}, done);
    });

    it('gets all user auth info', function (done) {
        auth.addUser('user_no_email', null, 'plaintext', true, {overwrite: true})
            .then(function () {
                return auth.getAllUserAuthInfo('user_no_email');
            })
            .nodeify(done);
    });

    it('gets all user auth info fails on non existent user id', function (done) {
        auth.getAllUserAuthInfo('user_does_not exist')
            .then(function () {
                throw new Error('Should have failed');
            })
            .catch(function (err) {
                if (err.message.indexOf('no such user') > -1) {
                    return;
                }
                throw new Error('Unexpected error ' + err);
            })
            .nodeify(done);
    });

    it('fails with invalid user for getProjectAuthorizationByUserId', function (done) {
        auth.getProjectAuthorizationByUserId('user_does_not exist')
            .then(function () {
                throw new Error('Should have failed');
            })
            .catch(function (err) {
                if (err.message.indexOf('No such user') > -1) {
                    return;
                }
                throw new Error('Unexpected error ' + err);
            })
            .nodeify(done);
    });

    it('gets user auth info', function (done) {
        auth.addUser('user_no_email', null, 'plaintext', true, {overwrite: true})
            .then(function () {
                return auth.getUserAuthInfo('user_no_email');
            })
            .nodeify(done);
    });

    it('gets user auth info fails on non existent user id', function (done) {
        auth.getUserAuthInfo('user_does_not exist')
            .then(function () {
                throw new Error('Should have failed');
            })
            .catch(function (err) {
                if (err.message.indexOf('no such user') > -1) {
                    return;
                }
                throw new Error('Unexpected error ' + err);
            })
            .nodeify(done);
    });

    it('throws for invalid session getAllUserAuthInfoBySession', function (done) {
        auth.getAllUserAuthInfoBySession('sessionId')
            .then(function () {
                throw new Error('Should have failed');
            })
            .catch(function (err) {
                if (err instanceof TypeError && err.message.indexOf('getSessionUser') > -1) {
                    return;
                }
                throw err;
            })
            .nodeify(done);
    });

    it('does not authorize by invalid session authorizeBySession', function (done) {
        auth.authorize('sessionId')
            .then(function () {
                throw new Error('Should have failed');
            })
            .catch(function (err) {
                if (err instanceof TypeError && err.message.indexOf('getSessionUser') > -1) {
                    return;
                }
                throw err;
            })
            .nodeify(done);
    });

    it('checks invalid and returns false', function (done) {
        auth.checkToken('token')
            .then(function (valid) {
                if (valid) {
                    done(new Error('should be invalid token'));
                    return;
                }
                done();
            });
    });

    it('should return with false using invalid token tokenAuth', function (done) {
        auth.tokenAuth('token')
            .then(function (valid) {
                if (valid[0]) {
                    done(new Error('should be invalid token'));
                    return;
                }
                done();
            });
    });

    it('does not get token for invalid session', function (done) {
        auth.getToken('sessionId')
            .then(function () {
                throw new Error('Should have failed');
            })
            .catch(function (err) {
                if (err instanceof TypeError && err.message.indexOf('getSessionUser') > -1) {
                    return;
                }
                throw err;
            })
            .nodeify(done);
    });

    it('does not generate token for invalid session', function (done) {
        auth.generateToken('sessionId')
            .then(function () {
                throw new Error('Should have failed');
            })
            .catch(function (err) {
                if (err instanceof TypeError && err.message.indexOf('getSessionUser') > -1) {
                    return;
                }
                throw err;
            })
            .nodeify(done);
    });

    it('does not get project auth by invalid session', function (done) {
        auth.getProjectAuthorizationBySession('sessionId')
            .then(function () {
                throw new Error('Should have failed');
            })
            .catch(function (err) {
                if (err instanceof TypeError && err.message.indexOf('getSessionUser') > -1) {
                    return;
                }
                throw err;
            })
            .nodeify(done);
    });

    it('removes user by id', function (done) {
        auth.addUser('user_to_remove', 'user_to_remove@example.com', 'plaintext', true, {overwrite: true}).
            then(function () {
                return auth.deleteUser('user_to_remove');
            })
            .nodeify(done);
    });

    it('should add a user with custom data provided', function (done) {
        var customData = {a: 1, b: {b1: 'b1'}};
        auth.addUser('user_w_data', 'e@mail', 'pass', true, {overwrite: true, data: customData})
            .then(function () {
                return auth.getUser('user_w_data');
            })
            .then(function (userData) {
                expect(userData.data).to.deep.equal(customData);
            })
            .nodeify(done);
    });

    it('should update a user with custom data provided and overwrite', function (done) {
        var customData = {a: 1};
        auth.addUser('user_w_data11', 'e@mail', 'pass', true, {overwrite: true, data: customData})
            .then(function () {
                return auth.updateUser('user_w_data11', {data: {b: 1}});
            })
            .then(function (userData) {
                expect(userData.data).to.deep.equal({b: 1});
            })
            .nodeify(done);
    });

    it('should fail to add a user with custom data that is not an object', function (done) {
        var customData = 'aString';
        auth.addUser('user_w_faulty_data1', 'e@mail', 'pass', true, {overwrite: true, data: customData})
            .then(function () {
                throw new Error('Should have failed!');
            })
            .catch(function (err) {
                expect(err.message).to.include('supplied userData.data is not an object [aString]');
            })
            .nodeify(done);
    });

    it('should fail to update a user with custom data that is not an object', function (done) {
        var customData = 'aString';
        auth.addUser('user_w_faulty_data2', 'e@mail', 'pass', true, {overwrite: true, data: {}})
            .then(function () {
                return auth.updateUser('user_w_faulty_data2', {data: customData});
            })
            .then(function () {
                throw new Error('Should have failed!');
            })
            .catch(function (err) {
                expect(err.message).to.include('supplied userData.data is not an object [aString]');
            })
            .nodeify(done);
    });

    it('updateUserDataField should update with all supplied', function (done) {
        var userId = 'user_w_data1',
            initData = {a: 1, b: 1},
            newData = {a: 2, b: 2};

        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, newData);
            })
            .then(function (customData) {
                expect(customData).to.deep.equal(newData);
            })
            .nodeify(done);
    });

    it('updateUserDataField should update given field and keep the old', function (done) {
        var userId = 'user_w_data2',
            initData = {a: 1, b: 1},
            newData = {a: 2};

        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, newData);
            })
            .then(function (customData) {
                expect(customData).to.deep.equal({a: 2, b: 1});
            })
            .nodeify(done);
    });

    it('updateUserDataField should add given field and keep the old', function (done) {
        var userId = 'user_w_data3',
            initData = {b: 1},
            newData = {a: 2};

        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, newData);
            })
            .then(function (customData) {
                expect(customData).to.deep.equal({a: 2, b: 1});
            })
            .nodeify(done);
    });

    it('updateUserDataField should update field deep down', function (done) {
        var userId = 'user_w_data4',
            initData = {a: {b: {c: {d: 1, e: 2}}}},
            newData = {a: {b: {c: {e: 5}}}};

        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, newData);
            })
            .then(function (customData) {
                expect(customData).to.deep.equal({a: {b: {c: {d: 1, e: 5}}}});
            })
            .nodeify(done);
    });

    it('updateUserDataField should overwrite array with array', function (done) {
        var userId = 'user_w_data5',
            initData = {a: {b: [1, 2], c: 'c'}},
            newData = {a: {b: [3, 4]}};

        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, newData);
            })
            .then(function (customData) {
                expect(customData).to.deep.equal({a: {b: [3, 4], c: 'c'}});
            })
            .nodeify(done);
    });

    it('updateUserDataField should overwrite object with array', function (done) {
        var userId = 'user_w_data6',
            initData = {a: {b: {d: 1}, c: 'c'}},
            newData = {a: {b: [3, 4]}};

        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, newData);
            })
            .then(function (customData) {
                expect(customData).to.deep.equal({a: {b: [3, 4], c: 'c'}});
            })
            .nodeify(done);
    });

    it('updateUserDataField should overwrite array with object', function (done) {
        var userId = 'user_w_data7',
            initData = {a: {b: [1, 2], c: 'c'}},
            newData = {a: {b: {d: 1}}};

        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, newData);
            })
            .then(function (customData) {
                expect(customData).to.deep.equal({a: {b: {d: 1}, c: 'c'}});
            })
            .nodeify(done);
    });

    it('updateUserDataField should overwrite object with null', function (done) {
        var userId = 'user_w_data8',
            initData = {a: {b: {d: 1}, c: 'c'}},
            newData = {a: {b: null}};

        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, newData);
            })
            .then(function (customData) {
                expect(customData).to.deep.equal({a: {b: null, c: 'c'}});
            })
            .nodeify(done);
    });

    it('updateUserDataField should overwrite null with object', function (done) {
        var userId = 'user_w_data9',
            initData = {a: {b: null, c: 'c'}},
            newData = {a: {b: {d: 1}}};

        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, newData);
            })
            .then(function (customData) {
                expect(customData).to.deep.equal({a: {b: {d: 1}, c: 'c'}});
            })
            .nodeify(done);
    });

    it('updateUserDataField should do nothing with empty object', function (done) {
        var userId = 'user_w_data10',
            initData = {a: {b: null, c: 'c'}},
            newData = {};

        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, newData);
            })
            .then(function (customData) {
                expect(customData).to.deep.equal(initData);
            })
            .nodeify(done);
    });

    it('updateUserData should reject with error when given data is a string', function (done) {
        var userId = 'user_w_data11',
            initData = {},
            newData = 'aString';
        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, newData);
            })
            .then(function () {
                throw new Error('Should have failed!');
            })
            .catch(function (err) {
                expect(err.message).to.include('supplied data is not an object [aString]');
            })
            .nodeify(done);
    });

    it('updateUserData should reject with error when given data is null', function (done) {
        var userId = 'user_w_data12',
            initData = {},
            newData = null;
        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, newData);
            })
            .then(function () {
                throw new Error('Should have failed!');
            })
            .catch(function (err) {
                expect(err.message).to.include('supplied data is not an object [null]');
            })
            .nodeify(done);
    });

    it('updateUserData should reject with error when given data is undefined', function (done) {
        var userId = 'user_w_data13',
            initData = {};
        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId);
            })
            .then(function () {
                throw new Error('Should have failed!');
            })
            .catch(function (err) {
                expect(err.message).to.include('supplied data is not an object [undefined]');
            })
            .nodeify(done);
    });

    it('updateUserData should reject with error when given data is an array', function (done) {
        var userId = 'user_w_data14',
            initData = {};
        auth.addUser(userId, 'e@mail', 'pass', true, {overwrite: true, data: initData})
            .then(function () {
                return auth.updateUserDataField(userId, [1, 2]);
            })
            .then(function () {
                throw new Error('Should have failed!');
            })
            .catch(function (err) {
                expect(err.message).to.include('supplied data is not an object [1,2]');
            })
            .nodeify(done);
    });

    it('updateUserData should reject with error when user does not exist', function (done) {
        auth.updateUserDataField('does_not_exist', {a: 1})
            .then(function () {
                throw new Error('Should have failed!');
            })
            .catch(function (err) {
                expect(err.message).to.include('no such user [does_not_exist]');
            })
            .nodeify(done);
    });

    // _projects
    it('should add and get a project', function (done) {
        var projectName = 'newly_added_project',
            ownerName = 'someUser',
            projId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(ownerName, projectName);
        auth.addProject(ownerName, projectName)
            .then(function (projectId) {
                expect(projectId).to.equal(projId);
                return auth.getProject(projectId);
            })
            .then(function (project) {
                expect(project).to.deep.equal({
                    _id: projId,
                    info: {},
                    owner: ownerName,
                    name: projectName
                });
            })
            .nodeify(done);
    });

    it('should add a project with supplied info', function (done) {
        var projectName = 'project_with_info1',
            ownerName = 'someUser',
            projId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(ownerName, projectName);
        auth.addProject(ownerName, projectName, {createdAt: 'justNow'})
            .then(function (projectId) {
                expect(projectId).to.equal(projId);
                return auth.getProject(projectId);
            })
            .then(function (project) {
                expect(project).to.deep.equal({
                    _id: projId,
                    info: {createdAt: 'justNow'},
                    owner: ownerName,
                    name: projectName,
                });
            })
            .nodeify(done);
    });

    it('should add a project and update info', function (done) {
        var projectName = 'project_with_info2',
            ownerName = 'someUser',
            projId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(ownerName, projectName);
        auth.addProject(ownerName, projectName, {createdAt: 'justNow'})
            .then(function (projectId) {
                expect(projectId).to.equal(projId);
                return auth.updateProjectInfo(projectId, {createdAt: 'aBitLater'});
            })
            .then(function (data) {
                expect(data.info).to.deep.equal({createdAt: 'aBitLater', modifiedAt: null, viewedAt: null,
                viewer: null, modifier: null, creator: null});
            })
            .nodeify(done);
    });

    it('should add a project and succeed with empty info', function (done) {
        var projectName = 'project_with_info3',
            ownerName = 'someUser',
            projId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(ownerName, projectName);
        auth.addProject(ownerName, projectName, {createdAt: 'justNow'})
            .then(function (projectId) {
                expect(projectId).to.equal(projId);
                return auth.updateProjectInfo(projectId, {});
            })
            .then(function (data) {
                expect(data.info).to.deep.equal({createdAt: 'justNow', modifiedAt: null, viewedAt: null,
                    viewer: null, modifier: null, creator: null});
            })
            .nodeify(done);
    });

    it('should add a project and not update with non allowed info', function (done) {
        var projectName = 'project_with_info4',
            ownerName = 'someUser',
            projId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(ownerName, projectName);
        auth.addProject(ownerName, projectName, {createdAt: 'justNow'})
            .then(function (projectId) {
                expect(projectId).to.equal(projId);
                return auth.updateProjectInfo(projectId, {aaa: 'should not persist'});
            })
            .then(function (data) {
                expect(data.info).to.deep.equal({createdAt: 'justNow', modifiedAt: null, viewedAt: null,
                    viewer: null, modifier: null, creator: null});
            })
            .nodeify(done);
    });

    it('should add a project and not update all info', function (done) {
        var projectName = 'project_with_info5',
            ownerName = 'someUser',
            projId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(ownerName, projectName),
            now = 'nu',
            info = {
                createdAt: now,
                viewedAt: now,
                modifiedAt: now,
                creator: 'user',
                viewer: 'user',
                modifier: 'user'
            };
        auth.addProject(ownerName, projectName, info)
            .then(function (projectId) {
                expect(projectId).to.equal(projId);
                info.createdAt = info.viewedAt = info.modifiedAt = 'nu1';
                return auth.updateProjectInfo(projectId, info);
            })
            .then(function (data) {
                expect(data.info).to.deep.equal(info);
            })
            .nodeify(done);
    });

    it('should fail to get a non-existing project', function (done) {
        var projectName = 'does_not_exist',
            ownerName = 'someUser',
            projId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(ownerName, projectName);
        auth.getProject(projId)
            .then(function () {
                throw new Error('should fail to get a non-existing project');
            })
            .catch(function (error) {
                expect(error instanceof Error);
                expect(error.message).to.contain('no such project [' + projId);
                done();
            })
            .done();
    });

    it('should fail to add an existing project', function (done) {
        var projectName = 'already_added',
            ownerName = 'someUser',
            projId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(ownerName, projectName);
        auth.addProject(ownerName, projectName)
            .then(function (projectId) {
                expect(projectId).to.equal(projId);
                return auth.addProject(ownerName, projectName);
            })
            .then(function () {
                throw new Error('should fail to add an existing project');
            })
            .catch(function (error) {
                expect(error instanceof Error);
                expect(error.message).to.equal('Project already exists someUser+already_added in _projects collection');
                done();
            })
            .done();
    });

    it('should delete a project', function (done) {
        var projectName = 'to_be_deleted',
            ownerName = 'someUser',
            projId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(ownerName, projectName);
        auth.addProject(ownerName, projectName)
            .then(function (projectId) {
                expect(projectId).to.equal(projId);
                return auth.getProject(projectId);
            })
            .then(function (project) {
                expect(project).to.deep.equal({
                    _id: projId,
                    info: {},
                    owner: ownerName,
                    name: projectName
                });
                return auth.deleteProject(projId);
            })
            .then(function () {
                return auth.getProject(projId);
            })
            .then(function () {
                throw new Error('should fail to get a deleted project');
            })
            .catch(function (error) {
                expect(error instanceof Error);
                expect(error.message).to.contain('no such project [' + projId);
                done();
            })
            .done();
    });

    it('should delete non-existing project', function (done) {
        auth.deleteProject('does_not_exist_project')
            .nodeify(done);
    });

    // Organizations
    it('should fail to get non existent organization', function (done) {
        auth.getOrganization('does_not_exist')
            .then(function () {
                throw new Error('Should have failed');
            })
            .catch(function (err) {
                if (err.message.indexOf('No such organization') > -1) {
                    return;
                }
                throw new Error('Unexpected error: ' + err);
            })
            .nodeify(done);
    });

    it('should fail to remove user from a non existent organization', function (done) {
        auth.removeUserFromOrganization('user', 'does_not_exist')
            .then(function () {
                throw new Error('Should have failed');
            })
            .catch(function (err) {
                if (err.message.indexOf('No such organization') > -1) {
                    return;
                }
                throw new Error('Unexpected error: ' + err);
            })
            .nodeify(done);
    });

    it.skip('should fail to remove a non existent user from an organization', function () {
        // TODO: implement
    });

    it('should fail to authorize organization with invalid type', function (done) {
        auth.authorizeOrganization('dummyOrgId', 'dummyProjectName', 'unknown', {}, function (err) {
            if (err.message.indexOf('unknown type') > -1) {
                done();
                return;
            }
            done(new Error('Unexpected error: ' + err));
        });
    });

    it('should fail to authorize by user id with invalid type', function (done) {
        auth.authorizeByUserId('user', 'dummyProjectName', 'unknown', {}, function (err) {
            if (err.message.indexOf('unknown type') > -1) {
                done();
                return;
            }
            done(new Error('Unexpected error: ' + err));
        });
    });

    it('should fail to authorize non existent organization', function (done) {
        auth.authorizeOrganization('dummyOrgId', 'unauthorized_project', 'create', {})
            .then(function () {
                throw new Error('Should have failed');
            })
            .catch(function (err) {
                if (err.message.indexOf('No such user or org') > -1) {
                    return;
                }
                throw new Error('Unexpected error: ' + err);
            })
            .nodeify(done);
    });

    it('should fail to get authorization info for non existent organization', function (done) {
        auth.getAuthorizationInfoByOrgId('org_does_not_exist', 'projectName')
            .then(function () {
                done(new Error('Should have failed'));
            }, function (err) {
                if (err.message.indexOf('No such organization') > -1) {
                    done();
                    return;
                }
                done(new Error('Unexpected error: ' + err));
            });
    });

    it('gets project names', function (done) {
        auth._getProjectNames(done);
    });

    it('should auth with a new token', function (done) {
        auth.generateTokenForUserId('user')
            .then(function (tokenId) {
                return Q.allSettled([auth.tokenAuthorization(tokenId, 'project'),
                    auth.tokenAuthorization(tokenId, 'unauthorized_project'),
                    auth.tokenAuthorization(tokenId, 'doesnt_exist_project')]);
            }).then(function (authorized) {
                authorized.should.deep.equal([
                    {state: 'fulfilled', value: true},
                    {state: 'fulfilled', value: false},
                    {state: 'fulfilled', value: false}
                ]);
            }).nodeify(done);
    });

    it('should have permissions', function (done) {
        return auth.getAuthorizationInfoByUserId('user', 'project')
            .then(function (authorized) {
                authorized.should.deep.equal({read: true, write: true, delete: false});
            }).then(function () {
                return auth.getProjectAuthorizationByUserId('user', 'project');
            }).then(function (authorized) {
                authorized.should.deep.equal({read: true, write: true, delete: false});
            })
            .nodeify(done);
    });

    it('should be able to revoke permissions', function (done) {
        return auth.authorizeByUserId('user', 'project', 'delete', {})
            .then(function () {
                return auth.getAuthorizationInfoByUserId('user', 'project');
            }).then(function (authorized) {
                authorized.should.deep.equal({read: false, write: false, delete: false});
            }).then(function () {
                return auth.getProjectAuthorizationByUserId('user', 'project');
            }).then(function (authorized) {
                authorized.should.deep.equal({read: false, write: false, delete: false});
            })
            .nodeify(done);
    });

    it('should be able to add organization', function (done) {
        var orgName = 'org1';
        return auth.addOrganization(orgName)
            .then(function () {
                return auth.getOrganization(orgName);
            }).then(function () {
                return auth.addUserToOrganization('user', orgName);
            }).then(function () {
                return auth.getOrganization(orgName);
            }).then(function (org) {
                org.users.should.deep.equal(['user']);
            }).nodeify(done);
    });

    it('should be able to list organization', function (done) {
        var orgName = 'org2',
            otherOrgName = 'otherOrgName';
        Q.allDone([
            auth.addOrganization(orgName),
            auth.addOrganization(otherOrgName)
        ])
            .then(function () {
                return auth.listOrganizations({});
            }).then(function (organizations) {
                expect(organizations).to.include({
                        _id: orgName,
                        info: {},
                        projects: {},
                        type: auth.CONSTANTS.ORGANIZATION,
                        admins: []
                    },
                    {
                        _id: otherOrgName,
                        info: {},
                        projects: {},
                        type: auth.CONSTANTS.ORGANIZATION,
                        admins: []
                    });
            }).nodeify(done);
    });

    it('should fail to add dup organization', function (done) {
        var orgName = 'org3';
        auth.addOrganization(orgName)
            .then(function () {
                return auth.addOrganization(orgName);
            })
            .then(function () {
                done(new Error('should have been rejected'));
            })
            .catch(function (err) {
                expect(err.message).to.include('duplicate key error');
                done();
            })
            .done();
    });

    it('should fail to add nonexistant organization', function (done) {
        var orgName = 'org_doesnt_exist';
        auth.addUserToOrganization('user', orgName)
            .then(function () {
                done(new Error('should have been rejected'));
            }, function (/*err*/) {
                done();
            });
    });

    it('should fail to add nonexistant user to organization', function (done) {
        var orgName = 'org1';
        auth.addUserToOrganization('user_doesnt_exist', orgName)
            .then(function () {
                done(new Error('should have been rejected'));
            }, function (/*err*/) {
                done();
            });
    });

    it('should authorize organization', function (done) {
        var orgName = 'org1',
            projectName = 'org_project';

        return auth.authorizeOrganization(orgName, projectName, 'create', {read: true, write: true, delete: false})
            .then(function () {
                return auth.getAuthorizationInfoByOrgId(orgName, projectName);
            })
            .then(function (rights) {
                rights.should.deep.equal({read: true, write: true, delete: false});
            })
            .nodeify(done);
    });

    it('should give the user project permissions from the organization', function (done) {
        return auth.getAuthorizationInfoByUserId('user', 'org_project')
            .then(function (authorized) {
                authorized.should.deep.equal({read: false, write: false, delete: false});
            })
            .then(function () {
                return auth.getProjectAuthorizationByUserId('user', 'org_project');
            })
            .then(function (authorized) {
                authorized.should.deep.equal({read: true, write: true, delete: false});
            })
            .nodeify(done);
    });

    it('should deauthorize organization', function (done) {
        var orgName = 'org1',
            projectName = 'org_project';

        return auth.authorizeOrganization(orgName, projectName, 'delete', {})
            .then(function () {
                return auth.getAuthorizationInfoByOrgId(orgName, projectName);
            })
            .then(function (rights) {
                rights.should.deep.equal({});
            })
            .nodeify(done);
    });

    it('should remove user from organization', function (done) {
        var orgName = 'org1';
        auth.removeUserFromOrganization('user', orgName)
            .nodeify(done);
    });

    it('should remove user from organization', function (done) {
        var orgId = 'orgWithUser',
            userId = 'userInOrg';
        auth.addUser(userId, '@', 'ss', true, {})
            .then(function () {
                return auth.addOrganization(orgId);
            })
            .then(function () {
                return auth.addUserToOrganization(userId, orgId);
            })
            .then(function () {
                return auth.getUser(userId);
            })
            .then(function (user) {
                expect(user.orgs).to.deep.equal(['orgWithUser']);
                return auth.removeUserFromOrganization(userId, orgId);
            })
            .then(function () {
                return auth.getUser(userId);
            })
            .then(function (user) {
                expect(user.orgs).to.deep.equal([]);
            })
            .nodeify(done);
    });

    it('should remove organization', function (done) {
        var orgName = 'org1';
        auth.removeOrganizationByOrgId(orgName)
            .nodeify(done);
    });

    it('should fail to remove organization twice', function (done) {
        var orgName = 'org1';
        auth.removeOrganizationByOrgId(orgName)
            .then(function () {
                done(new Error('should have been rejected'));
            }, function (/*err*/) {
                done();
            });
    });

    it('getAdminsInOrganization should fail with non-existing organization', function (done) {
        var orgId = 'doesNotExist';
        return auth.getAdminsInOrganization(orgId)
            .then(function () {
                throw new Error('getAdminsInOrganization should fail with non-existing organization');
            })
            .catch(function (error) {
                expect(error.message).to.include('No such organization [' + orgId);
                done();
            })
            .done();
    });

    it('getAdminsInOrganization return empty array for new organization', function (done) {
        var orgId = 'orgAdmin1';
        return auth.addOrganization(orgId)
            .then(function () {
                return auth.getAdminsInOrganization(orgId);
            })
            .then(function (admins) {
                expect(admins).to.deep.equal([]);
            })
            .nodeify(done);
    });

    it('should should make user admin for organization', function (done) {
        var orgId = 'orgAdmin2',
            userId = 'adminUser2';
        return auth.addOrganization(orgId)
            .then(function () {
                return auth.setAdminForUserInOrganization(userId, orgId, true);
            })
            .then(function () {
                return auth.getAdminsInOrganization(orgId);
            })
            .then(function (admins) {
                expect(admins.indexOf(userId) > - 1).to.equal(true);
            })
            .nodeify(done);
    });

    it('should should make user admin, then remove admin for organization', function (done) {
        var orgId = 'orgAdmin3',
            userId = 'adminUser3';
        return auth.addOrganization(orgId)
            .then(function () {
                return auth.setAdminForUserInOrganization(userId, orgId, true);
            })
            .then(function () {
                return auth.getAdminsInOrganization(orgId);
            })
            .then(function (admins) {
                expect(admins.indexOf(userId) > - 1).to.equal(true);
            })
            .then(function () {
                return auth.setAdminForUserInOrganization(userId, orgId, false);
            })
            .then(function () {
                return auth.getAdminsInOrganization(orgId);
            })
            .then(function (admins) {
                expect(admins.indexOf(userId) > - 1).to.equal(false);
            })
            .nodeify(done);
    });

    it('should should make user admin twice organization', function (done) {
        var orgId = 'orgAdmin4',
            userId = 'adminUser4';
        return auth.addOrganization(orgId)
            .then(function () {
                return auth.setAdminForUserInOrganization(userId, orgId, true);
            })
            .then(function () {
                return auth.getAdminsInOrganization(orgId);
            })
            .then(function (admins) {
                expect(admins.indexOf(userId) > - 1).to.equal(true);
            })
            .then(function () {
                return auth.setAdminForUserInOrganization(userId, orgId, true);
            })
            .then(function () {
                return auth.getAdminsInOrganization(orgId);
            })
            .then(function (admins) {
                expect(admins.indexOf(userId) > - 1).to.equal(true);
            })
            .nodeify(done);
    });

    it('should should remove user admin in organization', function (done) {
        var orgId = 'orgAdmin5',
            userId = 'adminUser5';
        return auth.addOrganization(orgId)
            .then(function () {
                return auth.setAdminForUserInOrganization(userId, orgId, false);
            })
            .then(function () {
                return auth.getAdminsInOrganization(orgId);
            })
            .then(function (admins) {
                expect(admins.indexOf(userId) > - 1).to.equal(false);
            })
            .nodeify(done);
    });

    it('getProjectAuthorizationListByUserId should include auth from organization', function (done) {
        var orgId = 'organ1',
            userId = 'userWithOrgan1',
            projectId1 = 'organsProject1',
            projectId2 = 'usersProject1';

        auth.addUser(userId, '@', 'p', true, {})
            .then(function () {
                return auth.addOrganization(orgId);
            })
            .then(function () {
                return auth.authorizeOrganization(orgId, projectId1, 'create',
                    {read: true, write: true, delete: true});
            })
            .then(function () {
                return auth.authorizeByUserId(userId, projectId2, 'create',
                    {read: true, write: true, delete: true});
            })
            .then(function () {
                return auth.getProjectAuthorizationListByUserId(userId);
            })
            .then(function (fullRights) {
                fullRights.should.deep.equal({
                    usersProject1: {
                        read: true,
                        write: true,
                        delete: true
                    }
                });
                return auth.addUserToOrganization(userId, orgId);
            })
            .then(function () {
                return auth.getProjectAuthorizationListByUserId(userId);
            })
            .then(function (fullRights) {
                fullRights.should.deep.equal({
                    usersProject1: {
                        read: true,
                        write: true,
                        delete: true
                    },
                    organsProject1: {
                        read: true,
                        write: true,
                        delete: true
                    }
                });
                return auth.removeUserFromOrganization(userId, orgId);
            })
            .then(function () {
                return auth.getProjectAuthorizationListByUserId(userId);
            })
            .then(function (fullRights) {
                fullRights.should.deep.equal({
                    usersProject1: {
                        read: true,
                        write: true,
                        delete: true
                    }
                });
            })
            .nodeify(done);
    });

    it('getProjectAuthorizationListByUserId should get the highest auth', function (done) {
        var orgId = 'organHighest1',
            userId = 'userWithOrganHighest1',
            projectId = 'organAndUserProject1';

        auth.addUser(userId, '@', 'p', true, {})
            .then(function () {
                return auth.addOrganization(orgId);
            })
            .then(function () {
                return auth.authorizeOrganization(orgId, projectId, 'create',
                    {read: true, write: false, delete: false});
            })
            .then(function () {
                return auth.authorizeByUserId(userId, projectId, 'create',
                    {read: true, write: true, delete: false});
            })
            .then(function () {
                return auth.getProjectAuthorizationListByUserId(userId);
            })
            .then(function (fullRights) {
                fullRights.should.deep.equal({
                    organAndUserProject1: {
                        read: true,
                        write: true,
                        delete: false
                    }
                });
                return auth.addUserToOrganization(userId, orgId);
            })
            .then(function () {
                return auth.getProjectAuthorizationListByUserId(userId);
            })
            .then(function (fullRights) {
                fullRights.should.deep.equal({
                    organAndUserProject1: {
                        read: true,
                        write: true,
                        delete: false
                    }
                });
                return auth.removeUserFromOrganization(userId, orgId);
            })
            .then(function () {
                return auth.getProjectAuthorizationListByUserId(userId);
            })
            .then(function (fullRights) {
                fullRights.should.deep.equal({
                    organAndUserProject1: {
                        read: true,
                        write: true,
                        delete: false
                    }
                });
            })
            .nodeify(done);
    });

    it('getProjectAuthorizationListByUserId should get the highest auth2', function (done) {
        var orgId = 'organHighest2',
            userId = 'userWithOrganHighest2',
            projectId = 'organAndUserProject2';

        auth.addUser(userId, '@', 'p', true, {})
            .then(function () {
                return auth.addOrganization(orgId);
            })
            .then(function () {
                return auth.authorizeOrganization(orgId, projectId, 'create',
                    {read: true, write: true, delete: true});
            })
            .then(function () {
                return auth.authorizeByUserId(userId, projectId, 'create',
                    {read: true, write: false, delete: false});
            })
            .then(function () {
                return auth.getProjectAuthorizationListByUserId(userId);
            })
            .then(function (fullRights) {
                fullRights.should.deep.equal({
                    organAndUserProject2: {
                        read: true,
                        write: false,
                        delete: false
                    }
                });
                return auth.addUserToOrganization(userId, orgId);
            })
            .then(function () {
                return auth.getProjectAuthorizationListByUserId(userId);
            })
            .then(function (fullRights) {
                fullRights.should.deep.equal({
                    organAndUserProject2: {
                        read: true,
                        write: true,
                        delete: true
                    }
                });
                return auth.removeUserFromOrganization(userId, orgId);
            })
            .then(function () {
                return auth.getProjectAuthorizationListByUserId(userId);
            })
            .then(function (fullRights) {
                fullRights.should.deep.equal({
                    organAndUserProject2: {
                        read: true,
                        write: false,
                        delete: false
                    }
                });
            })
            .nodeify(done);
    });

    it('getProjectAuthorizationList should fail if user does not exist', function (done) {
        var userId = 'getProjectAuthorizationListDoesNotExist';

        auth.getProjectAuthorizationListByUserId(userId).
            then(function () {
                throw new Error('Should have failed');
            })
            .catch(function (err) {
                expect(err.message).to.include('No such user [' + userId);
                done();
            })
            .done();
    });

    // project transfer
    it('transferProject should fail when project does not exit', function (done) {
        var oldOwner = 'currOwner',
            newOwner = 'newOwner',
            projectName = 'does_not_exist_transfer',
            projectId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(oldOwner, projectName);

        auth.transferProject(projectId, newOwner)
            .then(function () {
                throw new Error('should have failed!');
            })
            .catch(function (err) {
                expect(err.message).to.include('no such project [');
                done();
            })
            .done();
    });

    it.skip('transferProject should fail when newOwner does not exist', function (done) {
        // This is not checked in gmeAuth
        var oldOwner = 'currOwner',
            newOwner = 'newOwner_does_not_exist',
            projectName = 'owner_does_not_match_transfer',
            projectId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(oldOwner, projectName);

        auth.addProject(oldOwner, projectName)
            .then(function () {
                return auth.transferProject(projectId, newOwner);
            })
            .then(function () {
                throw new Error('should have failed!');
            })
            .catch(function (err) {
                expect(err.message).to.include('newOrgOrUserId [' + newOwner + '] does not exist');
                done();
            })
            .done();
    });

    it('transferProject should give full rights to new owner', function (done) {
        var oldOwner = 'currOwner',
            newOwner = 'newOwner',
            newProjectId,
            projectName = 'transferred1',
            projectId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(oldOwner, projectName);

        auth.addProject(oldOwner, projectName)
            .then(function () {
                return auth.addUser(oldOwner, '@', 'p', true, {});
            })
            .then(function () {
                return auth.addUser(newOwner, '@', 'p', true, {});
            })
            .then(function () {
                return auth.transferProject(projectId, newOwner);
            })
            .then(function (newProjectId_) {
                newProjectId = newProjectId_;
                return auth.getProject(newProjectId);
            })
            .then(function (projectData) {
                expect(projectData).to.deep.equal({
                    _id: 'newOwner+transferred1',
                    info: {},
                    name: 'transferred1',
                    owner: 'newOwner'
                });
                return auth.getProjectAuthorizationByUserId(newOwner, newProjectId);
            })
            .then(function (rights) {
                expect(rights).to.deep.equal({
                    read: true,
                    write: true,
                    delete: true
                });
            })
            .nodeify(done);
    });

    it('transferProject should save info about project', function (done) {
        var oldOwner = 'currOwner2',
            newOwner = 'newOwner2',
            newProjectId,
            projectName = 'transferred2',
            projectId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(oldOwner, projectName);

        auth.addProject(oldOwner, projectName, {firstOwner: oldOwner})
            .then(function () {
                return auth.addUser(oldOwner, '@', 'p', true, {});
            })
            .then(function () {
                return auth.addUser(newOwner, '@', 'p', true, {});
            })
            .then(function () {
                return auth.transferProject(projectId, newOwner);
            })
            .then(function (newProjectId_) {
                newProjectId = newProjectId_;
                return auth.getProject(newProjectId);
            })
            .then(function (projectData) {
                expect(projectData.info).to.deep.equal({firstOwner: oldOwner});
            })
            .nodeify(done);
    });

    it('transferProject should transfer to organization', function (done) {
        var oldOwner = 'currOwnerUser',
            newOwner = 'newOwnerOrg',
            projectName = 'transferred3',
            projectId = testFixture.storageUtil.getProjectIdFromOwnerIdAndProjectName(oldOwner, projectName);

        auth.addProject(oldOwner, projectName, {firstOwner: oldOwner})
            .then(function () {
                return auth.addUser(oldOwner, '@', 'p', true, {});
            })
            .then(function () {
                return auth.addOrganization(newOwner);
            })
            .then(function () {
                return auth.transferProject(projectId, newOwner);
            })
            .then(function (newProjectId) {
                return auth.getAuthorizationInfoByOrgId(newOwner, newProjectId);
            })
            .then(function (rights) {
                expect(rights).to.deep.equal({
                    read: true,
                    write: true,
                    delete: true
                });
            })
            .nodeify(done);
    });
});


text:
name: Bug report
about: Create a report about an issue you found

---

I confirm (by marking "x" in the [ ] below: [x]):

- [ ] This is not a troubleshooting question. [Troubleshooting questions go here: http://www.mattermost.org/troubleshoot/](http://www.mattermost.org/troubleshoot/).
- [ ] This doesn't reproduce on web browsers (such as in Chrome). If it does, [issue reports go to the Mattermost Server repository](https://github.com/mattermost/platform/issues).
- [ ] I have read [contributing guidelines](https://github.com/mattermost/desktop/blob/master/CONTRIBUTING.md).

---

**Summary**
<!--
Issue in one concise sentence.
-->

**Environment**
- Operating System:
- Mattermost Desktop App version: X.X.X <!-- See [Help] > [Version Number] -->
- Mattermost Server version: X.X.X <!-- See [Mattermost Menu] > [About Mattermost], where [Mattermost Menu] can be accessed by clicking on three dots next to your profile picture -->

**Steps to reproduce**

**Expected behavior**

**Observed behavior**

<!--
Please include relevant error messages and/or screenshots.
-->

**Possible fixes**

<!--
If you can, link to the line of code that might be responsible for the problem.
-->

redpajama_set_name: RedPajamaGithub


text:
using content::BrowserThread;

namespace drive {

namespace {

// OAuth2 scopes for Drive API.
const char kDriveScope[] = "https://www.googleapis.com/auth/drive";
const char kDriveAppsReadonlyScope[] =
    "https://www.googleapis.com/auth/drive.apps.readonly";

// Parses the JSON value into ResourceList and runs |callback|.
void ParseResourceListAndRun(
    const google_apis::GetResourceListCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<base::Value> value) {
  if (!value) {
    callback.Run(error, scoped_ptr<google_apis::ResourceList>());
    return;
  }

  // TODO(satorux): Parse the JSON value on a blocking pool. crbug.com/165088
  scoped_ptr<google_apis::ChangeList> change_list(
      google_apis::ChangeList::CreateFrom(*value));
  if (!change_list) {
    callback.Run(google_apis::GDATA_PARSE_ERROR,
                 scoped_ptr<google_apis::ResourceList>());
    return;
  }

  // TODO(satorux): Do the conversion on a blocking pool too. crbug.com/165088
  scoped_ptr<google_apis::ResourceList> resource_list =
      google_apis::ResourceList::CreateFromChangeList(*change_list);
  if (!resource_list) {
    callback.Run(google_apis::GDATA_PARSE_ERROR,
                 scoped_ptr<google_apis::ResourceList>());
    return;
  }

  callback.Run(error, resource_list.Pass());
}

// Parses the JSON value to ResourceEntry runs |callback|.
void ParseResourceEntryAndRun(
    const google_apis::GetResourceEntryCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<base::Value> value) {
  DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (!value) {
    callback.Run(error, scoped_ptr<google_apis::ResourceEntry>());
    return;
  }

  // Parsing FileResource is cheap enough to do on UI thread.
  scoped_ptr<google_apis::FileResource> file_resource =
      google_apis::FileResource::CreateFrom(*value);
  if (!file_resource) {
    callback.Run(google_apis::GDATA_PARSE_ERROR,
                 scoped_ptr<google_apis::ResourceEntry>());
    return;
  }

  // Converting to ResourceEntry is cheap enough to do on UI thread.
  scoped_ptr<google_apis::ResourceEntry> entry =
      google_apis::ResourceEntry::CreateFromFileResource(*file_resource);
  if (!entry) {
    callback.Run(google_apis::GDATA_PARSE_ERROR,
                 scoped_ptr<google_apis::ResourceEntry>());
    return;
  }

  callback.Run(error, entry.Pass());
}

// Parses the JSON value to AccountMetadataFeed on the blocking pool and runs
// |callback| on the UI thread once parsing is done.
void ParseAccounetMetadataAndRun(
    const google_apis::GetAccountMetadataCallback& callback,
    google_apis::GDataErrorCode error,
    scoped_ptr<base::Value> value) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (!value) {
    callback.Run(error, scoped_ptr<google_apis::AccountMetadataFeed>());
    return;
  }

  // Parsing AboutResource is cheap enough to do on UI thread.
  scoped_ptr<google_apis::AboutResource> about_resource =
      google_apis::AboutResource::CreateFrom(*value);

  // TODO(satorux): Convert AboutResource to AccountMetadataFeed.
  // For now just returning an error. crbug.com/165621
  callback.Run(google_apis::GDATA_PARSE_ERROR,
               scoped_ptr<google_apis::AccountMetadataFeed>());
}

}  // namespace

DriveAPIService::DriveAPIService(
    net::URLRequestContextGetter* url_request_context_getter,
    const std::string& custom_user_agent)
    : url_request_context_getter_(url_request_context_getter),
      profile_(NULL),
      runner_(NULL),
      custom_user_agent_(custom_user_agent) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

DriveAPIService::~DriveAPIService() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (runner_.get()) {
    runner_->operation_registry()->RemoveObserver(this);
    runner_->auth_service()->RemoveObserver(this);
  }
}

void DriveAPIService::Initialize(Profile* profile) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  profile_ = profile;

  std::vector<std::string> scopes;
  scopes.push_back(kDriveScope);
  scopes.push_back(kDriveAppsReadonlyScope);
  runner_.reset(
      new google_apis::OperationRunner(profile,
                                       url_request_context_getter_,
                                       scopes,
                                       custom_user_agent_));
  runner_->Initialize();

  runner_->auth_service()->AddObserver(this);
  runner_->operation_registry()->AddObserver(this);
}

void DriveAPIService::AddObserver(google_apis::DriveServiceObserver* observer) {
  observers_.AddObserver(observer);
}

void DriveAPIService::RemoveObserver(
    google_apis::DriveServiceObserver* observer) {
  observers_.RemoveObserver(observer);
}

bool DriveAPIService::CanStartOperation() const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  return HasRefreshToken();
}

void DriveAPIService::CancelAll() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  runner_->CancelAll();
}

bool DriveAPIService::CancelForFilePath(const FilePath& file_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  return operation_registry()->CancelForFilePath(file_path);
}

google_apis::OperationProgressStatusList
DriveAPIService::GetProgressStatusList() const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  return operation_registry()->GetProgressStatusList();
}

void DriveAPIService::GetResourceList(
    const GURL& url,
    int64 start_changestamp,
    const std::string& search_query,
    bool shared_with_me,
    const std::string& directory_resource_id,
    const google_apis::GetResourceListCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  if (search_query.empty())
    GetChangelist(url, start_changestamp, callback);
  else
    GetFilelist(url, search_query, callback);

  return;
  // TODO(kochi): Implement !directory_resource_id.empty() case.
  NOTREACHED();
}

void DriveAPIService::GetFilelist(
    const GURL& url,
    const std::string& search_query,
    const google_apis::GetResourceListCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  runner_->StartOperationWithRetry(
      new google_apis::GetFilelistOperation(
          operation_registry(),
          url_request_context_getter_,
          url,
          search_query,
          base::Bind(&ParseResourceListAndRun, callback)));
}

void DriveAPIService::GetChangelist(
    const GURL& url,
    int64 start_changestamp,
    const google_apis::GetResourceListCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  runner_->StartOperationWithRetry(
      new google_apis::GetChangelistOperation(
          operation_registry(),
          url_request_context_getter_,
          url,
          start_changestamp,
          base::Bind(&ParseResourceListAndRun, callback)));
}

void DriveAPIService::GetResourceEntry(
    const std::string& resource_id,
    const google_apis::GetResourceEntryCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  runner_->StartOperationWithRetry(new google_apis::GetFileOperation(
      operation_registry(),
      url_request_context_getter_,
      resource_id,
      base::Bind(&ParseResourceEntryAndRun, callback)));
}

void DriveAPIService::GetAccountMetadata(
    const google_apis::GetAccountMetadataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  runner_->StartOperationWithRetry(
      new google_apis::GetAboutOperation(
          operation_registry(),
          url_request_context_getter_,
          base::Bind(&ParseAccounetMetadataAndRun, callback)));
}

void DriveAPIService::GetApplicationInfo(
    const google_apis::GetDataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  runner_->StartOperationWithRetry(
      new google_apis::GetApplistOperation(operation_registry(),
                                           url_request_context_getter_,
                                           callback));
}

void DriveAPIService::DownloadHostedDocument(
    const FilePath& virtual_path,
    const FilePath& local_cache_path,
    const GURL& content_url,
    google_apis::DocumentExportFormat format,
    const google_apis::DownloadActionCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::DownloadFile(
      const FilePath& virtual_path,
      const FilePath& local_cache_path,
      const GURL& content_url,
      const google_apis::DownloadActionCallback& download_action_callback,
      const google_apis::GetContentCallback& get_content_callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!download_action_callback.is_null());
  // get_content_callback may be null.

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::DeleteResource(
    const GURL& edit_url,
    const google_apis::EntryActionCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::AddNewDirectory(
    const GURL& parent_content_url,
    const FilePath::StringType& directory_name,
    const google_apis::GetResourceEntryCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::CopyHostedDocument(
    const std::string& resource_id,
    const FilePath::StringType& new_name,
    const google_apis::GetResourceEntryCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::RenameResource(
    const GURL& edit_url,
    const FilePath::StringType& new_name,
    const google_apis::EntryActionCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::AddResourceToDirectory(
    const GURL& parent_content_url,
    const GURL& edit_url,
    const google_apis::EntryActionCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::RemoveResourceFromDirectory(
    const GURL& parent_content_url,
    const std::string& resource_id,
    const google_apis::EntryActionCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::InitiateUpload(
    const google_apis::InitiateUploadParams& params,
    const google_apis::InitiateUploadCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::ResumeUpload(
    const google_apis::ResumeUploadParams& params,
    const google_apis::ResumeUploadCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::AuthorizeApp(
    const GURL& edit_url,
    const std::string& app_ids,
    const google_apis::AuthorizeAppCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // TODO(kochi): Implement this.
  NOTREACHED();
}

bool DriveAPIService::HasAccessToken() const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  return runner_->auth_service()->HasAccessToken();
}

bool DriveAPIService::HasRefreshToken() const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  return runner_->auth_service()->HasRefreshToken();
}

google_apis::OperationRegistry* DriveAPIService::operation_registry() const {
  return runner_->operation_registry();
}

void DriveAPIService::OnOAuth2RefreshTokenChanged() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (CanStartOperation()) {
    FOR_EACH_OBSERVER(
        google_apis::DriveServiceObserver, observers_,
        OnReadyToPerformOperations());
  }
}

void DriveAPIService::OnProgressUpdate(
    const google_apis::OperationProgressStatusList& list) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  FOR_EACH_OBSERVER(
      google_apis::DriveServiceObserver, observers_, OnProgressUpdate(list));
}

void DriveAPIService::OnAuthenticationFailed(
    google_apis::GDataErrorCode error) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  FOR_EACH_OBSERVER(
      google_apis::DriveServiceObserver, observers_,
      OnAuthenticationFailed(error));
}

}  // namespace drive


text:
package domain;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

/**
 * Review containing a rating, the profile of the user who sent it, and who is receiving
 * it and an optional message that the sender can add to the review
 */
@DatabaseTable
public class Review {

		@DatabaseField
		private Integer rating;

		private Profile profileTarget;

		private Profile profileOrigin;

		@DatabaseField
		private String comment;

		@DatabaseField(generatedId = true)
		private Integer id;

		public Review(){
		}

		/**
		 * New review only containig who created the review and who its destined for,
		 * in other word, an empty review(it doesnt contain a rating or a comment)
		 * @param profile_orgin
		 * @param profileTarget
		 */
		public Review(Profile profile_orgin, Profile profileTarget) {
			this.profileOrigin = profile_orgin;
			this.profileTarget = profileTarget;
		}

		/**
		 * @param rec reciever of the review, profile that is being reviewed
		 * @param send sender of the review, profile that is making the review
		 * @param msg description contained in the review, the senders opinion on the reciever
		 * @param rat rating, whole number from 0 to 5 representing the overall opinion on the reciever
		 */
		public Review(Profile rec, Profile send, String msg, Integer rat){
			setRating(rat);
			this.profileTarget = rec;
			this.profileOrigin = send;
			this.comment = msg;
		}

		/**
		 * @return the reviews rating
		 */
		public Integer getRating() {
			return rating;
		}

		/**
		 * @param rating
		 * @throws IllegalArgumentException when the rating being set is not a value between 0 and 5
		 */
		private void setRating(Integer rating) throws IllegalArgumentException {
			if(rating >= 0 && rating <= 5){
				this.rating = rating;
			}else{
				throw new IllegalArgumentException("The rating must be a number between 0 and 5");
			}
		}

		/**
		 * @return the review's comment
		 */
		public String getComment()
		{
			return this.comment;
		}

		/**
		 * @return the user the review is targeted to
		 */
		public Profile getprofileTarget() {
			return profileTarget;
		}

		/**
		 * @return the user that is sending the review
		 */
		public Profile getprofileOrigin() {
			return profileOrigin;
		}

		public Integer getId() {
			return id;
		}

		public Profile getProfileTarget() {
			return profileTarget;
		}

		public void setProfileTarget(Profile profileTarget) {
			this.profileTarget = profileTarget;
		}

		public Profile getProfileOrigin() {
			return profileOrigin;
		}

		public void setProfileOrigin(Profile profileOrigin) {
			this.profileOrigin = profileOrigin;
		}
}


text:
package com.craftmend.openaudiomc.generic.commands.interfaces;

public interface CommandMiddleware {

    boolean continueCommand(GenericExecutor genericExecutor, SubCommand subCommand);

}


text:
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { loadUser, loadStarred } from '../actions'
import User from '../components/User'
import Repo from '../components/Repo'
import List from '../components/List'
import zip from 'lodash/zip'

function loadData(props) {
  const { login } = props
  props.loadUser(login, [ 'name' ])
  props.loadStarred(login)
}

class UserPage extends Component {
  constructor(props) {
    super(props)
    this.renderRepo = this.renderRepo.bind(this)
    this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this)
  }

  componentWillMount() {
    loadData(this.props)
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.login !== this.props.login) {
      loadData(nextProps)
    }
  }

  handleLoadMoreClick() {
    this.props.loadStarred(this.props.login, true)
  }

  renderRepo([ repo, owner ]) {
    return (
      <Repo repo={repo}
            owner={owner}
            key={repo.fullName} />
    )
  }

  render() {
    const { user, login } = this.props
    if (!user) {
      return
Loading {login}'s profile...

    }

    const { starredRepos, starredRepoOwners, starredPagination } = this.props
    return (

        <User user={user} />

        <List renderItem={this.renderRepo}
              items={zip(starredRepos, starredRepoOwners)}
              onLoadMoreClick={this.handleLoadMoreClick}
              loadingLabel={`Loading ${login}'s starred...`}
              {...starredPagination} />

    )
  }
}

UserPage.propTypes = {
  login: PropTypes.string.isRequired,
  user: PropTypes.object,
  starredPagination: PropTypes.object,
  starredRepos: PropTypes.array.isRequired,
  starredRepoOwners: PropTypes.array.isRequired,
  loadUser: PropTypes.func.isRequired,
  loadStarred: PropTypes.func.isRequired
}

function mapStateToProps(state, props) {
  const { login } = props.params
  const {
    pagination: { starredByUser },
    entities: { users, repos }
  } = state

  const starredPagination = starredByUser[login] || { ids: [] }
  const starredRepos = starredPagination.ids.map(id => repos[id])
  const starredRepoOwners = starredRepos.map(repo => users[repo.owner])

  return {
    login,
    starredRepos,
    starredRepoOwners,
    starredPagination,
    user: users[login]
  }
}

export default connect(mapStateToProps, {
  loadUser,
  loadStarred
})(UserPage)


text:
<?php

/* TwigBundle:Exception:error.rdf.twig */
class __TwigTemplate_04e5a06cd75365e923ef1715ae7ab22d542163e8577b5831d239022cfc2f573d extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        $this->env->loadTemplate("TwigBundle:Exception:error.xml.twig")->display($context);
    }

    public function getTemplateName()
    {
        return "TwigBundle:Exception:error.rdf.twig";
    }

    public function getDebugInfo()
    {
        return array (  19 => 1,);
    }
}


text:
package com.example.whatTravel.Models.wiki;

import com.example.whatTravel.API.WTAPIConstants;
import com.example.whatTravel.Models.WTApiQueries;

/**
 * Created by dlu on 4/12/15.
 */
public class WikiPageSearch extends WTApiQueries {
    public static final String ACTION_PARAM = "action";
    public static final String FORMAT_PARAM = "format";
    public static final String PROP_PARAM = "prop";
    public static final String INPROP_PARAM = "inprop";
    public static final String PAGEIDS_PARAM = "pageids";

    public WikiPageSearch() {
        super();
    }

    @Override
    protected String getBaseApiUrl() {
        return WTAPIConstants.WIKI_BASE_API;
    }

    @Override
    protected String getHttpScheme() {
        return WTAPIConstants.HTTP;
    }

    public void setAction(String query)
    {
        params.put(ACTION_PARAM, query);
    }

    public void setFormat(String format)
    {
        params.put(FORMAT_PARAM, format);
    }

    public void setProp(String prop)
    {
        params.put(PROP_PARAM, prop);
    }

    public void setInprop(String inprop)
    {
        params.put(INPROP_PARAM, inprop);
    }

    public void setPageIds(int pageIds)
    {
        params.put(PAGEIDS_PARAM, String.valueOf(pageIds));
    }
}


text:
package com.swe.zz_deprecated;

import com.jme3.app.Application;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;

public class EditorMenuItems extends DeprecatedSwing {

   public EditorMenuItems() {

    }

    protected void menuButtonz() {

        final JMenuItem itemOpen = new JMenuItem("Open");
        menuTortureMethods.add(itemOpen);
        itemOpen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

            }
        });
        final JMenuItem itemSave = new JMenuItem("Save");
        menuTortureMethods.add(itemSave);
        itemSave.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

            }
        });

        final JMenuItem itemExit = new JMenuItem("Exit");
        menuTortureMethods.add(itemExit);
        itemExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                frame.dispose();
                app.stop();
            }
        });

//        JButton loadDiffuseButton = new JButton("Load Diffuse Texture");
//        loadDiffuseButton.setSize(200, 20);
//        loadDiffuseButton.setPreferredSize(new Dimension(190, 20));
//        loadDiffuseButton.setVerticalTextPosition(AbstractButton.CENTER);
//        loadDiffuseButton.setHorizontalTextPosition(AbstractButton.LEADING);
//        loadDiffuseButton.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//              if (((BBSceneGrid)app).selectedEntity != null && strLst.size() > 0) loadDiffuseTexture();
//
//
//            }
//        });
//        optionPanel.add(loadDiffuseButton);
//
//        JButton loadNormalButton = new JButton("Load Normal Texture");
//        loadNormalButton.setSize(200, 20);
//        loadNormalButton.setPreferredSize(new Dimension(190, 20));
//        loadNormalButton.setVerticalTextPosition(AbstractButton.CENTER);
//        loadNormalButton.setHorizontalTextPosition(AbstractButton.LEADING);
//        loadNormalButton.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//              if (((BBSceneGrid)app).selectedEntity != null && strLst.size() > 0) loadNormalTexture();
//            }
//        });
//        optionPanel.add(loadNormalButton);
//
//        optionPanel.add(new JToolBar.Separator());
//
//
//        JButton RemoveSelectedModel = new JButton("Remove Selected Model");
//        RemoveSelectedModel.setSize(200, 20);
//        RemoveSelectedModel.setPreferredSize(new Dimension(190, 20));
//        RemoveSelectedModel.setVerticalTextPosition(AbstractButton.CENTER);
//        RemoveSelectedModel.setHorizontalTextPosition(AbstractButton.LEADING);
//        RemoveSelectedModel.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//
//
//                if (((BBSceneGrid)app).selectedEntity != null || listEntity.getSelectedValue() != null){
//                modelGeo.clear();
//                listGeo.repaint();
//
//                modelEntity.removeElement(((BBSceneGrid)app).selectedEntity);
//                listEntity.repaint();
//
//                ((BBSceneGrid)app).RemoveSelectedEntity();
//              }
//            }
//        });
//        optionPanel.add(RemoveSelectedModel);
//
//        JButton clearScene = new JButton("Clear Scene");
//        clearScene.setSize(200, 20);
//        clearScene.setPreferredSize(new Dimension(190, 20));
//        clearScene.setVerticalTextPosition(AbstractButton.CENTER);
//        clearScene.setHorizontalTextPosition(AbstractButton.LEADING);
//        clearScene.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//                ((BBSceneGrid)app).ClearScene();
//                modelEntity.clear();
//                listEntity.repaint();
//                modelGeo.clear();
//                listGeo.repaint();
//            }
//        });
//        optionPanel.add(clearScene);
//
//
//        optionPanel.add(new JToolBar.Separator());
//
//
//
//        JButton Nor_Inv_X = new JButton("Normal InvertX");
//        Nor_Inv_X.setSize(200, 20);
//        Nor_Inv_X.setPreferredSize(new Dimension(190, 20));
//        Nor_Inv_X.setVerticalTextPosition(AbstractButton.CENTER);
//        Nor_Inv_X.setHorizontalTextPosition(AbstractButton.LEADING);
//        Nor_Inv_X.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//                if (((BBSceneGrid)app).selectedEntity != null && strLst.size() > 0)
//                    ((BBSceneGrid)app).setShaderParam("Nor_Inv_X", strLst);
//            }
//        });
//        optionPanel.add(Nor_Inv_X);
//
//        JButton Nor_Inv_Y = new JButton("Normal InvertY");
//        Nor_Inv_Y.setSize(200, 20);
//        Nor_Inv_Y.setPreferredSize(new Dimension(190, 20));
//        Nor_Inv_Y.setVerticalTextPosition(AbstractButton.CENTER);
//        Nor_Inv_Y.setHorizontalTextPosition(AbstractButton.LEADING);
//        Nor_Inv_Y.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//                if (((BBSceneGrid)app).selectedEntity != null && strLst.size() > 0)
//                    ((BBSceneGrid)app).setShaderParam("Nor_Inv_Y", strLst);
//            }
//        });
//        optionPanel.add(Nor_Inv_Y);
//
//        JButton Alpha_A_Dif = new JButton("Alpha Diffuse");
//        Alpha_A_Dif.setSize(200, 20);
//        Alpha_A_Dif.setPreferredSize(new Dimension(190, 20));
//        Alpha_A_Dif.setVerticalTextPosition(AbstractButton.CENTER);
//        Alpha_A_Dif.setHorizontalTextPosition(AbstractButton.LEADING);
//        Alpha_A_Dif.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//                if (((BBSceneGrid)app).selectedEntity != null && strLst.size() > 0)
//                    ((BBSceneGrid)app).setShaderParam("Alpha_A_Dif", strLst);
//            }
//        });
//        optionPanel.add(Alpha_A_Dif);
//
//        JButton EmissiveMap = new JButton("Emissive Alpha Diffuse");
//        EmissiveMap.setSize(200, 20);
//        EmissiveMap.setPreferredSize(new Dimension(190, 20));
//        EmissiveMap.setVerticalTextPosition(AbstractButton.CENTER);
//        EmissiveMap.setHorizontalTextPosition(AbstractButton.LEADING);
//        EmissiveMap.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//                if (((BBSceneGrid)app).selectedEntity != null && strLst.size() > 0)
//                    ((BBSceneGrid)app).setShaderParam("EmissiveMap", strLst);
//            }
//        });
//        optionPanel.add(EmissiveMap);
//
//        JButton Spec_A_Nor = new JButton("Specular Normal");
//        Spec_A_Nor.setSize(200, 20);
//        Spec_A_Nor.setPreferredSize(new Dimension(190, 20));
//        Spec_A_Nor.setVerticalTextPosition(AbstractButton.CENTER);
//        Spec_A_Nor.setHorizontalTextPosition(AbstractButton.LEADING);
//        Spec_A_Nor.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//                if (((BBSceneGrid)app).selectedEntity != null && strLst.size() > 0)
//                    ((BBSceneGrid)app).setShaderParam("Spec_A_Nor", strLst);
//            }
//        });
//        optionPanel.add(Spec_A_Nor);
//
//        JButton Spec_A_Dif = new JButton("Specular Diffuse");
//        Spec_A_Dif.setSize(200, 20);
//        Spec_A_Dif.setPreferredSize(new Dimension(190, 20));
//        Spec_A_Dif.setVerticalTextPosition(AbstractButton.CENTER);
//        Spec_A_Dif.setHorizontalTextPosition(AbstractButton.LEADING);
//        Spec_A_Dif.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//                if (((BBSceneGrid)app).selectedEntity != null && strLst.size() > 0)
//                    ((BBSceneGrid)app).setShaderParam("Spec_A_Dif", strLst);
//            }
//        });
//        optionPanel.add(Spec_A_Dif);

    }

    protected void panelButtonz(Container cnt){

        JButton loadModelButton = new JButton("Load Model");
        loadModelButton.setSize(200, 20);
        loadModelButton.setPreferredSize(new Dimension(190, 20));
        loadModelButton.setVerticalTextPosition(AbstractButton.CENTER);
        loadModelButton.setHorizontalTextPosition(AbstractButton.LEADING);
        loadModelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
//                loadModelFromFile();

            }
        });
        cnt.add(loadModelButton);

//                JMenuItem loadModelButton = new JMenuItem("Load Model");
//        cnt.add(loadModelButton);
//        loadModelButton.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
////                    loadModelFromFile();
//            }
//        });

    }

//    private void loadModelFromFile(){
//        mFileCm.setFileFilter(modFilter);
//        int returnVal = mFileCm.showOpenDialog(null);
//
//        if (returnVal == JFileChooser.APPROVE_OPTION) {
//            File file = mFileCm.getSelectedFile();
////            try{
////                mLogArea.append("Loading file : " + file.getCanonicalPath() +"\n");
////                ((BBSceneGrid)app).loadExternalModel(file.getName(), file.getParent());
////
////                //Load Entity list
////
////                modelEntity.addElement(((BBSceneGrid)app).selectedEntity);
////                listEntity.repaint();
////                // Load Geometries list
////                modelGeo.clear();
////
////                for (int i=0; i<BBWorldManager.getInstance().getEntity(((BBSceneGrid)app).selectedEntity).getAllGeometries().toArray().length; i++) {
////                    Geometry geo = BBWorldManager.getInstance().getEntity(((BBSceneGrid)app).selectedEntity).getAllGeometries().get(i);
////                    geo.setUserData("Model", file.getName());
////                    modelGeo.add(i, geo.getName());
////                    }
////
////                listGeo.repaint();
////                strLst.clear();
////
////            }catch (IOException ex){}
//
//        }
//
//        mFileCm.setSelectedFile(null);
//    }

//    private void loadDiffuseTexture(){
//        mFileCm.setFileFilter(texFilter);
//        int returnVal = mFileCm.showOpenDialog(null);
//
//        if (returnVal == JFileChooser.APPROVE_OPTION) {
//            File file = mFileCm.getSelectedFile();
////            mFileCt.setCurrentDirectory(file);
//            try{
//                mLogArea.append("Loading file : " + file.getCanonicalPath() +"\n");
//
//                if (strLst.size() > 0 && ((BBSceneGrid)app).selectedEntity != null) {
//
//                ((BBSceneGrid)app).loadTexture("DiffuseMap", file.getName(), file.getParent(), strLst);
//                }
//            }catch (IOException ex){}
//        }
//
//        mFileCm.setSelectedFile(null);
//    }
//
//    private void loadNormalTexture(){
//        mFileCm.setFileFilter(texFilter);
//        int returnVal = mFileCm.showOpenDialog(null);
//
//        if (returnVal == JFileChooser.APPROVE_OPTION) {
//            File file = mFileCm.getSelectedFile();
////            mFileCt.setCurrentDirectory(file);
//            try{
//                mLogArea.append("Loading file : " + file.getCanonicalPath() +"\n");
//
//
//                if (strLst.size() > 0 && ((BBSceneGrid)app).selectedEntity != null) {
//
//                ((BBSceneGrid)app).loadTexture("NormalMap", file.getName(), file.getParent(), strLst);
//
//                }
//            }catch (IOException ex){}
//        }
//
//        mFileCm.setSelectedFile(null);
//    }

}


text:
package com.amazonaws.services.amplify.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Result structure for run job request.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StartJobResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * Summary for the Job.
     *

     */
    private JobSummary jobSummary;

    /**
     *

     * Summary for the Job.
     *

     *
     * @param jobSummary
     *        Summary for the Job.
     */

    public void setJobSummary(JobSummary jobSummary) {
        this.jobSummary = jobSummary;
    }

    /**
     *

     * Summary for the Job.
     *

     *
     * @return Summary for the Job.
     */

    public JobSummary getJobSummary() {
        return this.jobSummary;
    }

    /**
     *

     * Summary for the Job.
     *

     *
     * @param jobSummary
     *        Summary for the Job.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartJobResult withJobSummary(JobSummary jobSummary) {
        setJobSummary(jobSummary);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getJobSummary() != null)
            sb.append("JobSummary: ").append(getJobSummary());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof StartJobResult == false)
            return false;
        StartJobResult other = (StartJobResult) obj;
        if (other.getJobSummary() == null ^ this.getJobSummary() == null)
            return false;
        if (other.getJobSummary() != null && other.getJobSummary().equals(this.getJobSummary()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getJobSummary() == null) ? 0 : getJobSummary().hashCode());
        return hashCode;
    }

    @Override
    public StartJobResult clone() {
        try {
            return (StartJobResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
/**
 *

 * This package contains the annotations used for MicroProfile Metrics.
 *
 *
Metric Annotation

 *

 * The {@link org.eclipse.microprofile.metrics.annotation.Metric Metric}
 * annotation is used to provide metadata for the metric being injected. If a
 * metric with the same name exists in the
 * {@link org.eclipse.microprofile.metrics.MetricRegistry MetricRegistry}, the
 * metric is returned. Otherwise, a new metric is registered into the
 * MetricRegistry along with the metadata provided by the {@literal @}Metric
 * annotation.
 *

 * For example,
 *
 *

 *
 *     {@literal @}Inject
 *     {@literal @}Metric(name="histogram", description="The description")
 *     public Histogram histogram;
 *
 *

 *
 *
Interceptor Bindings

 *

 * MicroProfile Metrics provides four interceptor bindings which can be used to
 * instrument an application: {@literal @}Counted, {@literal @}Gauge,
 * {@literal @}Metered, {@literal @}Timed.
 *

 * An example using {@literal @}Counted,
 *
 *

 *
 *     {@literal @}Counted (name="visitorCount",
 *         description="The number of visitors to the application")
 *     public void visit () {
 *         ...
 *     }
 *
 *

 *

 * An example using {@literal @}Gauge,
 *
 *

 *
 *     {@literal @}Gauge(name = "queueSize")
 *     public int getQueueSize() {
 *         return queue.size;
 *     }
 *
 *

 *
 *
 *
CDI Qualifier

 *

 * The {@link org.eclipse.microprofile.metrics.annotation.RegistryType
 * RegistryType} is used to identify which MetricRegistry (Application, Base, or
 * Vendor) should be injected. By default, no RegistryType will
 * inject the application MetricRegistry.
 *
 *

 *
 *      {@literal @}Inject
 *      {@literal @}RegistryType(type=MetricRegistry.Type.BASE)
 *      MetricRegistry baseRegistry;
 *
 *

 *
 */
@org.osgi.annotation.versioning.Version("2.0")
@org.osgi.annotation.versioning.ProviderType
package org.eclipse.microprofile.metrics.annotation;


text:
package gov.nih.nci.cabig.caaers.domain;

import gov.nih.nci.cabig.caaers.resolver.RemoteStudyResolver;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Transient;

import com.semanticbits.coppa.domain.annotations.RemoteEntity;
import com.semanticbits.coppa.domain.annotations.RemoteProperty;
import com.semanticbits.coppa.domain.annotations.RemoteUniqueId;

/**
 * The Class RemoteStudy.
 *
 * @author Monish Dombla
 */

@Entity
@RemoteEntity(entityResolver=RemoteStudyResolver.class)
@DiscriminatorValue("REMOTE")
public class RemoteStudy extends Study{

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The investigational new drug list. */
	private List<InvestigationalNewDrug> investigationalNewDrugList = new ArrayList<InvestigationalNewDrug>();

	/* (non-Javadoc)
	 * @see gov.nih.nci.cabig.caaers.domain.Study#getExternalId()
	 */
	@RemoteUniqueId
    @RemoteProperty
    public String getExternalId() {
		return externalId;
	}

	/* (non-Javadoc)
	 * @see gov.nih.nci.cabig.caaers.domain.Study#getShortTitle()
	 */
	@RemoteProperty
    public String getShortTitle() {
        return shortTitle;
    }

	/* (non-Javadoc)
	 * @see gov.nih.nci.cabig.caaers.domain.Study#getLongTitle()
	 */
	@RemoteProperty
    public String getLongTitle() {
        return longTitle;
    }

	/* (non-Javadoc)
	 * @see gov.nih.nci.cabig.caaers.domain.Study#getPhaseCode()
	 */
	@RemoteProperty
    public String getPhaseCode() {
        return phaseCode;
    }

	/* (non-Javadoc)
	 * @see gov.nih.nci.cabig.caaers.domain.Study#getDescription()
	 */
	@RemoteProperty
    public String getDescription() {
        return description;
    }

	/* (non-Javadoc)
	 * @see gov.nih.nci.cabig.caaers.domain.Study#getStatus()
	 */
	@RemoteProperty
    public String getStatus() {
        return status;
    }

	/**
	 * Gets the investigational new drug list.
	 *
	 * @return the investigational new drug list
	 */
	@Transient
	public List<InvestigationalNewDrug> getInvestigationalNewDrugList() {
		return investigationalNewDrugList;
	}

	/**
	 * Sets the investigational new drug list.
	 *
	 * @param investigationalNewDrugList the new investigational new drug list
	 */
	public void setInvestigationalNewDrugList(
			List<InvestigationalNewDrug> investigationalNewDrugList) {
		this.investigationalNewDrugList = investigationalNewDrugList;
	}

	/**
	 * Adds the investigational new drug.
	 *
	 * @param investigationalNewDrug the investigational new drug
	 */
	public void addInvestigationalNewDrug(InvestigationalNewDrug investigationalNewDrug){
		getInvestigationalNewDrugList().add(investigationalNewDrug);
	}
}


text:
using namespace foundation;

namespace dense {

class DepthmapEstimatorWrapper {
 public:
  void AddView(pyarray_d K, pyarray_d R, pyarray_d t, pyarray_uint8 image,
               pyarray_uint8 mask) {
    if ((image.shape(0) != mask.shape(0)) || (image.shape(1) != mask.shape(1))){
      throw std::invalid_argument("image and mask must have matching shapes.");
    }
    de_.AddView(K.data(), R.data(), t.data(), image.data(), mask.data(),
                image.shape(1), image.shape(0));
  }

  void SetDepthRange(double min_depth, double max_depth, int num_depth_planes) {
    de_.SetDepthRange(min_depth, max_depth, num_depth_planes);
  }

  void SetPatchMatchIterations(int n) { de_.SetPatchMatchIterations(n); }

  void SetPatchSize(int size) { de_.SetPatchSize(size); }

  void SetMinPatchSD(float sd) { de_.SetMinPatchSD(sd); }

  py::object ComputePatchMatch() {
    DepthmapEstimatorResult result;
    {
      py::gil_scoped_release release;
      de_.ComputePatchMatch(&result);
    }
    return ComputeReturnValues(result);
  }

  py::object ComputePatchMatchSample() {
    DepthmapEstimatorResult result;
    {
      py::gil_scoped_release release;
      de_.ComputePatchMatchSample(&result);
    }
    return ComputeReturnValues(result);
  }

  py::object ComputeBruteForce() {
    DepthmapEstimatorResult result;
    {
      py::gil_scoped_release release;
      de_.ComputeBruteForce(&result);
    }
    return ComputeReturnValues(result);
  }

  py::object ComputeReturnValues(const DepthmapEstimatorResult &result) {
    py::list retn;
    retn.append(py_array_from_data(result.depth.ptr<float>(0),
                                   result.depth.rows, result.depth.cols));
    retn.append(py_array_from_data(result.plane.ptr<float>(0),
                                   result.plane.rows, result.plane.cols, 3));
    retn.append(py_array_from_data(result.score.ptr<float>(0),
                                   result.score.rows, result.score.cols));
    retn.append(py_array_from_data(result.nghbr.ptr<int>(0), result.nghbr.rows,
                                   result.nghbr.cols));
    return std::move(retn);
  }

 private:
  DepthmapEstimator de_;
};

class DepthmapCleanerWrapper {
 public:
  void SetSameDepthThreshold(float t) { dc_.SetSameDepthThreshold(t); }

  void SetMinConsistentViews(int n) { dc_.SetMinConsistentViews(n); }

  void AddView(pyarray_d K, pyarray_d R, pyarray_d t, pyarray_f depth) {
    dc_.AddView(K.data(), R.data(), t.data(), depth.data(), depth.shape(1),
                depth.shape(0));
  }

  py::object Clean() {
    cv::Mat depth;
    {
      py::gil_scoped_release release;
      dc_.Clean(&depth);
    }
    return py_array_from_data(depth.ptr<float>(0), depth.rows, depth.cols);
  }

 private:
  DepthmapCleaner dc_;
};

class DepthmapPrunerWrapper {
 public:
  void SetSameDepthThreshold(float t) { dp_.SetSameDepthThreshold(t); }

  void AddView(pyarray_d K, pyarray_d R, pyarray_d t, pyarray_f depth,
               pyarray_f plane, pyarray_uint8 color, pyarray_uint8 label) {
    if ((depth.shape(0) != plane.shape(0)) || (depth.shape(1) != plane.shape(1))){
      throw std::invalid_argument("depth and plane must have matching shapes.");
    }
    if ((depth.shape(0) != color.shape(0)) || (depth.shape(1) != color.shape(1))){
      throw std::invalid_argument("depth and color must have matching shapes.");
    }
    if ((depth.shape(0) != label.shape(0)) || (depth.shape(1) != label.shape(1))){
      throw std::invalid_argument("depth and label must have matching shapes.");
    }
    dp_.AddView(K.data(), R.data(), t.data(), depth.data(), plane.data(),
                color.data(), label.data(), depth.shape(1), depth.shape(0));
  }

  py::object Prune() {
    std::vector<float> points;
    std::vector<float> normals;
    std::vector<unsigned char> colors;
    std::vector<unsigned char> labels;

    {
      py::gil_scoped_release release;
      dp_.Prune(&points, &normals, &colors, &labels);
    }

    py::list retn;
    int n = int(points.size()) / 3;
    retn.append(py_array_from_data(&points[0], n, 3));
    retn.append(py_array_from_data(&normals[0], n, 3));
    retn.append(py_array_from_data(&colors[0], n, 3));
    retn.append(py_array_from_data(&labels[0], n));
    return std::move(retn);
  }

 private:
  DepthmapPruner dp_;
};

}  // namespace dense