text:
package org.apache.rocketmq.namesrv;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.Callable;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.rocketmq.common.MQVersion;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.logging.InternalLogger;
import org.apache.rocketmq.logging.InternalLoggerFactory;
import org.apache.rocketmq.common.namesrv.NamesrvConfig;
import org.apache.rocketmq.remoting.netty.NettyServerConfig;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.srvutil.ShutdownHookThread;
import org.slf4j.LoggerFactory;

public class NamesrvStartup {

    private static InternalLogger log;
    private static Properties properties = null;
    private static CommandLine commandLine = null;

    public static void main(String[] args) {
        main0(args);
    }

    public static NamesrvController main0(String[] args) {

        try {
            NamesrvController controller = createNamesrvController(args);
            start(controller);
            String tip = "The Name Server boot success. serializeType=" + RemotingCommand.getSerializeTypeConfigInThisServer();
            log.info(tip);
            System.out.printf("%s%n", tip);
            return controller;
        } catch (Throwable e) {
            e.printStackTrace();
            System.exit(-1);
        }

        return null;
    }

    public static NamesrvController createNamesrvController(String[] args) throws IOException, JoranException {
        System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, Integer.toString(MQVersion.CURRENT_VERSION));
        //PackageConflictDetect.detectFastjson();

        Options options = ServerUtil.buildCommandlineOptions(new Options());
        commandLine = ServerUtil.parseCmdLine("mqnamesrv", args, buildCommandlineOptions(options), new PosixParser());
        if (null == commandLine) {
            System.exit(-1);
            return null;
        }

        final NamesrvConfig namesrvConfig = new NamesrvConfig();
        final NettyServerConfig nettyServerConfig = new NettyServerConfig();
        nettyServerConfig.setListenPort(9876);
        if (commandLine.hasOption('c')) {
            String file = commandLine.getOptionValue('c');
            if (file != null) {
                InputStream in = new BufferedInputStream(new FileInputStream(file));
                properties = new Properties();
                properties.load(in);
                MixAll.properties2Object(properties, namesrvConfig);
                MixAll.properties2Object(properties, nettyServerConfig);

                namesrvConfig.setConfigStorePath(file);

                System.out.printf("load config properties file OK, %s%n", file);
                in.close();
            }
        }

        if (commandLine.hasOption('p')) {
            InternalLogger console = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_CONSOLE_NAME);
            MixAll.printObjectProperties(console, namesrvConfig);
            MixAll.printObjectProperties(console, nettyServerConfig);
            System.exit(0);
        }

        MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), namesrvConfig);

        if (null == namesrvConfig.getRocketmqHome()) {
            System.out.printf("Please set the %s variable in your environment to match the location of the RocketMQ installation%n", MixAll.ROCKETMQ_HOME_ENV);
            System.exit(-2);
        }

        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
        configurator.doConfigure(namesrvConfig.getRocketmqHome() + "/conf/logback_namesrv.xml");

        log = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_LOGGER_NAME);

        MixAll.printObjectProperties(log, namesrvConfig);
        MixAll.printObjectProperties(log, nettyServerConfig);

        final NamesrvController controller = new NamesrvController(namesrvConfig, nettyServerConfig);

        // remember all configs to prevent discard
        controller.getConfiguration().registerConfig(properties);

        return controller;
    }

    public static NamesrvController start(final NamesrvController controller) throws Exception {

        if (null == controller) {
            throw new IllegalArgumentException("NamesrvController is null");
        }

        boolean initResult = controller.initialize();
        if (!initResult) {
            controller.shutdown();
            System.exit(-3);
        }

        Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(log, new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                controller.shutdown();
                return null;
            }
        }));

        controller.start();

        return controller;
    }

    public static void shutdown(final NamesrvController controller) {
        controller.shutdown();
    }

    public static Options buildCommandlineOptions(final Options options) {
        Option opt = new Option("c", "configFile", true, "Name server config properties file");
        opt.setRequired(false);
        options.addOption(opt);

        opt = new Option("p", "printConfigItem", false, "Print all config item");
        opt.setRequired(false);
        options.addOption(opt);

        return options;
    }

    public static Properties getProperties() {
        return properties;
    }
}

redpajama_set_name: RedPajamaGithub


text:
var     mongoose = require('mongoose'),
        moment = require('moment'),
        shortid = require('shortid'),
        fs = require('fs'),
        bcrypt = require('bcryptjs'),
        files = require('./files');

//setup mongodb
//mongoose.connect('mongodb://localhost/iacio');
mongoose.connect('mongodb://localhost/discuss');
//define models

var UserSchema = mongoose.Schema;
var User = require('./models/user.js').make(UserSchema, mongoose, bcrypt);
var ItemSchema = mongoose.Schema;
var Item = require('./models/item.js').make(ItemSchema, mongoose);
var MessageSchema = mongoose.Schema;
var Message = require('./models/message.js').make(MessageSchema, mongoose);
var SectionSchema = mongoose.Schema;
var Section = require('./models/section.js').make(SectionSchema, mongoose);
var EpisodeSchema = mongoose.Schema;
var Episode = require('./models/episode.js').make(EpisodeSchema, mongoose);

var firsts = {};

module.exports = {
    do_fixes: do_fixes,
    reset_all: reset_all,
    get_firsts: get_firsts,
    create_from_template: create_from_template,
    create_episode_from_template: create_episode_from_template,
    add_user: add_user,
    oauth_user: oauth_user,
    validate_user_by_token: validate_user_by_token,
    validate_user: validate_user,
    get_users: get_users,
    get_user: get_user,
    get_user_by_email: get_user_by_email,
    get_touch_episode: get_touch_episode,
    touch_episode: touch_episode,
    create_episode: create_episode,
    update_episode: update_episode,
    get_episode: get_episode,
    add_member_episode: add_member_episode,
    remove_member_episode: remove_member_episode,
    set_members_episode: set_members_episode,
    get_episodes: get_episodes,
    get_member_episodes: get_member_episodes,
    delete_episode: delete_episode,
    create_section: create_section,
    get_sections: get_sections,
    get_section: get_section,
    add_message: add_message,
    get_messages: get_messages,
    promote_message: promote_message,
    add_item: add_item,
    get_item: get_item,
    get_items: get_items,
    get_items_for_stage: get_items_for_stage,
    get_item_archive: get_item_archive,
    get_item_grouped: get_item_grouped,
    get_item_annotations: get_item_annotations,
    update_item_content: update_item_content,
    update_item_group: update_item_group,
    update_item_annotate: update_item_annotate,
    update_item_label: update_item_label,
    update_item_pos: update_item_pos,
    update_item_links: update_item_links,
    update_item_section_id: update_item_section_id,
    update_item: update_item,
    mark_deleted_item: mark_deleted_item,
    delete_item: delete_item,
    duplicate_item: duplicate_item
};

//---------------- messy rest and initial setup --------------------------//
var cleardata = -1;
function reset_all(start){
    if(start){
        cleardata = 4;
        console.log('clearing: '+cleardata);
        Episode.find({}).remove().exec(function(){--cleardata; console.log('clearing: '+cleardata);});
        Section.find({}).remove().exec(function(){--cleardata; console.log('clearing: '+cleardata);});
        Message.find({}).remove().exec(function(){--cleardata; console.log('clearing: '+cleardata);});
        Item.find({}).remove().exec(function(){--cleardata; console.log('clearing: '+cleardata);});
    }
    if(cleardata > 0){
        setTimeout(reset_all, 100);
    }else if(cleardata === 0){
        cleardata = -1;
        create_from_template(true,'PI', 'Progressive Inquiry', 'Raymond');
    }
}

function create_users(){
    //create initial accounts from ./node/data/users.json
    User.count({}, function(err, usercnt){
        console.log("usercount: "+usercnt);
        if(usercnt === 0){
            var userfile = './node/data/users.json';
            fs.stat(userfile, function(err, stat) {
                if(err == null) {
                    var users = JSON.parse(fs.readFileSync(userfile, "utf8"));
                    var count = users.length;
                    for(var i = 0; i < count; i++){
                        add_user(users[i]);
                    }
                    console.log("users creared: "+count);

                }else{
                    console.log('users.json not found: '+userfile);
                }
            });

        }

    });

}

function fix_messages(){
//    Message.find({}).exec(function(err, messages){
//        console.log(err, messages);
//        var fs = '';
//        var slugparts = [];
//        var subslugparts = [];
//        var timeparts = [];
//        if(messages){
//            for(var i = 0; i < messages.length; i++){
//
//                fs = messages[i].full_slug;
//                slugparts = fs.split('/');
//                for(var j = 0; j < slugparts.length; j++){
//                    subslugparts = slugparts[j].split(':');
//                    timeparts = subslugparts[0].split('.');
//                    for(var k = 0; k < timeparts.length; k++){
//                        if(timeparts[k].length == 1) timeparts[k] = '0'+timeparts[k];
//                    }
//                    subslugparts[0] = timeparts.join('.');
//                    slugparts[j] = subslugparts.join(':');
//                }
//                fs = slugparts.join('/');
//                messages[i].full_slug = fs;
//                console.log(i, fs);
//
//                messages[i].save();
//            }
//        }
//    });

//    Section.find({}).exec(function(err, sections){
//        var sec2epi = {};
//
//        for(var i = 0; i < sections.length; i++){
//            sec2epi[sections[i]._id] = sections[i].episode_id;
//        }
//
//        Message.find({episode_id: null}).exec(function(err, messages){
//            if(messages){
//                for(var i = 0; i < messages.length; i++){
//                    messages[i].episode_id = sec2epi[messages[i].section_id];
//                    messages[i].save();
//                }
//            }
//        });
//
//
//    });
}

function do_fixes(){
    create_users();
    fix_messages();
}

function get_firsts(){
    return firsts;
}

////////////START TEMPLATE CREATE/////////////////////////////////////////////

var template, model;
function create_episode_from_template(setmodel, settings, username, user_slug, callback){
    model = setmodel || 'PI';
    template = JSON.parse(fs.readFileSync('./node/data/'+model+'_template.json', "utf8"));
    template.username = username;
    template.user_slug = user_slug;
//    var template_stages = [
//        'init',
//        'episode',
//        'section',
//        'discussion',
//        'items'
//    ];
    var members = settings.members;
    delete settings.members;

    //if(!settings.exports) settings.exports = template.exports;
    if(!settings.report) settings.report = template.report;
    if(!settings.report_publish) settings.report_publish = template.report_publish;
    if(!settings.phases) settings.phases = template.phases;

    create_episode(settings, null, function(err, result){
        template.episode_id = result._id;
        template.created_sections = 0;
        //add_member_episode(result._id, user_slug, true);
        var slugs = [];
        if(members){
            for(var i=0; i<members.length; i++){
                if(members[i].slug && user_slug !== members[i].slug){
                    slugs.push(members[i].slug);
                }
            }
        }

        set_members_episode(result._id, slugs, [template.user_slug], callback);

    });
}

function create_sections_from_template(){
    if(!template.episode_id) return false;

    var num_sections = template.sections.length;

    for (var i = 0; i < num_sections; i++) {
        (function (i){
            create_section(template.episode_id, template.sections[i].stage, template.sections[i], function(err, result){
                template.sections[i].section_id = result._id;
                if(template.mailin && template.sections[i].stage === template.mailin){
                    update_episode(template.episode_id, {drop_slug : result.slug}, function(err, result){

                    });
                }
                template.created_sections = template.created_sections + 1;
                create_items_from_template(i);
            });
        })(i);
    }

    return true;
}
function create_items_from_template(section_key){
    if(!template.episode_id) return false;
    if(!template.sections[section_key].section_id) return false;
    if(!template.sections[section_key].settings.items.fixed) return true;

    var section_id = template.sections[section_key].section_id;

    //fixed items
    template.sections[section_key].settings.items.created = 0;
    var num_items = template.sections[section_key].settings.items.fixed.length;

    for (var i = 0; i < num_items; i++) {

        (function (i){
            var item = template.sections[section_key].settings.items.fixed[i];
            var new_item = {
                title: item.name,
                body: item.body,
                slug: item.slug,
                username: template.username,
                user_slug: template.user_slug,
                stage: template.sections[section_key].stage,
                fixed: true
            };
            add_item(template.episode_id, section_id, new_item, function(err, result){
                template.sections[section_key].settings.items.created = template.sections[section_key].settings.items.created + 1;
            });
        })(i);
    }
}

function create_from_template(phase, setmodel, settings, username, user_slug, callback){
    if(!username) username = 'Raymond';
    if(!user_slug) user_slug = 'raymond';

    if(phase === true){
        if(setmodel){
            create_episode_from_template(setmodel, settings, username, user_slug, callback);
            create_from_template('sections');
        }
    }else if(phase === 'sections'){
        setTimeout(function(){create_sections_from_template();},500);
    }
}
////////////END TEMPLATE CREATE/////////////////////////////////////////////

function add_user(user, callback){
    if(!callback) callback = function(err, result){console.log('add_user callback',err, result);};

    if(!user.username) user.username = user.login;
    var slug = shortid.generate();

    var created = moment().format();
    var newUser = new User({
        slug: slug,
        login: user.login,
        password: user.password,
        username: user.username,
        email: user.email,
        created: created
    });
    if(user.oauth2_sub) newUser.oauth2_sub = user.oauth2_sub;
    if(user.oauth2_token) newUser.oauth2_token = user.oauth2_token;
    if(user.expire_time) newUser.expire_time = user.expire_time;
    if(user.admin){
        newUser.admin = user.admin;
    }else{
        //allow all users to create episodes
        newUser.admin = 1;
    }
    if(user.session) newUser.session = user.session;
    newUser.save(callback);
}

function oauth_user(profile, token_result, callback){
    if(!callback) callback = function(err, result){console.log('oauth_user callback', err, result);};
    User.findOne({$or: [{oauth2_sub: profile.sub},{email: profile.email}]}, function(err, user){
        var now = Math.round(new Date()/1000);
        var expire_time = now + token_result.expires_in;
        var logged = moment().format();

        console.log('oauth_user found user', (user == "null"), (user!==null), typeof user);
        if(user !== null){
            var session = user.session;;
            if(!session) session = [];
            if(session.length > 0){
                var new_session = [];
                for(var i = 0;i < session.length; i++){
                    if(session[i].expire > now && session[i].token !== token_result.access_token){
                        new_session.push(session[i]);
                    }
                }
                session = new_session;
            }
            session.push({
                token: token_result.access_token,
                socketid: token_result.access_token,
                expire: expire_time,
                last_login: logged
            });
            //update existing user
            user.session = session;
            user.markModified('session');
            user.last_login = logged;
            user.oauth2_sub = profile.sub;
//            user.oauth2_token = token_result.access_token;
//            user.oauth2_expire = expire_time;
//            user.socketid = token_result.access_token;
            user.login = profile.email;
            user.username = profile.name;
            user.email = profile.email;
            console.log('oauth_user update', user);

            user.save(callback);
        }else{
            var session = [{
                token: token_result.access_token,
                socketid: token_result.access_token,
                expire: expire_time,
                last_login: logged
            }];

            //add new user
            var newuser = {
                oauth2_sub: profile.sub,
//                oauth2_token: token_result.access_token,
//                oauth2_expire: expire_time,
                session: session,
                last_login: logged,
//                socketid: token_result.access_token,
                login: profile.email,
                password: shortid.generate(),
                username: profile.name,
                email: profile.email
            }
            console.log('oauth_user add', newuser);
            add_user(newuser, callback);
        }
    });

    callback();
}

function validate_user_by_token(oauth2_token, newsocketid, callback){
    if(!callback) callback = function(err, result){console.log('validate_user_by_token',result);};

    var query = {"session.token" : oauth2_token};
    User.findOne(query, function(err, user) {
        if (err){
            callback(err, { success: false});
        }else{
            if(user && user.login_user){
                // test a matching password
                var logged = moment().format();
                user.login_user(null, oauth2_token, null, newsocketid, logged, callback);
            }else{
                callback(null, { success: false});
            }
        }
    });
}

function validate_user(login, passwd, socketid, newsocketid, callback){
    if(!callback) callback = function(err, result){console.log('validate_user',result);};

    User.findOne({ login: login }, function(err, user) {
        if (err){
            callback(err, { success: false});
        }else{
            if(user && user.login_user){
                // test a matching password
                var logged = moment().format();
                user.login_user(passwd, null, socketid, newsocketid, logged, callback);
            }else{
                callback(null, { success: false});
            }
        }
    });
}

function get_users(query, fields, callback){
    if(!callback) callback = function(err, result){console.log('get_users',result);};

    if(/^([a-zA-Z0-9@\.\-_\s]{2,})/.test(query)){
        var filter = {$or: [{username: new RegExp(''+query+'', "i")}, {email: new RegExp(''+query+'', "i")}]};
        User.find(filter, fields).sort('username').exec(callback);
    }else{
        callback();
    }
}

function get_user(user_slug, callback){
    if(!callback) callback = function(err, result){console.log('get_user',result);};

    User.findOne({ slug: user_slug }, callback);
}

function get_user_by_email(email, fields, callback){
    if(!callback) callback = function(err, result){console.log('get_user_by_email',result);};
    console.log('get_user_by_email', email);
    User.findOne({ email: email }, fields, callback);
}

//add_user({login: 'aa', password: 'bb'}, function(err, data){
//    console.log('add_user', err, data);
//    validate_user('aa', 'bb', null, null, function(err, result){
//        console.log('validate_user',result);
//    });
//});

function get_touch_episode(user_slug, episode_slug, callback){
    if(!callback) callback = function(err, result){console.log('get touch episode',err, result);};

    Episode.findOne({ slug: episode_slug }, function(err, episode) {
        if (err){
            callback(err, { success: false});
        }else{
            if(episode && episode.get_touches){
                episode.get_touches(user_slug, callback);
            }else{
                callback(null, { success: false});
            }
        }
    });
}

function touch_episode(user_slug, episode_slug, section_id, item_slug, message_id, callback){
    if(!callback) callback = function(err, result){console.log('toucn episode',err, result);};

    Episode.findOne({ slug: episode_slug }, function(err, episode) {
        if (err){
            callback(err, { success: false});
        }else{
            if(episode && episode.set_touch){
                episode.set_touch(user_slug, section_id, item_slug, message_id, callback);
            }else{
                callback(null, { success: false});
            }
        }
    });
}

function create_episode(settings, slug, callback){
    if(!callback) callback = function(err, result){console.log('insert_episode',result);};
    if(!slug) slug = shortid.generate();
    if(!settings.title || settings.title === '') settings.title = 'untitled';
    if(!settings.mail_slug || settings.mail_slug === '') settings.mail_slug = '';
    if(!settings.report) settings.report = [];
    if(!settings.report_publish) settings.report_publish = [];
    if(!settings.phases) settings.phases = [];
    var created = moment().format();

    var new_episode = {
        title: settings.title,
        slug: slug,
        mail_slug: settings.mail_slug,
        members: {},
        report: settings.report,
        report_publish: settings.report_publish,
        phases: settings.phases,
        created: created
    };
    var episode = new Episode(new_episode);
    episode.save(callback);
}

function update_episode(episode_id, updates, callback){
    if(!callback) callback = function(err, result){console.log('update_episode',result);};

    var slugs = [];
    var admin_slugs = [];

    if(updates.members){
        var members = updates.members;
        admin_slugs.push(updates.admin_slug);

        if(members){
            for(var i=0; i<members.length; i++){
                if(members[i].slug){
                    if(!members[i].admin){
                        slugs.push(members[i].slug);
                    }else{
                        admin_slugs.push(members[i].slug);
                    }
                }
            }
        }
        delete updates.admin_slug;
        delete updates.members;
    }

    Episode.findOneAndUpdate({_id: episode_id}, updates, {'new': true}, function(err, episode){
        if(slugs.length > 0 || admin_slugs.length > 0){
            episode.set_members(User, slugs, admin_slugs, callback);
        }else{
            callback(err, episode);
        }
    });
}

function get_episode(episode_id, slug, mail_slug, user_slug, callback){
    if(!callback) callback = function(err, result){console.log('get_episode',result);};
    var filter = {};

    if(episode_id)  filter._id = episode_id;
    if(slug)   filter.slug = slug;
    if(mail_slug)   filter.mail_slug = mail_slug;

    if(user_slug) filter["members."+ user_slug +".active"] = true;

    Episode.findOne(filter, null, callback);
}

function add_member_episode(episode_id, user_slug, epi_admin, callback){
    console.log('add_member_episode', episode_id, user_slug, epi_admin);
    if(!callback) callback = function(err, result){console.log('add_member_episode',result);};
    if(!epi_admin) epi_admin = false;
    Episode.findOne({_id: episode_id}, null, function(err, episode){
        episode.add_member(User, user_slug, epi_admin, callback);
    });
}

function remove_member_episode(episode_id, user_slug, callback){
    if(!callback) callback = function(err, result){console.log('remove_member_episode',result);};
    Episode.findOne({_id: episode_id}, null, function(err, episode){
        episode.remove_member(user_slug, false, callback);
    });
}

function set_members_episode(episode_id, slugs, admin_slugs, callback){
    if(!callback) callback = function(err, result){console.log('set_members_episode',result);};
    Episode.findOne({_id: episode_id}, null, function(err, episode){
        episode.set_members(User, slugs, admin_slugs, callback);
    });
}

function get_episodes(callback){
    if(!callback) callback = function(err, result){console.log('get_episodes',result);};
    Episode.find({}).sort('-created').exec(callback);
}

function get_member_episodes(user_slug, admin, callback){
    if(!callback) callback = function(err, result){console.log('get_member_episodes',result);};
    var filter = {};
    filter["members."+ user_slug +".active"] = true;
    if(admin) filter["members."+ user_slug +".admin"] = true;

    Episode.find(filter).sort('-created').exec(function(err, result){
        console.log(filter, err, result);
        callback(err, result);
    });
}

function delete_episode(episode_id, callback){
    if(!callback) callback = function(err, result){console.log('delete_episode',result);};
    callback({deleted: episode_id});
    Episode.find({_id: episode_id}).remove().exec(function(){console.log('clearing: episode');});
    Section.find({episode_id: episode_id}).exec(function(err, result){
        for(var i = 0; i < result.length; i++){
            Message.find({section_id: result[i]._id}).remove().exec(function(){console.log('clearing: messages section '+i);});
            Section.find({_id: result[i]._id}).remove().exec(function(){console.log('clearing: section '+i);});
        }
    });
    Item.find({episode_id: episode_id}).exec(function(err, result){
        console.log('find items',result);
        for(var i = 0; i < result.length; i++){
            delete_item(result[i]._id, function(){console.log('clearing: items '+ i);});
        }
    });
}

function create_section(episode_id, stage, section, callback){
    if(!callback) callback = function(err, result){console.log('insert_section',result);};
    if(!stage) stage = '';
    var created = moment().format();

    if(!section.slug) section.slug = shortid.generate();
    if(!section.title || section.title === '') section.title = 'untitled';
    if(!section.description || section.description === '') section.description = '';
    if(!section.phase) section.phase = '';
    if(!section.settings) section.settings = {
        discussion: true,
        items: {
            add                 : true,
            position            : true,
            grouping            : false,
            label               : '',
            fixed_from_label    : '',
            fixed               : [],
            annotate_for_stage  : ''
        }
    };

    var new_section = {
        episode_id: episode_id,
        stage: stage,
        phase: section.phase,
        slug: section.slug,
        title: section.title,
        description: section.description,
        order: section.order,
        created: created,
        settings: section.settings
    };
    var section = new Section(new_section);
    section.save(callback);
}

function get_sections(episode_id, callback){
    if(!callback) callback = function(err, result){console.log('get_sections',result);};
    var filter = {episode_id: episode_id};
    Section.find(filter)
            .sort('order')
            .exec(callback);
}

function get_section(episode_id, stage, slug, callback){
    if(!callback) callback = function(err, result){console.log('get_section',result);};
    var filter = {episode_id: episode_id};
    if(stage) filter.stage = stage;
    if(slug) filter.slug = slug;
    Section.findOne(filter, null, callback);
}

function add_message(episode_id, section_id, message, callback){
    if(!callback) callback = function(err, result){console.log('insert_message',result);};
    var posted = moment().format();
    var slug_part = shortid.generate();
    var full_slug_part = moment(posted).format('YYYY.MM.DD.HH.mm.ss') + ':' + slug_part;

    var newmessage = {
            episode_id: episode_id,
            section_id: section_id,
            slug: slug_part,
            full_slug: full_slug_part,
            parent_slug: message.parent_slug || '',
            level: 0,
            posted: posted,
            username: message.username,
            user_slug: message.user_slug,
            message: message.message
        };
    if(message.item_slug) newmessage.item_slug = message.item_slug;
    if(message.message_type) newmessage.message_type = message.message_type;
    if(message.promotion) newmessage.promotion = message.promotion;
    if(message.parent_slug){
        Message.findOne({section_id: section_id, slug: message.parent_slug }, null, function(err, doc){
            if(doc){
                newmessage.slug = doc.slug + '/' + slug_part;
                newmessage.full_slug = doc.full_slug + '/' + full_slug_part;
                newmessage.level = doc.level + 1;
            }
            var message = new Message(newmessage);
            message.save(callback);
        });
    }else{
        var message = new Message(newmessage);
        message.save(callback);
    }
}

function get_messages(episode_id, section_id, filter, skip, limit, callback){
    if(!callback) callback = function(err, result){console.log('get_messages',result);};

    if(!episode_id && !section_id){
        callback();
    }else{
        if(!filter) filter = {};
        if(episode_id) filter.episode_id = episode_id;
        if(section_id) filter.section_id = section_id;
        Message.find(filter)
                .skip(skip)
                .limit(limit)
                .sort({'full_slug':1})
                .exec(callback);
    }
}

function promote_message(episode_id, message_slug, section_id, stage, orig_stage, username, user_slug, callback){
    Message.findOne({slug: message_slug}, null, function(err, doc){
        if(doc){
            var new_item_slug = shortid.generate();
            var promotion = {
                username: username,
                user_slug: user_slug,
                promoted: moment().format(),
                item_slug: new_item_slug,
                message_slug: message_slug,
                stage: stage,
                section_id: doc.section_id,
                orig_stage: orig_stage

            };

            var new_item = {
                slug: new_item_slug,
                stage: stage,
                username: username,
                user_slug: user_slug,
                title: 'From discussion',
                body: doc.message,
                promotion: promotion
            };

            var orig_section_id = doc.section_id;
            var orig_item_slug = doc.item_slug;
            var orig_level = doc.level;
            var orig_parent_slug = doc.parent_slug;
            var orig_message_slug = doc.slug;
            var orig_full_slug = doc.full_slug;

            var new_message_slug = shortid.generate();

            var slugparts = doc.full_slug.split('/');
            slugparts.splice(0, orig_level);
            var first_slugparts = slugparts[0].split(':');
            first_slugparts[1] = new_message_slug;
            var new_full_slug = first_slugparts.join(':');
            var new_parent_slug = "";
            var new_level = 0;

            var new_message = {
                episode_id: episode_id,
                section_id: section_id,
                item_slug: new_item_slug,
                slug: new_message_slug,
                full_slug: new_full_slug,
                parent_slug: new_parent_slug,
                level: new_level,
                posted: doc.posted,
                username: doc.username,
                user_slug: doc.user_slug,
                message: doc.message,
                message_type: doc.message_type
            };
            var message = new Message(new_message);
            message.save()

            var wrapup = function(){
                add_item(episode_id, section_id, new_item, function(err, result){
                    callback(err, {
                        success: true,
                        orig_section_id: orig_section_id,
                        orig_item_slug: orig_item_slug,
                        item: result
                    });
                });
            };

            //set original message to readonly and mark the promotion
            doc.readonly = true;
            doc.promotion = promotion;
            doc.save();

            var filter = {
                level: {$gt: orig_level},
                section_id: orig_section_id,
                item_slug: orig_item_slug
            };

            Message.find(filter).exec(function(err, result){
                var new_sub_message = {};
                var new_slug = '';
                var full_slug = '';
                var parent_slug = '';
                var level = 0;
                if(result){
                    if(result.length === 0){
                        wrapup();
                    }else{
                        for(var i = 0; i < result.length; i++){
                            /* orig_item_slug substring van parent_slug */
                            if(result[i].parent_slug.indexOf(orig_message_slug) === 0){
                                new_slug = result[i].slug.replace(orig_message_slug, new_message.slug);
                                full_slug = result[i].full_slug.replace(orig_full_slug, new_message.full_slug);
                                parent_slug = result[i].parent_slug.replace(orig_message_slug, new_message.slug);
                                level = result[i].level - orig_level;
                                new_sub_message = {
                                    episode_id: episode_id,
                                    section_id: section_id,
                                    item_slug: new_item_slug,
                                    slug: new_slug,
                                    full_slug: full_slug,
                                    parent_slug: parent_slug,
                                    level: level,
                                    posted: result[i].posted,
                                    username: result[i].username,
                                    user_slug: result[i].user_slug,
                                    message: result[i].message,
                                    message_type: result[i].message_type
                                };

                                //create new message in target section
                                var sub_message = new Message(new_sub_message);

                                sub_message.save();
    //                            add_message(section_id, new_sub_message, (i === result.length -1)?wrapup:null);

                                //set original to readonly
                                result[i].readonly = true;
                                result[i].save();
                                //Message.findOneAndUpdate({slug: result[i].slug}, message_update, null);
                            }

                            console.log('promoting '+i+' of '+result.length, (i === result.length-1));
                            if(i === result.length-1){
                                wrapup();
                            }
                        }
                    }
                }else{
                    wrapup();
                }
            });
        }
    });
};

function add_item(episode_id, section_id, item, callback){
    if(!callback) callback = function(err, result){console.log('insert_item',result);};
    if(!item.slug) item.slug = shortid.generate();
    var created = moment().format();

    var new_item = {
            episode_id: episode_id,
            slug: item.slug,
            section_id: section_id,
            created: created,
            updated: created,
            title: '',
            body: '',
            group: {},
            annotate: '',
            username: item.username,
            user_slug: item.user_slug,
            labels: {},
            archive: false
        };

    if(item.title)  new_item.title = item.title;
    if(item.body)   new_item.body = item.body;
    if(item.group)  new_item.group = item.group;
    if(item.annotate)  new_item.annotate = item.annotate;
    if(item.comment)   new_item.comment = item.comment;
    if(item.fixed)  new_item.fixed = item.fixed;
    if(item.stage)  new_item.stage = item.stage;
    if(item.pos)    new_item.pos = item.pos;
    if(item.links)  new_item.links = item.links;
    if(item.labels) new_item.labels = item.labels;
    if(item.promotion) new_item.promotion = item.promotion;

    var item = new Item(new_item);
    item.save(callback);
}

function get_item(episode_id, item_slug, callback){
    if(!callback) callback = function(err, result){console.log('get_item',result);};
    var filter = {
        episode_id: episode_id,
        slug: item_slug
    };

    Item.findOne(filter, null, callback);
}

function get_items(episode_id, section_id, stage, callback){
    if(!callback) callback = function(err, result){console.log('get_items',result);};
    var filter = {archive: false};
    filter.episode_id = episode_id;
    if(section_id)  filter.section_id = section_id;
    if(stage)       filter.stage = stage;
    Item.find(filter)
        .sort({order: 1, updated: -1})
        .exec(callback);
}

function get_items_for_stage(episode_id, stage, callback){
    if(!callback) callback = function(err, result){console.log('get_items',result);};
    var filter = {archive: false};
    filter.episode_id = episode_id;
    if(stage) filter.stage = stage;
    Item.find(filter)
        .sort({updated: -1})
        .exec(callback);
}

function get_item_archive(episode_id, slug, callback){
    if(!callback) callback = function(err, result){console.log('get_item_archive',result);};
    var filter = {
        episode_id: episode_id,
        slug: slug
    };
    Item.find(filter)
        .sort({updated: -1})
        .exec(callback);
}

function get_item_grouped(episode_id, item_id, callback){
    if(!callback) callback = function(err, result){console.log('get_item_grouped',result);};
    var filter = {
        archive: false,
        episode_id: episode_id
    };
    filter['group.'+item_id] = true;
    Item.find(filter)
        .sort({updated: -1})
        .exec(callback);
}

function get_item_annotations(episode_id, item_id, callback){
    if(!callback) callback = function(err, result){console.log('get_item_annotations',result);};
    var filter = {
        archive: false,
        episode_id: episode_id,
        annotate: item_id
    };
    Item.find(filter)
        .sort({updated: -1})
        .exec(callback);
}

function update_item_content(item_id, title, body, username, user_slug, callback){
    if(!callback) callback = function(err, result){console.log('update_item_content',result);};
    var updates = {
        username: username,
        user_slug: user_slug,
        title: title,
        body: body
    };
    update_item(item_id, updates, callback);
}

function update_item_group(item_id, group, username, user_slug, callback){
    if(!callback) callback = function(err, result){console.log('update_item_group',result);};

    var updates = {
        username: username,
        user_slug: user_slug,
        group: group
    };
    update_item(item_id, updates, callback);
}

function update_item_annotate(item_id, annotate, username, user_slug, callback){
    if(!callback) callback = function(err, result){console.log('update_item_annotate',result);};
    var updates = {
        username: username,
        user_slug: user_slug,
        annotate: annotate
    };
    update_item(item_id, updates, callback);
}

function update_item_label(item_id, label, tags, username, user_slug, callback){
    if(!callback) callback = function(err, result){console.log('update_item_label',result);};
    var updates = {
        username: username,
        user_slug: user_slug,
        labels: {}
    };
    updates.labels[label] = tags;
    update_item(item_id, updates, callback);
}

function update_item_pos(item_id, x, y, z, username, user_slug, callback){
    if(!callback) callback = function(err, result){console.log('update_item_pos',result);};
    var pos = {
        x: x,
        y: y,
        z: z
    };
    var updates = {
        username: username,
        user_slug: user_slug,
        pos: pos
    };
    update_item(item_id, updates, callback);
}

function update_item_links(item_id, username, user_slug, links, callback){
    if(!callback) callback = function(err, result){console.log('update_item_links',result);};
    var updates = {
        username: username,
        user_slug: user_slug,
        links: links
    };
    update_item(item_id, updates, callback);
}

function update_item_section_id(item_id, section_id, stage, username, user_slug, callback){
    if(!callback) callback = function(err, result){console.log('update_item_section_id',result);};
    var updates = {
        section_id: section_id,
        stage: stage,
        username: username,
        user_slug: user_slug,
    };
    update_item(item_id, updates, callback);
}

function archive_item(item){
    item.archive = true;
    delete item._id;
    var item = new Item(item);
    item.save(function(err, results){
        console.log('archive_item', results);
    });
}

function update_item(item_id, updates, callback){
    if(!callback) callback = function(err, result){console.log('update_item',result);};

    //todo: check if there are indeed changes between current and updates

    Item.findById(item_id, function (err, item) {
        if (err) return handleError(err);
        var archive = item.toObject();
        var changed = false;
        var updated_item = {};

        if(updates.section_id && updates.section_id !== archive.section_id){
            changed = true;
            updated_item.section_id = updates.section_id;
            updated_item.stage = updates.stage;
            updated_item.promotion = {
                username: updates.username,
                user_slug: updates.user_slug,
                promoted: moment().format(),
                stage: updates.stage,
                section_id: updates.section_id,
                orig_stage: item.stage
            };
            if(item.labels && item.labels[item.stage]){
                updated_item.labels = item.labels;
                updated_item.labels[updates.stage] = item.labels[item.stage];
            }
        }
        if((updates.title || updates.title === '') && updates.title !== archive.title){
            changed = true;
            updated_item.title = updates.title;
        }
        if((updates.body || updates.body === '') && updates.body !== archive.body){
            changed = true;
            updated_item.body = updates.body;
        }
        if(updates.group){
            changed = true;
            updated_item.group = updates.group;
        }
        if((updates.annotate || updates.annotate === '') && updates.annotate !== archive.annotate){
            changed = true;
            updated_item.annotate = updates.annotate;
        }
        if(updates.username && updates.username !== archive.username){
            changed = true;
            updated_item.username = updates.username;
        }
        if(updates.user_slug && updates.user_slug !== archive.user_slug){
            changed = true;
            updated_item.user_slug = updates.user_slug;
        }
        if(updates.pos && (updates.pos.x !== archive.pos.x
                       || updates.pos.y !== archive.pos.y
                       || updates.pos.z !== archive.pos.z)){
            changed = true;
            updated_item.pos = updates.pos;
        }
        if(updates.links){
            changed = true;
            updated_item.links = updates.links;
        }
        if(updates.promotion){
            changed = true;
            updated_item.promotion = updates.promotion;
        }
        if(updates.labels){
            changed = true;
            if(archive.labels){
                updated_item.labels = archive.labels;
                for (var label in updates.labels) { updated_item.labels[label] = updates.labels[label]; }
            }else{
                updated_item.labels = updates.labels;
            }
        }

        if(changed){
            updated_item.updated = moment().format();
            if(
                    updated_item.user_slug ||
                    moment(updated_item.updated).diff(moment(archive.archived), 'minutes', true) > 10
                ){
                archive.archived = updated_item.updated;
                archive_item(archive);
            }
            Item.findOneAndUpdate({_id: item_id}, updated_item, {'new': true}, callback);
        }
    });
}

function mark_deleted_item(item_id, deleted, callback){
    if(!callback) callback = function(err, result){console.log('mark_deleted_item',result);};
    if(item_id){
        Item.findOneAndUpdate({_id: item_id}, {deleted: deleted}, null, callback);

    }
}

function delete_item(item_id, callback){
    if(!callback) callback = function(err, result){console.log('delete_item',err, result);};
    if(item_id){
        Item.findOne({_id: item_id}, null, function(err, result){
            files.delete_item_folder(result.slug);

            Item.find({_id: item_id}).remove().exec(function(err, result){
                Item.find({annotate: item_id}).remove().exec(callback);
            });

        });

    }
}

function duplicate_item(item_id, username, user_slug, callback){
    if(!callback) callback = function(err, result){console.log('duplicate_item', err, result);};
    if(item_id){
        Item.findOne({_id: item_id}, null, function(err, result){

            if(result && !result.fixed){
                var new_item = result.toObject();

                delete new_item._id;
                var created = moment().format();

                new_item.slug = shortid.generate();
                new_item.created = created;
                new_item.updated = created;
                new_item.group = {};
                new_item.annotate = '';
                new_item.comment = '';
                new_item.username = username;
                new_item.user_slug = user_slug;
                new_item.deleted = false;
                new_item.title = "[copy] "+new_item.title;

                delete new_item.promotion;
                delete new_item.archived;

                var item = new Item(new_item);
                item.save(callback);
            }
        });
    }
}


text:
layout: emd_customer
status: publish
published: true
title: Mini Caravy
author: make-your-life-simple
author_login: picky-demo-admin
author_email: admin@emarketdesign.com
excerpt: |-
  CUSTOMER NUMBER: 209
  FIRST NAME: Fr
  LAST NAME: Citeaux
  PHONE: 88.60.1555
  CREDIT LIMIT: 53800
wordpress_id: 11770
wordpress_url: http://wordpressc.com/?emd_customer=mini-caravy
date: 2013-11-14 03:29:00.000000000 -05:00
categories: []
tags: []
comments: []
---
CUSTOMER NUMBER: 209
FIRST NAME: Fr
LAST NAME: Citeaux
PHONE: 88.60.1555
CREDIT LIMIT: 53800


text:
class CallbacksController < Devise::OmniauthCallbacksController
  def slack_signin
    @user = User.from_omniauth(request.env["omniauth.auth"])
    raise User::NotFound if @user.nil?

    @user.remember_me = true
    sign_in_and_redirect @user

  rescue User::DifferentGroup
    message = "그 팀으로는 로그인하실 수 없습니다. 이상한 모임으로 로그인해주세요!"
    redirect_to new_user_session_path, notice: message
  rescue User::NotFound
    message = "해당하는 사용자를 찾을 수 없습니다. 운영팀에게 문의해주세요."
    redirect_to new_user_session_path, notice: message
  end
end


text:
package org.hisp.dhis.dataelement;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

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

import org.hisp.dhis.DhisSpringTest;
import org.hisp.dhis.common.DataDimensionType;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Lars Helge Overland
 */
public class DataElementCategoryServiceTest
    extends DhisSpringTest
{
    private DataElementCategoryOption categoryOptionA;
    private DataElementCategoryOption categoryOptionB;
    private DataElementCategoryOption categoryOptionC;

    private DataElementCategory categoryA;
    private DataElementCategory categoryB;
    private DataElementCategory categoryC;

    private List<DataElementCategoryOption> categoryOptions;

    @Autowired
    private DataElementCategoryService categoryService;

    // -------------------------------------------------------------------------
    // Fixture
    // -------------------------------------------------------------------------

    @Override
    public void setUpTest()
    {
        categoryOptionA = createCategoryOption( 'A' );
        categoryOptionB = createCategoryOption( 'B' );
        categoryOptionC = createCategoryOption( 'C' );

        categoryService.addDataElementCategoryOption( categoryOptionA );
        categoryService.addDataElementCategoryOption( categoryOptionB );
        categoryService.addDataElementCategoryOption( categoryOptionC );

        categoryOptions = new ArrayList<>();

        categoryOptions.add( categoryOptionA );
        categoryOptions.add( categoryOptionB );
        categoryOptions.add( categoryOptionC );
    }

    // -------------------------------------------------------------------------
    // Category
    // -------------------------------------------------------------------------

    @Test
    public void testAddGet()
    {
        categoryA = createDataElementCategory( 'A', categoryOptionA, categoryOptionB, categoryOptionC );
        categoryB = createDataElementCategory( 'B', categoryOptionA, categoryOptionB, categoryOptionC );
        categoryC = createDataElementCategory( 'C', categoryOptionA, categoryOptionB, categoryOptionC );

        int idA = categoryService.addDataElementCategory( categoryA );
        int idB = categoryService.addDataElementCategory( categoryB );
        int idC = categoryService.addDataElementCategory( categoryC );

        assertEquals( categoryA, categoryService.getDataElementCategory( idA ) );
        assertEquals( categoryB, categoryService.getDataElementCategory( idB ) );
        assertEquals( categoryC, categoryService.getDataElementCategory( idC ) );

        assertEquals( categoryOptions, categoryService.getDataElementCategory( idA ).getCategoryOptions() );
        assertEquals( categoryOptions, categoryService.getDataElementCategory( idB ).getCategoryOptions() );
        assertEquals( categoryOptions, categoryService.getDataElementCategory( idC ).getCategoryOptions() );
    }

    @Test
    public void testDelete()
    {
        categoryA = new DataElementCategory( "CategoryA", DataDimensionType.DISAGGREGATION, categoryOptions );
        categoryB = new DataElementCategory( "CategoryB", DataDimensionType.DISAGGREGATION, categoryOptions );
        categoryC = new DataElementCategory( "CategoryC", DataDimensionType.DISAGGREGATION, categoryOptions );

        int idA = categoryService.addDataElementCategory( categoryA );
        int idB = categoryService.addDataElementCategory( categoryB );
        int idC = categoryService.addDataElementCategory( categoryC );

        assertNotNull( categoryService.getDataElementCategory( idA ) );
        assertNotNull( categoryService.getDataElementCategory( idB ) );
        assertNotNull( categoryService.getDataElementCategory( idC ) );

        categoryService.deleteDataElementCategory( categoryA );

        assertNull( categoryService.getDataElementCategory( idA ) );
        assertNotNull( categoryService.getDataElementCategory( idB ) );
        assertNotNull( categoryService.getDataElementCategory( idC ) );

        categoryService.deleteDataElementCategory( categoryB );

        assertNull( categoryService.getDataElementCategory( idA ) );
        assertNull( categoryService.getDataElementCategory( idB ) );
        assertNotNull( categoryService.getDataElementCategory( idC ) );
    }

    @Test
    public void testGetAll()
    {
        categoryA = createDataElementCategory( 'A' );
        categoryB = createDataElementCategory( 'B' );
        categoryC = createDataElementCategory( 'C' );

        categoryService.addDataElementCategory( categoryA );
        categoryService.addDataElementCategory( categoryB );
        categoryService.addDataElementCategory( categoryC );

        List<DataElementCategory> categories = categoryService.getAllDataElementCategories();

        assertEquals( 4, categories.size() ); // Including default
        assertTrue( categories.contains( categoryA ) );
        assertTrue( categories.contains( categoryB ) );
        assertTrue( categories.contains( categoryC ) );
    }

    // -------------------------------------------------------------------------
    // CategoryOptionGroup
    // -------------------------------------------------------------------------

    @Test
    public void testAddGetCategoryGroup()
    {
        CategoryOptionGroup groupA = createCategoryOptionGroup( 'A' );
        CategoryOptionGroup groupB = createCategoryOptionGroup( 'B' );
        CategoryOptionGroup groupC = createCategoryOptionGroup( 'C' );

        groupA.getMembers().add( categoryOptionA );
        groupA.getMembers().add( categoryOptionB );
        groupB.getMembers().add( categoryOptionC );

        int idA = categoryService.saveCategoryOptionGroup( groupA );
        int idB = categoryService.saveCategoryOptionGroup( groupB );
        int idC = categoryService.saveCategoryOptionGroup( groupC );

        assertEquals( groupA, categoryService.getCategoryOptionGroup( idA ) );
        assertEquals( groupB, categoryService.getCategoryOptionGroup( idB ) );
        assertEquals( groupC, categoryService.getCategoryOptionGroup( idC ) );

        assertEquals( 2, categoryService.getCategoryOptionGroup( idA ).getMembers().size() );
        assertEquals( 1, categoryService.getCategoryOptionGroup( idB ).getMembers().size() );
        assertEquals( 0, categoryService.getCategoryOptionGroup( idC ).getMembers().size() );
    }

    // -------------------------------------------------------------------------
    // CategoryOptionGroupSet
    // -------------------------------------------------------------------------

    @Test
    public void testAddGetCategoryGroupSet()
    {
        CategoryOptionGroup groupA = createCategoryOptionGroup( 'A' );
        CategoryOptionGroup groupB = createCategoryOptionGroup( 'B' );
        CategoryOptionGroup groupC = createCategoryOptionGroup( 'C' );

        groupA.getMembers().add( categoryOptionA );
        groupA.getMembers().add( categoryOptionB );
        groupB.getMembers().add( categoryOptionC );

        categoryService.saveCategoryOptionGroup( groupA );
        categoryService.saveCategoryOptionGroup( groupB );
        categoryService.saveCategoryOptionGroup( groupC );

        CategoryOptionGroupSet groupSetA = createCategoryOptionGroupSet( 'A' );
        CategoryOptionGroupSet groupSetB = createCategoryOptionGroupSet( 'B' );
        CategoryOptionGroupSet groupSetC = createCategoryOptionGroupSet( 'C' );

        groupSetA.getMembers().add( groupA );
        groupSetA.getMembers().add( groupB );
        groupSetB.getMembers().add( groupC );

        int idA = categoryService.saveCategoryOptionGroupSet( groupSetA );
        int idB = categoryService.saveCategoryOptionGroupSet( groupSetB );
        int idC = categoryService.saveCategoryOptionGroupSet( groupSetC );

        assertEquals( groupSetA, categoryService.getCategoryOptionGroupSet( idA ) );
        assertEquals( groupSetB, categoryService.getCategoryOptionGroupSet( idB ) );
        assertEquals( groupSetC, categoryService.getCategoryOptionGroupSet( idC ) );

        assertEquals( 2, categoryService.getCategoryOptionGroupSet( idA ).getMembers().size() );
        assertEquals( 1, categoryService.getCategoryOptionGroupSet( idB ).getMembers().size() );
        assertEquals( 0, categoryService.getCategoryOptionGroupSet( idC ).getMembers().size() );
    }
}


text:
exports.Reader = require('./lib/reader');
// exports.Writer = require('./lib/writer');


text:
#include "jerryscript.h"
#include "jerryscript-port.h"
#include "jerryscript-port-default.h"
#include "test-common.h"

static const jerry_char_t test_source[] = TEST_STRING_LITERAL (
  "var p1 = create_promise1();"
  "var p2 = create_promise2();"
  "p1.then(function(x) { "
  "  assert(x==='resolved'); "
  "}); "
  "p2.catch(function(x) { "
  "  assert(x==='rejected'); "
  "}); "
);

static int count_in_assert = 0;
static jerry_value_t my_promise1;
static jerry_value_t my_promise2;
static const jerry_char_t s1[] = "resolved";
static const jerry_char_t s2[] = "rejected";

static jerry_value_t
create_promise1_handler (const jerry_call_info_t *call_info_p, /**< call information */
                         const jerry_value_t args_p[], /**< arguments list */
                         const jerry_length_t args_cnt) /**< arguments length */
{
  JERRY_UNUSED (call_info_p);
  JERRY_UNUSED (args_p);
  JERRY_UNUSED (args_cnt);

  jerry_value_t ret =  jerry_create_promise ();
  my_promise1 = jerry_acquire_value (ret);

  return ret;
} /* create_promise1_handler */

static jerry_value_t
create_promise2_handler (const jerry_call_info_t *call_info_p, /**< call information */
                         const jerry_value_t args_p[], /**< arguments list */
                         const jerry_length_t args_cnt) /**< arguments length */
{
  JERRY_UNUSED (call_info_p);
  JERRY_UNUSED (args_p);
  JERRY_UNUSED (args_cnt);

  jerry_value_t ret =  jerry_create_promise ();
  my_promise2 = jerry_acquire_value (ret);

  return ret;
} /* create_promise2_handler */

static jerry_value_t
assert_handler (const jerry_call_info_t *call_info_p, /**< call information */
                const jerry_value_t args_p[], /**< function arguments */
                const jerry_length_t args_cnt) /**< number of function arguments */
{
  JERRY_UNUSED (call_info_p);

  count_in_assert++;

  if (args_cnt == 1
      && jerry_value_is_boolean (args_p[0])
      && jerry_get_boolean_value (args_p[0]))
  {
    return jerry_create_boolean (true);
  }
  else
  {
    TEST_ASSERT (false);
  }
} /* assert_handler */

/**
 * Register a JavaScript function in the global object.
 */
static void
register_js_function (const char *name_p, /**< name of the function */
                      jerry_external_handler_t handler_p) /**< function callback */
{
  jerry_value_t global_obj_val = jerry_get_global_object ();

  jerry_value_t function_val = jerry_create_external_function (handler_p);
  jerry_value_t function_name_val = jerry_create_string ((const jerry_char_t *) name_p);
  jerry_value_t result_val = jerry_set_property (global_obj_val, function_name_val, function_val);

  jerry_release_value (function_name_val);
  jerry_release_value (function_val);
  jerry_release_value (global_obj_val);

  jerry_release_value (result_val);
} /* register_js_function */

int
main (void)
{
  jerry_init (JERRY_INIT_EMPTY);

  if (!jerry_is_feature_enabled (JERRY_FEATURE_PROMISE))
  {
    jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Promise is disabled!\n");
    jerry_cleanup ();
    return 0;
  }

  register_js_function ("create_promise1", create_promise1_handler);
  register_js_function ("create_promise2", create_promise2_handler);
  register_js_function ("assert", assert_handler);

  jerry_value_t parsed_code_val = jerry_parse (test_source,
                                               sizeof (test_source) - 1,
                                               NULL);
  TEST_ASSERT (!jerry_value_is_error (parsed_code_val));

  jerry_value_t res = jerry_run (parsed_code_val);
  TEST_ASSERT (!jerry_value_is_error (res));

  jerry_release_value (res);
  jerry_release_value (parsed_code_val);

  /* Test jerry_create_promise and jerry_value_is_promise. */
  TEST_ASSERT (jerry_value_is_promise (my_promise1));
  TEST_ASSERT (jerry_value_is_promise (my_promise2));

  TEST_ASSERT (count_in_assert == 0);

  /* Test jerry_resolve_or_reject_promise. */
  jerry_value_t str_resolve = jerry_create_string (s1);
  jerry_value_t str_reject = jerry_create_string (s2);

  jerry_resolve_or_reject_promise (my_promise1, str_resolve, true);
  jerry_resolve_or_reject_promise (my_promise2, str_reject, false);

  /* The resolve/reject function should be invalid after the promise has the result. */
  jerry_resolve_or_reject_promise (my_promise2, str_resolve, true);
  jerry_resolve_or_reject_promise (my_promise1, str_reject, false);

  /* Run the jobqueue. */
  res = jerry_run_all_enqueued_jobs ();

  TEST_ASSERT (!jerry_value_is_error (res));
  TEST_ASSERT (count_in_assert == 2);

  jerry_release_value (my_promise1);
  jerry_release_value (my_promise2);
  jerry_release_value (str_resolve);
  jerry_release_value (str_reject);

  jerry_cleanup ();

  return 0;
} /* main */


text:
package ca.corefacility.bioinformatics.irida.pipeline.upload.galaxy.integration;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;

import ca.corefacility.bioinformatics.irida.annotation.GalaxyIntegrationTest;
import ca.corefacility.bioinformatics.irida.config.conditions.WindowsPlatformCondition;
import ca.corefacility.bioinformatics.irida.model.enums.AnalysisState;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.JobError;
import ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission;
import ca.corefacility.bioinformatics.irida.pipeline.upload.galaxy.GalaxyJobErrorsService;
import ca.corefacility.bioinformatics.irida.repositories.analysis.submission.AnalysisSubmissionRepository;
import ca.corefacility.bioinformatics.irida.repositories.analysis.submission.JobErrorRepository;
import ca.corefacility.bioinformatics.irida.service.analysis.workspace.AnalysisWorkspaceService;
import ca.corefacility.bioinformatics.irida.service.AnalysisExecutionScheduledTask;
import ca.corefacility.bioinformatics.irida.service.CleanupAnalysisSubmissionCondition;
import ca.corefacility.bioinformatics.irida.service.DatabaseSetupGalaxyITService;
import ca.corefacility.bioinformatics.irida.service.analysis.execution.AnalysisExecutionService;
import ca.corefacility.bioinformatics.irida.service.impl.AnalysisExecutionScheduledTaskImpl;
import ca.corefacility.bioinformatics.irida.service.EmailController;

import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.DatabaseTearDown;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;

/**
 * Integration tests for getting job error info from Galaxy for
 * {@link AnalysisSubmission}s.
 */
@GalaxyIntegrationTest
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class,
		WithSecurityContextTestExecutionListener.class })
@DatabaseSetup("/ca/corefacility/bioinformatics/irida/repositories/analysis/AnalysisRepositoryIT.xml")
@DatabaseTearDown("/ca/corefacility/bioinformatics/irida/test/integration/TableReset.xml")
public class GalaxyJobErrorsServiceIT {

	@Autowired
	private GalaxyJobErrorsService galaxyJobErrorsService;

	@Autowired
	private DatabaseSetupGalaxyITService databaseSetupGalaxyITService;

	private UUID validIridaWorkflowId = UUID.fromString("1f9ea289-5053-4e4a-bc76-1f0c60b179f8");
	private UUID iridaWorkflowIdWithError = UUID.fromString("9ac828e9-2ee4-409d-80dd-f1bf955fd8b9");

	private Path sequenceFilePath;
	private Path referenceFilePath;
	private AnalysisExecutionScheduledTask analysisExecutionScheduledTask;

	@Autowired
	private AnalysisSubmissionRepository analysisSubmissionRepository;
	@Autowired
	private AnalysisExecutionService analysisExecutionService;
	@Autowired
	private JobErrorRepository jobErrorRepository;

	@Autowired
	private EmailController emailController;

	@Autowired
	private AnalysisWorkspaceService analysisWorkspaceService;

	@BeforeEach
	public void setup() throws URISyntaxException, IOException {
		assumeFalse(WindowsPlatformCondition.isWindows());
		Path sequenceFilePathReal = Paths
				.get(DatabaseSetupGalaxyITService.class.getResource("testData1.fastq").toURI());
		Path referenceFilePathReal = Paths
				.get(DatabaseSetupGalaxyITService.class.getResource("testReference.fasta").toURI());

		sequenceFilePath = Files.createTempFile("testData1", ".fastq");
		Files.delete(sequenceFilePath);
		Files.copy(sequenceFilePathReal, sequenceFilePath);

		referenceFilePath = Files.createTempFile("testReference", ".fasta");
		Files.delete(referenceFilePath);
		Files.copy(referenceFilePathReal, referenceFilePath);

		analysisExecutionScheduledTask = new AnalysisExecutionScheduledTaskImpl(analysisSubmissionRepository,
				analysisExecutionService, CleanupAnalysisSubmissionCondition.ALWAYS_CLEANUP, galaxyJobErrorsService,
				jobErrorRepository, emailController, analysisWorkspaceService);
	}

	/**
	 * Test that a successfully completed Galaxy workflow analysis does not
	 * return any {@link JobError}s
	 */
	@Test
	@WithMockUser(username = "aaron", roles = "ADMIN")
	public void testSuccessfulAnalysisReturnsNoJobErrors() throws Exception {
		databaseSetupGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath,
				validIridaWorkflowId, false);

		AnalysisSubmission submission = runAnalysis();
		List<JobError> errors = galaxyJobErrorsService.createNewJobErrors(submission);
		assertTrue(errors.isEmpty());
	}

	/**
	 * Test that a failure producing Galaxy workflow analysis returns a
	 * {@link JobError}
	 */
	@Test
	@WithMockUser(username = "aaron", roles = "ADMIN")
	public void testFailingAnalysisReturnsJobError() throws Exception {
		databaseSetupGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath,
				iridaWorkflowIdWithError, false);
		AnalysisSubmission submission = runAnalysis();
		assertEquals(AnalysisState.ERROR, submission.getAnalysisState());

		List<JobError> errors = galaxyJobErrorsService.createNewJobErrors(submission);

		assertTrue(errors.size() == 1, "There should only be one JobError");

		JobError jobError = errors.get(0);
		assertTrue(jobError.getStandardError() != null && !jobError.getStandardError().equals(""),
				"JobError should have some stderr message");
		assertTrue(jobError.getStandardError().contains("IndexError: list index out of range"),
				"JobError should be triggered by 'IndexError: list index out of range'");
		assertTrue(jobError.getToolId().equals("Filter1"), "JobError tool ID should be 'Filter1'");
		assertTrue(jobError.getExitCode() == 1, "JobError exit code should be '1'");
	}

	/**
	 * Prepare and execute any submitted analyses to Galaxy and wait for
	 * completion
	 *
	 * @return {@link AnalysisSubmission} object of completed analysis
	 * @throws Exception
	 */
	private AnalysisSubmission runAnalysis() throws Exception {
		analysisExecutionScheduledTask.prepareAnalyses().iterator().next().get();
		databaseSetupGalaxyITService
				.waitUntilSubmissionComplete(analysisExecutionScheduledTask.executeAnalyses().iterator().next().get());
		return analysisExecutionScheduledTask.monitorRunningAnalyses().iterator().next().get();
	}

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using TankLib.Math;

namespace TankLib {
    /// Tank Animation, type 006
    public class teAnimation {
        /// Animation header
        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        public struct AnimHeader {
            ///
            /// Animation "priority". Is 160 for many animations. No idea what it is used for
            ///
            public short Priority;

            /// Number of bones animated
            public ushort BoneCount;

            /// Unknown flags
            public ushort Flags;

            public ushort Unknown1;

            public uint Unknown2;

            public ushort Unknown3;

            public ushort Unknown4;

            public uint Unknown5;

            /// Duration, in seconds
            public float Duration;

            public float Unknown6;

            /// Frames Per Second
            public float FPS;

            public float Unknown7;

            public float Unknown8;

            /// AnimationEffect reference
            /// <remarks>File type 08F</remarks>
            public teResourceGUID Effect;

            public long EffectStorage;

            /// Offset to bone list
            public long BoneListOffset;

            public long Unknown9;

            public long Unknown10;

            public long Unknown11;

            public long Unknown12;

            public long Unknown13;

            public long SomeTableOffset; // new animation param table, usually float tracks

            /// Offset to info table
            public long InfoTableOffset;

            public long Padding;
        }

        public struct InfoTable {
            /// Number of scales
            public ushort ScaleCount;

            /// Number of positions
            public ushort PositionCount;

            /// Number of rotations
            public ushort RotationCount;

            /// Unknown flags
            public ushort Flags;

            /// Offset to scale indices
            public int ScaleIndicesOffset;

            /// Offset to position indices
            public int PositionIndicesOffset;

            /// Offset to rotation indices
            public int RotationIndicesOffset;

            /// Offset to scale data
            public int ScaleDataOffset;

            /// Offset to postion data
            public int PositionDataOffset;

            /// Offset to rotation data
            public int RotationDataOffset;
        }

        public class BoneAnimation {
            public Dictionary<int, teVec3> Positions;
            public Dictionary<int, teVec3> Scales;
            public Dictionary<int, teQuat> Rotations;

            public BoneAnimation() {
                Positions = new Dictionary<int, teVec3>();
                Scales = new Dictionary<int, teVec3>();
                Rotations = new Dictionary<int, teQuat>();
            }
            // key = frame number; value = abs value this frame
            // then slerp between or whatever
        }

        /// Header data
        public AnimHeader Header;

        /// Number of info tables
        public int InfoTableSize;

        /// Bone IDs
        public int[] BoneList;

        /// Bone info tables
        public InfoTable[] InfoTables;

        public BoneAnimation[] BoneAnimations;

        /// Load animation from a stream
        public teAnimation(Stream stream, bool keepOpen = false) {
            using (BinaryReader reader = new BinaryReader(stream, Encoding.Default, keepOpen)) {
                Header = reader.Read<AnimHeader>();

                InfoTableSize = (int)(Header.FPS * Header.Duration) + 1;

                reader.BaseStream.Position = Header.BoneListOffset;
                BoneList = reader.ReadArray<int>(Header.BoneCount);

                reader.BaseStream.Position = Header.InfoTableOffset;
                InfoTables = new InfoTable[Header.BoneCount];
                BoneAnimations = new BoneAnimation[Header.BoneCount];

                for (int boneIndex = 0; boneIndex < Header.BoneCount; boneIndex++) {
                    long streamPos = reader.BaseStream.Position;
                    InfoTable infoTable = reader.Read<InfoTable>();
                    long afterTablePos = reader.BaseStream.Position;
                    InfoTables[boneIndex] = infoTable;

                    long scaleIndicesPos = (long)infoTable.ScaleIndicesOffset * 4 + streamPos;
                    long positionIndicesPos = (long)infoTable.PositionIndicesOffset * 4 + streamPos;
                    long rotationIndicesPos = (long)infoTable.RotationIndicesOffset * 4 + streamPos;
                    long scaleDataPos = (long)infoTable.ScaleDataOffset * 4 + streamPos;
                    long positionDataPos = (long)infoTable.PositionDataOffset * 4 + streamPos;
                    long rotationDataPos = (long)infoTable.RotationDataOffset * 4 + streamPos;

                    reader.BaseStream.Position = scaleIndicesPos;
                    int[] scaleIndices = ReadIndices(reader, infoTable.ScaleCount);

                    reader.BaseStream.Position = positionIndicesPos;
                    int[] positionIndices = ReadIndices(reader, infoTable.PositionCount);

                    reader.BaseStream.Position = rotationIndicesPos;
                    int[] rotationIndices = ReadIndices(reader, infoTable.RotationCount);

                    BoneAnimation boneAnimation = new BoneAnimation();
                    BoneAnimations[boneIndex] = boneAnimation;

                    reader.BaseStream.Position = scaleDataPos;
                    for (int j = 0; j < infoTable.ScaleCount; j++) {
                        int frame = System.Math.Abs(scaleIndices[j]) % InfoTableSize;
                        boneAnimation.Scales[frame] = ReadScale(reader);
                    }

                    reader.BaseStream.Position = positionDataPos;
                    for (int j = 0; j < infoTable.PositionCount; j++) {
                        int frame = System.Math.Abs(positionIndices[j]) % InfoTableSize;
                        boneAnimation.Positions[frame] = ReadPosition(reader);
                    }

                    reader.BaseStream.Position = rotationDataPos;
                    for (int j = 0; j < infoTable.RotationCount; j++) {
                        int frame = System.Math.Abs(rotationIndices[j]) % InfoTableSize;
                        boneAnimation.Rotations[frame] = ReadRotation(reader);
                    }

                    reader.BaseStream.Position = afterTablePos;
                }
            }
        }

        ///
        /// Read rotation value
        ///
        /// <param name="reader">Source reader</param>
        /// <returns>Rotation value</returns>
        private static teQuat ReadRotation(BinaryReader reader) {
            ushort x = reader.ReadUInt16();
            ushort y = reader.ReadUInt16();
            ushort z = reader.ReadUInt16();

            return UnpackRotation(x, y, z);
        }

        ///
        /// Read position value
        ///
        /// <param name="reader">Source reader</param>
        /// <returns>Position value</returns>
        private static teVec3 ReadPosition(BinaryReader reader) {
            float x = reader.ReadSingle();
            float y = reader.ReadSingle();
            float z = reader.ReadSingle();

            return new teVec3(x, y, z);
        }

        ///
        /// Read scale value
        ///
        /// <param name="reader">Source reader</param>
        /// <returns>Scale value</returns>
        private static teVec3 ReadScale(BinaryReader reader) {
            ushort x = reader.ReadUInt16();
            ushort y = reader.ReadUInt16();
            ushort z = reader.ReadUInt16();

            return UnpackScale(x, y, z);
        }

        ///
        /// Unpack rotation value
        ///
        /// <param name="a">Packed A component</param>
        /// <param name="b">Packed B component</param>
        /// <param name="c">Packed C component</param>
        /// <returns>Unpacked rotation value</returns>
        private static teQuat UnpackRotation(ushort a, ushort b, ushort c) {
            teQuat q = new teQuat();

            int axis1 = a >> 15;
            int axis2 = b >> 15;
            int axis = axis2 << 1 | axis1;

            a = (ushort)(a & 0x7FFF);
            b = (ushort)(b & 0x7FFF);

            double x = 1.41421 * (a - 0x4000) / 0x8000;
            double y = 1.41421 * (b - 0x4000) / 0x8000;
            double z = 1.41421 * (c - 0x8000) / 0x10000;
            double w = System.Math.Pow(1.0 - x * x - y * y - z * z, 0.5);

            // Console.Out.WriteLine("Unpack Values: X: {0}, Y: {1}, Z: {2}, W: {3}, Axis: {4}", x, y, z, w, axis);

            if (axis == 0) {
                q = new teQuat(w, x, y, z);
            } else if (axis == 1) {
                q = new teQuat(x, w, y, z);
            } else if (axis == 2) {
                q = new teQuat(x, y, w, z);
            } else if (axis == 3) {
                q = new teQuat(x, y, z, w);
            } else {
                Console.Out.WriteLine($"Unknown Axis detected! Axis: {axis}");
            }

            return q;
        }

        ///
        /// Unpack scale value
        ///
        /// <param name="a">Packed X component</param>
        /// <param name="b">Packed Y component</param>
        /// <param name="c">Packed Z component</param>
        /// <returns>Unpacked scale value</returns>
        private static teVec3 UnpackScale(ushort a, ushort b, ushort c) {
            double x = a / 1024d;
            double y = b / 1024d;
            double z = c / 1024d;

            double xDelta = (1 - x) / 1024d;
            double yDelta = (1 - y) / 1024d;
            double zDelta = (1 - z) / 1024d;

            return new teVec3(xDelta + 1, yDelta + 1, zDelta + 1);
        }

        ///
        /// Read frame indices
        ///
        /// <param name="reader">Source BinaryReader</param>
        /// <param name="count">Number of indices</param>
        /// <returns>Frame indices</returns>
        private int[] ReadIndices(BinaryReader reader, ushort count) {
            int[] ret = new int[count];
            for (int i = 0; i < count; i++) {
                if (InfoTableSize <= 255) {
                    ret[i] = reader.ReadByte();
                } else {
                    ret[i] = reader.ReadInt16();
                }
            }
            return ret;
        }
    }
}


text:
<template name="ShuttleSearchInput">
    {{! index: EasySearchIndex }}
    {{! attributes?: Object }}
    {{> EasySearch.Input index=index attributes=_attributes }}
</template>
<template name="ShuttleSearchItems">
    {{! source: Document }}
    {{! index: EasySearchIndex }}
    {{! tree: Mongo.Collection }}
    {{! multiple: Boolean = false }}
    {{! ignoreInherited: Boolean = true }}
    {{#EasySearch.Each index=index }}
        {{> ShuttleSearchItem document=this source=(../../source) tree=(../../tree) }}
    {{/EasySearch.Each}}
</template>
<template name="ShuttleSearchItem">
    {{! document: Document }}
    {{! source: Document }}
    {{! tree: Mongo.Collection }}
    <a href="#" class="shuttle-ui-bootstrap-3-search-item list-group-item {{#if hasLink}}disabled{{/if}}" style="cursor: pointer;">
        {{> Templater document=document type="ShuttleSearchItem"}}
    </a>
</template>
<template name="ShuttleSearchDefault">
    {{! source: Document, tree: Mongo.Collection }}
	{{#each Shuttle.groups}}
		{{> ShuttleSearchItem document=this source=(../source) tree=(../tree)}}
	{{/each}}
	{{> ShuttleSearchItem document=Meteor.user source=source tree=tree}}
</template>


text:
* [PGS Upgrade](#pgs-upgrade)
* [Gateway Upgrade](#gateway-upgrade)
* [Configuration Master Upgrade](#configuration-master-upgrade)
* [Zookeeper Upgrade](#zookeeper-upgrade)

## PGS Upgrade
You can upgrade PGS with the administrative script. Please follow the procedure below:
*	Copy the upgrade binary file to $NBASE_ARC_HOME/bin in the machine where the administrative
script has been installed, and go to the directory where the script is located.
*	Open the `mgmt/config/conf_dnode.py` file, and change the values of REDIS_VERSION and SMR_VERSION to the upgrade binary's version.
```
REDIS_VERSION = <Version of nbase-arc>
SMR_VERSION = <Version of nbase-arc>
```
*	Run the script.
```
$ cd $NBASE_ARC_HOME/mgmt
$ fab main
```
*	Select "Upgrade PGS."
*	Enter the name of cluster you want to upgrade for Cluster Name, when the prompt message that asks
for upgrade options is displayed.
*	When the upgrade is finished, use "Show cluster information" of the script to check the status of
upgraded PGSes. Each PG should contain one master PGS and several slave PGSes.

## Gateway Upgrade
You can upgrade gateways with the administrative script. Please follow the procedure below:
*	Copy the upgrade binary file to $NBASE_ARC_HOME/bin in the machine where the administrative script has been installed,
and go to the directory where the script is located.
*	Open the `mgmt/config/conf_dnode.py` file, and change the value of GW_VERSION to the upgrade binary's version.
```
GW_VERSION = <Version of nbase-arc>
```
*	Run the script.
```
$ cd $NBASE_ARC_HOME/mgmt
$ fab main
```
*	Select "Upgrade GW."
*	Enter the name of cluster you want to upgrade for Cluster Name, when the prompt message that asks
for upgrade options is displayed.
*	When the upgrade is finished, use "Show cluster information" of the script to check if the status of upgraded gateways is N (Normal).

## Configuration Master Upgrade
Configuration Master does not support automatic upgrade with the script. Please follow the procedure below to
manually upgrade Configuration Master.
*	Copy the new version of Configuration Master to `$HOME/nbase-arc/confmaster`.
*	Kill all Configuration Master processes that are running on multiple machines.
```
$ kill -9 <confmaster pid>
```
*	Check if z-nodes used to manage Configuration Master are deleted from ZooKeeper. Check the folders, /RC/CC /LE and /RC/CC/FD. They should not be in those folders. If the z-nodes still exist in the folders even after you terminate all the Configuration Master processes, check again after a while.
```
$ zkCli.sh
zookeeper prompt$ ls /RC/CC/FD
[]
zookeeper prompt$ ls /RC/CC/LE
[]
```
*	Run the new version of Configuration Master.
```
$ cd $NBASE_ARC_HOME/confmaster
$ ./confmaster.sh
```

## Zookeeper Upgrade
You can upgrade ZooKeeper by using rolling restart. Please refer to
"What are the options-process for upgrading ZooKeeper?" in the official website of ZooKeeper
(https://cwiki.apache.org/confluence/display/ZOOKEEPER/FAQ), for more information.


text:
namespace SimpleSoft.IniParser.Impl
{
    /// <summary>
    /// INI normalization options
    /// </summary>
    public class IniNormalizationOptions
    {
        /// <summary>
        /// Default options instance.
        /// </summary>
        public static readonly IniNormalizationOptions Default = new IniNormalizationOptions();

        /// <summary>
        /// Should empty comments be included? Defaults to <value>false</value>.
        /// </summary>
        public bool IncludeEmptyComments { get; set; } = false;

        /// <summary>
        /// Should empty sections be included? Defaults to <value>false</value>.
        /// </summary>
        public bool IncludeEmptySections { get; set; } = false;

        /// <summary>
        /// Should empty properties be included? Defaults to <value>false</value>.
        /// </summary>
        public bool IncludeEmptyProperties { get; set; } = false;

        /// <summary>
        /// Are section and property names case sensitive? Defaults to <value>false</value>.
        /// </summary>
        public bool IsCaseSensitive { get; set; } = false;

        /// <summary>
        /// Replace a duplicated property for the last found value? Defaults to <value>false</value>.
        /// </summary>
        public bool ReplaceOnDuplicatedProperties { get; set; } = false;

        /// <summary>
        /// Merge duplicated sections into a single one with all properties? Defaults to <value>false</value>.
        /// </summary>
        public bool MergeOnDuplicatedSections { get; set; } = false;

        /// <summary>
        /// Throw exceptions on errors? Defaults to <value>true</value>.
        /// </summary>
        public bool ThrowExceptions { get; set; } = true;

        /// <summary>
        /// Sort sections? Defaults to <see cref="IniNormalizationSortType.None"/>.
        /// </summary>
        public IniNormalizationSortType SortSections { get; set; } = IniNormalizationSortType.None;

        /// <summary>
        /// Sort properties by section? Defaults to <see cref="IniNormalizationSortType.None"/>.
        /// </summary>
        public IniNormalizationSortType SortProperties { get; set; } = IniNormalizationSortType.None;
    }
}


text:
<?php

namespace OAuthTest\Unit\OAuth2\Service;

use OAuth\OAuth2\Service\Dropbox;
use OAuth\Common\Token\TokenInterface;

class DropboxTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers OAuth\OAuth2\Service\Dropbox::__construct
     */
    public function testConstructCorrectInterfaceWithoutCustomUri()
    {
        $service = new Dropbox(
            $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
            $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'),
            $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
        );

        $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service);
    }

    /**
     * @covers OAuth\OAuth2\Service\Dropbox::__construct
     */
    public function testConstructCorrectInstanceWithoutCustomUri()
    {
        $service = new Dropbox(
            $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
            $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'),
            $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
        );

        $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service);
    }

    /**
     * @covers OAuth\OAuth2\Service\Dropbox::__construct
     */
    public function testConstructCorrectInstanceWithCustomUri()
    {
        $service = new Dropbox(
            $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
            $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'),
            $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'),
            array(),
            $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface')
        );

        $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service);
    }

    /**
     * @covers OAuth\OAuth2\Service\Dropbox::__construct
     * @covers OAuth\OAuth2\Service\Dropbox::getAuthorizationUri
     */
    public function testGetAuthorizationUriWithoutAdditionalParams()
    {
        $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface');
        $credentials->expects($this->once())->method('getConsumerId')->will($this->returnValue('foo'));
        $credentials->expects($this->once())->method('getCallbackUrl')->will($this->returnValue('bar'));

        $service = new Dropbox(
            $credentials,
            $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'),
            $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
        );

        $this->assertSame(
            'https://www.dropbox.com/1/oauth2/authorize?client_id=foo&redirect_uri=bar&response_type=code&scope=',
            $service->getAuthorizationUri()->getAbsoluteUri()
        );
    }

    /**
     * @covers OAuth\OAuth2\Service\Dropbox::__construct
     * @covers OAuth\OAuth2\Service\Dropbox::getAuthorizationUri
     */
    public function testGetAuthorizationUriWithAdditionalParams()
    {
        $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface');
        $credentials->expects($this->once())->method('getConsumerId')->will($this->returnValue('foo'));
        $credentials->expects($this->once())->method('getCallbackUrl')->will($this->returnValue('bar'));

        $service = new Dropbox(
            $credentials,
            $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'),
            $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
        );

        $this->assertSame(
            'https://www.dropbox.com/1/oauth2/authorize?client_id=foo&redirect_uri=bar&response_type=code&scope=',
            $service->getAuthorizationUri()->getAbsoluteUri()
        );
    }

    /**
     * @covers OAuth\OAuth2\Service\Dropbox::__construct
     * @covers OAuth\OAuth2\Service\Dropbox::getAuthorizationEndpoint
     */
    public function testGetAuthorizationEndpoint()
    {
        $service = new Dropbox(
            $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
            $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'),
            $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
        );

        $this->assertSame('https://www.dropbox.com/1/oauth2/authorize', $service->getAuthorizationEndpoint()->getAbsoluteUri());
    }

    /**
     * @covers OAuth\OAuth2\Service\Dropbox::__construct
     * @covers OAuth\OAuth2\Service\Dropbox::getAccessTokenEndpoint
     */
    public function testGetAccessTokenEndpoint()
    {
        $service = new Dropbox(
            $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
            $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'),
            $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
        );

        $this->assertSame('https://api.dropbox.com/1/oauth2/token', $service->getAccessTokenEndpoint()->getAbsoluteUri());
    }

    /**
     * @covers OAuth\OAuth2\Service\Dropbox::__construct
     * @covers OAuth\OAuth2\Service\Dropbox::getAuthorizationMethod
     */
    public function testGetAuthorizationMethod()
    {
        $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface');
        $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0));

        $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface');
        $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES));
        $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo'));

        $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface');
        $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token));

        $service = new Dropbox(
            $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
            $client,
            $storage
        );

        $uri         = $service->request('https://pieterhordijk.com/my/awesome/path');
        $absoluteUri = parse_url($uri->getAbsoluteUri());

        $this->assertSame('access_token=foo', $absoluteUri['query']);
    }

    /**
     * @covers OAuth\OAuth2\Service\Dropbox::__construct
     * @covers OAuth\OAuth2\Service\Dropbox::parseAccessTokenResponse
     */
    public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse()
    {
        $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface');
        $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null));

        $service = new Dropbox(
            $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
            $client,
            $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
        );

        $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException');

        $service->requestAccessToken('foo');
    }

    /**
     * @covers OAuth\OAuth2\Service\Dropbox::__construct
     * @covers OAuth\OAuth2\Service\Dropbox::parseAccessTokenResponse
     */
    public function testParseAccessTokenResponseThrowsExceptionOnError()
    {
        $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface');
        $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error'));

        $service = new Dropbox(
            $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
            $client,
            $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
        );

        $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException');

        $service->requestAccessToken('foo');
    }

    /**
     * @covers OAuth\OAuth2\Service\Dropbox::__construct
     * @covers OAuth\OAuth2\Service\Dropbox::parseAccessTokenResponse
     */
    public function testParseAccessTokenResponseValidWithoutRefreshToken()
    {
        $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface');
        $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}'));

        $service = new Dropbox(
            $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
            $client,
            $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
        );

        $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo'));
    }

    /**
     * @covers OAuth\OAuth2\Service\Dropbox::__construct
     * @covers OAuth\OAuth2\Service\Dropbox::parseAccessTokenResponse
     */
    public function testParseAccessTokenResponseValidWithRefreshToken()
    {
        $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface');
        $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}'));

        $service = new Dropbox(
            $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
            $client,
            $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
        );

        $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo'));
    }
}


text:
<?php

/**
 * @namespace
 */
namespace ShiftContentNew\Exception;

use ShiftContentNew\Exception as ContentException;

/**
 * ShiftContent module domain exception
 *
 * @category    Projectshift
 * @package     ShiftContentNew
 * @subpackage  Exception
 */

class DomainException
    extends \LogicException
    implements ContentException
{
}