<commit_before>/**
 * module to handle the urlshortener challenge
 */

const randomizeNumber = () => {
  return Math.floor(Math.random() * (999999 - 1 + 1) + 1)
}
const validateUrl = value => {
  const testurl = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i
  return testurl.test(value)
}
const searchId = (id, urls) => {
  // return !!urls.find(item=>item.urlid===id);
  const result = urls.find(item => item.urlid === id)
  if (result) {
    return true
  }
  return false
}
const createShortUrl = value => {
  const shortNOK={shortId: -1, original_url: value.url, shortened_url: 'NOK'};
  const isvalid = validateUrl(value.url)
  const listofUrls = [...value.urls]
  if (isvalid) {
    console.log('====================================');
    console.log(`entered is valid:${isvalid}\nlistofurls=>${JSON.stringify(listofUrls,null,2)}`);
    console.log('====================================');
    let randomId = randomizeNumber()
    console.log('====================================');
    console.log(`randomId:${isvalid}`);
    console.log('====================================');
    while (searchId(randomId, listofUrls)) {
      randomId = randomizeNumber()
      console.log('====================================');
      console.log(`randomId:${JSON.stringify(randomId,null,2)}`);
      console.log('====================================');

    }
    const shortOK={
      shortId: randomId,
      shortened_url:
        process.env.NODE.env !== 'production'
          ? `http://localhost:5000/api/short/${randomId}`
          : `https://freecodecampapichallenges.herokuapp.com/api/short/${randomId}`,
      original_url: value.url
    }
    console.log('====================================');
    console.log(`short ok:${JSON.stringify(shortOK,null,2)}`);
    console.log('====================================');
    return shortOK;
    // return {
    //   shortId: randomId,
    //   shortened_url:
    //     process.env.NODE.env !== 'production'
    //       ? `http://localhost:5000/api/short/${randomId}`
    //       : `https://freecodecampapichallenges.herokuapp.com/api/short/${randomId}`,
    //   original_url: value.url
    // }
  }
  return shortNOK;
}
export default createShortUrl
<commit_msg>urlshort corrected check for node env var<commit_after>/**
 * module to handle the urlshortener challenge
 */

const randomizeNumber = () => {
  return Math.floor(Math.random() * (999999 - 1 + 1) + 1)
}
const validateUrl = value => {
  const testurl = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i
  return testurl.test(value)
}
const searchId = (id, urls) => {
  // return !!urls.find(item=>item.urlid===id);
  const result = urls.find(item => item.urlid === id)
  if (result) {
    return true
  }
  return false
}
const createShortUrl = value => {
  const shortNOK={shortId: -1, original_url: value.url, shortened_url: 'NOK'};
  const isvalid = validateUrl(value.url)
  const listofUrls = [...value.urls]
  if (isvalid) {
    let randomId = randomizeNumber()
    console.log('====================================');
    console.log(`randomId:${randomId}`);
    console.log('====================================');
    while (searchId(randomId, listofUrls)) {
      randomId = randomizeNumber()
      console.log('====================================');
      console.log(`randomId:${JSON.stringify(randomId,null,2)}`);
      console.log('====================================');

    }
    const shortOK={
      shortId: randomId,
      shortened_url:
      process.env.NODE_ENV!=='production'
          ? `http://localhost:5000/api/short/${randomId}`
          : `https://freecodecampapichallenges.herokuapp.com/api/short/${randomId}`,
      original_url: value.url
    }
    console.log('====================================');
    console.log(`short ok:${JSON.stringify(shortOK,null,2)}`);
    console.log('====================================');
    return shortOK;
  }
  return shortNOK;
}
export default createShortUrl
<|endoftext|>


<commit_before>var request = require('request');
var _ = require('underscore');
var Promise = require('bluebird');
var Boom = require('boom');
var spawn = require('child_process').spawn;
var fs = require('fs');
var os = require('os');
var path = require('path');

module.exports = function (server, conf) {

	var handler = {};

	const startExecutionServers = function(){
		return Promise.map(_.keys(conf.executionservers), function(eskey){
			return new Promise(function(resolve, reject){
				var token = server.methods.jwtauth.sign({ executionserver: eskey });
				var filename = path.join(os.tmpdir(), "." + eskey);
				fs.writeFile(filename, JSON.stringify(token), function(err){
					if(err){
						reject(err);
					}else{
						resolve(filename);
					}
				})
			})
			.then(function(filename){
				return new Promise(function(resolve, reject){
					var executionserver = conf.executionservers[eskey];
					var destination = path.join(executionserver.sourcedir, ".token");

					const scp = spawn('scp', ['-i', executionserver.identityfile, filename, executionserver.user + "@" + executionserver.hostname + ":" + destination ]);
					var alldata = "";
					scp.stdout.on('data', function(data){
						alldata += data;
					});

					var allerror = "";
					scp.stderr.on('data', function(data){
						allerror += data;
					});

					scp.on('close', function(code){
						if(code !== 0 || allerror !== ''){
							reject(Boom.badImplementation(allerror));
						}else{
							resolve(filename);
						}
					});
				});
			})
			.then(function(filename){
				try{
					var stats = fs.statSync(filename);
					if(stats){
						fs.unlink(filename);
					}
				}catch(e){
					console.error(e);
				}

			})
			.catch(function(err){
				console.error(err);
			});
		});
	}

	server.method({
		name: "executionserver.startExecutionServers",
		method: startExecutionServers,
		options: {}
	});

	handler.getExecutionServers = function(req, rep){
		var executionservers = [];
		_.each(conf.executionservers, function(es, key){
			var obj = {
				name: key
			};
			if(es.queues){
				obj.queues = es.queues;
			}
			executionservers.push(obj);
		});
		rep(executionservers);
	}

	const getExecutionServer = function(key){
		return conf.executionservers[key];
	}

	server.method({
		name: 'executionserver.getExecutionServer',
		method: getExecutionServer,
		options: {}
	});
	/*
	*/
	handler.submitJob = function(req, rep){

		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){
			var executionserver = conf.executionservers[doc.executionserver];
			if(!executionserver){
				throw Boom.notFound("The server " + doc.executionserver + " is not configured.");
			}

			var params = ['-q', '-i', executionserver.identityfile, executionserver.user + "@" + executionserver.hostname, "node", executionserver.sourcedir + "/index.js", "-j", req.params.id, "--submit"];

			if(req.payload.force){
				params.push("-f");
			}

			const submitjob = spawn('ssh', params);

			var alldata = "";
			submitjob.stdout.on('data', function(data){
				alldata += data;
			});

			var allerror = "";
			submitjob.stderr.on('data', function(data){
				allerror += data;
			});

			submitjob.on('close', function(code){
				if(code !== 0 || allerror !== ''){
					console.error(allerror);
					console.log(alldata);
					rep(Boom.badImplementation(allerror));
				}else{
					var view = "_design/getJob/_view/status?key=" + JSON.stringify(doc._id);
				    server.methods.clusterprovider.getView(view)
				    .then(function(docs){
				    	rep(_.pluck(docs, "value")[0]);
				    })
				    .catch(function(e){
				    	rep(Boom.badImplementation(e));
				    });
				}
			});
		}).catch(function(e){
			rep(Boom.badImplementation(e));
		});
	}

	handler.killJob = function(req, rep){
		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){
			var executionserver = conf.executionservers[doc.executionserver];
			if(!executionserver){
				throw Boom.notFound("The server " + doc.executionserver + " is not configured.");
			}

			const killjob = spawn('ssh', ['-q', '-i', executionserver.identityfile, executionserver.user + "@" + executionserver.hostname, "node", executionserver.sourcedir + "/index.js", "-j", req.params.id, "--kill"]);

			var alldata = "";
			killjob.stdout.on('data', function(data){
				alldata += data;
			});

			var allerror = "";
			killjob.stderr.on('data', function(data){
				allerror += data;
			});

			killjob.on('close', function(code){
				if(code !== 0 || allerror !== ''){
					console.error(allerror);
					console.log(alldata);
				}
				var view = "_design/getJob/_view/status?key=" + JSON.stringify(doc._id);
			    server.methods.clusterprovider.getView(view)
			    .then(function(docs){
			    	rep(_.pluck(docs, "value")[0]);
			    })
			    .catch(function(e){
			    	rep(Boom.badImplementation(e));
			    });
			});

		}).catch(function(e){
			rep(Boom.badImplementation(e));
		});
	}

	const jobstatus = function(doc){
		return new Promise(function(resolve, reject){
			try{
				var executionserver = conf.executionservers[doc.executionserver];
				const jobstatus = spawn('ssh', ['-q', '-i', executionserver.identityfile, executionserver.user + "@" + executionserver.hostname, "node", executionserver.sourcedir + "/index.js", "-j", doc._id, "--status"]);

				var alldata = "";
				jobstatus.stdout.on('data', function(data){
					alldata += data;
				});

				var allerror = "";
				jobstatus.stderr.on('data', function(data){
					allerror += data;
				});

				jobstatus.on('close', function(code){
					if(allerror !== ""){
						alldata += allerror;
					}
					var view = "_design/getJob/_view/status?key=" + JSON.stringify(doc._id);
				    server.methods.clusterprovider.getView(view)
				    .then(function(docs){
				    	resolve(_.pluck(docs, "value")[0]);
				    })
				    .catch(reject);
				});
			}catch(e){
				reject(e);
			}
		});
	}

	server.method({
	    name: 'executionserver.jobstatus',
	    method: jobstatus,
	    options: {}
	});

	handler.jobStatus = function(req, rep){

		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){
			return server.methods.executionserver.jobstatus(doc);
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.badRequest(e));
		})

	}

	const jobdelete = function(doc){
		return new Promise(function(resolve, reject){
			try{
				var executionserver = conf.executionservers[doc.executionserver];
				const jobdelete = spawn('ssh', ['-q', '-i', executionserver.identityfile, executionserver.user + "@" + executionserver.hostname, "node", executionserver.sourcedir + "/index.js", "-j", doc._id, "--delete"]);

				var alldata = "";
				jobdelete.stdout.on('data', function(data){
					alldata += data;
				});

				var allerror = "";
				jobdelete.stderr.on('data', function(data){
					allerror += data;
				});

				jobdelete.on('close', function(code){
					if(allerror !== ""){
						reject(Boom.badImplementation(allerror));
					}else{
						resolve(alldata);
					}
				});
			}catch(e){
				reject(e);
			}
		});
	}

	server.method({
	    name: 'executionserver.jobdelete',
	    method: jobdelete,
	    options: {}
	});

	return handler;

}<commit_msg>ENH: Unreference spawn when retrieving job status<commit_after>var request = require('request');
var _ = require('underscore');
var Promise = require('bluebird');
var Boom = require('boom');
var spawn = require('child_process').spawn;
var fs = require('fs');
var os = require('os');
var path = require('path');

module.exports = function (server, conf) {

	var handler = {};

	const startExecutionServers = function(){
		return Promise.map(_.keys(conf.executionservers), function(eskey){
			return new Promise(function(resolve, reject){
				var token = server.methods.jwtauth.sign({ executionserver: eskey });
				var filename = path.join(os.tmpdir(), "." + eskey);
				fs.writeFile(filename, JSON.stringify(token), function(err){
					if(err){
						reject(err);
					}else{
						resolve(filename);
					}
				})
			})
			.then(function(filename){
				return new Promise(function(resolve, reject){
					var executionserver = conf.executionservers[eskey];
					var destination = path.join(executionserver.sourcedir, ".token");

					const scp = spawn('scp', ['-i', executionserver.identityfile, filename, executionserver.user + "@" + executionserver.hostname + ":" + destination ]);
					var alldata = "";
					scp.stdout.on('data', function(data){
						alldata += data;
					});

					var allerror = "";
					scp.stderr.on('data', function(data){
						allerror += data;
					});

					scp.on('close', function(code){
						if(code !== 0 || allerror !== ''){
							reject(Boom.badImplementation(allerror));
						}else{
							resolve(filename);
						}
					});
				});
			})
			.then(function(filename){
				try{
					var stats = fs.statSync(filename);
					if(stats){
						fs.unlink(filename);
					}
				}catch(e){
					console.error(e);
				}

			})
			.catch(function(err){
				console.error(err);
			});
		});
	}

	server.method({
		name: "executionserver.startExecutionServers",
		method: startExecutionServers,
		options: {}
	});

	handler.getExecutionServers = function(req, rep){
		var executionservers = [];
		_.each(conf.executionservers, function(es, key){
			var obj = {
				name: key
			};
			if(es.queues){
				obj.queues = es.queues;
			}
			executionservers.push(obj);
		});
		rep(executionservers);
	}

	const getExecutionServer = function(key){
		return conf.executionservers[key];
	}

	server.method({
		name: 'executionserver.getExecutionServer',
		method: getExecutionServer,
		options: {}
	});
	/*
	*/
	handler.submitJob = function(req, rep){

		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){
			var executionserver = conf.executionservers[doc.executionserver];
			if(!executionserver){
				throw Boom.notFound("The server " + doc.executionserver + " is not configured.");
			}

			var params = ['-q', '-i', executionserver.identityfile, executionserver.user + "@" + executionserver.hostname, "node", executionserver.sourcedir + "/index.js", "-j", req.params.id, "--submit"];

			if(req.payload.force){
				params.push("-f");
			}

			const submitjob = spawn('ssh', params);

			var alldata = "";
			submitjob.stdout.on('data', function(data){
				alldata += data;
			});

			var allerror = "";
			submitjob.stderr.on('data', function(data){
				allerror += data;
			});

			submitjob.on('close', function(code){
				if(code !== 0 || allerror !== ''){
					console.error(allerror);
					console.log(alldata);
					rep(Boom.badImplementation(allerror));
				}else{
					var view = "_design/getJob/_view/status?key=" + JSON.stringify(doc._id);
				    server.methods.clusterprovider.getView(view)
				    .then(function(docs){
				    	rep(_.pluck(docs, "value")[0]);
				    })
				    .catch(function(e){
				    	rep(Boom.badImplementation(e));
				    });
				}
			});
		}).catch(function(e){
			rep(Boom.badImplementation(e));
		});
	}

	handler.killJob = function(req, rep){
		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){
			var executionserver = conf.executionservers[doc.executionserver];
			if(!executionserver){
				throw Boom.notFound("The server " + doc.executionserver + " is not configured.");
			}

			const killjob = spawn('ssh', ['-q', '-i', executionserver.identityfile, executionserver.user + "@" + executionserver.hostname, "node", executionserver.sourcedir + "/index.js", "-j", req.params.id, "--kill"]);

			var alldata = "";
			killjob.stdout.on('data', function(data){
				alldata += data;
			});

			var allerror = "";
			killjob.stderr.on('data', function(data){
				allerror += data;
			});

			killjob.on('close', function(code){
				if(code !== 0 || allerror !== ''){
					console.error(allerror);
					console.log(alldata);
				}
				var view = "_design/getJob/_view/status?key=" + JSON.stringify(doc._id);
			    server.methods.clusterprovider.getView(view)
			    .then(function(docs){
			    	rep(_.pluck(docs, "value")[0]);
			    })
			    .catch(function(e){
			    	rep(Boom.badImplementation(e));
			    });
			});

		}).catch(function(e){
			rep(Boom.badImplementation(e));
		});
	}

	const jobstatus = function(doc){
		return new Promise(function(resolve, reject){
			try{
				var executionserver = conf.executionservers[doc.executionserver];
				const jobstatus = spawn('ssh', ['-q', '-i', executionserver.identityfile, executionserver.user + "@" + executionserver.hostname, "node", executionserver.sourcedir + "/index.js", "-j", doc._id, "--status"]);

				jobstatus.on('error', reject);

				jobstatus.unref();

				var view = "_design/getJob/_view/status?key=" + JSON.stringify(doc._id);
			    server.methods.clusterprovider.getView(view)
			    .then(function(docs){
			    	resolve(_.pluck(docs, "value")[0]);
			    })
			    .catch(reject);

			}catch(e){
				reject(e);
			}
		});
	}

	server.method({
	    name: 'executionserver.jobstatus',
	    method: jobstatus,
	    options: {}
	});

	handler.jobStatus = function(req, rep){

		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){
			return server.methods.executionserver.jobstatus(doc)
			.then(function(res){
				return res;
			});
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.badRequest(e));
		});

	}

	const jobdelete = function(doc){
		return new Promise(function(resolve, reject){
			try{
				var executionserver = conf.executionservers[doc.executionserver];
				const jobdelete = spawn('ssh', ['-q', '-i', executionserver.identityfile, executionserver.user + "@" + executionserver.hostname, "node", executionserver.sourcedir + "/index.js", "-j", doc._id, "--delete"]);

				var alldata = "";
				jobdelete.stdout.on('data', function(data){
					alldata += data;
				});

				var allerror = "";
				jobdelete.stderr.on('data', function(data){
					allerror += data;
				});

				jobdelete.on('close', function(code){
					if(allerror !== ""){
						reject(Boom.badImplementation(allerror));
					}else{
						resolve(alldata);
					}
				});
			}catch(e){
				reject(e);
			}
		});
	}

	server.method({
	    name: 'executionserver.jobdelete',
	    method: jobdelete,
	    options: {}
	});

	return handler;

}<|endoftext|>


<commit_before>var SolverPage = new Object();

SolverPage.initialize = function () {
    //Range format [ MIN, DEFAULT, MAX ]
    SolverPage.N_BODY_RANGE = [1, 3, 8];
    SolverPage.SPACIAL_PRECISION_RANGE = [1, 1, 1];
    SolverPage.TIME_PRECISION_RANGE = [1, 10, 50];
    SolverPage.MAX_MASS_RANGE = [1, 1, 20];

    SolverPage.currentBodyCount = SolverPage.N_BODY_RANGE[1];
    SolverPage.currentTimePrecision = SolverPage.TIME_PRECISION_RANGE[1];
    SolverPage.currentMaxMass = SolverPage.MAX_MASS_RANGE[1];
    SolverPage.currentEqualMass = true;
    SolverPage.solutionSeed = undefined;

    SolverPage.displayScale = 150;

    this.resultCanvas = $("#orbit-display")[0];

    /**/
    window.addEventListener('resize', SolverPage.resize, false);
    SolverPage.resize();
    /**/

    $("#n-body-count").val(SolverPage.currentBodyCount);
    $("#time-steps").val(SolverPage.currentTimePrecision);
    $("#equal-masses").prop("checked", SolverPage.currentEqualMass);
    $("#maximum-mass").val(SolverPage.currentMaxMass);
    $("#canvas-scale").val(SolverPage.displayScale);

};

SolverPage.resize = function () {
    var styleWidth = 66; //padding + padding + border * (east,west)

    var extent = [$(window).width(), $(window).height()];
    extent[1] = (extent[1] - $("#header-section").height());

    $("#canvas-section").width(extent[0] - 50);
    $("#canvas-section").height(extent[1] - 115);

    SolverPage.resultCanvas.width = ($("#canvas-section").innerWidth() - styleWidth);
    SolverPage.resultCanvas.height = ($("#canvas-section").innerHeight());

};

SolverPage.validateInput = function () {
    var errorMsg = "";

    var nBodies = parseInt($("#n-body-count").val());
    var timeSteps = parseInt($("#time-steps").val());
    var areEqual = $("#equal-masses").is(":checked");
    var maxMass = parseInt($("#maximum-mass").val());

    if (nBodies >= SolverPage.N_BODY_RANGE[0]
            && nBodies <= SolverPage.N_BODY_RANGE[2]) {
        SolverPage.currentBodyCount = nBodies;
    } else {
        errorMsg = "nBodyCount outside range!";
    }

    if (timeSteps >= SolverPage.TIME_PRECISION_RANGE[0]
            && timeSteps <= SolverPage.TIME_PRECISION_RANGE[2]) {
        SolverPage.currentTimePrecision = timeSteps;
    } else {
        errorMsg = "Time step outside range!";
    }

    if (maxMass >= SolverPage.MAX_MASS_RANGE[0]
            && maxMass <= SolverPage.MAX_MASS_RANGE[2]) {
        SolverPage.currentMaxMass = maxMass;
    } else {
        errorMsg = "Maximum mass outside range!";
    }

    if (errorMsg.length === 0) {
        SolverPage.currentEqualMass = areEqual;
        if ($("#solution-seed").val().trim().length > 0) {
            SolverPage.solutionSeed = $("#solution-seed");
        } else {
            SolverPage.solutionSeed = undefined;
        }
    }
    SolverPage.displayScale = parseInt($("#canvas-scale").val());

    return errorMsg;
};

SolverPage.applySettings = function () {
    var err = SolverPage.validateInput();
    if (err.length === 0) {
        PF('settings-dialog').hide();
    } else {
        $("#error-section").text(err);
    }
};

SolverPage.generateOrbit = function () {
    var config = {
        "nBodies": SolverPage.currentBodyCount,
        "precision": [
            SolverPage.SPACIAL_PRECISION_RANGE[1],
            SolverPage.currentTimePrecision
        ],
        "equalMasses": SolverPage.currentEqualMass,
        "maximumMass": SolverPage.currentMaxMass,
        "gravConst": 1.0,
        "seedValue": SolverPage.solutionSeed
    };

    var solverConfig = new SolverParams(config);

    $("#message-section").empty();
    var preloader = $("#bowlG-original").clone();
    $(preloader).prop('id', 'bowlG');
    $(preloader).children("#bowl_ringG-original").prop('id', 'bowl_ringG');

    $("#message-section").prepend($(preloader));

    SolverUtil.setParams(solverConfig);
    SolverUtil.minimizeFunction(SolverPage.solvedOrbital);
};

SolverPage.solvedOrbital = function () {
    $("#message-section").empty();
    if (typeof SolverUtil !== "undefined" && SolverUtil.solved) {
        SolverPage.displayOrbit(SolverUtil);
    } else {
        $("#message-section").text("Unable to solve orbit for given settings.");
    }
};

SolverPage.redraw = function () {
    SolverPage.displayOrbit(SolverUtil);
};

SolverPage.displayOrbit = function (solverUtil) {

    if (typeof solverUtil !== "undefined" && typeof solverUtil.paramSet !== "undefined") {
        var positionMap = solverUtil.getPositionMap(solverUtil.solution);
        var xList, yList;
        var canvasContext;

        if (typeof positionMap !== "undefined" && positionMap.length) {

            canvasContext = $("canvas")[0].getContext('2d');
            if (typeof canvasContext !== "undefined") {
                canvasContext.clearRect(0, 0, $("canvas").width(), $("canvas").height());

                for (var n = 0; n < positionMap.length; n++) {
                    xList = (positionMap[n])[0];
                    yList = (positionMap[n])[1];

                    var colour = SolverPage.getPastelColour();
                    canvasContext.save();

                    canvasContext.translate($("canvas").width() / 2, $("canvas").height() / 2);
                    canvasContext.scale(SolverPage.displayScale, -SolverPage.displayScale);
                    canvasContext.strokeStyle = colour;
                    canvasContext.lineWidth = 1 / SolverPage.displayScale;

                    var radius = (1 / SolverPage.displayScale) * (solverUtil.paramSet.massValues[n]);

                    canvasContext.beginPath();
                    canvasContext.arc(xList[0], yList[0], radius, 0, 2 * Math.PI, false);
                    canvasContext.fillStyle = colour;
                    canvasContext.fill();
                    canvasContext.stroke();

                    for (var r = 1; r < xList.length; r++) {
                        canvasContext.beginPath();
                        canvasContext.moveTo(xList[r - 1], yList[r - 1]);
                        canvasContext.lineTo(xList[r], yList[r]);
                        canvasContext.stroke();
                    }
                    canvasContext.beginPath();
                    canvasContext.moveTo(xList[xList.length - 1], yList[yList.length - 1]);
                    canvasContext.lineTo(xList[0], yList[0]);
                    canvasContext.stroke();
                    canvasContext.restore();
                }

            } else {
                console.log("Context not available.");
            }
        } else {
            console.log("No available position map.");
        }
    }

};
<commit_msg>Missed variable name change during restructure.<commit_after>var SolverPage = new Object();

SolverPage.initialize = function () {
    //Range format [ MIN, DEFAULT, MAX ]
    SolverPage.N_BODY_RANGE = [1, 3, 8];
    SolverPage.SPACIAL_PRECISION_RANGE = [1, 1, 1];
    SolverPage.TIME_PRECISION_RANGE = [1, 10, 50];
    SolverPage.MAX_MASS_RANGE = [1, 1, 20];

    SolverPage.currentBodyCount = SolverPage.N_BODY_RANGE[1];
    SolverPage.currentTimePrecision = SolverPage.TIME_PRECISION_RANGE[1];
    SolverPage.currentMaxMass = SolverPage.MAX_MASS_RANGE[1];
    SolverPage.currentEqualMass = true;
    SolverPage.solutionSeed = undefined;

    SolverPage.displayScale = 150;

    this.resultCanvas = $("#orbit-display")[0];

    /**/
    window.addEventListener('resize', SolverPage.resize, false);
    SolverPage.resize();
    /**/

    $("#n-body-count").val(SolverPage.currentBodyCount);
    $("#time-steps").val(SolverPage.currentTimePrecision);
    $("#equal-masses").prop("checked", SolverPage.currentEqualMass);
    $("#maximum-mass").val(SolverPage.currentMaxMass);
    $("#canvas-scale").val(SolverPage.displayScale);

};

SolverPage.resize = function () {
    var styleWidth = 66; //padding + padding + border * (east,west)

    var extent = [$(window).width(), $(window).height()];
    extent[1] = (extent[1] - $("#header-section").height());

    $("#canvas-section").width(extent[0] - 50);
    $("#canvas-section").height(extent[1] - 115);

    SolverPage.resultCanvas.width = ($("#canvas-section").innerWidth() - styleWidth);
    SolverPage.resultCanvas.height = ($("#canvas-section").innerHeight());

};

SolverPage.validateInput = function () {
    var errorMsg = "";

    var nBodies = parseInt($("#n-body-count").val());
    var timeSteps = parseInt($("#time-steps").val());
    var areEqual = $("#equal-masses").is(":checked");
    var maxMass = parseInt($("#maximum-mass").val());

    if (nBodies >= SolverPage.N_BODY_RANGE[0]
            && nBodies <= SolverPage.N_BODY_RANGE[2]) {
        SolverPage.currentBodyCount = nBodies;
    } else {
        errorMsg = "nBodyCount outside range!";
    }

    if (timeSteps >= SolverPage.TIME_PRECISION_RANGE[0]
            && timeSteps <= SolverPage.TIME_PRECISION_RANGE[2]) {
        SolverPage.currentTimePrecision = timeSteps;
    } else {
        errorMsg = "Time step outside range!";
    }

    if (maxMass >= SolverPage.MAX_MASS_RANGE[0]
            && maxMass <= SolverPage.MAX_MASS_RANGE[2]) {
        SolverPage.currentMaxMass = maxMass;
    } else {
        errorMsg = "Maximum mass outside range!";
    }

    if (errorMsg.length === 0) {
        SolverPage.currentEqualMass = areEqual;
        if ($("#solution-seed").val().trim().length > 0) {
            SolverPage.solutionSeed = $("#solution-seed");
        } else {
            SolverPage.solutionSeed = undefined;
        }
    }
    SolverPage.displayScale = parseInt($("#canvas-scale").val());

    return errorMsg;
};

SolverPage.applySettings = function () {
    var err = SolverPage.validateInput();
    if (err.length === 0) {
        PF('settings-dialog').hide();
    } else {
        $("#error-section").text(err);
    }
};

SolverPage.generateOrbit = function () {
    var config = {
        "nBodies": SolverPage.currentBodyCount,
        "precision": [
            SolverPage.SPACIAL_PRECISION_RANGE[1],
            SolverPage.currentTimePrecision
        ],
        "equalMasses": SolverPage.currentEqualMass,
        "maximumMass": SolverPage.currentMaxMass,
        "gravConst": 1.0,
        "seedValue": SolverPage.solutionSeed
    };

    var solverConfig = new SolverParams(config);

    $("#message-section").empty();
    var preloader = $("#bowlG-original").clone();
    $(preloader).prop('id', 'bowlG');
    $(preloader).children("#bowl_ringG-original").prop('id', 'bowl_ringG');

    $("#message-section").prepend($(preloader));

    SolverUtil.setParams(solverConfig);
    SolverUtil.minimizeFunction(SolverPage.solvedOrbital);
};

SolverPage.solvedOrbital = function () {
    $("#message-section").empty();
    if (typeof SolverUtil !== "undefined" && SolverUtil.solved) {
        SolverPage.displayOrbit(SolverUtil);
    } else {
        $("#message-section").text("Unable to solve orbit for given settings.");
    }
};

SolverPage.redraw = function () {
    SolverPage.displayOrbit(SolverUtil);
};

SolverPage.displayOrbit = function (solverUtil) {

    if (typeof solverUtil !== "undefined" && typeof solverUtil.paramSet !== "undefined") {
        var positionMap = solverUtil.getPositionMap(solverUtil.solution);
        var xList, yList;
        var canvasContext;

        if (typeof positionMap !== "undefined" && positionMap.length) {

            canvasContext = $("canvas")[0].getContext('2d');
            if (typeof canvasContext !== "undefined") {
                canvasContext.clearRect(0, 0, $("canvas").width(), $("canvas").height());

                for (var n = 0; n < positionMap.length; n++) {
                    xList = (positionMap[n])[0];
                    yList = (positionMap[n])[1];

                    var colour = SolverUtil.getPastelColour();
                    canvasContext.save();

                    canvasContext.translate($("canvas").width() / 2, $("canvas").height() / 2);
                    canvasContext.scale(SolverPage.displayScale, -SolverPage.displayScale);
                    canvasContext.strokeStyle = colour;
                    canvasContext.lineWidth = 1 / SolverPage.displayScale;

                    var radius = (1 / SolverPage.displayScale) * (solverUtil.paramSet.massValues[n]);

                    canvasContext.beginPath();
                    canvasContext.arc(xList[0], yList[0], radius, 0, 2 * Math.PI, false);
                    canvasContext.fillStyle = colour;
                    canvasContext.fill();
                    canvasContext.stroke();

                    for (var r = 1; r < xList.length; r++) {
                        canvasContext.beginPath();
                        canvasContext.moveTo(xList[r - 1], yList[r - 1]);
                        canvasContext.lineTo(xList[r], yList[r]);
                        canvasContext.stroke();
                    }
                    canvasContext.beginPath();
                    canvasContext.moveTo(xList[xList.length - 1], yList[yList.length - 1]);
                    canvasContext.lineTo(xList[0], yList[0]);
                    canvasContext.stroke();
                    canvasContext.restore();
                }

            } else {
                console.log("Context not available.");
            }
        } else {
            console.log("No available position map.");
        }
    }

};
<|endoftext|>


<commit_before>/*
 Copyright 2007-2009 WebDriver committers
 Copyright 2007-2009 Google Inc.
 Portions copyright 2007 ThoughtWorks, Inc

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/**
 * @fileOverview Contains a Javascript implementation for
 * a custom nsICertOverrideService. This class will forward requests to the
 * original certificate override service - unless it was told to accept all
 * of them.
 */

const CC = Components.classes;
const CI = Components.interfaces;

const CONSOLE = CC["@mozilla.org/consoleservice;1"].
                  getService(CI["nsIConsoleService"]);

function localdump(message) {
  try {
    CONSOLE.logStringMessage(message + "\n");
  } catch (e) {
    dump(message + "\n");
  }
}

function getPreferenceFromProfile(prefName, prefDefaultValue) {
  var prefs =
      CC["@mozilla.org/preferences-service;1"].getService(CI["nsIPrefBranch"]);

  if (!prefs.prefHasUserValue(prefName)) {
    localdump(prefName + ' not set; defaulting to ' + prefDefaultValue);
    return prefDefaultValue;
  }

  var prefValue = prefs.getBoolPref(prefName);
  localdump("Found preference for " + prefName + ": " + prefValue);

  return prefValue;
}

function shouldAcceptUntrustedCerts() {
  return getPreferenceFromProfile("webdriver_accept_untrusted_certs", true);
}

function shouldAssumeUntrustedIssuer() {
  return getPreferenceFromProfile("webdriver_assume_untrusted_issuer", true);
}

function WdCertOverrideService() {
  // Defaults to true - accepting untrusted certificates.
  // This puts the module into effect - setting it to false
  // will delegate all calls to the original service.
  this.acceptAll = shouldAcceptUntrustedCerts();

  // If untrusted issuer is set to false by the user,
  // the initial bitmask will not include ERROR_UNTRUSTED.
  //
  // See the javadoc for FirefoxProfile and documentation
  // for fillNeededBits for further explanation.
  var untrusted_issuer = shouldAssumeUntrustedIssuer();
  if (untrusted_issuer) {
    this.default_bits = this.ERROR_UNTRUSTED;
  } else {
    this.default_bits = 0;
  }

  localdump("Accept untrusted certificates: " + this.acceptAll);

  // UUID of the original implementor of this service.
  var ORIGINAL_OVERRIDE_SERVICE_ID = "{67ba681d-5485-4fff-952c-2ee337ffdcd6}";

  // Keep a reference to the original bad certificate listener.
  var originalService = Components.classesByID[ORIGINAL_OVERRIDE_SERVICE_ID].
      getService();

  this.origListener_ =
      originalService.QueryInterface(
        Components.interfaces.nsICertOverrideService);
};

// Constants needed since WdCertOverrideService implements
// nsICertOverrideService
WdCertOverrideService.prototype = {
  ERROR_UNTRUSTED: 1,
  ERROR_MISMATCH: 2,
  ERROR_TIME: 4
};

// Returns the bit needed to mask if the certificate has expired, 0 otherwise.
WdCertOverrideService.prototype.certificateExpiredBit_ = function
  (theCert, verification_result) {
  if ((verification_result & theCert.CERT_EXPIRED) != 0) {
    localdump("Certificate expired.");
    return this.ERROR_TIME;
  }

  return 0;
}

// Returns the bit needed to mask untrusted issuers, 0 otherwise.
// Note that this bit is already set by default in default_bits
WdCertOverrideService.prototype.certificateIssuerUntrusted_ = function
  (theCert, verification_result) {
  if (((verification_result & theCert.ISSUER_UNKNOWN) != 0) ||
      ((verification_result & theCert.ISSUER_NOT_TRUSTED) != 0) ||
      ((verification_result & theCert.CERT_NOT_TRUSTED) != 0) ||
      ((verification_result & theCert.INVALID_CA) != 0)) {
    localdump("Certificate issuer unknown.");
    localdump("Unknown: " + (theCert.ISSUER_UNKNOWN & verification_result));
    localdump("Issuer not trusted: " + (theCert.ISSUER_NOT_TRUSTED & verification_result));
    localdump("Cert not trusted: " + (theCert.CERT_NOT_TRUSTED & verification_result));
    localdump("Invalid CA: " + (theCert.INVALID_CA & verification_result));

    return this.ERROR_UNTRUSTED;
  }

  return 0;
}

// Returns the bit needed to mask mismatch between actual hostname
// and the hostname the certificate was issued for, 0 otherwise.
WdCertOverrideService.prototype.certificateHostnameMismatch_ = function
  (theCert, aHost) {
  commonNameRE = new RegExp("^" + theCert.commonName.replace('*', '\\w+') + "$", "i");
  if (aHost.match(commonNameRE) === null) {
    localdump("Host name mismatch: cert: " + theCert.commonName + " get: " + aHost);
    return this.ERROR_MISMATCH;
  }

  return 0;
}

// Given a certificate and the host it was received for, fill in the bits
// needed to accept this certificate for this host, even though the
// certificate is invalid.
//
// Note that the bitmask has to be accurate: At the moment, Firefox expects
// the returned bitmask to match *exactly* to the errors the certificate
// caused. If extra bits will be set, the untrusted certificate screen
// will appear.
WdCertOverrideService.prototype.fillNeededBits = function(aCert, aHost) {
  var verification_bits = aCert.verifyForUsage(aCert.CERT_USAGE_SSLClient);
  var return_bits = this.default_bits;

  localdump("Certificate verification results: " + verification_bits);

  return_bits = return_bits | this.certificateExpiredBit_(
      aCert, verification_bits);
  return_bits = return_bits | this.certificateHostnameMismatch_(aCert, aHost);

  // Return bits will be 0 here only if:
  // 1. Both checks above returned 0.
  // 2. shouldAssumeUntrustedIssuer is false (otherwise this.default_bits = 1)
  // It has been observed that if there's a host name mismatch then it
  // may not be required to check the trust status of the certificate issuer.
  if (return_bits == 0) {
    localdump("Checking issuer since certificate has not expired or has a host name mismatch.");
    return_bits = return_bits | this.certificateIssuerUntrusted_(
        aCert, verification_bits);
  }

  localdump("return_bits now: " + return_bits);
  return return_bits;
};

// Interface functions from now on.
WdCertOverrideService.prototype.hasMatchingOverride = function(
    aHostName, aPort, aCert, aOverrideBits, aIsTemporary) {
  var retval = false;

  if (this.acceptAll === true) {
    localdump("Allowing certificate from site: " + aHostName + ":" + aPort);
    retval = true;
    aIsTemporary.value = false;

    aOverrideBits.value = this.fillNeededBits(aCert, aHostName);
    localdump("Override Bits: " + aOverrideBits.value);
  } else {
    retval = this.origListener_.hasMatchingOverride(aHostName, aPort,
              aCert, aOverrideBits, aIsTemporary);
  }

  return retval;
};

// Delegate the rest of the functions - they are not interesting as they are not
// called during validation of invalid certificate normally.
WdCertOverrideService.prototype.clearValidityOverride = function(aHostName,
                                                                 aPort) {
  this.origListener_.clearValidityOverride(aHostName, aPort);
};

WdCertOverrideService.prototype.getAllOverrideHostsWithPorts = function(
    aCount, aHostsWithPortsArray) {
  this.origListener_.getAllOverrideHostsWithPorts(aCert, aHostsWithPortsArray);
};

WdCertOverrideService.prototype.getValidityOverride = function(
    aHostName, aPort, aHashAlg, aFingerprint, aOverrideBits, aIsTemporary) {
  return this.origListener_.getValidityOverride(
      aHostName, aPort, aHashAlg, aFingerprint, aOverrideBits, aIsTemporary);
};

WdCertOverrideService.prototype.isCertUsedForOverrides = function(
    aCert, aCheckTemporaries, aCheckPermanents) {
  return this.origListener_.isCertUsedForOverrides(
      aCert, aCheckTemporaries, aCheckPermanents);
};

WdCertOverrideService.prototype.rememberValidityOverride = function(
    aHostName, aPort, aCert, aOverrideBits, aTemporary) {
  this.origListener_.rememberValidityOverride(
      aHostName, aPort, aCert, aOverrideBits, aTemporary);
};

WdCertOverrideService.prototype.QueryInterface = function(aIID) {
  if (aIID.equals(Components.interfaces.nsICertOverrideService) ||
      aIID.equals(Components.interfaces.nsIInterfaceRequestor) ||
      aIID.equals(Components.interfaces.nsISupports)) {
    return this;
  }

  throw Components.results.NS_ERROR_NO_INTERFACE;
};

// Service contract ID which we override
const CERTOVERRIDE_CONTRACT_ID = "@mozilla.org/security/certoverride;1";
// UUID for this instance specifically.
const DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID =
  Components.ID('{c8fffaba-9b7a-41aa-872d-7e7366c16715}');

var service = undefined;

var WDCertOverrideFactory = {
  createInstance: function (aOuter, aIID) {
    if (aOuter != null)
      throw Components.results.NS_ERROR_NO_AGGREGATION;
    if (service == undefined) {
      service = new WdCertOverrideService();
    }
    return service;
  }
};

function WDBadCertListenerModule() {
  this.firstTime_ = true;
}

WDBadCertListenerModule.prototype.registerSelf = function(
    aCompMgr, aFileSpec, aLocation, aType) {

  if (this.firstTime_) {
    this.firstTime_ = false;
    throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  }

  localdump("Registering Override Certificate service.");
  aCompMgr = aCompMgr.QueryInterface(
      Components.interfaces.nsIComponentRegistrar);
  aCompMgr.registerFactoryLocation(
      DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID, "badCertListener",
      CERTOVERRIDE_CONTRACT_ID, aFileSpec, aLocation, aType);
};

WDBadCertListenerModule.prototype.unregisterSelf = function(
    aCompMgr, aLocation, aType) {
  localdump("Un-registering Override Certificate service.");
  aCompMgr =
  aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  aCompMgr.unregisterFactoryLocation(DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID, aLocation);
};

const FACTORY = {
  createInstance: function (aOuter, aIID) {
    if (aOuter != null)
      throw Components.results.NS_ERROR_NO_AGGREGATION;

    if (service != undefined) {
      return service;
    }

    var raw = new WdCertOverrideService();

    var mainThread = CC["@mozilla.org/thread-manager;1"].getService().mainThread;
    var proxyManager = CC["@mozilla.org/xpcomproxy;1"]
        .getService(CI.nsIProxyObjectManager);

    // 5 == NS_PROXY_ALWAYS | NS_PROXY_SYNC
    service = proxyManager.getProxyForObject(mainThread,
                CI.nsICertOverrideService, raw, 5);

    return service;
  }
};

WdCertOverrideService.prototype._xpcom_factory = FACTORY;

WDBadCertListenerModule.prototype.getClassObject = function(
    aCompMgr, aCID, aIID) {
  if (!aIID.equals(Components.interfaces.nsIFactory))
    throw Components.results.NS_ERROR_NOT_IMPLEMENTED;

  if (aCID.equals(DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID)) {
    return FACTORY;
  }

  throw Components.results.NS_ERROR_NO_INTERFACE;
};

WDBadCertListenerModule.prototype.canUnload = function(aCompMgr) {
  return true;
};

function NSGetModule(comMgr, fileSpec) {
  var appInfo = Components.classes['@mozilla.org/xre/app-info;1'].
    getService(Components.interfaces.nsIXULAppInfo);
  var versionChecker = Components.classes['@mozilla.org/xpcom/version-comparator;1'].
    getService(Components.interfaces.nsIVersionComparator);
  if (versionChecker.compare(appInfo.version, '3.0') >= 0) {
    return new WDBadCertListenerModule();
  }
}

WdCertOverrideService.prototype.classID = DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID;
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
if (XPCOMUtils.generateNSGetFactory) {
  const NSGetFactory = XPCOMUtils.generateNSGetFactory([WdCertOverrideService]);
}<commit_msg>EranMes: Merging patch from issue 116. Hosts with dash in their name will now be correctly matched against the commonName field in SSL certificates.<commit_after>/*
 Copyright 2007-2009 WebDriver committers
 Copyright 2007-2009 Google Inc.
 Portions copyright 2007 ThoughtWorks, Inc

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/**
 * @fileOverview Contains a Javascript implementation for
 * a custom nsICertOverrideService. This class will forward requests to the
 * original certificate override service - unless it was told to accept all
 * of them.
 */

const CC = Components.classes;
const CI = Components.interfaces;

const CONSOLE = CC["@mozilla.org/consoleservice;1"].
                  getService(CI["nsIConsoleService"]);

function localdump(message) {
  try {
    CONSOLE.logStringMessage(message + "\n");
  } catch (e) {
    dump(message + "\n");
  }
}

function getPreferenceFromProfile(prefName, prefDefaultValue) {
  var prefs =
      CC["@mozilla.org/preferences-service;1"].getService(CI["nsIPrefBranch"]);

  if (!prefs.prefHasUserValue(prefName)) {
    localdump(prefName + ' not set; defaulting to ' + prefDefaultValue);
    return prefDefaultValue;
  }

  var prefValue = prefs.getBoolPref(prefName);
  localdump("Found preference for " + prefName + ": " + prefValue);

  return prefValue;
}

function shouldAcceptUntrustedCerts() {
  return getPreferenceFromProfile("webdriver_accept_untrusted_certs", true);
}

function shouldAssumeUntrustedIssuer() {
  return getPreferenceFromProfile("webdriver_assume_untrusted_issuer", true);
}

function WdCertOverrideService() {
  // Defaults to true - accepting untrusted certificates.
  // This puts the module into effect - setting it to false
  // will delegate all calls to the original service.
  this.acceptAll = shouldAcceptUntrustedCerts();

  // If untrusted issuer is set to false by the user,
  // the initial bitmask will not include ERROR_UNTRUSTED.
  //
  // See the javadoc for FirefoxProfile and documentation
  // for fillNeededBits for further explanation.
  var untrusted_issuer = shouldAssumeUntrustedIssuer();
  if (untrusted_issuer) {
    this.default_bits = this.ERROR_UNTRUSTED;
  } else {
    this.default_bits = 0;
  }

  localdump("Accept untrusted certificates: " + this.acceptAll);

  // UUID of the original implementor of this service.
  var ORIGINAL_OVERRIDE_SERVICE_ID = "{67ba681d-5485-4fff-952c-2ee337ffdcd6}";

  // Keep a reference to the original bad certificate listener.
  var originalService = Components.classesByID[ORIGINAL_OVERRIDE_SERVICE_ID].
      getService();

  this.origListener_ =
      originalService.QueryInterface(
        Components.interfaces.nsICertOverrideService);
};

// Constants needed since WdCertOverrideService implements
// nsICertOverrideService
WdCertOverrideService.prototype = {
  ERROR_UNTRUSTED: 1,
  ERROR_MISMATCH: 2,
  ERROR_TIME: 4
};

// Returns the bit needed to mask if the certificate has expired, 0 otherwise.
WdCertOverrideService.prototype.certificateExpiredBit_ = function
  (theCert, verification_result) {
  if ((verification_result & theCert.CERT_EXPIRED) != 0) {
    localdump("Certificate expired.");
    return this.ERROR_TIME;
  }

  return 0;
}

// Returns the bit needed to mask untrusted issuers, 0 otherwise.
// Note that this bit is already set by default in default_bits
WdCertOverrideService.prototype.certificateIssuerUntrusted_ = function
  (theCert, verification_result) {
  if (((verification_result & theCert.ISSUER_UNKNOWN) != 0) ||
      ((verification_result & theCert.ISSUER_NOT_TRUSTED) != 0) ||
      ((verification_result & theCert.CERT_NOT_TRUSTED) != 0) ||
      ((verification_result & theCert.INVALID_CA) != 0)) {
    localdump("Certificate issuer unknown.");
    localdump("Unknown: " + (theCert.ISSUER_UNKNOWN & verification_result));
    localdump("Issuer not trusted: " + (theCert.ISSUER_NOT_TRUSTED & verification_result));
    localdump("Cert not trusted: " + (theCert.CERT_NOT_TRUSTED & verification_result));
    localdump("Invalid CA: " + (theCert.INVALID_CA & verification_result));

    return this.ERROR_UNTRUSTED;
  }

  return 0;
}

// Returns the bit needed to mask mismatch between actual hostname
// and the hostname the certificate was issued for, 0 otherwise.
WdCertOverrideService.prototype.certificateHostnameMismatch_ = function
  (theCert, aHost) {
  var commonNameRE = new RegExp("^" + theCert.commonName.replace('*', '[\\w|\-]+') + "$", "i");
  if (aHost.match(commonNameRE) === null) {
    localdump("Host name mismatch: cert: " + theCert.commonName + " get: " + aHost);
    return this.ERROR_MISMATCH;
  }

  return 0;
}

// Given a certificate and the host it was received for, fill in the bits
// needed to accept this certificate for this host, even though the
// certificate is invalid.
//
// Note that the bitmask has to be accurate: At the moment, Firefox expects
// the returned bitmask to match *exactly* to the errors the certificate
// caused. If extra bits will be set, the untrusted certificate screen
// will appear.
WdCertOverrideService.prototype.fillNeededBits = function(aCert, aHost) {
  var verification_bits = aCert.verifyForUsage(aCert.CERT_USAGE_SSLClient);
  var return_bits = this.default_bits;

  localdump("Certificate verification results: " + verification_bits);

  return_bits = return_bits | this.certificateExpiredBit_(
      aCert, verification_bits);
  return_bits = return_bits | this.certificateHostnameMismatch_(aCert, aHost);

  // Return bits will be 0 here only if:
  // 1. Both checks above returned 0.
  // 2. shouldAssumeUntrustedIssuer is false (otherwise this.default_bits = 1)
  // It has been observed that if there's a host name mismatch then it
  // may not be required to check the trust status of the certificate issuer.
  if (return_bits == 0) {
    localdump("Checking issuer since certificate has not expired or has a host name mismatch.");
    return_bits = return_bits | this.certificateIssuerUntrusted_(
        aCert, verification_bits);
  }

  localdump("return_bits now: " + return_bits);
  return return_bits;
};

// Interface functions from now on.
WdCertOverrideService.prototype.hasMatchingOverride = function(
    aHostName, aPort, aCert, aOverrideBits, aIsTemporary) {
  var retval = false;

  if (this.acceptAll === true) {
    localdump("Allowing certificate from site: " + aHostName + ":" + aPort);
    retval = true;
    aIsTemporary.value = false;

    aOverrideBits.value = this.fillNeededBits(aCert, aHostName);
    localdump("Override Bits: " + aOverrideBits.value);
  } else {
    retval = this.origListener_.hasMatchingOverride(aHostName, aPort,
              aCert, aOverrideBits, aIsTemporary);
  }

  return retval;
};

// Delegate the rest of the functions - they are not interesting as they are not
// called during validation of invalid certificate normally.
WdCertOverrideService.prototype.clearValidityOverride = function(aHostName,
                                                                 aPort) {
  this.origListener_.clearValidityOverride(aHostName, aPort);
};

WdCertOverrideService.prototype.getAllOverrideHostsWithPorts = function(
    aCount, aHostsWithPortsArray) {
  this.origListener_.getAllOverrideHostsWithPorts(aCert, aHostsWithPortsArray);
};

WdCertOverrideService.prototype.getValidityOverride = function(
    aHostName, aPort, aHashAlg, aFingerprint, aOverrideBits, aIsTemporary) {
  return this.origListener_.getValidityOverride(
      aHostName, aPort, aHashAlg, aFingerprint, aOverrideBits, aIsTemporary);
};

WdCertOverrideService.prototype.isCertUsedForOverrides = function(
    aCert, aCheckTemporaries, aCheckPermanents) {
  return this.origListener_.isCertUsedForOverrides(
      aCert, aCheckTemporaries, aCheckPermanents);
};

WdCertOverrideService.prototype.rememberValidityOverride = function(
    aHostName, aPort, aCert, aOverrideBits, aTemporary) {
  this.origListener_.rememberValidityOverride(
      aHostName, aPort, aCert, aOverrideBits, aTemporary);
};

WdCertOverrideService.prototype.QueryInterface = function(aIID) {
  if (aIID.equals(Components.interfaces.nsICertOverrideService) ||
      aIID.equals(Components.interfaces.nsIInterfaceRequestor) ||
      aIID.equals(Components.interfaces.nsISupports)) {
    return this;
  }

  throw Components.results.NS_ERROR_NO_INTERFACE;
};

// Service contract ID which we override
const CERTOVERRIDE_CONTRACT_ID = "@mozilla.org/security/certoverride;1";
// UUID for this instance specifically.
const DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID =
  Components.ID('{c8fffaba-9b7a-41aa-872d-7e7366c16715}');

var service = undefined;

var WDCertOverrideFactory = {
  createInstance: function (aOuter, aIID) {
    if (aOuter != null)
      throw Components.results.NS_ERROR_NO_AGGREGATION;
    if (service == undefined) {
      service = new WdCertOverrideService();
    }
    return service;
  }
};

function WDBadCertListenerModule() {
  this.firstTime_ = true;
}

WDBadCertListenerModule.prototype.registerSelf = function(
    aCompMgr, aFileSpec, aLocation, aType) {

  if (this.firstTime_) {
    this.firstTime_ = false;
    throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  }

  localdump("Registering Override Certificate service.");
  aCompMgr = aCompMgr.QueryInterface(
      Components.interfaces.nsIComponentRegistrar);
  aCompMgr.registerFactoryLocation(
      DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID, "badCertListener",
      CERTOVERRIDE_CONTRACT_ID, aFileSpec, aLocation, aType);
};

WDBadCertListenerModule.prototype.unregisterSelf = function(
    aCompMgr, aLocation, aType) {
  localdump("Un-registering Override Certificate service.");
  aCompMgr =
  aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  aCompMgr.unregisterFactoryLocation(DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID, aLocation);
};

const FACTORY = {
  createInstance: function (aOuter, aIID) {
    if (aOuter != null)
      throw Components.results.NS_ERROR_NO_AGGREGATION;

    if (service != undefined) {
      return service;
    }

    var raw = new WdCertOverrideService();

    var mainThread = CC["@mozilla.org/thread-manager;1"].getService().mainThread;
    var proxyManager = CC["@mozilla.org/xpcomproxy;1"]
        .getService(CI.nsIProxyObjectManager);

    // 5 == NS_PROXY_ALWAYS | NS_PROXY_SYNC
    service = proxyManager.getProxyForObject(mainThread,
                CI.nsICertOverrideService, raw, 5);

    return service;
  }
};

WdCertOverrideService.prototype._xpcom_factory = FACTORY;

WDBadCertListenerModule.prototype.getClassObject = function(
    aCompMgr, aCID, aIID) {
  if (!aIID.equals(Components.interfaces.nsIFactory))
    throw Components.results.NS_ERROR_NOT_IMPLEMENTED;

  if (aCID.equals(DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID)) {
    return FACTORY;
  }

  throw Components.results.NS_ERROR_NO_INTERFACE;
};

WDBadCertListenerModule.prototype.canUnload = function(aCompMgr) {
  return true;
};

function NSGetModule(comMgr, fileSpec) {
  var appInfo = Components.classes['@mozilla.org/xre/app-info;1'].
    getService(Components.interfaces.nsIXULAppInfo);
  var versionChecker = Components.classes['@mozilla.org/xpcom/version-comparator;1'].
    getService(Components.interfaces.nsIVersionComparator);
  if (versionChecker.compare(appInfo.version, '3.0') >= 0) {
    return new WDBadCertListenerModule();
  }
}

WdCertOverrideService.prototype.classID = DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID;
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
if (XPCOMUtils.generateNSGetFactory) {
  const NSGetFactory = XPCOMUtils.generateNSGetFactory([WdCertOverrideService]);
}<|endoftext|>


<commit_before>$(document).ready(function() {
    init();
});

var map, controls;
var stands;
var currentStep = 1;
var steps = [undefined]; // start with a blank to make it 1-indexed

function init() {
    map = new OpenLayers.Map('map',
        {
            projection: new OpenLayers.Projection('EPSG:3857')
        }
    );
    var switcher = new OpenLayers.Control.LayerSwitcher({'div':OpenLayers.Util.getElement('layerswitcher')});
    map.addControl(switcher);

    map.addControl( new OpenLayers.Control.Navigation({
            dragPanOptions: {
                enableKinetic: false
            }
        }));

    map.addControl(new OpenLayers.Control.KeyboardDefaults({observeElement: 'map'}));

    map.addControl(new OpenLayers.Control.Attribution());

    map.addControl(new OpenLayers.Control.ScaleLine());

    var arrayAerial = [
        "http://otile1.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
        "http://otile2.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
        "http://otile3.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
        "http://otile4.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg"];
    var baseAerial = new OpenLayers.Layer.OSM("Aerial Imagery",
        arrayAerial, {attribution:"MapQuest"});
    map.addLayer(baseAerial);

    var arrayOSM = [
        "http://otile1.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg",
        "http://otile2.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg",
        "http://otile3.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg",
        "http://otile4.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg"];
    var baseOSM = new OpenLayers.Layer.OSM("Street Map",
        arrayOSM, {attribution:"Mapquest, OpenStreetMap"});
    map.addLayer(baseOSM);

    var esriLayers = [
      ["Topo map (Digital)", 'World_Topo_Map', 'USGS'],
      ["Topo map (Quads)", 'World_Topo_Map', 'USGS'],
      ["Satellite Imagery", 'World_Imagery']
    ];

    for (var i=esriLayers.length-1; i>=0; --i) {
        var lyrLongName = esriLayers[i][0];
        var lyrShortName = esriLayers[i][1];
        var attribution = "Basemaps by ESRI";
        if (esriLayers[i].length > 2) {
            attribution = attribution + ', ' + esriLayers[i][2];
        }

        var config = {
            sphericalMercator: true,
            attribution: attribution
        };

        if (esriLayers[i][0] == "Topo map (Quads)") {
            config.resolutions = [156543.03390625,78271.516953125,39135.7584765625,19567.87923828125,9783.939619140625,4891.9698095703125,2445.9849047851562,1222.9924523925781,611.4962261962891,305.74811309814453,152.87405654907226,76.43702827453613,38.218514137268066,19.109257068634033,9.554628534317017,4.777314267158508,2.388657133579254,1.194328566789627,0.5971642833948135];
            config.serverResolutions = [156543.03390625,78271.516953125,39135.7584765625,19567.87923828125,9783.939619140625,4891.9698095703125,2445.9849047851562,1222.9924523925781,611.4962261962891,305.74811309814453,152.87405654907226,76.43702827453613,38.218514137268066,19.109257068634033,9.554628534317017,4.777314267158508];
        }

        var lyr = new OpenLayers.Layer.XYZ( lyrLongName,
            "http://server.arcgisonline.com/ArcGIS/rest/services/"+ lyrShortName +"/MapServer/tile/${z}/${y}/${x}",
            config
        );
        lyr.shortName = lyrShortName;
        map.addLayer(lyr);
    }

    var tileServerLayers = [
        [ "Wetlands", "LOT_wetlands"],
        [ "Stream Buffers", "LOT_streambuffers"],
        [ "Streams", "LOT_streams"]
    ];

    for (var i=tileServerLayers.length-1; i>=0; --i) {
        var lyrLongName = tileServerLayers[i][0];
        var lyrShortName = tileServerLayers[i][1];
        var arrayTile = [
            "http://a.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
            "http://b.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
            "http://c.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
            "http://d.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
        ];
        var lyr = new OpenLayers.Layer.XYZ( lyrLongName, arrayTile,
            {sphericalMercator: true, isBaseLayer: false, visibility: false, attribution:"Ecotrust"}
        );
        lyr.shortName = lyrShortName;
        map.addLayer(lyr);
        lyr.events.register('visibilitychanged', lyr, function(evt) {
            if (this.visibility) {
                $('#legend').append('
' +
                    '');
            } else {
                $('#' + this.shortName + '-legend').remove();
            }
        });
    }

    var soils = new OpenLayers.Layer.XYZ( "Soil Types (Names)",
        "http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/Soil_Survey_Map/MapServer/tile/${z}/${y}/${x}",
        {sphericalMercator: true,
         isBaseLayer: false,
         visibility: false,
         opacity: 0.75,
         attribution: "ESRI, USDA NRCS"}
    );
    map.addLayer(soils);
    soils.events.register('visibilitychanged', soils, function(evt) {
        if (soils.visibility) {
            $('.layersDiv').append('

more info
');
        } else {
            $('#soil-legend').remove();
        }
    });

     var soilsWMS = new OpenLayers.Layer.WMS( "Soil Types (Codes)",
        "http://sdmdataaccess.nrcs.usda.gov/Spatial/SDM.wms",
        {
            layers: 'MapunitPoly',
            transparent: true
        }
        , {
            isBaseLayer: false,
            attribution: "USDA NRCS",
            visibility: false
        }
    );
    map.addLayer(soilsWMS);

    var tileServerLayers2 = [
        [ "Conservation Easements", "LOT_natconseasedb"],
        [ "Critical Habitat (Public Land)", "Crithab"],
        [ "Critical Stream Habitat", "Crithab_streams"],
        [ "Land Ownership", "LOT_protareas"],
        [ "Mill Facilities", "USFSMillFacilities", "USFS"],
        [ "Watershed Boundaries", "LOT_watersheds"],
        [ "Counties", "LOT_counties"],
        [ "Township and Range", "LOT_plss"],
        [ "Tax Lots (where available)", "LOT_parcels"],
        [ "Steep Slopes (>40%)", "LOT_steepslopes"]
    ];

    for (var i=tileServerLayers2.length-1; i>=0; --i) {
        var lyrLongName = tileServerLayers2[i][0];
        var lyrShortName = tileServerLayers2[i][1];
        var arrayTile = [
            "http://a.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
            "http://b.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
            "http://c.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
            "http://d.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
        ];
        var attribution = "Ecotrust"
        if (tileServerLayers2[i].length > 2){
            attribution = tileServerLayers2[i][2];
        }
        var lyr = new OpenLayers.Layer.XYZ( lyrLongName, arrayTile,
            {sphericalMercator: true, isBaseLayer: false, visibility: false, attribution:attribution}
        );
        lyr.shortName = lyrShortName;
        map.addLayer(lyr);
        lyr.events.register('visibilitychanged', lyr, function(evt) {
            if (this.visibility) {
                $('#legend').append('
' +
                    '');
            } else {
                $('#' + this.shortName + '-legend').remove();
            }
        });
    }

    map.setCenter(new OpenLayers.LonLat(0, 0), 7);

    for (var i=map.layers.length-1; i>=0; --i) {
        map.layers[i].animationEnabled = true;
    }

    app.markers = new OpenLayers.Layer.Markers("search", {displayInLayerSwitcher: false});
    map.addLayer(app.markers);

    // Add stands
    var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
    app.renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;

    new_features = new OpenLayers.Layer.Vector("New Features", {
        renderers: app.renderer,
        styleMap: map_styles.drawn,
        displayInLayerSwitcher: false
    }
    );
    map.addLayer(new_features);
    app.new_features = new_features;

    app.geojson_format = new OpenLayers.Format.GeoJSON(),
    app.property_layer = new OpenLayers.Layer.Vector("My Properties",  {
        renderers: app.renderer,
        styleMap: map_styles.forestProperty
    });
    app.stand_layer = new OpenLayers.Layer.Vector("Stands",  {
        renderers: app.renderer,
        styleMap: map_styles.forestProperty
    });
    map.addLayer(app.property_layer);

    // add controls, save references
    app.selectFeature = new OpenLayers.Control.SelectFeature(app.property_layer,
        { "clickout": false});

    // reenable click and drag in vectors
    app.selectFeature.handlers.feature.stopDown = false;

    map.addControl(app.selectFeature);
    app.modifyFeature = new OpenLayers.Control.ModifyFeature(app.property_layer);
    map.addControl(app.modifyFeature);
    // draw is in tree.js TODO: move)
    // activate select now
    app.selectFeature.activate();

    //
    // Snapping control for drawing properties
    //
    existing_snap = new OpenLayers.Control.Snapping({
                layer: app.property_layer,
                targets: [app.property_layer],
                greedy: false
            });
    existing_snap.activate();

    draw = new OpenLayers.Control.DrawFeature(new_features, OpenLayers.Handler.Polygon);
    map.addControl(draw);
    app.drawFeature = draw;

    // new app methods
    app.cleanupForm = function ($form) {
      // remove the submit button, strip out the geometry
      $form
        .find('input:submit').remove().end()
        .find('#id_geometry_final').closest('.field').remove();

      // put the form in a well and focus the first field
      $form.addClass('well');
      $form.find('.field').each(function () {
        var $this = $(this);
        // add the bootstrap classes
        $this.addClass('control-group');
        $this.find('label').addClass('control-label');
        $this.find('input').wrap($('
', { "class": "controls"}));
        $this.find('.controls').append($('
', { "class": "help-block"}));

      });
      $form.find('input:visible').first().focus();
    };
} //end init

<commit_msg>fixing link to Topo Map (Quads)<commit_after>$(document).ready(function() {
    init();
});

var map, controls;
var stands;
var currentStep = 1;
var steps = [undefined]; // start with a blank to make it 1-indexed

function init() {
    map = new OpenLayers.Map('map',
        {
            projection: new OpenLayers.Projection('EPSG:3857')
        }
    );
    var switcher = new OpenLayers.Control.LayerSwitcher({'div':OpenLayers.Util.getElement('layerswitcher')});
    map.addControl(switcher);

    map.addControl( new OpenLayers.Control.Navigation({
            dragPanOptions: {
                enableKinetic: false
            }
        }));

    map.addControl(new OpenLayers.Control.KeyboardDefaults({observeElement: 'map'}));

    map.addControl(new OpenLayers.Control.Attribution());

    map.addControl(new OpenLayers.Control.ScaleLine());

    var arrayAerial = [
        "http://otile1.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
        "http://otile2.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
        "http://otile3.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
        "http://otile4.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg"];
    var baseAerial = new OpenLayers.Layer.OSM("Aerial Imagery",
        arrayAerial, {attribution:"MapQuest"});
    map.addLayer(baseAerial);

    var arrayOSM = [
        "http://otile1.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg",
        "http://otile2.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg",
        "http://otile3.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg",
        "http://otile4.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg"];
    var baseOSM = new OpenLayers.Layer.OSM("Street Map",
        arrayOSM, {attribution:"Mapquest, OpenStreetMap"});
    map.addLayer(baseOSM);

    var esriLayers = [
      ["Topo map (Digital)", 'World_Topo_Map', 'USGS'],
      ["Topo map (Quads)", 'USA_Topo_Maps', 'USGS'],
      ["Satellite Imagery", 'World_Imagery']
    ];

    for (var i=esriLayers.length-1; i>=0; --i) {
        var lyrLongName = esriLayers[i][0];
        var lyrShortName = esriLayers[i][1];
        var attribution = "Basemaps by ESRI";
        if (esriLayers[i].length > 2) {
            attribution = attribution + ', ' + esriLayers[i][2];
        }

        var config = {
            sphericalMercator: true,
            attribution: attribution
        };

        if (esriLayers[i][0] == "Topo map (Quads)") {
            config.resolutions = [156543.03390625,78271.516953125,39135.7584765625,19567.87923828125,9783.939619140625,4891.9698095703125,2445.9849047851562,1222.9924523925781,611.4962261962891,305.74811309814453,152.87405654907226,76.43702827453613,38.218514137268066,19.109257068634033,9.554628534317017,4.777314267158508,2.388657133579254,1.194328566789627,0.5971642833948135];
            config.serverResolutions = [156543.03390625,78271.516953125,39135.7584765625,19567.87923828125,9783.939619140625,4891.9698095703125,2445.9849047851562,1222.9924523925781,611.4962261962891,305.74811309814453,152.87405654907226,76.43702827453613,38.218514137268066,19.109257068634033,9.554628534317017,4.777314267158508];
        }

        var lyr = new OpenLayers.Layer.XYZ( lyrLongName,
            "http://server.arcgisonline.com/ArcGIS/rest/services/"+ lyrShortName +"/MapServer/tile/${z}/${y}/${x}",
            config
        );
        lyr.shortName = lyrShortName;
        map.addLayer(lyr);
    }

    var tileServerLayers = [
        [ "Wetlands", "LOT_wetlands"],
        [ "Stream Buffers", "LOT_streambuffers"],
        [ "Streams", "LOT_streams"]
    ];

    for (var i=tileServerLayers.length-1; i>=0; --i) {
        var lyrLongName = tileServerLayers[i][0];
        var lyrShortName = tileServerLayers[i][1];
        var arrayTile = [
            "http://a.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
            "http://b.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
            "http://c.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
            "http://d.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
        ];
        var lyr = new OpenLayers.Layer.XYZ( lyrLongName, arrayTile,
            {sphericalMercator: true, isBaseLayer: false, visibility: false, attribution:"Ecotrust"}
        );
        lyr.shortName = lyrShortName;
        map.addLayer(lyr);
        lyr.events.register('visibilitychanged', lyr, function(evt) {
            if (this.visibility) {
                $('#legend').append('
' +
                    '');
            } else {
                $('#' + this.shortName + '-legend').remove();
            }
        });
    }

    var soils = new OpenLayers.Layer.XYZ( "Soil Types (Names)",
        "http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/Soil_Survey_Map/MapServer/tile/${z}/${y}/${x}",
        {sphericalMercator: true,
         isBaseLayer: false,
         visibility: false,
         opacity: 0.75,
         attribution: "ESRI, USDA NRCS"}
    );
    map.addLayer(soils);
    soils.events.register('visibilitychanged', soils, function(evt) {
        if (soils.visibility) {
            $('.layersDiv').append('

more info
');
        } else {
            $('#soil-legend').remove();
        }
    });

     var soilsWMS = new OpenLayers.Layer.WMS( "Soil Types (Codes)",
        "http://sdmdataaccess.nrcs.usda.gov/Spatial/SDM.wms",
        {
            layers: 'MapunitPoly',
            transparent: true
        }
        , {
            isBaseLayer: false,
            attribution: "USDA NRCS",
            visibility: false
        }
    );
    map.addLayer(soilsWMS);

    var tileServerLayers2 = [
        [ "Conservation Easements", "LOT_natconseasedb"],
        [ "Critical Habitat (Public Land)", "Crithab"],
        [ "Critical Stream Habitat", "Crithab_streams"],
        [ "Land Ownership", "LOT_protareas"],
        [ "Mill Facilities", "USFSMillFacilities", "USFS"],
        [ "Watershed Boundaries", "LOT_watersheds"],
        [ "Counties", "LOT_counties"],
        [ "Township and Range", "LOT_plss"],
        [ "Tax Lots (where available)", "LOT_parcels"],
        [ "Steep Slopes (>40%)", "LOT_steepslopes"]
    ];

    for (var i=tileServerLayers2.length-1; i>=0; --i) {
        var lyrLongName = tileServerLayers2[i][0];
        var lyrShortName = tileServerLayers2[i][1];
        var arrayTile = [
            "http://a.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
            "http://b.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
            "http://c.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
            "http://d.tiles.ecotrust.org/tiles/" + lyrShortName + "/${z}/${x}/${y}.png",
        ];
        var attribution = "Ecotrust"
        if (tileServerLayers2[i].length > 2){
            attribution = tileServerLayers2[i][2];
        }
        var lyr = new OpenLayers.Layer.XYZ( lyrLongName, arrayTile,
            {sphericalMercator: true, isBaseLayer: false, visibility: false, attribution:attribution}
        );
        lyr.shortName = lyrShortName;
        map.addLayer(lyr);
        lyr.events.register('visibilitychanged', lyr, function(evt) {
            if (this.visibility) {
                $('#legend').append('
' +
                    '');
            } else {
                $('#' + this.shortName + '-legend').remove();
            }
        });
    }

    map.setCenter(new OpenLayers.LonLat(0, 0), 7);

    for (var i=map.layers.length-1; i>=0; --i) {
        map.layers[i].animationEnabled = true;
    }

    app.markers = new OpenLayers.Layer.Markers("search", {displayInLayerSwitcher: false});
    map.addLayer(app.markers);

    // Add stands
    var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
    app.renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;

    new_features = new OpenLayers.Layer.Vector("New Features", {
        renderers: app.renderer,
        styleMap: map_styles.drawn,
        displayInLayerSwitcher: false
    }
    );
    map.addLayer(new_features);
    app.new_features = new_features;

    app.geojson_format = new OpenLayers.Format.GeoJSON(),
    app.property_layer = new OpenLayers.Layer.Vector("My Properties",  {
        renderers: app.renderer,
        styleMap: map_styles.forestProperty
    });
    app.stand_layer = new OpenLayers.Layer.Vector("Stands",  {
        renderers: app.renderer,
        styleMap: map_styles.forestProperty
    });
    map.addLayer(app.property_layer);

    // add controls, save references
    app.selectFeature = new OpenLayers.Control.SelectFeature(app.property_layer,
        { "clickout": false});

    // reenable click and drag in vectors
    app.selectFeature.handlers.feature.stopDown = false;

    map.addControl(app.selectFeature);
    app.modifyFeature = new OpenLayers.Control.ModifyFeature(app.property_layer);
    map.addControl(app.modifyFeature);
    // draw is in tree.js TODO: move)
    // activate select now
    app.selectFeature.activate();

    //
    // Snapping control for drawing properties
    //
    existing_snap = new OpenLayers.Control.Snapping({
                layer: app.property_layer,
                targets: [app.property_layer],
                greedy: false
            });
    existing_snap.activate();

    draw = new OpenLayers.Control.DrawFeature(new_features, OpenLayers.Handler.Polygon);
    map.addControl(draw);
    app.drawFeature = draw;

    // new app methods
    app.cleanupForm = function ($form) {
      // remove the submit button, strip out the geometry
      $form
        .find('input:submit').remove().end()
        .find('#id_geometry_final').closest('.field').remove();

      // put the form in a well and focus the first field
      $form.addClass('well');
      $form.find('.field').each(function () {
        var $this = $(this);
        // add the bootstrap classes
        $this.addClass('control-group');
        $this.find('label').addClass('control-label');
        $this.find('input').wrap($('
', { "class": "controls"}));
        $this.find('.controls').append($('
', { "class": "help-block"}));

      });
      $form.find('input:visible').first().focus();
    };
} //end init

<|endoftext|>


<commit_before>/*jslint node: true */

/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

/**
 * @exports DiagnosticTags
 */
var LoggerFactory = require("./LoggerFactory");
var log = LoggerFactory.getLogger("joynr.system.DiagnosticTags");
var DiagnosticTags = {};

/**
 * @param {JoynrMessage}
 *            joynrMessage
 */
DiagnosticTags.forJoynrMessage = function forJoynrMessage(joynrMessage) {
    return {
        diagnosticTag: "JoynrMessage",
        from: joynrMessage.from,
        to: joynrMessage.to,
        type: joynrMessage.type
    };
};

/**
 * @param {String}
 *            channelInfo.channelUrl
 * @param {String}
 *            channelInfo.channelId
 * @param {String}
 *            channelInfo.status
 * @param {String}
 *            channelInfo.responseText
 */
DiagnosticTags.forChannel = function forChannel(channelInfo) {
    return {
        diagnosticTag: "ChannelInfo",
        channelUrl: channelInfo.channelUrl,
        channelId: channelInfo.channelId,
        status: channelInfo.status,
        responseText: channelInfo.responseText
    };
};

/**
 * @param {Object} requestInfo
 */
DiagnosticTags.forRequest = function forRequest(requestInfo) {
    var tagsForRequest = {
        diagnosticTag: "Request",
        requestReplyId: requestInfo.request.requestReplyId,
        to: requestInfo.to,
        from: requestInfo.from
    };
    if (log.isDebugEnabled() && requestInfo.request.params) {
        tagsForRequest.params = JSON.stringify(requestInfo.request.params);
    }
    return tagsForRequest;
};

/**
 * @param {Object} requestInfo
 */
DiagnosticTags.forOneWayRequest = function forOneWayRequest(requestInfo) {
    var tagsForOneWayRequest = {
        diagnosticTag: "OneWayRequest",
        to: requestInfo.to,
        from: requestInfo.from
    };
    if (log.isDebugEnabled() && requestInfo.request.params) {
        tagsForOneWayRequest.params = JSON.stringify(requestInfo.request.params);
    }
    return tagsForOneWayRequest;
};

/**
 * @param {Object} replyInfo
 */
DiagnosticTags.forReply = function forReply(replyInfo) {
    var tagsForReply = {
        diagnosticTag: "Reply",
        requestReplyId: replyInfo.reply.requestReplyId,
        to: replyInfo.to,
        from: replyInfo.from
    };
    if (log.isDebugEnabled()) {
        if (replyInfo.reply.error) {
            tagsForReply.error = JSON.stringify(replyInfo.reply.error);
        } else {
            tagsForReply.response = JSON.stringify(replyInfo.reply.response);
        }
    }
    return tagsForReply;
};

/**
 * @param {Object} subscriptionReplyInfo
 */
DiagnosticTags.forSubscriptionReply = function forSubscriptionReply(subscriptionReplyInfo) {
    return {
        diagnosticTag: "SubscriptionReply",
        subscriptionId: subscriptionReplyInfo.subscriptionReply.subscriptionId,
        to: subscriptionReplyInfo.to,
        from: subscriptionReplyInfo.from
    };
};

/**
 * @param {Object} subscriptionRequestInfo
 */
DiagnosticTags.forMulticastSubscriptionRequest = function forMulticastSubscriptionRequest(subscriptionRequestInfo) {
    return {
        diagnosticTag: "MulticastSubscriptionRequest",
        eventName: subscriptionRequestInfo.subscriptionRequest.subscribedToName,
        subscriptionId: subscriptionRequestInfo.subscriptionRequest.subscriptionId,
        multicastId: subscriptionRequestInfo.subscriptionRequest.multicastId,
        to: subscriptionRequestInfo.to,
        from: subscriptionRequestInfo.from
    };
};

/**
 * @param {Object} subscriptionRequestInfo
 */
DiagnosticTags.forBroadcastSubscriptionRequest = function forBroadcastSubscriptionRequest(subscriptionRequestInfo) {
    return {
        diagnosticTag: "BroadcastSubscriptionRequest",
        eventName: subscriptionRequestInfo.subscriptionRequest.subscribedToName,
        subscriptionId: subscriptionRequestInfo.subscriptionRequest.subscriptionId,
        to: subscriptionRequestInfo.to,
        from: subscriptionRequestInfo.from
    };
};

/**
 * @param {Object} subscriptionRequestInfo
 */
DiagnosticTags.forSubscriptionRequest = function forSubscriptionRequest(subscriptionRequestInfo) {
    return {
        diagnosticTag: "SubscriptionRequest",
        attributeName: subscriptionRequestInfo.subscriptionRequest.subscribedToName,
        subscriptionId: subscriptionRequestInfo.subscriptionRequest.subscriptionId,
        to: subscriptionRequestInfo.to,
        from: subscriptionRequestInfo.from
    };
};

/**
 * @param {Object} subscriptionStopInfo
 */
DiagnosticTags.forSubscriptionStop = function forSubscriptionStop(subscriptionStopInfo) {
    return {
        diagnosticTag: "SubscriptionStop",
        subscriptionId: subscriptionStopInfo.subscriptionId,
        to: subscriptionStopInfo.to,
        from: subscriptionStopInfo.from
    };
};

/**
 * @param {Object} publicationInfo
 */
DiagnosticTags.forPublication = function forPublication(publicationInfo) {
    var tagsForPublication = {
        diagnosticTag: "Publication",
        subscriptionId: publicationInfo.publication.subscriptionId,
        to: publicationInfo.to,
        from: publicationInfo.from
    };
    if (log.isDebugEnabled()) {
        tagsForPublication.response = JSON.stringify(publicationInfo.publication.response);
    }
    return tagsForPublication;
};

/**
 * @param {Object} publicationInfo - multicast publication info
 */
DiagnosticTags.forMulticastPublication = function forMulticastPublication(publicationInfo) {
    var tagsForMulticastPublication = {
        diagnosticTag: "MulticastPublication",
        multicastId: publicationInfo.publication.multicastId,
        from: publicationInfo.from
    };
    if (log.isDebugEnabled()) {
        tagsForMulticastPublication.response = JSON.stringify(publicationInfo.publication.response);
    }
    return tagsForMulticastPublication;
};

module.exports = DiagnosticTags;
<commit_msg>[JS] avoid log.isDebugEnabled in DiagnosticTags<commit_after>/*jslint node: true */

/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

/**
 * @exports DiagnosticTags
 */
var Util = require("../util/UtilInternal");
var loggingManager = require("./LoggingManager");
var DiagnosticTags = {};

/**
 * @param {JoynrMessage}
 *            joynrMessage
 */
DiagnosticTags.forJoynrMessage = function forJoynrMessage(joynrMessage) {
    return {
        diagnosticTag: "JoynrMessage",
        from: joynrMessage.from,
        to: joynrMessage.to,
        type: joynrMessage.type
    };
};

/**
 * @param {String}
 *            channelInfo.channelUrl
 * @param {String}
 *            channelInfo.channelId
 * @param {String}
 *            channelInfo.status
 * @param {String}
 *            channelInfo.responseText
 */
DiagnosticTags.forChannel = function forChannel(channelInfo) {
    return {
        diagnosticTag: "ChannelInfo",
        channelUrl: channelInfo.channelUrl,
        channelId: channelInfo.channelId,
        status: channelInfo.status,
        responseText: channelInfo.responseText
    };
};

var forRequestHelper = function forRequestHelper(tagsForRequest, requestInfo) {
    if (requestInfo.request.params) {
        tagsForRequest.params = JSON.stringify(requestInfo.request.params);
    }
};

/**
 * @param {Object} requestInfo
 */
DiagnosticTags.forRequest = function forRequest(requestInfo) {
    var tagsForRequest = {
        diagnosticTag: "Request",
        requestReplyId: requestInfo.request.requestReplyId,
        to: requestInfo.to,
        from: requestInfo.from
    };
    forRequestHelper(tagsForRequest, requestInfo);
    return tagsForRequest;
};

var forOneWayRequestHelper = function(tagsForOneWayRequest, requestInfo) {
    if (requestInfo.request.params) {
        tagsForOneWayRequest.params = JSON.stringify(requestInfo.request.params);
    }
};

/**
 * @param {Object} requestInfo
 */
DiagnosticTags.forOneWayRequest = function forOneWayRequest(requestInfo) {
    var tagsForOneWayRequest = {
        diagnosticTag: "OneWayRequest",
        to: requestInfo.to,
        from: requestInfo.from
    };
    forOneWayRequestHelper(tagsForOneWayRequest, requestInfo);
    return tagsForOneWayRequest;
};

var forReplyHelper = function(tagsForReply, replyInfo) {
    if (replyInfo.reply.error) {
        tagsForReply.error = JSON.stringify(replyInfo.reply.error);
    } else {
        tagsForReply.response = JSON.stringify(replyInfo.reply.response);
    }
};

/**
 * @param {Object} replyInfo
 */
DiagnosticTags.forReply = function forReply(replyInfo) {
    var tagsForReply = {
        diagnosticTag: "Reply",
        requestReplyId: replyInfo.reply.requestReplyId,
        to: replyInfo.to,
        from: replyInfo.from
    };
    forReplyHelper(tagsForReply, replyInfo);
    return tagsForReply;
};

/**
 * @param {Object} subscriptionReplyInfo
 */
DiagnosticTags.forSubscriptionReply = function forSubscriptionReply(subscriptionReplyInfo) {
    return {
        diagnosticTag: "SubscriptionReply",
        subscriptionId: subscriptionReplyInfo.subscriptionReply.subscriptionId,
        to: subscriptionReplyInfo.to,
        from: subscriptionReplyInfo.from
    };
};

/**
 * @param {Object} subscriptionRequestInfo
 */
DiagnosticTags.forMulticastSubscriptionRequest = function forMulticastSubscriptionRequest(subscriptionRequestInfo) {
    return {
        diagnosticTag: "MulticastSubscriptionRequest",
        eventName: subscriptionRequestInfo.subscriptionRequest.subscribedToName,
        subscriptionId: subscriptionRequestInfo.subscriptionRequest.subscriptionId,
        multicastId: subscriptionRequestInfo.subscriptionRequest.multicastId,
        to: subscriptionRequestInfo.to,
        from: subscriptionRequestInfo.from
    };
};

/**
 * @param {Object} subscriptionRequestInfo
 */
DiagnosticTags.forBroadcastSubscriptionRequest = function forBroadcastSubscriptionRequest(subscriptionRequestInfo) {
    return {
        diagnosticTag: "BroadcastSubscriptionRequest",
        eventName: subscriptionRequestInfo.subscriptionRequest.subscribedToName,
        subscriptionId: subscriptionRequestInfo.subscriptionRequest.subscriptionId,
        to: subscriptionRequestInfo.to,
        from: subscriptionRequestInfo.from
    };
};

/**
 * @param {Object} subscriptionRequestInfo
 */
DiagnosticTags.forSubscriptionRequest = function forSubscriptionRequest(subscriptionRequestInfo) {
    return {
        diagnosticTag: "SubscriptionRequest",
        attributeName: subscriptionRequestInfo.subscriptionRequest.subscribedToName,
        subscriptionId: subscriptionRequestInfo.subscriptionRequest.subscriptionId,
        to: subscriptionRequestInfo.to,
        from: subscriptionRequestInfo.from
    };
};

/**
 * @param {Object} subscriptionStopInfo
 */
DiagnosticTags.forSubscriptionStop = function forSubscriptionStop(subscriptionStopInfo) {
    return {
        diagnosticTag: "SubscriptionStop",
        subscriptionId: subscriptionStopInfo.subscriptionId,
        to: subscriptionStopInfo.to,
        from: subscriptionStopInfo.from
    };
};

var forPublicationHelper = function(tagsForPublication, publicationInfo) {
    tagsForPublication.response = JSON.stringify(publicationInfo.publication.response);
};

/**
 * @param {Object} publicationInfo
 */
DiagnosticTags.forPublication = function forPublication(publicationInfo) {
    var tagsForPublication = {
        diagnosticTag: "Publication",
        subscriptionId: publicationInfo.publication.subscriptionId,
        to: publicationInfo.to,
        from: publicationInfo.from
    };
    forPublicationHelper(tagsForPublication, publicationInfo);
    return tagsForPublication;
};

var forMulticastPublicationHelper = function(tagsForMulticastPublication, publicationInfo) {
    tagsForMulticastPublication.response = JSON.stringify(publicationInfo.publication.response);
};

/**
 * @param {Object} publicationInfo - multicast publication info
 */
DiagnosticTags.forMulticastPublication = function forMulticastPublication(publicationInfo) {
    var tagsForMulticastPublication = {
        diagnosticTag: "MulticastPublication",
        multicastId: publicationInfo.publication.multicastId,
        from: publicationInfo.from
    };
    forMulticastPublicationHelper(tagsForMulticastPublication, publicationInfo);
    return tagsForMulticastPublication;
};

function logLevelChangedCb(level) {
    if (level !== loggingManager.LogLevel.DEBUG && level !== loggingManager.LogLevel.TRACE) {
        forRequestHelper = Util.emptyFunction;
        forOneWayRequestHelper = Util.emptyFunction;
        forReplyHelper = Util.emptyFunction;
        forPublicationHelper = Util.emptyFunction;
        forMulticastPublicationHelper = Util.emptyFunction;
    }
}

loggingManager.registerForLogLevelChanged(logLevelChangedCb);

module.exports = DiagnosticTags;
<|endoftext|>