<repo_name>animesiki/MEAN_Study<file_sep>/WebPortalDemo/routes/uploadFile.js
/**
 * Created by JIANGWI on 5/22/2015.
 */
var fs = require('fs');

exports.uploadFile = function (req, res) {
    var file = req.files.file;
    var path = file.path;
    var fileName = file.originalname;

    fs.readFile(path, function (error, data) {
        if (error) {
            console.log(error);
        }
        res.send({'content': data, 'xsltName': fileName});
    });

};<file_sep>/WebPortalDemo/routes/datasource.js
/**
 * Created by williamjiang on 2015/5/6.
 */
var DataSourceModel = require('../models/DataSourceModel');

var DataSource = DataSourceModel.DataSource;



exports.createDS = function (req, res) {
    var reqDataSource = req.body;
    reqDataSource.create_time = Date.now();

    if (req.body.channelType == 'FTPInbound') {
        reqDataSource.channel = req.body.ftpInboundChannel;
        reqDataSource.channel.channel_type='FTPInbound';
    }


    if (req.body.channelType == 'FTPOutbound') {
        reqDataSource.channel = req.body.ftpOutboundChannel;
        reqDataSource.channel.channel_type='FTPOutbound';
    }

    if (req.body.channelType == 'EmailInbound') {
        reqDataSource.channel =req.body.emailInboundChannel;
        reqDataSource.channel.channel_type='EmailInbound';
    }

    if (req.body.channelType == 'EmailOutbound') {
        reqDataSource.channel = req.body.emailOutboundChannel;
        reqDataSource.channel.channel_type='EmailOutbound';
    }

    DataSource.create(reqDataSource,function (err, docu) {
        if (err) {
            console.log(err);
        } else {
            console.log('datasource:' + docu);
            res.json(docu);
        }
    });

};

exports.getAllDS = function (req, res) {
    DataSource.find({},{'transformer.xslt':0},function (error, docs) {
        if (error) {
            console.log(error);
            res.send(error);
        }
        if (docs) {
            res.json(docs);
        }
    });
};

exports.getDSBySearchCon = function (req, res) {
    console.log(req.query.app_name);
    console.log(req.query.type);
    var con = {
        app_name: req.query.app_name
    };
    if (req.query.type) {
        con.type = req.query.type
    }
    ;

    DataSource.find(con,{'transformer.xslt':0},function (error, docs) {
        if (error) {
            console.log(error);
            res.send(error);
        }
        if (docs) {
            console.log(docs);
            res.json(docs);
        }
    });

};


exports.getDSById = function (req, res) {
    var reqId = req.query.id;
    console.log('reqId:' + reqId);
    DataSource.find({'_id': reqId},{'transformer.xslt':0},function (error, doc) {
        if (error) {
            console.log(error);
            res.send(error);
        }
        if (doc) {
            console.log('getDSById:' + doc);
            res.json(doc);
        }
    });
};

exports.removeDS = function (req, res) {
    var id = req.body._id;
    console.log("remove id:" + id);
    DataSource.remove({_id: id}, function (err) {
        if (err) {
            console.log(err);
        } else {
            console.log("remove datasource success");
            res.send("remove success");
        }
    });

};

exports.updateDS = function (req, res) {
    var reqDataSource=req.body;
    var id = req.body._id;
    if (req.body.channelType == "FTPInbound") {
        reqDataSource.channel=req.body.ftpInboundChannel;
        reqDataSource.channel.channel_type='FTPInbound';
    }

    if (req.body.channelType == "FTPOutbound") {
        reqDataSource.channel=req.body.ftpOutboundChannel;
        reqDataSource.channel.channel_type='FTPOutbound';
    }

    if (req.body.channelType == "EmailInbound") {
        reqDataSource.channel=req.body.emailInboundChannel;
        reqDataSource.channel.channel_type='EmailInbound';
    }

    if (req.body.channelType == "EmailOutbound") {
        reqDataSource.channel=req.body.emailOutboundChannel;
        reqDataSource.channel.channel_type='EmailOutbound';
    }
    reqDataSource.update_time=Date.now();

    DataSource.findByIdAndUpdate(id, {$set: reqDataSource}, function (err, doc) {
        if (err) {
            console.log(err);
        } else {
            console.log("update datasource success");
            res.json(doc);
        }
    });

};

exports.getDataSourceCount = function (req, res) {
    DataSource.count(function (err, count) {
        if (err) {
            console.log(err);
        }
        res.send({'count': count});
    })

};

<file_sep>/WebPortalDemo/models/DataSourceModel.js
/**
 * Created by williamjiang on 2015/5/6.
 */
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var DataSourceSchema = new Schema({
    app_name: {type: String,required:true},
    owner_specific_key: {type: String},
    type: {type: String},
    is_inbound: {type: Boolean},
    is_internal: {type: Boolean},
    is_route: {type: Boolean},
    create_time: {type: Date},
    update_time: {type: Date},
    adapter: {
        adapter_type: {type: String},
        with_col_header: {type: Boolean},
        is_multi_sheets: {type: Boolean}
    },
    channel: {
        host: {type: String},
        user: {type: String},
        pass: {type: String},
        channel_type:{type:String},
        read_pattern: {type: String},
        write_pattern: {type: String},
        dir_path: {type: String},
        cron_expression: {type: String},
        from: {type: String},
        subject: {type: String},
        send_to: {type: String},
        subject_template: {type: String},
        email_body_template: {type: String}
    },
    transformer: {
        xslt_name: {type: String},
        need_split: {type: Boolean},
        split_num: {type: Number},
        node_path: {type: String},
        xslt: {type: Buffer}
    }
}
);

var DataSource = mongoose.model('DataSource', DataSourceSchema);

// entity method,use in entity layer
//DataSourceSchema.methods.findSimilarTypes=function(cb){
//    return DataSource.find({type:this.type},cb);
//};
////static method, use in model layer
//DataSource.methods.findDataSourceByKey=function(key,cb){
//    this.find({owner_specific_key:key},cb);
//};

//virtual attribute
DataSourceSchema.virtual('code').get(function(){
    return this.app_name+'/'+this.owner_specific_key;
});
DataSourceSchema.virtual('code').set(function(code){
    var split=code.split('/');
    this.app_name=split[0];
    this.owner_specific_key=split[1];
});


exports.DataSource = DataSource;

<file_sep>/WebPortalDemo/app/app.js

/**
 * Created by williamjiang on 2015/4/22.
 */

// Declare app level module which depends on views, and components
var reportApp = angular.module('webPortalApp', [
    'ngRoute',
    'webPortalApp.mainController',
    'webPortalApp.dataSourceController',
    'webPortalApp.services',
    'webPortalApp.filters',
    'webPortalApp.directives'
]);

reportApp.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/home', {
            templateUrl: 'home.html',
            controller: 'home'
        })
        .when('/DataSourceMgn', {
            templateUrl: 'ds_manage.html',
            controller: 'dataSourceMng'
        })
        .otherwise({
            redirectTo: '/home'
        });
}]);

<file_sep>/WebPortalDemo/routes/dmtpApp.js
/**
 * Created by williamjiang on 2015/5/6.
 */
var AppModel = require('../models/AppModel');

var App = AppModel.App;
var Type = AppModel.Type;

exports.getAllApps = function (req, res) {
    App.find(function (error, docs) {
        if (error) {
            console.log(error);
            res.send(error);
        }
        if (docs) {
            console.log(docs);
            console.log(docs[0].types);
            res.json(docs);
        }
    });

};

exports.getAppCount = function (req, res) {
    App.count(function (err, count) {
        if (err) {
            console.log(err);
        }
        res.send({'count': count});
    })

};<file_sep>/MeanLoginDemo/routes/user.js
/**
 * Created by williamjiang on 2015/5/6.
 */
var path = require('path');
var UsersModel=require('../model/UsersModel');

var User=UsersModel.User;



exports.loginCheck=function(req,res){
    console.log("request:"+req);
    console.log("request body:"+req.body);

    var name=req.body.name;
    var password=req.body.password;
    console.log(name);
    User.findOne({name:name,password:password},function(error,doc){
        if(error){
            console.log(error);
            res.send(error);
        }
        if(doc){
            console.log(doc);
            res.send({redirect: '/index',user:doc});
        }

    });


};




exports.allUser=function(req,res){
    User.find({},{name:1,password:1,email:1,_id:1},function(err,result){
        if(err){
            console.log(err);
            res.send(err);
        }
        console.log(result);
        res.json(result);
    });
};

exports.href=function(req,res){
    var ident=req.body.ident;
    console.log(ident);
    if(ident=="signup"){
        res.send({redirect:"/signup"});
    }else{
        res.send({redirect:"/login"});
    }
};


exports.nameCheck=function(req,res){
    console.log("request:"+req);
    console.log("request body:"+req.body);

    var name=req.body.name;
    console.log(name);
    User.findOne({name:name},function(error,doc){
        if(error){
            console.log(error);
            res.send(error);
        }
        console.log(doc);
        if(doc){
            res.send({hint:"name exist"});
        }else{
            res.send({hint:"correct"});
        }

    });

};



exports.SignUp=function(req,res){
    console.log("request:"+req);
    console.log("request body:"+req.body);

    var name=req.body.name;
    var password=<PASSWORD>;
    var email=req.body.email;
    console.log(name);
    User.create({name:name,password:<PASSWORD>,email:email},function(error,doc){
        if(error){
            console.log(error);
            res.send(error);
        }
        if(doc){
            console.log(doc);
            res.send({hint:"Sign up success, pls login",redirect:"/login"});
        }

    });

};<file_sep>/WebPortalDemo/routes/routes.js
/**
 * Created by williamjiang on 2015/5/6.
 */
var user = require('./user');
var datasource = require('./datasource');
var dmtpApp = require('./dmtpApp');
var upload = require('./uploadFile');
var download = require('./downloadFile');


module.exports = function (app) {
    //app.get('/login',user.showLoginPage);
    app.post('/loginCheck', user.loginCheck);
    app.get('/logOut', user.logOut);
    app.get('/getAllApps', dmtpApp.getAllApps);
    app.get('/getAppCount', dmtpApp.getAppCount);
    app.get('/getAllDS', datasource.getAllDS);
    app.get('/searchDSByCon', datasource.getDSBySearchCon);
    app.post('/createDS', datasource.createDS);
    app.post('/updateDS', datasource.updateDS);
    app.get('/getDSById', datasource.getDSById);
    app.post('/removeDS', datasource.removeDS);
    app.get('/getDataSourceCount', datasource.getDataSourceCount);
    app.post('/uploadFile', upload.uploadFile);
    app.get('/downloadFile', download.downloadFile);
}
<file_sep>/WebPortalDemo/models/UsersModel.js
/**
 * Created by williamjiang on 2015/5/6.
 */
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    name: {type: String},
    password: {type: String},
    email: {type: String},
    age: {type: Number,min:18,max:70}
});

exports.User = mongoose.model('User', UserSchema);<file_sep>/WebPortalDemo/models/AppModel.js
/**
 * Created by williamjiang on 2015/5/6.
 */
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var AppSchema = new Schema({
    name: {type: String, unique: true},
    types: [String]
});

var App = mongoose.model('App', AppSchema);
exports.App = App;


<file_sep>/WebPortalDemo/routes/user.js
/**
 * Created by williamjiang on 2015/5/6.
 */
var path = require('path');
var UsersModel = require('../models/UsersModel');

var User = UsersModel.User;


exports.showLoginPage = function (req, res) {
    var html = path.normalize(__dirname + '/../app/login.html');
    res.sendfile(html);
};

exports.loginCheck = function (req, res) {
    console.log("request:" + req);
    console.log("request body:" + req.body);
    var name = req.body.name;
    var password = req.body.password;
    console.log(name);
    User.findOne({name: name, password: <PASSWORD>}, function (error, doc) {
        if (error) {
            console.log(error);
            res.send(error);
        }
        if (doc) {
            console.log(doc);
            req.session.user_id = doc._id;
            res.json(doc);
        }

    });

};

exports.logOut = function (req, res) {
    req.session.destroy(function (err) {
        // cannot access session here
        console.log("log out error" + err);
    });
    res.send('log out success');
};
<file_sep>/WebPortalDemo/server.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var multer = require('multer');
var path = require('path');
var routes = require('./routes/routes');
var DMTPAPP = require('./models/AppModel');
var session = require('express-session');

var app = express();
var db = mongoose.connect('mongodb://localhost:27017/meandb');
db.connection.on("error", function (error) {
    console.log("connect failed：" + error);
});
db.connection.on("open", function () {
    console.log("connect success");
});


app.set('views', __dirname + '/app');
app.set('view engine', 'html');
app.use(express.static(require('path').join(__dirname, 'app')));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(multer());
app.engine('.html', require('ejs').__express);

// create application/json parser
var jsonParser = bodyParser.json();

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({extended: false});

//add session
app.use(session({
    //genid: function(req) {
    //	return genuuid() // use UUIDs for session IDs
    //},
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true
}));

app.use('/index', function (req, res, next) {
    if (req.session.user_id) {
        next();
    } else {
        res.redirect('/login');
    }
});


routes(app);
//Definition model

var App = DMTPAPP.App;

var App1 = new App({
    name: 'DCS',
    types: ['LOK', 'IGH']
});

App1.types.push('CGO','RPL');
App1.save(function (error, doc) {
    if (error) {
        console.log("error :" + error);
    } else {
        console.log(doc);
    }
});

app.get('/index', function (req, res) {
    res.render('index');
});

app.get('/login', function (req, res) {
    res.render('login');
});
var server = app.listen(8800, function () {
    console.log('listening on port %d', server.address().port);
});
<file_sep>/WebPortalDemo/routes/downloadFile.js
/**
 * Created by JIANGWI on 5/22/2015.
 */
var fs = require('fs');
var DataSourceModel = require('../models/DataSourceModel');
var DataSource = DataSourceModel.DataSource;
var path = require('path');


exports.downloadFile = function (req, res) {
    var dataSourceId = req.query.id;
    var dataSource;
    //find datasource transformer and xslt
    DataSource.findOne({_id: dataSourceId}, function (error, doc) {
        if (error) {
            console.log(error);
        }
        dataSource = doc;
        var xsltBuffer =dataSource.transformer.xslt;
        var xsltName =dataSource.transformer.xslt_name;
        res.attachment(xsltName);
        res.write(xsltBuffer);
        res.end();
    });


};