lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | error: pathspec 'src/main/java/com/google/sps/servlets/IndexServlet.java' did not match any file(s) known to git
| d96707bb69f7f1c775c82a72a7fc9d92c805d653 | 1 | googleinterns/step132-2020,googleinterns/step132-2020,googleinterns/step132-2020 | // Copyright 2019 Google LLC
//
// 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
//
// https://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.
package com.google.sps.servlets;
import com.google.sps.data.Tutor;
import com.google.sps.data.TimeRange;
import com.google.sps.data.TutorSession;
import com.google.sps.data.SampleData;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Optional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.sps.utilities.RealAvailabilityDatastore;
import com.google.sps.utilities.MockAvailabilityDatastore;
import com.google.sps.utilities.AvailabilityDatastoreService;
/** Servlet that sets what the first page will be. */
@WebServlet("/")
public class IndexServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("plain/text");
response.sendRedirect("/homepage.html");
return;
}
}
| src/main/java/com/google/sps/servlets/IndexServlet.java | Create index servlet (#59)
| src/main/java/com/google/sps/servlets/IndexServlet.java | Create index servlet (#59) | <ide><path>rc/main/java/com/google/sps/servlets/IndexServlet.java
<add>// Copyright 2019 Google LLC
<add>//
<add>// Licensed under the Apache License, Version 2.0 (the "License");
<add>// you may not use this file except in compliance with the License.
<add>// You may obtain a copy of the License at
<add>//
<add>// https://www.apache.org/licenses/LICENSE-2.0
<add>//
<add>// Unless required by applicable law or agreed to in writing, software
<add>// distributed under the License is distributed on an "AS IS" BASIS,
<add>// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add>// See the License for the specific language governing permissions and
<add>// limitations under the License.
<add>
<add>package com.google.sps.servlets;
<add>
<add>import com.google.sps.data.Tutor;
<add>import com.google.sps.data.TimeRange;
<add>import com.google.sps.data.TutorSession;
<add>import com.google.sps.data.SampleData;
<add>import com.google.gson.Gson;
<add>import java.io.IOException;
<add>import java.util.Optional;
<add>import java.util.ArrayList;
<add>import java.util.Arrays;
<add>import java.util.List;
<add>import javax.servlet.annotation.WebServlet;
<add>import javax.servlet.http.HttpServlet;
<add>import javax.servlet.http.HttpServletRequest;
<add>import javax.servlet.http.HttpServletResponse;
<add>import com.google.sps.utilities.RealAvailabilityDatastore;
<add>import com.google.sps.utilities.MockAvailabilityDatastore;
<add>import com.google.sps.utilities.AvailabilityDatastoreService;
<add>
<add>/** Servlet that sets what the first page will be. */
<add>@WebServlet("/")
<add>public class IndexServlet extends HttpServlet {
<add> @Override
<add> public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
<add> response.setContentType("plain/text");
<add> response.sendRedirect("/homepage.html");
<add> return;
<add> }
<add>} |
|
JavaScript | apache-2.0 | b4f190ce8dbfb5a2679ed133c6de6ccd30e94d56 | 0 | justindujardin/pow2,justindujardin/pow2,justindujardin/pow2 | module.exports = function(grunt) {
grunt.option('force', true);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
notify: {
options: {
title: 'E.B.U.R.P.'
},
sprites:{
options: {
message: 'Sprite Sheets built.'
}
},
maps:{
options: {
message: 'Maps compiled.'
}
},
server:{
options: {
message: 'Server restarted.'
}
},
code:{
options: {
message: 'Code build complete.'
}
}
},
/**
* Concatenate data files
*/
concat: {
options: {
separator: '\n'
},
game: {
src: [
"data/game.js",
"data/*.js"
],
dest: 'web/<%= pkg.name %>.data.js'
},
maps: {
src: [
"data/maps/*.js"
],
dest: 'web/<%= pkg.name %>.maps.js'
}
},
/**
* Compile CoffeeScript
*/
coffee: {
options:{
join:true
},
game: {
src: [
"src/core/util.coffee",
"src/core/*.coffee",
"src/scene/*.coffee",
"src/scene/objects/*.coffee",
"src/scene/views/*.coffee",
"src/device.coffee",
"src/ui/view.coffee",
"src/ui/*.coffee",
"src/model/*.coffee",
"src/adventure/*.coffee",
"src/combat/*.coffee",
"src/game/*.coffee",
"src/gurk.coffee"
],
dest: 'web/<%= pkg.name %>.js',
ext: '.js'
}
},
/**
* Uglify the output javascript files in production builds. This task is only
* ever invoked with `heroku:production`, and simply obfuscates/minifies the existing
* files.
*/
uglify: {
options: {
banner: '\n/*!\n <%= pkg.name %> - v<%= pkg.version %>\n built: <%= grunt.template.today("yyyy-mm-dd") %>\n */\n'
},
game: {
files: {
'web/<%= pkg.name %>.data.js' : ['web/<%= pkg.name %>.data.js'],
'web/<%= pkg.name %>.maps.js' : ['web/<%= pkg.name %>.maps.js'],
'web/<%= pkg.name %>.sprites.js' : ['web/<%= pkg.name %>.sprites.js'],
'web/<%= pkg.name %>.js' : ['web/<%= pkg.name %>.js']
}
}
},
/**
* Build sprite sheets.
*/
sprites: {
game: {
options: {
metaFile: 'web/<%= pkg.name %>.sprites.js'
},
files: [
{src: 'data/textures/characters/*.png', dest: 'web/images/characters'},
{src: 'data/textures/animation/*.png', dest: 'web/images/animation'},
{src: 'data/textures/creatures/*.png', dest: 'web/images/creatures'},
{src: 'data/textures/environment/*.png', dest: 'web/images/environment'},
{src: 'data/textures/equipment/*.png', dest: 'web/images/equipment'},
{src: 'data/textures/items/*.png', dest: 'web/images/items'},
{src: 'data/textures/ui/*.png', dest: 'web/images/ui'}
]
}
},
/**
* Game server. Useful for deploys (e.g. to heroku), and for getting
* around security restrictions of running the game from index.html on your
* hard drive.
*/
express: {
options: {
script: 'tools/gameServer.js',
port: 5215
},
production: {
options: {
node_env: 'production'
}
}
},
/**
* Trigger a new build when files change
*/
watch: {
options:{
atBegin:true,
spawn: false
},
code: {
files: [
'<%= coffee.game.src %>'
],
tasks: ['default', 'notify:code']
},
maps: {
files: [
'<%= concat.maps.src %>'
],
tasks: ['concat', 'notify:maps']
},
sprites: {
files: [
'data/textures/**/*.png'
],
tasks: ['sprites', 'notify:sprites']
},
express: {
files: [ 'index.html', 'tools/gameServer.js' ],
tasks: [ 'express', 'notify:server' ],
options: {
nospawn: true //Without this option specified express won't be reloaded
}
}
}
});
grunt.registerMultiTask('sprites', 'Pack sprites into output sheets', function()
{
var Q = require('q');
var done = this.async();
var spritePacker = require('./tools/spritePacker');
var queue = [];
var options = this.options({
metaFile: null
});
this.files.forEach(function(f) {
queue.push(spritePacker(f.src, {
outName: f.dest,
scale: 1
}));
});
var jsChunks = [];
Q.all(queue).then(function(results){
results.forEach(function(r){
grunt.log.writeln('File "' + r.file + '" created.');
jsChunks.push("eburp.registerSprites('" + r.name + "'," + JSON.stringify(r.meta,null,3)+");");
});
// Write out metadata if specified.
if(options.metaFile){
grunt.file.write(options.metaFile,jsChunks.join('\n'));
grunt.log.writeln('File "' + options.metaFile + '" created.');
}
done();
},function(error){
grunt.log.error('Failed to create spritesheet: ' + error);
done(error);
});
});
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Support system notifications in non-production environments
if(process.env.NODE_ENV !== 'production'){
grunt.loadNpmTasks('grunt-express-server');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-notify');
grunt.registerTask('default', ['sprites', 'concat', 'coffee']);
}
else {
grunt.registerTask('default', ['sprites', 'concat', 'coffee']);
grunt.registerTask('heroku:production', ['concat','coffee', 'uglify']);
}
}; | Gruntfile.js | module.exports = function(grunt) {
grunt.option('force', true);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
notify: {
options: {
title: 'E.B.U.R.P.'
},
sprites:{
options: {
message: 'Sprite Sheets built.'
}
},
maps:{
options: {
message: 'Maps compiled.'
}
},
server:{
options: {
message: 'Server restarted.'
}
},
code:{
options: {
message: 'Code build complete.'
}
}
},
/**
* Concatenate data files
*/
concat: {
options: {
separator: '\n'
},
game: {
src: [
"data/game.js",
"data/*.js"
],
dest: 'web/<%= pkg.name %>.data.js'
},
maps: {
src: [
"data/maps/*.js"
],
dest: 'web/<%= pkg.name %>.maps.js'
}
},
/**
* Compile CoffeeScript
*/
coffee: {
options:{
join:true
},
game: {
src: [
"src/core/util.coffee",
"src/core/*.coffee",
"src/scene/*.coffee",
"src/scene/objects/*.coffee",
"src/scene/views/*.coffee",
"src/device.coffee",
"src/ui/view.coffee",
"src/ui/*.coffee",
"src/model/*.coffee",
"src/adventure/*.coffee",
"src/combat/*.coffee",
"src/game/*.coffee",
"src/gurk.coffee"
],
dest: 'web/<%= pkg.name %>.js',
ext: '.js'
}
},
/**
* Uglify the output javascript files in production builds. This task is only
* ever invoked with `heroku:production`, and simply obfuscates/minifies the existing
* files.
*/
uglify: {
options: {
banner: '\n/*!\n <%= pkg.name %> - v<%= pkg.version %>\n built: <%= grunt.template.today("yyyy-mm-dd") %>\n */\n'
},
game: {
files: {
'web/<%= pkg.name %>.data.js' : ['web/<%= pkg.name %>.data.js'],
'web/<%= pkg.name %>.maps.js' : ['web/<%= pkg.name %>.maps.js'],
'web/<%= pkg.name %>.sprites.js' : ['web/<%= pkg.name %>.sprites.js'],
'web/<%= pkg.name %>.js' : ['web/<%= pkg.name %>.js']
}
}
},
/**
* Build sprite sheets.
*/
sprites: {
game: {
options: {
metaFile: 'web/<%= pkg.name %>.sprites.js'
},
files: [
{src: 'data/textures/characters/*.png', dest: 'web/images/characters'},
{src: 'data/textures/animation/*.png', dest: 'web/images/animation'},
{src: 'data/textures/creatures/*.png', dest: 'web/images/creatures'},
{src: 'data/textures/environment/*.png', dest: 'web/images/environment'},
{src: 'data/textures/equipment/*.png', dest: 'web/images/equipment'},
{src: 'data/textures/items/*.png', dest: 'web/images/items'},
{src: 'data/textures/ui/*.png', dest: 'web/images/ui'}
]
}
},
/**
* Game server. Useful for deploys (e.g. to heroku), and for getting
* around security restrictions of running the game from index.html on your
* hard drive.
*/
express: {
options: {
script: 'tools/gameServer.js',
port: 5215
},
production: {
options: {
node_env: 'production'
}
}
},
/**
* Trigger a new build when files change
*/
watch: {
options:{
atBegin:true,
spawn: false
},
code: {
files: [
'<%= coffee.game.src %>'
],
tasks: ['default', 'notify:code']
},
maps: {
files: [
'<%= concat.maps.src %>'
],
tasks: ['concat', 'notify:maps']
},
sprites: {
files: [
'data/textures/**/*.png'
],
tasks: ['sprites', 'notify:sprites']
},
express: {
files: [ 'index.html', 'tools/gameServer.js' ],
tasks: [ 'express', 'notify:server' ],
options: {
nospawn: true //Without this option specified express won't be reloaded
}
}
}
});
grunt.registerMultiTask('sprites', 'Pack sprites into output sheets', function()
{
var Q = require('q');
var done = this.async();
var spritePacker = require('./tools/spritePacker');
var queue = [];
var options = this.options({
metaFile: null
});
this.files.forEach(function(f) {
queue.push(spritePacker(f.src, {
outName: f.dest,
scale: 1
}));
});
var jsChunks = [];
Q.all(queue).then(function(results){
results.forEach(function(r){
grunt.log.writeln('File "' + r.file + '" created.');
jsChunks.push("eburp.registerSprites('" + r.name + "'," + JSON.stringify(r.meta,null,3)+");");
});
// Write out metadata if specified.
if(options.metaFile){
grunt.file.write(options.metaFile,jsChunks.join('\n'));
grunt.log.writeln('File "' + options.metaFile + '" created.');
}
done();
},function(error){
grunt.log.error('Failed to create spritesheet: ' + error);
done(error);
});
});
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Support system notifications in non-production environments
if(process.env.NODE_ENV !== 'production'){
grunt.loadNpmTasks('grunt-express-server');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-notify');
grunt.registerTask('default', ['sprites', 'concat', 'coffee']);
}
else {
grunt.registerTask('default', ['sprites', 'concat', 'coffee']);
grunt.registerTask('heroku:production', ['sprites','concat','coffee', 'uglify']);
}
}; | Don't build sprite on heroku, IIRC heroku takes your unversioned local files, so they should be there.
| Gruntfile.js | Don't build sprite on heroku, IIRC heroku takes your unversioned local files, so they should be there. | <ide><path>runtfile.js
<ide> }
<ide> else {
<ide> grunt.registerTask('default', ['sprites', 'concat', 'coffee']);
<del> grunt.registerTask('heroku:production', ['sprites','concat','coffee', 'uglify']);
<add> grunt.registerTask('heroku:production', ['concat','coffee', 'uglify']);
<ide> }
<ide> }; |
|
Java | mit | b6407e12e363bc408fc1bad2c52ab8dc476013e0 | 0 | HadoopGenomics/Hadoop-BAM,HadoopGenomics/Hadoop-BAM,fnothaft/Hadoop-BAM,HadoopGenomics/Hadoop-BAM,cmnbroad/Hadoop-BAM,fnothaft/Hadoop-BAM,ryan-williams/Hadoop-BAM,cmnbroad/Hadoop-BAM,tomwhite/Hadoop-BAM,ryan-williams/Hadoop-BAM,fnothaft/Hadoop-BAM,tkrishp/Hadoop-BAM | // Copyright (c) 2013 Aalto University
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// File created: 2013-06-20 14:17:25
package fi.tkk.ics.hadoop.bam.cli;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.fs.Path;
import fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser;
import static fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser.Option.*;
import fi.tkk.ics.hadoop.bam.cli.CLIPlugin;
import fi.tkk.ics.hadoop.bam.util.Pair;
/** Like CLIPlugin, but has lots of useful defaults for MapReduce-using
* plugins.
*/
public abstract class CLIMRPlugin extends CLIPlugin {
protected boolean verbose;
protected int reduceTasks;
protected Path outPath;
private static final List<Pair<CmdLineParser.Option, String>> optionDescs
= new ArrayList<Pair<CmdLineParser.Option, String>>();
protected static final CmdLineParser.Option
reducersOpt = new IntegerOption('r', "reducers=N"),
verboseOpt = new BooleanOption('v', "verbose"),
/** Left undescribed here because there may be relevant
* application-specific details.
*/
outputPathOpt = new StringOption('o', "output-merged-path=PATH");
static {
optionDescs.add(new Pair<CmdLineParser.Option, String>(
reducersOpt, "use N reduce tasks (default: 1), i.e. produce N "+
"outputs in parallel"));
optionDescs.add(new Pair<CmdLineParser.Option, String>(
verboseOpt, "tell the Hadoop job to be more verbose"));
}
protected CLIMRPlugin(
String commandName, String description, String version,
String usageParams, List<Pair<CmdLineParser.Option, String>> optionDescs,
String longDescription)
{
// "call to super must be first statement in constructor" so you get that
// lovely expression instead of two simple statements.
super(
commandName, description, version, usageParams,
optionDescs == null
? CLIMRPlugin.optionDescs
: (optionDescs.addAll(CLIMRPlugin.optionDescs)
? optionDescs : optionDescs),
longDescription);
}
/** Should be called before accessing any of the protected data such as
* verbose.
*/
public boolean cacheAndSetProperties(CmdLineParser parser) {
verbose = parser.getBoolean(verboseOpt);
reduceTasks = parser.getInt (reducersOpt, 1);
final String out = (String)parser.getOptionValue(outputPathOpt);
outPath = out == null ? null : new Path(out);
getConf().setInt("mapred.reduce.tasks", reduceTasks);
getConf().setInt("mapreduce.job.reduces", reduceTasks);
return true;
}
}
| src/fi/tkk/ics/hadoop/bam/cli/CLIMRPlugin.java | // Copyright (c) 2013 Aalto University
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// File created: 2013-06-20 14:17:25
package fi.tkk.ics.hadoop.bam.cli;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.fs.Path;
import fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser;
import static fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser.Option.*;
import fi.tkk.ics.hadoop.bam.cli.CLIPlugin;
import fi.tkk.ics.hadoop.bam.util.Pair;
/** Like CLIPlugin, but has lots of useful defaults for MapReduce-using
* plugins.
*/
public abstract class CLIMRPlugin extends CLIPlugin {
protected boolean verbose;
protected int reduceTasks;
protected Path outPath;
private static final List<Pair<CmdLineParser.Option, String>> optionDescs
= new ArrayList<Pair<CmdLineParser.Option, String>>();
protected static final CmdLineParser.Option
reducersOpt = new IntegerOption('r', "reducers=N"),
verboseOpt = new BooleanOption('v', "verbose"),
/** Left undescribed here because there may be relevant
* application-specific details.
*/
outputPathOpt = new StringOption('o', "output-merged-path=PATH");
static {
optionDescs.add(new Pair<CmdLineParser.Option, String>(
reducersOpt, "use N reduce tasks (default: 1), i.e. produce N "+
"outputs in parallel"));
optionDescs.add(new Pair<CmdLineParser.Option, String>(
verboseOpt, "tell the Hadoop job to be more verbose"));
}
protected CLIMRPlugin(
String commandName, String description, String version,
String usageParams, List<Pair<CmdLineParser.Option, String>> optionDescs,
String longDescription)
{
// "call to super must be first statement in constructor" so you get that
// lovely expression instead of two simple statements.
super(
commandName, description, version, usageParams,
optionDescs == null
? CLIMRPlugin.optionDescs
: (optionDescs.addAll(CLIMRPlugin.optionDescs)
? optionDescs : optionDescs),
longDescription);
}
/** Should be called before accessing any of the protected data such as
* verbose.
*/
public boolean cacheAndSetProperties(CmdLineParser parser) {
verbose = parser.getBoolean(verboseOpt);
reduceTasks = parser.getInt (reducersOpt, 1);
final String out = (String)parser.getOptionValue(outputPathOpt);
outPath = out == null ? null : new Path(out);
getConf().setInt("mapred.reduce.tasks", reduceTasks);
return true;
}
}
| CLIMRPlugin: set non-deprecated reduce tasks # too
| src/fi/tkk/ics/hadoop/bam/cli/CLIMRPlugin.java | CLIMRPlugin: set non-deprecated reduce tasks # too | <ide><path>rc/fi/tkk/ics/hadoop/bam/cli/CLIMRPlugin.java
<ide> final String out = (String)parser.getOptionValue(outputPathOpt);
<ide> outPath = out == null ? null : new Path(out);
<ide>
<del> getConf().setInt("mapred.reduce.tasks", reduceTasks);
<add> getConf().setInt("mapred.reduce.tasks", reduceTasks);
<add> getConf().setInt("mapreduce.job.reduces", reduceTasks);
<ide>
<ide> return true;
<ide> } |
|
JavaScript | mit | c45c2497677bed437d71c424da161a3e8b1be55b | 0 | froggy666uk/node-sonos-discovery,jishi/node-sonos-discovery | 'use strict';
const url = require('url');
const Subscriber = require('../Subscriber');
const soap = require('../helpers/soap');
const streamer = require('../helpers/streamer');
const TYPE = soap.TYPE;
const flow = require('xml-flow');
const XmlEntities = require('html-entities').XmlEntities;
const path = require('path');
const requireDir = require('../helpers/require-dir');
const logger = require('../helpers/logger');
const musicServices = require('../musicservices');
const xmlEntities = new XmlEntities();
const util = require('util');
const EventEmitter = require('events').EventEmitter;
const EMPTY_STATE = require('../types/empty-state');
const PLAY_MODE = require('../types/play-mode');
const REPEAT_MODE = require('../types/repeat-mode');
function reversePlayMode() {
let lookup = {};
for (let key in PLAY_MODE) {
lookup[PLAY_MODE[key]] = key;
}
return lookup;
}
const PLAY_MODE_LOOKUP = Object.freeze(reversePlayMode());
function getPlayMode(state) {
let key = state.shuffle << 1 | (state.repeat === REPEAT_MODE.ONE ? 4 : (state.repeat === REPEAT_MODE.ALL ? 1 : 0));
return PLAY_MODE_LOOKUP[key];
}
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
function parseTime(formattedTime) {
if (formattedTime === undefined) {
return 0;
}
var chunks = formattedTime.split(':').reverse();
var timeInSeconds = 0;
for (var i = 0; i < chunks.length; i++) {
timeInSeconds += parseInt(chunks[i], 10) * Math.pow(60, i);
}
return isNaN(timeInSeconds) ? 0 : timeInSeconds;
}
function zpad(number) {
return ('00' + number).substr(-2);
}
function formatTime(seconds) {
var chunks = [];
var remainingTime = seconds;
// hours
var hours = Math.floor(remainingTime / 3600);
chunks.push(zpad(hours));
remainingTime -= hours * 3600;
// minutes
var minutes = Math.floor(remainingTime / 60);
chunks.push(zpad(minutes));
remainingTime -= minutes * 60;
// seconds
chunks.push(zpad(remainingTime));
return chunks.join(':');
}
function parseTrackMetadata(metadata, nextTrack) {
return new Promise((resolve, reject) => {
let track = nextTrack ? clone(EMPTY_STATE.nextTrack) : clone(EMPTY_STATE.currentTrack);
if (!metadata) resolve(track);
const sax = flow(streamer(metadata.val));
sax.on('tag:item', (item) => {
track.uri = item.res.$text;
track.duration = parseTime((item.res.$attrs || item.res).duration);
track.artist = item['dc:creator'];
track.album = item['upnp:album'];
track.title = item['r:streamcontent'] || item['dc:title'];
track.albumArtUri = item['upnp:albumarturi'];
});
sax.on('error', reject);
sax.on('end', () => {
resolve(track);
});
});
}
function parseAVTransportMetadata(metadata) {
return new Promise((resolve, reject) => {
if (!metadata) resolve({});
const sax = flow(streamer(metadata.val));
const avTransportMetadata = {};
sax.on('tag:item', (item) => {
avTransportMetadata.stationName = item['dc:title'];
});
sax.on('error', reject);
sax.on('end', () => {
resolve(avTransportMetadata);
});
});
}
function getState(playerInternal, coordinatorInternal) {
var diff = 0;
if (coordinatorInternal.playbackState === 'PLAYING')
diff = Date.now() - coordinatorInternal.stateTime;
var elapsedTime = coordinatorInternal.relTime + Math.floor(diff / 1000);
return Object.freeze({
currentTrack: coordinatorInternal.currentTrack,
nextTrack: coordinatorInternal.nextTrack,
volume: playerInternal.volume,
mute: playerInternal.mute,
trackNo: coordinatorInternal.trackNo,
elapsedTime: elapsedTime,
elapsedTimeFormatted: formatTime(elapsedTime),
playbackState: coordinatorInternal.playbackState,
playMode: coordinatorInternal.playMode
});
}
function Player(data, listener, system) {
let _this = this;
_this.system = system;
_this.roomName = data.zonename;
_this.uuid = data.uuid;
_this.avTransportUri = '';
_this.avTransportUriMetadata = '';
_this.outputFixed = false;
// This is just a default, SonosSystem is responsible for updating this
_this.coordinator = _this;
_this.groupState = {
volume: 0,
mute: false
};
let state = clone(EMPTY_STATE);
Object.defineProperty(_this, 'state', {
get: () => getState(state, _this.coordinator._state)
});
// This is used internally only
Object.defineProperty(_this, '_state', {
get: () => state
});
_this.ownVolumeEvents = [];
_this._setVolume = function _setVolume(level) {
state.volume = level;
};
let uri = url.parse(data.location);
_this.baseUrl = `${uri.protocol}//${uri.host}`;
let subscribeEndpoints = [
'/MediaRenderer/AVTransport/Event',
'/MediaRenderer/RenderingControl/Event',
'/MediaRenderer/GroupRenderingControl/Event',
'/MediaServer/ContentDirectory/Event'
];
let subscriptions = subscribeEndpoints.map((path) => {
return new Subscriber(`${_this.baseUrl}${path}`, listener.endpoint());
});
_this.dispose = function dispose() {
subscriptions.forEach((subscriber) => {
subscriber.dispose();
});
};
function getPositionInfo() {
return soap.invoke(
`${_this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.GetPositionInfo)
.then(soap.parse)
.then(response => {
// Simplifies testing by not requiring mock data
if (!response) {
return;
}
if (response.reltime !== undefined) state.relTime = parseTime(response.reltime);
state.stateTime = Date.now();
})
.catch((err) => {
logger.error(err);
});
}
function notificationHandler(uuid, data) {
if (uuid !== _this.uuid) {
// This was not intended for us, skip it.
return;
}
if (data.avtransporturi) {
_this.avTransportUri = data.avtransporturi.val;
}
if (data.avtransporturimetadata) {
_this.avTransportUriMetadata = data.avtransporturimetadata.val;
}
if (data.transportstate) {
state.playbackState = data.transportstate.val;
state.trackNo = parseInt(data.currenttrack.val);
state.playMode.crossfade = data.currentcrossfademode.val === '1';
// bitwise check if shuffle or repeat. Return boolean if flag is set.
let currentPlayMode = PLAY_MODE[data.currentplaymode.val];
state.playMode.repeat = !!(currentPlayMode & PLAY_MODE.REPEAT_ALL) ? REPEAT_MODE.ALL : !!(currentPlayMode & PLAY_MODE.REPEAT_ONE) ? REPEAT_MODE.ONE : REPEAT_MODE.NONE;
state.playMode.shuffle = !!(PLAY_MODE[data.currentplaymode.val] & PLAY_MODE.SHUFFLE_NOREPEAT);
parseTrackMetadata(data.currenttrackmetadata)
.then(track => {
state.currentTrack = track;
state.currentTrack.type = _this.getUriType(_this.avTransportUri);
if (data.avtransporturimetadata && data.avtransporturimetadata.val) {
return parseAVTransportMetadata(data.avtransporturimetadata)
.then(radioInfo => {
state.currentTrack.artist = radioInfo.stationName;
if (state.currentTrack.albumArtUri && state.currentTrack.albumArtUri.startsWith('http')) {
state.currentTrack.absoluteAlbumArtUri = track.albumArtUri;
} else {
state.currentTrack.absoluteAlbumArtUri = `${_this.baseUrl}${track.albumArtUri}`;
}
});
}
return musicServices.tryGetHighResArt(state.currentTrack.uri)
.then((highResAlbumArtUrl) => {
track.absoluteAlbumArtUri = highResAlbumArtUrl;
}).catch(() => {
if (track.albumArtUri && track.albumArtUri.startsWith('http')) {
track.absoluteAlbumArtUri = track.albumArtUri;
} else if (track.albumArtUri) {
track.absoluteAlbumArtUri = `${_this.baseUrl}${track.albumArtUri}`;
}
});
})
.then(() => parseTrackMetadata(data['r:nexttrackmetadata'], true))
.then(track => {
state.nextTrack = track;
if (track.uri) {
return musicServices.tryGetHighResArt(state.nextTrack.uri)
.then((highResAlbumArtUri) => {
track.absoluteAlbumArtUri = highResAlbumArtUri;
})
.catch(() => {
if (track.albumArtUri && track.albumArtUri.startsWith('http')) {
track.absoluteAlbumArtUri = track.albumArtUri;
} else if (track.albumArtUri) {
track.absoluteAlbumArtUri = `${_this.baseUrl}${track.albumArtUri}`;
}
});
}
})
.then(() => {
if (
!_this.avTransportUri.startsWith('x-rincon:') &&
_this.state.playbackState !== 'TRANSITIONING'
) {
// Only fetch position info if coordinator
return getPositionInfo();
}
})
.then(() => {
_this.emit('transport-state', _this.state);
_this.system.emit('transport-state', _this);
});
}
if (data.mute) {
let master = data.mute.find(x => x.channel === 'Master');
const previousMute = state.mute;
state.mute = master.val === '1';
_this.emit('mute-change', {
previousMute,
newMute: state.mute,
roomName: _this.roomName
});
_this.system.emit('mute-change', {
uuid: _this.uuid,
previousMute,
newMute: state.mute,
roomName: _this.roomName
});
}
if (data.volume) {
let master = data.volume.find(x => x.channel === 'Master');
const previousVolume = state.volume;
state.volume = parseInt(master.val);
_this.emit('volume-change', {
previousVolume,
newVolume: state.volume,
roomName: _this.roomName
});
_this.system.emit('volume-change', {
uuid: _this.uuid,
previousVolume,
newVolume: state.volume,
roomName: _this.roomName
});
_this.coordinator.recalculateGroupVolume();
}
if (data.outputfixed) {
_this.outputFixed = data.outputfixed.val === '1';
}
}
function groupMuteHandler(uuid, mute) {
if (uuid !== _this.uuid) {
// This was not intended for us, skip it.
return;
}
let previousMute = _this.groupState.mute;
_this.groupState.mute = mute == '1';
_this.emit('group-mute', {
uuid: _this.uuid,
previousMute,
newMute: _this.groupState.mute,
roomName: _this.roomName
});
_this.system.emit('group-mute', {
uuid: _this.uuid,
previousMute,
newMute: _this.groupState.mute,
roomName: _this.roomName
});
}
listener.on('group-mute', groupMuteHandler);
listener.on('last-change', notificationHandler);
}
util.inherits(Player, EventEmitter);
Player.prototype.play = function play() {
logger.debug('invoking play');
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Play);
};
Player.prototype.pause = function pause() {
logger.debug('invoking pause');
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Pause);
};
Player.prototype.stop = function stop() {
logger.debug('invoking stop');
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Stop);
};
Player.prototype.nextTrack = function nextTrack() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Next);
};
Player.prototype.previousTrack = function previousTrack() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Previous);
};
Player.prototype.mute = function mute() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/RenderingControl/Control`,
TYPE.Mute,
{ mute: 1 });
};
Player.prototype.unMute = function unMute() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/RenderingControl/Control`,
TYPE.Mute,
{ mute: 0 });
};
Player.prototype.unMuteGroup = function unMuteGroup() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/GroupRenderingControl/Control`,
TYPE.GroupMute,
{ mute: 0 });
};
Player.prototype.muteGroup = function muteGroup() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/GroupRenderingControl/Control`,
TYPE.GroupMute,
{ mute: 1 });
};
Player.prototype.setVolume = function setVolume(level) {
if (this.outputFixed) {
return Promise.resolve();
}
// If prefixed with + or -
if (/^[+\-]/.test(level)) {
level = this.state.volume + parseInt(level);
}
if (level < 0) level = 0;
this._setVolume(level);
// stash this update to ignore the event when it comes back.
this.ownVolumeEvents.push(level);
return soap.invoke(
`${this.baseUrl}/MediaRenderer/RenderingControl/Control`,
TYPE.Volume,
{ volume: level });
};
Player.prototype.timeSeek = function timeSeek(seconds) {
let formattedTime = formatTime(seconds);
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Seek,
{ unit: 'REL_TIME', value: formattedTime });
};
Player.prototype.trackSeek = function trackSeek(trackNo) {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Seek,
{ unit: 'TRACK_NR', value: trackNo });
};
Player.prototype.clearQueue = function clearQueue() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.RemoveAllTracksFromQueue);
};
Player.prototype.removeTrackFromQueue = function removeTrackFromQueue(index) {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.RemoveTrackFromQueue,
{ track: index || 0 });
};
Player.prototype.removeTrackRangeFromQueue = function removeTrackRangeFromQueue(startIndex, numberOfTracks) {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.RemoveTrackRangeFromQueue,
{
startIndex: parseInt(startIndex, 10) || 0,
numberOfTracks: parseInt(numberOfTracks, 10) || 0
});
};
Player.prototype.reorderTracksInQueue = function reorderTracksInQueue(startIndex, numberOfTracks, insertBefore) {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.ReorderTracksInQueue,
{
startIndex: parseInt(startIndex, 10) || 0,
numberOfTracks: parseInt(numberOfTracks, 10) || 0,
insertBefore: parseInt(insertBefore, 10) || 0
});
};
Player.prototype.saveQueue = function saveQueue(title) {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.SaveQueue,
{
title
});
};
Player.prototype.addURIToQueue = function addURIToQueue(uri, metadata, enqueueAsNext, desiredFirstTrackNumberEnqueued) {
desiredFirstTrackNumberEnqueued =
desiredFirstTrackNumberEnqueued === undefined
? 0
: desiredFirstTrackNumberEnqueued;
enqueueAsNext = enqueueAsNext ? 1 : 0;
if (metadata === undefined) {
metadata = '';
}
metadata = xmlEntities.encode(metadata);
uri = xmlEntities.encode(uri);
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.AddURIToQueue,
{
uri,
metadata,
desiredFirstTrackNumberEnqueued,
enqueueAsNext
}).then(soap.parse);
};
Player.prototype.addMultipleURIsToQueue = function addMultipleURIsToQueue(elements, containerURI, containerMetadata, enqueueAsNext, desiredFirstTrackNumberEnqueued) {
desiredFirstTrackNumberEnqueued = desiredFirstTrackNumberEnqueued === undefined ? 0 : desiredFirstTrackNumberEnqueued;
enqueueAsNext = enqueueAsNext ? 1 : 0;
let uris = [];
let metadatas = [];
elements.forEach(element => {
uris.push(xmlEntities.encode(element[0]));
metadatas.push(xmlEntities.encode(element[1] || ''));
});
if (containerMetadata === undefined) {
containerMetadata = '';
}
containerMetadata = xmlEntities.encode(containerMetadata);
containerURI = xmlEntities.encode(containerURI);
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.AddURIToQueue,
{
amount: uris.length,
uris: uris.join(' '),
metadatas: metadatas.join(' '),
containerURI,
containerMetadata,
desiredFirstTrackNumberEnqueued,
enqueueAsNext
}).then(soap.parse);
};
Player.prototype.setPlayMode = function setPlayMode(newPlayMode) {
let promise = Promise.resolve();
if (newPlayMode.repeat !== undefined || newPlayMode.shuffle !== undefined) {
const desiredPlayMode = Object.assign({}, this.state.playMode, newPlayMode);
const playMode = getPlayMode(desiredPlayMode);
logger.debug(`repeat: ${newPlayMode.repeat}, shuffle: ${newPlayMode.shuffle}`);
logger.debug(`calculated playmode to ${playMode}`);
promise = promise.then(() => {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.SetPlayMode,
{ playMode })
.catch((err) => {
logger.warn(err, `Failed when trying to set playmode ${playMode}, could be playing radiostation or line-in, no worries.`);
});
});
}
if (newPlayMode.crossfade !== undefined) {
promise = promise.then(() => {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.SetCrossfadeMode,
{ crossfadeMode: newPlayMode.crossfade ? 1 : 0 });
});
}
return promise;
};
Player.prototype.repeat = function repeat(mode) {
let repeatMode = mode;
if (typeof mode === 'boolean') repeatMode = mode ? REPEAT_MODE.ALL : REPEAT_MODE.NONE;
return this.setPlayMode({ repeat: repeatMode });
};
Player.prototype.shuffle = function shuffle(enabled) {
return this.setPlayMode({ shuffle: Boolean(enabled) });
};
Player.prototype.crossfade = function crossfade(enabled) {
logger.debug(`Setting crossfade to ${enabled}`);
return this.setPlayMode({ crossfade: Boolean(enabled) });
};
Player.prototype.sleep = function sleep(seconds) {
let formattedTime = '';
if (seconds != 0) {
formattedTime = formatTime(seconds);
}
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.ConfigureSleepTimer,
{ time: formattedTime });
};
Player.prototype.setAVTransport = function setAVTransport(uri, metadata) {
if (metadata === undefined) {
metadata = '';
}
let entityEncodedMetadata = xmlEntities.encode(metadata);
let entityEncodedUri = xmlEntities.encode(uri);
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.SetAVTransportURI,
{ uri: entityEncodedUri, metadata: entityEncodedMetadata });
};
Player.prototype.becomeCoordinatorOfStandaloneGroup = function becomeCoordinatorOfStandaloneGroup() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.BecomeCoordinatorOfStandaloneGroup);
};
Player.prototype.refreshShareIndex = function refreshShareIndex() {
return soap.invoke(
`${this.baseUrl}/MediaServer/ContentDirectory/Control`,
TYPE.RefreshShareIndex);
};
Player.prototype.browse = function browse(objectId, startIndex, limit) {
startIndex = startIndex === undefined ? 0 : startIndex;
limit = limit === undefined ? 0 : limit;
return soap.invoke(
`${this.baseUrl}/MediaServer/ContentDirectory/Control`,
TYPE.Browse,
{ objectId, startIndex, limit })
.then(soap.parse)
.then(res => {
return new Promise((resolve, reject) => {
let returnResult = {
startIndex,
items: []
};
returnResult.numberReturned = parseInt(res.numberreturned, 10);
returnResult.totalMatches = parseInt(res.totalmatches, 10);
let stream = streamer(res.result);
let sax = flow(stream, { preserveMarkup: flow.NEVER });
sax.on('tag:item', (item) => {
returnResult.items.push({
uri: item.res ? item.res.$text : '',
title: item['dc:title'],
artist: item['dc:creator'],
album: item['upnp:album'],
albumArtUri: item['upnp:albumarturi'] instanceof Array
? item['upnp:albumarturi'][0]
: item['upnp:albumarturi'],
metadata: item['r:resmd']
});
});
sax.on('tag:container', (item) => {
returnResult.items.push({
uri: item.res.$text,
title: item['dc:title'],
albumArtUri: item['upnp:albumarturi']
});
});
sax.on('end', () => {
resolve(returnResult);
});
sax.on('error', (error) => {
reject(error);
});
});
});
};
Player.prototype.browseAll = function browseAll(objectId) {
let result = {
items: [],
startIndex: 0,
numberReturned: 0,
totalMatches: 1
};
let getChunk = (chunk) => {
if (!chunk || !Array.isArray(chunk.items) || isNaN(chunk.totalMatches)) {
// something went wrong. prevent infinite loop
return Promise.reject(new Error('browse() returned an invalid payload'));
}
Array.prototype.push.apply(result.items, chunk.items);
result.numberReturned += chunk.numberReturned;
result.totalMatches = chunk.totalMatches;
if (chunk.startIndex + chunk.numberReturned >= chunk.totalMatches) {
return result.items;
}
// Recursive promise chain
return this.browse(objectId, chunk.startIndex + chunk.numberReturned, 0)
.then(getChunk);
};
return Promise.resolve(result)
.then(getChunk);
};
Player.prototype.getQueue = function getQueue() {
return this.browseAll('Q:0');
};
Player.prototype.toJSON = function toJSON() {
return {
uuid: this.uuid,
coordinator: this.coordinator.uuid,
roomName: this.roomName,
state: this.state,
groupState: this.coordinator.groupState,
avTransportUri: this.avTransportUri,
avTransportUriMetadata: this.avTransportUriMetadata
};
};
requireDir(path.join(__dirname, '../prototypes/Player'), (proto) => {
Player.prototype[proto.name] = proto;
});
module.exports = Player;
| lib/models/Player.js | 'use strict';
const url = require('url');
const Subscriber = require('../Subscriber');
const soap = require('../helpers/soap');
const streamer = require('../helpers/streamer');
const TYPE = soap.TYPE;
const flow = require('xml-flow');
const XmlEntities = require('html-entities').XmlEntities;
const path = require('path');
const requireDir = require('../helpers/require-dir');
const logger = require('../helpers/logger');
const musicServices = require('../musicservices');
const xmlEntities = new XmlEntities();
const util = require('util');
const EventEmitter = require('events').EventEmitter;
const EMPTY_STATE = require('../types/empty-state');
const PLAY_MODE = require('../types/play-mode');
const REPEAT_MODE = require('../types/repeat-mode');
function reversePlayMode() {
let lookup = {};
for (let key in PLAY_MODE) {
lookup[PLAY_MODE[key]] = key;
}
return lookup;
}
const PLAY_MODE_LOOKUP = Object.freeze(reversePlayMode());
function getPlayMode(state) {
let key = state.shuffle << 1 | (state.repeat === REPEAT_MODE.ONE ? 4 : (state.repeat === REPEAT_MODE.ALL ? 1 : 0));
return PLAY_MODE_LOOKUP[key];
}
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
function parseTime(formattedTime) {
if (formattedTime === undefined) {
return 0;
}
var chunks = formattedTime.split(':').reverse();
var timeInSeconds = 0;
for (var i = 0; i < chunks.length; i++) {
timeInSeconds += parseInt(chunks[i], 10) * Math.pow(60, i);
}
return isNaN(timeInSeconds) ? 0 : timeInSeconds;
}
function zpad(number) {
return ('00' + number).substr(-2);
}
function formatTime(seconds) {
var chunks = [];
var remainingTime = seconds;
// hours
var hours = Math.floor(remainingTime / 3600);
chunks.push(zpad(hours));
remainingTime -= hours * 3600;
// minutes
var minutes = Math.floor(remainingTime / 60);
chunks.push(zpad(minutes));
remainingTime -= minutes * 60;
// seconds
chunks.push(zpad(remainingTime));
return chunks.join(':');
}
function parseTrackMetadata(metadata, nextTrack) {
return new Promise((resolve, reject) => {
let track = nextTrack ? clone(EMPTY_STATE.nextTrack) : clone(EMPTY_STATE.currentTrack);
if (!metadata) resolve(track);
const sax = flow(streamer(metadata.val));
sax.on('tag:item', (item) => {
track.uri = item.res.$text;
track.duration = parseTime((item.res.$attrs || item.res).duration);
track.artist = item['dc:creator'];
track.album = item['upnp:album'];
track.title = item['r:streamcontent'] || item['dc:title'];
track.albumArtUri = item['upnp:albumarturi'];
});
sax.on('error', reject);
sax.on('end', () => {
resolve(track);
});
});
}
function parseAVTransportMetadata(metadata) {
return new Promise((resolve, reject) => {
if (!metadata) resolve({});
const sax = flow(streamer(metadata.val));
const avTransportMetadata = {};
sax.on('tag:item', (item) => {
avTransportMetadata.stationName = item['dc:title'];
});
sax.on('error', reject);
sax.on('end', () => {
resolve(avTransportMetadata);
});
});
}
function getState(playerInternal, coordinatorInternal) {
var diff = 0;
if (coordinatorInternal.playbackState === 'PLAYING')
diff = Date.now() - coordinatorInternal.stateTime;
var elapsedTime = coordinatorInternal.relTime + Math.floor(diff / 1000);
return Object.freeze({
currentTrack: coordinatorInternal.currentTrack,
nextTrack: coordinatorInternal.nextTrack,
volume: playerInternal.volume,
mute: playerInternal.mute,
trackNo: coordinatorInternal.trackNo,
elapsedTime: elapsedTime,
elapsedTimeFormatted: formatTime(elapsedTime),
playbackState: coordinatorInternal.playbackState,
playMode: coordinatorInternal.playMode
});
}
function Player(data, listener, system) {
let _this = this;
_this.system = system;
_this.roomName = data.zonename;
_this.uuid = data.uuid;
_this.avTransportUri = '';
_this.avTransportUriMetadata = '';
_this.outputFixed = false;
// This is just a default, SonosSystem is responsible for updating this
_this.coordinator = _this;
_this.groupState = {
volume: 0,
mute: false
};
let state = clone(EMPTY_STATE);
Object.defineProperty(_this, 'state', {
get: () => getState(state, _this.coordinator._state)
});
// This is used internally only
Object.defineProperty(_this, '_state', {
get: () => state
});
_this.ownVolumeEvents = [];
_this._setVolume = function _setVolume(level) {
state.volume = level;
};
let uri = url.parse(data.location);
_this.baseUrl = `${uri.protocol}//${uri.host}`;
let subscribeEndpoints = [
'/MediaRenderer/AVTransport/Event',
'/MediaRenderer/RenderingControl/Event',
'/MediaRenderer/GroupRenderingControl/Event',
'/MediaServer/ContentDirectory/Event'
];
let subscriptions = subscribeEndpoints.map((path) => {
return new Subscriber(`${_this.baseUrl}${path}`, listener.endpoint());
});
_this.dispose = function dispose() {
subscriptions.forEach((subscriber) => {
subscriber.dispose();
});
};
function getPositionInfo() {
return soap.invoke(
`${_this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.GetPositionInfo)
.then(soap.parse)
.then(response => {
// Simplifies testing by not requiring mock data
if (!response) {
return;
}
if (response.reltime !== undefined) state.relTime = parseTime(response.reltime);
state.stateTime = Date.now();
})
.catch((err) => {
logger.error(err);
});
}
function notificationHandler(uuid, data) {
if (uuid !== _this.uuid) {
// This was not intended for us, skip it.
return;
}
if (data.avtransporturi) {
_this.avTransportUri = data.avtransporturi.val;
}
if (data.avtransporturimetadata) {
_this.avTransportUriMetadata = data.avtransporturimetadata.val;
}
if (data.transportstate) {
state.playbackState = data.transportstate.val;
state.trackNo = parseInt(data.currenttrack.val);
state.playMode.crossfade = data.currentcrossfademode.val === '1';
// bitwise check if shuffle or repeat. Return boolean if flag is set.
let currentPlayMode = PLAY_MODE[data.currentplaymode.val];
state.playMode.repeat = !!(currentPlayMode & PLAY_MODE.REPEAT_ALL) ? REPEAT_MODE.ALL : !!(currentPlayMode & PLAY_MODE.REPEAT_ONE) ? REPEAT_MODE.ONE : REPEAT_MODE.NONE;
state.playMode.shuffle = !!(PLAY_MODE[data.currentplaymode.val] & PLAY_MODE.SHUFFLE_NOREPEAT);
parseTrackMetadata(data.currenttrackmetadata)
.then(track => {
state.currentTrack = track;
state.currentTrack.type = _this.getUriType(_this.avTransportUri);
if (data.avtransporturimetadata && data.avtransporturimetadata.val) {
return parseAVTransportMetadata(data.avtransporturimetadata)
.then(radioInfo => {
state.currentTrack.artist = radioInfo.stationName;
if (state.currentTrack.albumArtUri && state.currentTrack.albumArtUri.startsWith('http')) {
state.currentTrack.absoluteAlbumArtUri = track.albumArtUri;
} else {
state.currentTrack.absoluteAlbumArtUri = `${_this.baseUrl}${track.albumArtUri}`;
}
});
}
return musicServices.tryGetHighResArt(state.currentTrack.uri)
.then((highResAlbumArtUrl) => {
track.absoluteAlbumArtUri = highResAlbumArtUrl;
}).catch(() => {
if (track.albumArtUri && track.albumArtUri.startsWith('http')) {
track.absoluteAlbumArtUri = track.albumArtUri;
} else if (track.albumArtUri) {
track.absoluteAlbumArtUri = `${_this.baseUrl}${track.albumArtUri}`;
}
});
})
.then(() => parseTrackMetadata(data['r:nexttrackmetadata'], true))
.then(track => {
state.nextTrack = track;
if (track.uri) {
return musicServices.tryGetHighResArt(state.nextTrack.uri)
.then((highResAlbumArtUri) => {
track.absoluteAlbumArtUri = highResAlbumArtUri;
})
.catch(() => {
if (track.albumArtUri && track.albumArtUri.startsWith('http')) {
track.absoluteAlbumArtUri = track.albumArtUri;
} else if (track.albumArtUri) {
track.absoluteAlbumArtUri = `${_this.baseUrl}${track.albumArtUri}`;
}
});
}
})
.then(() => {
if (
!_this.avTransportUri.startsWith('x-rincon:') &&
_this.state.playbackState !== 'TRANSITIONING'
) {
// Only fetch position info if coordinator
return getPositionInfo();
}
})
.then(() => {
_this.emit('transport-state', _this.state);
_this.system.emit('transport-state', _this);
});
}
if (data.mute) {
let master = data.mute.find(x => x.channel === 'Master');
const previousMute = state.mute;
state.mute = master.val === '1';
_this.emit('mute-change', {
previousMute,
newMute: state.mute,
roomName: _this.roomName
});
_this.system.emit('mute-change', {
uuid: _this.uuid,
previousMute,
newMute: state.mute,
roomName: _this.roomName
});
}
if (data.volume) {
let master = data.volume.find(x => x.channel === 'Master');
const previousVolume = state.volume;
state.volume = parseInt(master.val);
_this.emit('volume-change', {
previousVolume,
newVolume: state.volume,
roomName: _this.roomName
});
_this.system.emit('volume-change', {
uuid: _this.uuid,
previousVolume,
newVolume: state.volume,
roomName: _this.roomName
});
_this.coordinator.recalculateGroupVolume();
}
if (data.outputfixed) {
_this.outputFixed = data.outputfixed.val === '1';
}
}
function groupMuteHandler(uuid, mute) {
if (uuid !== _this.uuid) {
// This was not intended for us, skip it.
return;
}
let previousMute = _this.groupState.mute;
_this.groupState.mute = mute == '1';
_this.emit('group-mute', {
uuid: _this.uuid,
previousMute,
newMute: _this.groupState.mute,
roomName: _this.roomName
});
_this.system.emit('group-mute', {
uuid: _this.uuid,
previousMute,
newMute: _this.groupState.mute,
roomName: _this.roomName
});
}
listener.on('group-mute', groupMuteHandler);
listener.on('last-change', notificationHandler);
}
util.inherits(Player, EventEmitter);
Player.prototype.play = function play() {
logger.debug('invoking play');
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Play);
};
Player.prototype.pause = function pause() {
logger.debug('invoking pause');
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Pause);
};
Player.prototype.stop = function stop() {
logger.debug('invoking stop');
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Stop);
};
Player.prototype.nextTrack = function nextTrack() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Next);
};
Player.prototype.previousTrack = function previousTrack() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Previous);
};
Player.prototype.mute = function mute() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/RenderingControl/Control`,
TYPE.Mute,
{ mute: 1 });
};
Player.prototype.unMute = function unMute() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/RenderingControl/Control`,
TYPE.Mute,
{ mute: 0 });
};
Player.prototype.unMuteGroup = function unMuteGroup() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/GroupRenderingControl/Control`,
TYPE.GroupMute,
{ mute: 0 });
};
Player.prototype.muteGroup = function muteGroup() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/GroupRenderingControl/Control`,
TYPE.GroupMute,
{ mute: 1 });
};
Player.prototype.setVolume = function setVolume(level) {
if (this.outputFixed) {
return Promise.resolve();
}
// If prefixed with + or -
if (/^[+\-]/.test(level)) {
level = this.state.volume + parseInt(level);
}
if (level < 0) level = 0;
this._setVolume(level);
// stash this update to ignore the event when it comes back.
this.ownVolumeEvents.push(level);
return soap.invoke(
`${this.baseUrl}/MediaRenderer/RenderingControl/Control`,
TYPE.Volume,
{ volume: level });
};
Player.prototype.timeSeek = function timeSeek(seconds) {
let formattedTime = formatTime(seconds);
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Seek,
{ unit: 'REL_TIME', value: formattedTime });
};
Player.prototype.trackSeek = function trackSeek(trackNo) {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.Seek,
{ unit: 'TRACK_NR', value: trackNo });
};
Player.prototype.clearQueue = function clearQueue() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.RemoveAllTracksFromQueue);
};
Player.prototype.removeTrackFromQueue = function removeTrackFromQueue(index) {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.RemoveTrackFromQueue,
{ track: index || 0 });
};
Player.prototype.removeTrackRangeFromQueue = function removeTrackRangeFromQueue(startIndex, numberOfTracks) {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.RemoveTrackRangeFromQueue,
{
startIndex: parseInt(startIndex, 10) || 0,
numberOfTracks: parseInt(numberOfTracks, 10) || 0
});
};
Player.prototype.reorderTracksInQueue = function reorderTracksInQueue(startIndex, numberOfTracks, insertBefore) {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.ReorderTracksInQueue,
{
startIndex: parseInt(startIndex, 10) || 0,
numberOfTracks: parseInt(numberOfTracks, 10) || 0,
insertBefore: parseInt(insertBefore, 10) || 0
});
};
Player.prototype.saveQueue = function saveQueue(title) {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.SaveQueue,
{
title
});
};
Player.prototype.addURIToQueue = function addURIToQueue(uri, metadata, enqueueAsNext, desiredFirstTrackNumberEnqueued) {
desiredFirstTrackNumberEnqueued =
desiredFirstTrackNumberEnqueued === undefined
? 0
: desiredFirstTrackNumberEnqueued;
enqueueAsNext = enqueueAsNext ? 1 : 0;
if (metadata === undefined) {
metadata = '';
}
metadata = xmlEntities.encode(metadata);
uri = xmlEntities.encode(uri);
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.AddURIToQueue,
{
uri,
metadata,
desiredFirstTrackNumberEnqueued,
enqueueAsNext
}).then(soap.parse);
};
Player.prototype.addMultipleURIsToQueue = function addMultipleURIsToQueue(elements, containerURI, containerMetadata, enqueueAsNext, desiredFirstTrackNumberEnqueued) {
desiredFirstTrackNumberEnqueued = desiredFirstTrackNumberEnqueued === undefined ? 0 : desiredFirstTrackNumberEnqueued;
enqueueAsNext = enqueueAsNext ? 1 : 0;
let uris = [];
let metadatas = [];
elements.forEach(element => {
uris.push(xmlEntities.encode(element[0]));
metadatas.push(xmlEntities.encode(element[1] || ''));
});
if (containerMetadata === undefined) {
containerMetadata = '';
}
containerMetadata = xmlEntities.encode(containerMetadata);
containerURI = xmlEntities.encode(containerURI);
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.AddURIToQueue,
{
amount: uris.length,
uris: uris.join(' '),
metadatas: metadatas.join(' '),
containerURI,
containerMetadata,
desiredFirstTrackNumberEnqueued,
enqueueAsNext
}).then(soap.parse);
};
Player.prototype.setPlayMode = function setPlayMode(newPlayMode) {
let promise = Promise.resolve();
if (newPlayMode.repeat !== undefined || newPlayMode.shuffle !== undefined) {
const desiredPlayMode = Object.assign({}, this.state.playMode, newPlayMode);
const playMode = getPlayMode(desiredPlayMode);
logger.debug(`repeat: ${newPlayMode.repeat}, shuffle: ${newPlayMode.shuffle}`);
logger.debug(`calculated playmode to ${playMode}`);
promise = promise.then(() => {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.SetPlayMode,
{ playMode })
.catch((err) => {
logger.warn(err, `Failed when trying to set playmode ${playMode}, could be playing radiostation or line-in, no worries.`);
});
});
}
if (newPlayMode.crossfade !== undefined) {
promise = promise.then(() => {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.SetCrossfadeMode,
{ crossfadeMode: newPlayMode.crossfade ? 1 : 0 });
});
}
return promise;
};
Player.prototype.repeat = function repeat(mode) {
let repeatMode = mode;
if (typeof mode === 'boolean') repeatMode = mode ? REPEAT_MODE.ALL : REPEAT_MODE.NONE;
return this.setPlayMode({ repeat: repeatMode });
};
Player.prototype.shuffle = function shuffle(enabled) {
return this.setPlayMode({ shuffle: Boolean(enabled) });
};
Player.prototype.crossfade = function crossfade(enabled) {
logger.debug(`Setting crossfade to ${enabled}`);
return this.setPlayMode({ crossfade: Boolean(enabled) });
};
Player.prototype.sleep = function sleep(seconds) {
let formattedTime = '';
if (seconds != 0) {
formattedTime = formatTime(seconds);
}
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.ConfigureSleepTimer,
{ time: formattedTime });
};
Player.prototype.setAVTransport = function setAVTransport(uri, metadata) {
if (metadata === undefined) {
metadata = '';
}
let entityEncodedMetadata = xmlEntities.encode(metadata);
let entityEncodedUri = xmlEntities.encode(uri);
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.SetAVTransportURI,
{ uri: entityEncodedUri, metadata: entityEncodedMetadata });
};
Player.prototype.becomeCoordinatorOfStandaloneGroup = function becomeCoordinatorOfStandaloneGroup() {
return soap.invoke(
`${this.baseUrl}/MediaRenderer/AVTransport/Control`,
TYPE.BecomeCoordinatorOfStandaloneGroup);
};
Player.prototype.refreshShareIndex = function refreshShareIndex() {
return soap.invoke(
`${this.baseUrl}/MediaServer/ContentDirectory/Control`,
TYPE.RefreshShareIndex);
};
Player.prototype.browse = function browse(objectId, startIndex, limit) {
startIndex = startIndex === undefined ? 0 : startIndex;
limit = limit === undefined ? 0 : limit;
return soap.invoke(
`${this.baseUrl}/MediaServer/ContentDirectory/Control`,
TYPE.Browse,
{ objectId, startIndex, limit })
.then(soap.parse)
.then(res => {
return new Promise((resolve, reject) => {
let returnResult = {
startIndex,
items: []
};
returnResult.numberReturned = parseInt(res.numberreturned, 10);
returnResult.totalMatches = parseInt(res.totalmatches, 10);
let stream = streamer(res.result);
let sax = flow(stream, { preserveMarkup: flow.NEVER });
sax.on('tag:item', (item) => {
returnResult.items.push({
uri: item.res ? item.res.$text : '',
title: item['dc:title'],
artist: item['dc:creator'],
album: item['upnp:album'],
albumArtUri: item['upnp:albumarturi'] instanceof Array
? item['upnp:albumarturi'][0]
: item['upnp:albumarturi'],
metadata: item['r:resmd']
});
});
sax.on('tag:container', (item) => {
returnResult.items.push({
uri: item.res.$text,
title: item['dc:title'],
albumArtUri: item['upnp:albumarturi']
});
});
sax.on('end', () => {
resolve(returnResult);
});
sax.on('error', (error) => {
reject(error);
});
});
});
};
Player.prototype.browseAll = function browseAll(objectId) {
let result = {
items: [],
startIndex: 0,
numberReturned: 0,
totalMatches: 1
};
let getChunk = (chunk) => {
if (!chunk || !Array.isArray(chunk.items) || isNaN(chunk.totalMatches)) {
// something went wrong. prevent infinite loop
return Promise.reject(new Error('browse() returned an invalid payload'));
}
Array.prototype.push.apply(result.items, chunk.items);
result.numberReturned += chunk.numberReturned;
result.totalMatches = chunk.totalMatches;
if (chunk.startIndex + chunk.numberReturned >= chunk.totalMatches) {
return result.items;
}
// Recursive promise chain
return this.browse(objectId, chunk.startIndex + chunk.numberReturned, 0)
.then(getChunk);
};
return Promise.resolve(result)
.then(getChunk);
};
Player.prototype.getQueue = function getQueue() {
return this.browseAll('Q:0');
};
Player.prototype.toJSON = function toJSON() {
return {
uuid: this.uuid,
coordinator: this.coordinator.uuid,
roomName: this.roomName,
state: this.state,
avTransportUri: this.avTransportUri,
avTransportUriMetadata: this.avTransportUriMetadata
};
};
requireDir(path.join(__dirname, '../prototypes/Player'), (proto) => {
Player.prototype[proto.name] = proto;
});
module.exports = Player;
| Add groupState to player serialization
| lib/models/Player.js | Add groupState to player serialization | <ide><path>ib/models/Player.js
<ide> coordinator: this.coordinator.uuid,
<ide> roomName: this.roomName,
<ide> state: this.state,
<add> groupState: this.coordinator.groupState,
<ide> avTransportUri: this.avTransportUri,
<ide> avTransportUriMetadata: this.avTransportUriMetadata
<ide> }; |
|
Java | apache-2.0 | 53465b931de3629cdbe5a69a1755f509761c6150 | 0 | vert-x3/vertx-jdbc-client | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.impl;
import io.vertx.core.AsyncResult;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.impl.ContextInternal;
import io.vertx.core.impl.VertxInternal;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.shareddata.LocalMap;
import io.vertx.core.shareddata.Shareable;
import io.vertx.core.spi.metrics.PoolMetrics;
import io.vertx.core.spi.metrics.VertxMetrics;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.jdbc.impl.actions.AbstractJDBCAction;
import io.vertx.ext.jdbc.impl.actions.JDBCQuery;
import io.vertx.ext.jdbc.impl.actions.JDBCStatementHelper;
import io.vertx.ext.jdbc.impl.actions.JDBCUpdate;
import io.vertx.ext.jdbc.spi.DataSourceProvider;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.SQLClient;
import io.vertx.ext.sql.SQLConnection;
import io.vertx.ext.sql.UpdateResult;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public class JDBCClientImpl implements JDBCClient {
private static final String DS_LOCAL_MAP_NAME = "__vertx.JDBCClient.datasources";
private final Vertx vertx;
private final DataSourceHolder holder;
// We use this executor to execute getConnection requests
private final ExecutorService exec;
private final DataSource ds;
private final PoolMetrics metrics;
// Helper that can do param and result transforms, its behavior is defined by the
// initial config and immutable after that moment. It is safe to reuse since there
// is no state involved
private final JDBCStatementHelper helper;
/*
Create client with specific datasource
*/
public JDBCClientImpl(Vertx vertx, DataSource dataSource) {
Objects.requireNonNull(vertx);
Objects.requireNonNull(dataSource);
this.vertx = vertx;
this.holder = new DataSourceHolder((VertxInternal) vertx, dataSource);
this.exec = holder.exec();
this.ds = dataSource;
this.metrics = holder.metrics;
this.helper = new JDBCStatementHelper();
setupCloseHook();
}
/*
Create client with shared datasource
*/
public JDBCClientImpl(Vertx vertx, JsonObject config, String datasourceName) {
Objects.requireNonNull(vertx);
Objects.requireNonNull(config);
Objects.requireNonNull(datasourceName);
this.vertx = vertx;
this.holder = lookupHolder(datasourceName, config);
this.exec = holder.exec();
this.ds = holder.ds();
this.metrics = holder.metrics;
this.helper = new JDBCStatementHelper(config);
setupCloseHook();
}
private void setupCloseHook() {
Context ctx = Vertx.currentContext();
if (ctx != null && ctx.owner() == vertx) {
ctx.addCloseHook(holder::close);
}
}
@Override
public void close() {
holder.close(null);
}
@Override
public void close(Handler<AsyncResult<Void>> completionHandler) {
holder.close(completionHandler);
}
@Override
public JDBCClient update(String sql, Handler<AsyncResult<UpdateResult>> resultHandler) {
ContextInternal ctx = (ContextInternal) vertx.getOrCreateContext();
executeDirect(ctx, new JDBCUpdate(vertx, helper, null, ctx, sql, null), resultHandler);
return this;
}
@Override
public JDBCClient updateWithParams(String sql, JsonArray in, Handler<AsyncResult<UpdateResult>> resultHandler) {
ContextInternal ctx = (ContextInternal) vertx.getOrCreateContext();
executeDirect(ctx, new JDBCUpdate(vertx, helper, null, ctx, sql, in), resultHandler);
return this;
}
@Override
public JDBCClient query(String sql, Handler<AsyncResult<ResultSet>> resultHandler) {
ContextInternal ctx = (ContextInternal) vertx.getOrCreateContext();
executeDirect(ctx, new JDBCQuery(vertx, helper, null, ctx, sql, null), resultHandler);
return this;
}
@Override
public JDBCClient queryWithParams(String sql, JsonArray in, Handler<AsyncResult<ResultSet>> resultHandler) {
ContextInternal ctx = (ContextInternal) vertx.getOrCreateContext();
executeDirect(ctx, new JDBCQuery(vertx, helper, null, ctx, sql, in), resultHandler);
return this;
}
private <T> void executeDirect(Context ctx, AbstractJDBCAction<T> action, Handler<AsyncResult<T>> handler) {
getConnection(ctx, ar1 -> {
Future<T> fut = Future.future();
fut.setHandler(ar2 -> ctx.runOnContext(v -> handler.handle(ar2)));
if (ar1.succeeded()) {
JDBCConnectionImpl conn = (JDBCConnectionImpl) ar1.result();
try {
T result = action.execute(conn.conn);
fut.complete(result);
} catch (Exception e) {
fut.fail(e);
} finally {
if (metrics != null) {
metrics.end(conn.metric, true);
}
try {
conn.conn.close();
} catch (Exception e) {
JDBCConnectionImpl.log.error("Failure in closing connection", ar1.cause());
}
}
} else {
fut.fail(ar1.cause());
}
});
}
private void getConnection(Context ctx, Handler<AsyncResult<SQLConnection>> handler) {
boolean enabled = metrics != null;
Object queueMetric = enabled ? metrics.submitted() : null;
PoolMetrics metrics = enabled ? this.metrics : null;
exec.execute(() -> {
Future<SQLConnection> res = Future.future();
res.setHandler(handler);
try {
/*
This can block until a connection is free.
We don't want to do that while running on a worker as we can enter a deadlock situation as the worker
might have obtained a connection, and won't release it until it is run again
There is a general principle here:
*User code* should be executed on a worker and can potentially block, it's up to the *user* to deal with
deadlocks that might occur there.
If the *service code* internally blocks waiting for a resource that might be obtained by *user code*, then
this can cause deadlock, so the service should ensure it never does this, by executing such code
(e.g. getConnection) on a different thread to the worker pool.
We don't want to use the vert.x internal pool for this as the threads might end up all blocked preventing
other important operations from occurring (e.g. async file access)
*/
Connection conn = ds.getConnection();
Object execMetric = null;
if (metrics != null) {
execMetric = metrics.begin(queueMetric);
}
// wrap it
res.complete(new JDBCConnectionImpl(ctx, helper, conn, metrics, execMetric));
} catch (SQLException e) {
if (metrics != null) {
metrics.rejected(queueMetric);
}
res.fail(e);
}
});
}
@Override
public SQLClient getConnection(Handler<AsyncResult<SQLConnection>> handler) {
Context ctx = vertx.getOrCreateContext();
getConnection(ctx, ar -> ctx.runOnContext(v -> handler.handle(ar)));
return this;
}
private DataSourceHolder lookupHolder(String datasourceName, JsonObject config) {
synchronized (vertx) {
LocalMap<String, DataSourceHolder> map = vertx.sharedData().getLocalMap(DS_LOCAL_MAP_NAME);
DataSourceHolder theHolder = map.get(datasourceName);
if (theHolder == null) {
theHolder = new DataSourceHolder((VertxInternal) vertx, config, map, datasourceName);
} else {
theHolder.incRefCount();
}
return theHolder;
}
}
private class DataSourceHolder implements Shareable {
private final VertxInternal vertx;
private final LocalMap<String, DataSourceHolder> map;
DataSourceProvider provider;
JsonObject config;
DataSource ds;
PoolMetrics metrics;
ExecutorService exec;
private int refCount = 1;
private final String name;
DataSourceHolder(VertxInternal vertx, DataSource ds) {
this.ds = ds;
this.metrics = vertx.metricsSPI() != null ? vertx.metricsSPI().createPoolMetrics("datasource", UUID.randomUUID().toString(), -1) : null;
this.vertx = vertx;
this.map = null;
this.name = null;
}
DataSourceHolder(VertxInternal vertx, JsonObject config, LocalMap<String, DataSourceHolder> map, String name) {
this.config = config;
this.map = map;
this.vertx = vertx;
this.name = name;
map.put(name, this);
}
synchronized DataSource ds() {
if (ds == null) {
String providerClass = config.getString("provider_class");
if (providerClass == null) {
providerClass = DEFAULT_PROVIDER_CLASS;
}
VertxMetrics vertxMetrics = vertx.metricsSPI();
if (Thread.currentThread().getContextClassLoader() != null) {
try {
// Try with the TCCL
Class clazz = Thread.currentThread().getContextClassLoader().loadClass(providerClass);
provider = (DataSourceProvider) clazz.newInstance();
ds = provider.getDataSource(config);
int poolSize = provider.maximumPoolSize(ds, config);
metrics = vertxMetrics != null ? vertxMetrics.createPoolMetrics( "datasource", name, poolSize) : null;
return ds;
} catch (ClassNotFoundException e) {
// Next try.
} catch (InstantiationException | SQLException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
try {
// Try with the classloader of the current class.
Class clazz = this.getClass().getClassLoader().loadClass(providerClass);
provider = (DataSourceProvider) clazz.newInstance();
ds = provider.getDataSource(config);
int poolSize = provider.maximumPoolSize(ds, config);
metrics = vertxMetrics != null ? vertxMetrics.createPoolMetrics( "datasource", name, poolSize) : null;
return ds;
} catch (ClassNotFoundException | InstantiationException | SQLException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return ds;
}
synchronized ExecutorService exec() {
if (exec == null) {
exec = new ThreadPoolExecutor(1, 1,
1000L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(),
(r -> new Thread(r, "vertx-jdbc-service-get-connection-thread")));
}
return exec;
}
void incRefCount() {
refCount++;
}
void close(Handler<AsyncResult<Void>> completionHandler) {
synchronized (vertx) {
if (--refCount == 0) {
if (metrics != null) {
metrics.close();
}
Future<Void> f1 = Future.future();
Future<Void> f2 = Future.future();
if (completionHandler != null) {
CompositeFuture.all(f1, f2).<Void>map(f -> null).setHandler(completionHandler);
}
if (provider != null) {
vertx.executeBlocking(future -> {
try {
provider.close(ds);
future.complete();
} catch (SQLException e) {
future.fail(e);
}
}, f2);
} else {
f2.complete();
}
try {
if (exec != null) {
exec.shutdown();
}
if (map != null) {
map.remove(name);
if (map.isEmpty()) {
map.close();
}
}
f1.complete();
} catch (Throwable t) {
f1.fail(t);
}
} else {
if (completionHandler != null) {
completionHandler.handle(Future.succeededFuture());
}
}
}
}
}
}
| src/main/java/io/vertx/ext/jdbc/impl/JDBCClientImpl.java | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.impl;
import io.vertx.core.AsyncResult;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.impl.ContextInternal;
import io.vertx.core.impl.VertxInternal;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.shareddata.LocalMap;
import io.vertx.core.shareddata.Shareable;
import io.vertx.core.spi.metrics.PoolMetrics;
import io.vertx.core.spi.metrics.VertxMetrics;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.jdbc.impl.actions.AbstractJDBCAction;
import io.vertx.ext.jdbc.impl.actions.JDBCQuery;
import io.vertx.ext.jdbc.impl.actions.JDBCStatementHelper;
import io.vertx.ext.jdbc.impl.actions.JDBCUpdate;
import io.vertx.ext.jdbc.spi.DataSourceProvider;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.SQLClient;
import io.vertx.ext.sql.SQLConnection;
import io.vertx.ext.sql.UpdateResult;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public class JDBCClientImpl implements JDBCClient {
private static final String DS_LOCAL_MAP_NAME = "__vertx.JDBCClient.datasources";
private final Vertx vertx;
private final DataSourceHolder holder;
// We use this executor to execute getConnection requests
private final ExecutorService exec;
private final DataSource ds;
private final PoolMetrics metrics;
// Helper that can do param and result transforms, its behavior is defined by the
// initial config and immutable after that moment. It is safe to reuse since there
// is no state involved
private final JDBCStatementHelper helper;
/*
Create client with specific datasource
*/
public JDBCClientImpl(Vertx vertx, DataSource dataSource) {
Objects.requireNonNull(vertx);
Objects.requireNonNull(dataSource);
this.vertx = vertx;
this.holder = new DataSourceHolder((VertxInternal) vertx, dataSource);
this.exec = holder.exec();
this.ds = dataSource;
this.metrics = holder.metrics;
this.helper = new JDBCStatementHelper();
setupCloseHook();
}
/*
Create client with shared datasource
*/
public JDBCClientImpl(Vertx vertx, JsonObject config, String datasourceName) {
Objects.requireNonNull(vertx);
Objects.requireNonNull(config);
Objects.requireNonNull(datasourceName);
this.vertx = vertx;
this.holder = lookupHolder(datasourceName, config);
this.exec = holder.exec();
this.ds = holder.ds();
this.metrics = holder.metrics;
this.helper = new JDBCStatementHelper(config);
setupCloseHook();
}
private void setupCloseHook() {
Context ctx = Vertx.currentContext();
if (ctx != null && ctx.owner() == vertx) {
ctx.addCloseHook(holder::close);
}
}
@Override
public void close() {
holder.close(null);
}
@Override
public void close(Handler<AsyncResult<Void>> completionHandler) {
holder.close(completionHandler);
}
@Override
public JDBCClient update(String sql, Handler<AsyncResult<UpdateResult>> resultHandler) {
ContextInternal ctx = (ContextInternal) vertx.getOrCreateContext();
executeDirect(ctx, new JDBCUpdate(vertx, helper, null, ctx, sql, null), resultHandler);
return this;
}
@Override
public JDBCClient updateWithParams(String sql, JsonArray in, Handler<AsyncResult<UpdateResult>> resultHandler) {
ContextInternal ctx = (ContextInternal) vertx.getOrCreateContext();
executeDirect(ctx, new JDBCUpdate(vertx, helper, null, ctx, sql, in), resultHandler);
return this;
}
@Override
public JDBCClient query(String sql, Handler<AsyncResult<ResultSet>> resultHandler) {
ContextInternal ctx = (ContextInternal) vertx.getOrCreateContext();
executeDirect(ctx, new JDBCQuery(vertx, helper, null, ctx, sql, null), resultHandler);
return this;
}
@Override
public JDBCClient queryWithParams(String sql, JsonArray in, Handler<AsyncResult<ResultSet>> resultHandler) {
ContextInternal ctx = (ContextInternal) vertx.getOrCreateContext();
executeDirect(ctx, new JDBCQuery(vertx, helper, null, ctx, sql, in), resultHandler);
return this;
}
private <T> void executeDirect(Context ctx, AbstractJDBCAction<T> action, Handler<AsyncResult<T>> handler) {
getConnection(ctx, ar1 -> {
Future<T> fut = Future.future();
fut.setHandler(ar2 -> ctx.runOnContext(v -> handler.handle(ar2)));
if (ar1.succeeded()) {
JDBCConnectionImpl conn = (JDBCConnectionImpl) ar1.result();
try {
T result = action.execute(conn.conn);
fut.complete(result);
} catch (Exception e) {
fut.fail(e);
} finally {
if (metrics != null) {
metrics.end(conn.metric, true);
}
try {
conn.conn.close();
} catch (Exception e) {
JDBCConnectionImpl.log.error("Failure in closing connection", ar1.cause());
}
}
} else {
fut.fail(ar1.cause());
}
});
}
private void getConnection(Context ctx, Handler<AsyncResult<SQLConnection>> handler) {
boolean enabled = metrics != null;
Object queueMetric = enabled ? metrics.submitted() : null;
PoolMetrics metrics = enabled ? this.metrics : null;
exec.execute(() -> {
Future<SQLConnection> res = Future.future();
res.setHandler(handler);
try {
/*
This can block until a connection is free.
We don't want to do that while running on a worker as we can enter a deadlock situation as the worker
might have obtained a connection, and won't release it until it is run again
There is a general principle here:
*User code* should be executed on a worker and can potentially block, it's up to the *user* to deal with
deadlocks that might occur there.
If the *service code* internally blocks waiting for a resource that might be obtained by *user code*, then
this can cause deadlock, so the service should ensure it never does this, by executing such code
(e.g. getConnection) on a different thread to the worker pool.
We don't want to use the vert.x internal pool for this as the threads might end up all blocked preventing
other important operations from occurring (e.g. async file access)
*/
Connection conn = ds.getConnection();
Object execMetric = null;
if (metrics != null) {
execMetric = metrics.begin(queueMetric);
}
// wrap it
res.complete(new JDBCConnectionImpl(ctx, helper, conn, metrics, execMetric));
} catch (SQLException e) {
if (metrics != null) {
metrics.rejected(queueMetric);
}
res.fail(e);
}
});
}
@Override
public SQLClient getConnection(Handler<AsyncResult<SQLConnection>> handler) {
Context ctx = vertx.getOrCreateContext();
getConnection(ctx, ar -> ctx.runOnContext(v -> handler.handle(ar)));
return this;
}
private DataSourceHolder lookupHolder(String datasourceName, JsonObject config) {
synchronized (vertx) {
LocalMap<String, DataSourceHolder> map = vertx.sharedData().getLocalMap(DS_LOCAL_MAP_NAME);
DataSourceHolder theHolder = map.get(datasourceName);
if (theHolder == null) {
theHolder = new DataSourceHolder((VertxInternal) vertx, config, map, datasourceName);
} else {
theHolder.incRefCount();
}
return theHolder;
}
}
private class DataSourceHolder implements Shareable {
private final VertxInternal vertx;
private final LocalMap<String, DataSourceHolder> map;
DataSourceProvider provider;
JsonObject config;
DataSource ds;
PoolMetrics metrics;
ExecutorService exec;
private int refCount = 1;
private final String name;
DataSourceHolder(VertxInternal vertx, DataSource ds) {
this.ds = ds;
this.metrics = vertx.metricsSPI() != null ? vertx.metricsSPI().createPoolMetrics("datasource", UUID.randomUUID().toString(), -1) : null;
this.vertx = vertx;
this.map = null;
this.name = null;
}
DataSourceHolder(VertxInternal vertx, JsonObject config, LocalMap<String, DataSourceHolder> map, String name) {
this.config = config;
this.map = map;
this.vertx = vertx;
this.name = name;
map.put(name, this);
}
synchronized DataSource ds() {
if (ds == null) {
String providerClass = config.getString("provider_class");
if (providerClass == null) {
providerClass = DEFAULT_PROVIDER_CLASS;
}
VertxMetrics vertxMetrics = vertx.metricsSPI();
if (Thread.currentThread().getContextClassLoader() != null) {
try {
// Try with the TCCL
Class clazz = Thread.currentThread().getContextClassLoader().loadClass(providerClass);
provider = (DataSourceProvider) clazz.newInstance();
ds = provider.getDataSource(config);
int poolSize = provider.maximumPoolSize(ds, config);
metrics = vertxMetrics != null ? vertxMetrics.createPoolMetrics( "datasource", name, poolSize) : null;
return ds;
} catch (ClassNotFoundException e) {
// Next try.
} catch (InstantiationException | SQLException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
try {
// Try with the classloader of the current class.
Class clazz = this.getClass().getClassLoader().loadClass(providerClass);
provider = (DataSourceProvider) clazz.newInstance();
ds = provider.getDataSource(config);
int poolSize = provider.maximumPoolSize(ds, config);
metrics = vertxMetrics != null ? vertxMetrics.createPoolMetrics( "datasource", name, poolSize) : null;
return ds;
} catch (ClassNotFoundException | InstantiationException | SQLException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return ds;
}
synchronized ExecutorService exec() {
if (exec == null) {
exec = new ThreadPoolExecutor(1, 1,
1000L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(),
(r -> new Thread(r, "vertx-jdbc-service-get-connection-thread")));
}
return exec;
}
void incRefCount() {
refCount++;
}
void close(Handler<AsyncResult<Void>> completionHandler) {
synchronized (vertx) {
if (--refCount == 0) {
if (metrics != null) {
metrics.close();
}
Future<Void> f1 = Future.future();
Future<Void> f2 = Future.future();
if (completionHandler != null) {
CompositeFuture.all(f1, f2).<Void>map(f -> null).setHandler(completionHandler);
}
if (provider != null) {
vertx.executeBlocking(future -> {
try {
provider.close(ds);
future.complete();
} catch (SQLException e) {
future.fail(e);
}
}, f2.completer());
} else {
f2.complete();
}
try {
if (exec != null) {
exec.shutdown();
}
if (map != null) {
map.remove(name);
if (map.isEmpty()) {
map.close();
}
}
f1.complete();
} catch (Throwable t) {
f1.fail(t);
}
} else {
if (completionHandler != null) {
completionHandler.handle(Future.succeededFuture());
}
}
}
}
}
}
| Remove usage of completer()
| src/main/java/io/vertx/ext/jdbc/impl/JDBCClientImpl.java | Remove usage of completer() | <ide><path>rc/main/java/io/vertx/ext/jdbc/impl/JDBCClientImpl.java
<ide> } catch (SQLException e) {
<ide> future.fail(e);
<ide> }
<del> }, f2.completer());
<add> }, f2);
<ide> } else {
<ide> f2.complete();
<ide> } |
|
JavaScript | isc | 06ba505f3fa86b96ec4057fde9ef911f07354383 | 0 | colinmeinke/universal-js | import React from 'react';
import Home from '../components/Home';
import Edit from '../components/Edit';
import { updateName } from '../actions/name';
const getRoutes = () => ([
[ '/', { name: updateName }, <Home /> ],
[ 'edit', { name: updateName }, <Edit /> ],
[ '*', <h1>Not found</h1> ],
]);
let routes = getRoutes();
if ( __DEVELOPMENT__ && module.hot ) {
module.hot.accept();
routes = getRoutes();
}
export default routes;
| src/common/config/routes.js | import React from 'react';
import Home from '../components/Home';
import Edit from '../components/Edit';
import { updateName } from '../actions/name';
const routes = [
[ '/', { name: updateName }, <Home /> ],
[ 'edit', { name: updateName }, <Edit /> ],
[ '*', <h1>Not found</h1> ],
];
export default routes;
| fix(hot): hot reload components
| src/common/config/routes.js | fix(hot): hot reload components | <ide><path>rc/common/config/routes.js
<ide>
<ide> import { updateName } from '../actions/name';
<ide>
<del>const routes = [
<add>const getRoutes = () => ([
<ide> [ '/', { name: updateName }, <Home /> ],
<ide> [ 'edit', { name: updateName }, <Edit /> ],
<ide> [ '*', <h1>Not found</h1> ],
<del>];
<add>]);
<add>
<add>let routes = getRoutes();
<add>
<add>if ( __DEVELOPMENT__ && module.hot ) {
<add> module.hot.accept();
<add> routes = getRoutes();
<add>}
<ide>
<ide> export default routes; |
|
Java | agpl-3.0 | 5575c03ff5dfe7bccdf34ad1f11511d24d9eadbb | 0 | ua-eas/kfs-devops-automation-fork,bhutchinson/kfs,kuali/kfs,ua-eas/kfs,smith750/kfs,smith750/kfs,quikkian-ua-devops/will-financials,smith750/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,kuali/kfs,kuali/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,kkronenb/kfs,ua-eas/kfs,kkronenb/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,bhutchinson/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,smith750/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,kuali/kfs,kkronenb/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,kuali/kfs | /*
* Copyright 2008 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.
*/
package org.kuali.kfs.module.cam.document;
import java.sql.Date;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import org.kuali.kfs.module.cam.businessobject.Asset;
import org.kuali.kfs.module.cam.document.service.AssetService;
import org.kuali.kfs.module.cam.document.service.EquipmentLoanOrReturnService;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.document.FinancialSystemTransactionalDocumentBase;
import org.kuali.rice.kim.bo.Person;
import org.kuali.rice.kns.bo.Country;
import org.kuali.rice.kns.bo.PostalCode;
import org.kuali.rice.kns.bo.State;
import org.kuali.rice.kns.document.MaintenanceLock;
import org.kuali.rice.kns.rule.event.KualiDocumentEvent;
import org.kuali.rice.kns.rule.event.SaveDocumentEvent;
import org.kuali.rice.kns.service.CountryService;
import org.kuali.rice.kns.service.DateTimeService;
import org.kuali.rice.kns.service.MaintenanceDocumentService;
import org.kuali.rice.kns.service.PostalCodeService;
import org.kuali.rice.kns.service.StateService;
import org.kuali.rice.kns.workflow.service.KualiWorkflowDocument;
public class EquipmentLoanOrReturnDocument extends FinancialSystemTransactionalDocumentBase {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(EquipmentLoanOrReturnDocument.class);
private String hiddenFieldForError;
private String documentNumber;
private Date loanDate;
private Date expectedReturnDate;
private Date loanReturnDate;
private String borrowerUniversalIdentifier;
private String borrowerAddress;
private String borrowerCityName;
private String borrowerStateCode;
private String borrowerZipCode;
private String borrowerCountryCode;
private String borrowerPhoneNumber;
private String borrowerStorageAddress;
private String borrowerStorageCityName;
private String borrowerStorageStateCode;
private String borrowerStorageZipCode;
private String borrowerStorageCountryCode;
private String borrowerStoragePhoneNumber;
private Long capitalAssetNumber;
private State borrowerState;
private State borrowerStorageState;
private Country borrowerCountry;
private Country borrowerStorageCountry;
private Person borrowerPerson;
private Asset asset;
private PostalCode borrowerPostalZipCode;
private PostalCode borrowerStoragePostalZipCode;
// sets document status (i.e. new loan, return, or renew)
private boolean newLoan;
private boolean returnLoan;
/**
* Default constructor.
*/
public EquipmentLoanOrReturnDocument() {
super();
}
/**
* Gets the asset attribute.
*
* @return Returns the asset
*/
public Asset getAsset() {
return asset;
}
/**
* Sets the asset attribute.
*
* @param asset The asset to set.
*/
public void setAsset(Asset asset) {
this.asset = asset;
}
/**
* Gets the borrowerCountry attribute.
*
* @return Returns the borrowerCountry
*/
public Country getBorrowerCountry() {
borrowerCountry = SpringContext.getBean(CountryService.class).getByPrimaryIdIfNecessary(this, borrowerCountryCode, borrowerCountry);
return borrowerCountry;
}
/**
* Sets the borrowerCountry attribute.
*
* @param borrowerCountry The borrowerCountry to set.
*/
public void setBorrowerCountry(Country borrowerCountry) {
this.borrowerCountry = borrowerCountry;
}
/**
* Gets the borrowerState attribute.
*
* @return Returns the borrowerState
*/
public State getBorrowerState() {
borrowerState = SpringContext.getBean(StateService.class).getByPrimaryIdIfNecessary(this, borrowerCountryCode, borrowerStateCode, borrowerState);
return borrowerState;
}
/**
* Sets the borrowerState attribute.
*
* @param borrowerState The borrowerState to set.
*/
public void setBorrowerState(State borrowerState) {
this.borrowerState = borrowerState;
}
/**
* Gets the borrowerStorageCountry attribute.
*
* @return Returns the borrowerStorageCountry
*/
public Country getBorrowerStorageCountry() {
borrowerStorageCountry = SpringContext.getBean(CountryService.class).getByPrimaryIdIfNecessary(this, borrowerStorageCountryCode, borrowerStorageCountry);
return borrowerStorageCountry;
}
/**
* Sets the borrowerStorageCountry attribute.
*
* @param borrowerStorageCountry The borrowerStorageCountry to set.
*/
public void setBorrowerStorageCountry(Country borrowerStorageCountry) {
this.borrowerStorageCountry = borrowerStorageCountry;
}
/**
* Gets the getBorrowerStorageState attribute.
*
* @return Returns the getBorrowerStorageState
*/
public State getBorrowerStorageState() {
borrowerStorageState = SpringContext.getBean(StateService.class).getByPrimaryIdIfNecessary(this, borrowerStorageCountryCode, borrowerStorageStateCode, borrowerStorageState);
return borrowerStorageState;
}
/**
* Sets the borrowerStorageState attribute.
*
* @param borrowerStorageState The borrowerStorageState to set.
*/
public void setBorrowerStorageState(State borrowerStorageState) {
this.borrowerStorageState = borrowerStorageState;
}
/**
* Gets the borrowerPerson attribute.
*
* @return Returns the borrowerPerson
*/
public Person getBorrowerPerson() {
borrowerPerson = SpringContext.getBean(org.kuali.rice.kim.service.PersonService.class).updatePersonIfNecessary(borrowerUniversalIdentifier, borrowerPerson);
return borrowerPerson;
}
/**
* Sets the borrowerPerson attribute.
*
* @param borrowerPerson The borrowerPerson to set.
*/
public void setBorrowerPerson(Person borrowerPerson) {
this.borrowerPerson = borrowerPerson;
}
/**
* Gets the borrowerAddress attribute.
*
* @return Returns the borrowerAddress
*/
public String getBorrowerAddress() {
return borrowerAddress;
}
/**
* Sets the borrowerAddress attribute.
*
* @param borrowerAddress The borrowerAddress to set.
*/
public void setBorrowerAddress(String borrowerAddress) {
this.borrowerAddress = borrowerAddress;
}
/**
* Gets the borrowerCityName attribute.
*
* @return Returns the borrowerCityName
*/
public String getBorrowerCityName() {
return borrowerCityName;
}
/**
* Sets the borrowerCityName attribute.
*
* @param borrowerCityName The borrowerCityName to set.
*/
public void setBorrowerCityName(String borrowerCityName) {
this.borrowerCityName = borrowerCityName;
}
/**
* Gets the borrowerCountryCode attribute.
*
* @return Returns the borrowerCountryCode
*/
public String getBorrowerCountryCode() {
return borrowerCountryCode;
}
/**
* Sets the borrowerCountryCode attribute.
*
* @param borrowerCountryCode The borrowerCountryCode to set.
*/
public void setBorrowerCountryCode(String borrowerCountryCode) {
this.borrowerCountryCode = borrowerCountryCode;
}
/**
* Gets the borrowerPhoneNumber attribute.
*
* @return Returns the borrowerPhoneNumber
*/
public String getBorrowerPhoneNumber() {
return borrowerPhoneNumber;
}
/**
* Sets the borrowerPhoneNumber attribute.
*
* @param borrowerPhoneNumber The borrowerPhoneNumber to set.
*/
public void setBorrowerPhoneNumber(String borrowerPhoneNumber) {
this.borrowerPhoneNumber = borrowerPhoneNumber;
}
/**
* Gets the borrowerStateCode attribute.
*
* @return Returns the borrowerStateCode
*/
public String getBorrowerStateCode() {
return borrowerStateCode;
}
/**
* Sets the borrowerStateCode attribute.
*
* @param borrowerStateCode The borrowerStateCode to set.
*/
public void setBorrowerStateCode(String borrowerStateCode) {
this.borrowerStateCode = borrowerStateCode;
}
/**
* Gets the borrowerStorageAddress attribute.
*
* @return Returns the borrowerStorageAddress
*/
public String getBorrowerStorageAddress() {
return borrowerStorageAddress;
}
/**
* Sets the borrowerStorageAddress attribute.
*
* @param borrowerStorageAddress The borrowerStorageAddress to set.
*/
public void setBorrowerStorageAddress(String borrowerStorageAddress) {
this.borrowerStorageAddress = borrowerStorageAddress;
}
/**
* Gets the borrowerStorageCityName attribute.
*
* @return Returns the borrowerStorageCityName
*/
public String getBorrowerStorageCityName() {
return borrowerStorageCityName;
}
/**
* Sets the borrowerStorageCityName attribute.
*
* @param borrowerStorageCityName The borrowerStorageCityName to set.
*/
public void setBorrowerStorageCityName(String borrowerStorageCityName) {
this.borrowerStorageCityName = borrowerStorageCityName;
}
/**
* Gets the borrowerStorageCountryCode attribute.
*
* @return Returns the borrowerStorageCountryCode
*/
public String getBorrowerStorageCountryCode() {
return borrowerStorageCountryCode;
}
/**
* Sets the borrowerStorageCountryCode attribute.
*
* @param borrowerStorageCountryCode The borrowerStorageCountryCode to set.
*/
public void setBorrowerStorageCountryCode(String borrowerStorageCountryCode) {
this.borrowerStorageCountryCode = borrowerStorageCountryCode;
}
/**
* Gets the borrowerStoragePhoneNumber attribute.
*
* @return Returns the borrowerStoragePhoneNumber
*/
public String getBorrowerStoragePhoneNumber() {
return borrowerStoragePhoneNumber;
}
/**
* Sets the borrowerStoragePhoneNumber attribute.
*
* @param borrowerStoragePhoneNumber The borrowerStoragePhoneNumber to set.
*/
public void setBorrowerStoragePhoneNumber(String borrowerStoragePhoneNumber) {
this.borrowerStoragePhoneNumber = borrowerStoragePhoneNumber;
}
/**
* Gets the borrowerStorageStateCode attribute.
*
* @return Returns the borrowerStorageStateCode
*/
public String getBorrowerStorageStateCode() {
return borrowerStorageStateCode;
}
/**
* Sets the borrowerStorageStateCode attribute.
*
* @param borrowerStorageStateCode The borrowerStorageStateCode to set.
*/
public void setBorrowerStorageStateCode(String borrowerStorageStateCode) {
this.borrowerStorageStateCode = borrowerStorageStateCode;
}
/**
* Gets the borrowerStorageZipCode attribute.
*
* @return Returns the borrowerStorageZipCode
*/
public String getBorrowerStorageZipCode() {
return borrowerStorageZipCode;
}
/**
* Sets the borrowerStorageZipCode attribute.
*
* @param borrowerStorageZipCode The borrowerStorageZipCode to set.
*/
public void setBorrowerStorageZipCode(String borrowerStorageZipCode) {
this.borrowerStorageZipCode = borrowerStorageZipCode;
}
/**
* Gets the borrowerPostalZipCode attribute.
*
* @return Returns the borrowerPostalZipCode
*/
public PostalCode getBorrowerPostalZipCode() {
borrowerPostalZipCode = SpringContext.getBean(PostalCodeService.class).getByPrimaryIdIfNecessary(this, borrowerCountryCode, borrowerZipCode, borrowerPostalZipCode);
return borrowerPostalZipCode;
}
/**
* Sets the borrowerPostalZipCode attribute.
*
* @param borrowerPostalZipCode The borrowerPostalZipCode to set.
*/
public void setBorrowerPostalZipCode(PostalCode borrowerPostalZipCode) {
this.borrowerPostalZipCode = borrowerPostalZipCode;
}
/**
* Sets the borrowerStoragePostalZipCode attribute.
*
* @param borrowerStoragePostalZipCode The borrowerStoragePostalZipCode to set.
*/
public PostalCode getBorrowerStoragePostalZipCode() {
borrowerStoragePostalZipCode = SpringContext.getBean(PostalCodeService.class).getByPrimaryIdIfNecessary(this, borrowerStorageCountryCode, borrowerStorageZipCode, borrowerStoragePostalZipCode);
return borrowerStoragePostalZipCode;
}
/**
* Gets the borrowerStoragePostalZipCode attribute.
*
* @return Returns the borrowerStoragePostalZipCode
*/
public void setborrowerStoragePostalZipCode(PostalCode borrowerStoragePostalZipCode) {
this.borrowerStoragePostalZipCode = borrowerStoragePostalZipCode;
}
/**
* Gets the borrowerUniversalIdentifier attribute.
*
* @return Returns the borrowerUniversalIdentifier
*/
public String getBorrowerUniversalIdentifier() {
return borrowerUniversalIdentifier;
}
/**
* Sets the borrowerUniversalIdentifier attribute.
*
* @param borrowerUniversalIdentifier The borrowerUniversalIdentifier to set.
*/
public void setBorrowerUniversalIdentifier(String borrowerUniversalIdentifier) {
this.borrowerUniversalIdentifier = borrowerUniversalIdentifier;
}
/**
* Gets the borrowerZipCode attribute.
*
* @return Returns the borrowerZipCode
*/
public String getBorrowerZipCode() {
return borrowerZipCode;
}
/**
* Sets the borrowerZipCode attribute.
*
* @param borrowerZipCode The borrowerZipCode to set.
*/
public void setBorrowerZipCode(String borrowerZipCode) {
this.borrowerZipCode = borrowerZipCode;
}
/**
* Gets the documentNumber attribute.
*
* @return Returns the documentNumber
*/
public String getDocumentNumber() {
return documentNumber;
}
/**
* Sets the documentNumber attribute.
*
* @param documentNumber The documentNumber to set.
*/
public void setDocumentNumber(String documentNumber) {
this.documentNumber = documentNumber;
}
/**
* Gets the expectedReturnDate attribute.
*
* @return Returns the expectedReturnDate
*/
public Date getExpectedReturnDate() {
return expectedReturnDate;
}
/**
* Sets the expectedReturnDate attribute.
*
* @param expectedReturnDate The expectedReturnDate to set.
*/
public void setExpectedReturnDate(Date expectedReturnDate) {
this.expectedReturnDate = expectedReturnDate;
}
/**
* Gets the loanDate attribute.
*
* @return Returns the loanDate
*/
public Date getLoanDate() {
if (loanDate != null) {
return loanDate;
}
else {
return SpringContext.getBean(DateTimeService.class).getCurrentSqlDate();
}
}
/**
* Sets the loanDate attribute.
*
* @param loanDate The loanDate to set.
*/
public void setLoanDate(Date loanDate) {
this.loanDate = loanDate;
}
/**
* Gets the loanReturnDate attribute.
*
* @return Returns the loanReturnDate
*/
public Date getLoanReturnDate() {
return loanReturnDate;
}
/**
* Sets the loanReturnDate attribute.
*
* @param loanReturnDate The loanReturnDate to set.
*/
public void setLoanReturnDate(Date loanReturnDate) {
this.loanReturnDate = loanReturnDate;
}
/**
* @see org.kuali.rice.kns.document.DocumentBase#postProcessSave(org.kuali.rice.kns.rule.event.KualiDocumentEvent)
*/
@Override
public void postProcessSave(KualiDocumentEvent event) {
super.postProcessSave(event);
if (!(event instanceof SaveDocumentEvent)) { // don't lock until they route
MaintenanceDocumentService maintenanceDocumentService = SpringContext.getBean(MaintenanceDocumentService.class);
AssetService assetService = SpringContext.getBean(AssetService.class);
maintenanceDocumentService.deleteLocks(this.getDocumentNumber());
List<MaintenanceLock> maintenanceLocks = new ArrayList<MaintenanceLock>();
maintenanceLocks.add(assetService.generateAssetLock(documentNumber, capitalAssetNumber));
maintenanceDocumentService.storeLocks(maintenanceLocks);
}
}
/**
* If the document final, unlock the document
*
* @see org.kuali.rice.kns.document.DocumentBase#handleRouteStatusChange()
*/
@Override
public void handleRouteStatusChange() {
super.handleRouteStatusChange();
KualiWorkflowDocument workflowDocument = getDocumentHeader().getWorkflowDocument();
if (workflowDocument.stateIsProcessed()) {
SpringContext.getBean(EquipmentLoanOrReturnService.class).processApprovedEquipmentLoanOrReturn(this);
SpringContext.getBean(MaintenanceDocumentService.class).deleteLocks(getDocumentNumber());
}
if (workflowDocument.stateIsCanceled() || workflowDocument.stateIsDisapproved()) {
SpringContext.getBean(MaintenanceDocumentService.class).deleteLocks(this.getDocumentNumber());
}
}
/**
* @see org.kuali.rice.kns.bo.BusinessObjectBase#toStringMapper()
*/
protected LinkedHashMap<String, String> toStringMapper() {
LinkedHashMap<String, String> m = new LinkedHashMap<String, String>();
m.put("documentNumber", this.documentNumber);
return m;
}
/**
* Gets the capitalAssetNumber attribute.
*
* @return Returns the capitalAssetNumber
*/
public Long getCapitalAssetNumber() {
return capitalAssetNumber;
}
/**
* Sets the capitalAssetNumber attribute.
*
* @param capitalAssetNumber The capitalAssetNumber to set.
*/
public void setCapitalAssetNumber(Long capitalAssetNumber) {
this.capitalAssetNumber = capitalAssetNumber;
}
public boolean isNewLoan() {
return newLoan;
}
public void setNewLoan(boolean newLoan) {
this.newLoan = newLoan;
}
public boolean isReturnLoan() {
return returnLoan;
}
public void setReturnLoan(boolean returnLoan) {
this.returnLoan = returnLoan;
}
public String getHiddenFieldForError() {
return hiddenFieldForError;
}
public void setHiddenFieldForError(String hiddenFieldForError) {
this.hiddenFieldForError = hiddenFieldForError;
}
} | work/src/org/kuali/kfs/module/cam/document/EquipmentLoanOrReturnDocument.java | /*
* Copyright 2008 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.
*/
package org.kuali.kfs.module.cam.document;
import java.sql.Date;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import org.kuali.kfs.module.cam.businessobject.Asset;
import org.kuali.kfs.module.cam.document.service.AssetService;
import org.kuali.kfs.module.cam.document.service.EquipmentLoanOrReturnService;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.document.FinancialSystemTransactionalDocumentBase;
import org.kuali.rice.kim.bo.Person;
import org.kuali.rice.kns.bo.Country;
import org.kuali.rice.kns.bo.PostalCode;
import org.kuali.rice.kns.bo.State;
import org.kuali.rice.kns.document.MaintenanceLock;
import org.kuali.rice.kns.rule.event.KualiDocumentEvent;
import org.kuali.rice.kns.rule.event.SaveDocumentEvent;
import org.kuali.rice.kns.service.CountryService;
import org.kuali.rice.kns.service.DateTimeService;
import org.kuali.rice.kns.service.MaintenanceDocumentService;
import org.kuali.rice.kns.service.PostalCodeService;
import org.kuali.rice.kns.service.StateService;
import org.kuali.rice.kns.workflow.service.KualiWorkflowDocument;
public class EquipmentLoanOrReturnDocument extends FinancialSystemTransactionalDocumentBase {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(EquipmentLoanOrReturnDocument.class);
private String documentNumber;
private Date loanDate;
private Date expectedReturnDate;
private Date loanReturnDate;
private String borrowerUniversalIdentifier;
private String borrowerAddress;
private String borrowerCityName;
private String borrowerStateCode;
private String borrowerZipCode;
private String borrowerCountryCode;
private String borrowerPhoneNumber;
private String borrowerStorageAddress;
private String borrowerStorageCityName;
private String borrowerStorageStateCode;
private String borrowerStorageZipCode;
private String borrowerStorageCountryCode;
private String borrowerStoragePhoneNumber;
private Long capitalAssetNumber;
private State borrowerState;
private State borrowerStorageState;
private Country borrowerCountry;
private Country borrowerStorageCountry;
private Person borrowerPerson;
private Asset asset;
private PostalCode borrowerPostalZipCode;
private PostalCode borrowerStoragePostalZipCode;
// sets document status (i.e. new loan, return, or renew)
private boolean newLoan;
private boolean returnLoan;
/**
* Default constructor.
*/
public EquipmentLoanOrReturnDocument() {
super();
}
/**
* Gets the asset attribute.
*
* @return Returns the asset
*/
public Asset getAsset() {
return asset;
}
/**
* Sets the asset attribute.
*
* @param asset The asset to set.
*/
public void setAsset(Asset asset) {
this.asset = asset;
}
/**
* Gets the borrowerCountry attribute.
*
* @return Returns the borrowerCountry
*/
public Country getBorrowerCountry() {
borrowerCountry = SpringContext.getBean(CountryService.class).getByPrimaryIdIfNecessary(this, borrowerCountryCode, borrowerCountry);
return borrowerCountry;
}
/**
* Sets the borrowerCountry attribute.
*
* @param borrowerCountry The borrowerCountry to set.
*/
public void setBorrowerCountry(Country borrowerCountry) {
this.borrowerCountry = borrowerCountry;
}
/**
* Gets the borrowerState attribute.
*
* @return Returns the borrowerState
*/
public State getBorrowerState() {
borrowerState = SpringContext.getBean(StateService.class).getByPrimaryIdIfNecessary(this, borrowerCountryCode, borrowerStateCode, borrowerState);
return borrowerState;
}
/**
* Sets the borrowerState attribute.
*
* @param borrowerState The borrowerState to set.
*/
public void setBorrowerState(State borrowerState) {
this.borrowerState = borrowerState;
}
/**
* Gets the borrowerStorageCountry attribute.
*
* @return Returns the borrowerStorageCountry
*/
public Country getBorrowerStorageCountry() {
borrowerStorageCountry = SpringContext.getBean(CountryService.class).getByPrimaryIdIfNecessary(this, borrowerStorageCountryCode, borrowerStorageCountry);
return borrowerStorageCountry;
}
/**
* Sets the borrowerStorageCountry attribute.
*
* @param borrowerStorageCountry The borrowerStorageCountry to set.
*/
public void setBorrowerStorageCountry(Country borrowerStorageCountry) {
this.borrowerStorageCountry = borrowerStorageCountry;
}
/**
* Gets the getBorrowerStorageState attribute.
*
* @return Returns the getBorrowerStorageState
*/
public State getBorrowerStorageState() {
borrowerStorageState = SpringContext.getBean(StateService.class).getByPrimaryIdIfNecessary(this, borrowerStorageCountryCode, borrowerStorageStateCode, borrowerStorageState);
return borrowerStorageState;
}
/**
* Sets the borrowerStorageState attribute.
*
* @param borrowerStorageState The borrowerStorageState to set.
*/
public void setBorrowerStorageState(State borrowerStorageState) {
this.borrowerStorageState = borrowerStorageState;
}
/**
* Gets the borrowerPerson attribute.
*
* @return Returns the borrowerPerson
*/
public Person getBorrowerPerson() {
borrowerPerson = SpringContext.getBean(org.kuali.rice.kim.service.PersonService.class).updatePersonIfNecessary(borrowerUniversalIdentifier, borrowerPerson);
return borrowerPerson;
}
/**
* Sets the borrowerPerson attribute.
*
* @param borrowerPerson The borrowerPerson to set.
*/
public void setBorrowerPerson(Person borrowerPerson) {
this.borrowerPerson = borrowerPerson;
}
/**
* Gets the borrowerAddress attribute.
*
* @return Returns the borrowerAddress
*/
public String getBorrowerAddress() {
return borrowerAddress;
}
/**
* Sets the borrowerAddress attribute.
*
* @param borrowerAddress The borrowerAddress to set.
*/
public void setBorrowerAddress(String borrowerAddress) {
this.borrowerAddress = borrowerAddress;
}
/**
* Gets the borrowerCityName attribute.
*
* @return Returns the borrowerCityName
*/
public String getBorrowerCityName() {
return borrowerCityName;
}
/**
* Sets the borrowerCityName attribute.
*
* @param borrowerCityName The borrowerCityName to set.
*/
public void setBorrowerCityName(String borrowerCityName) {
this.borrowerCityName = borrowerCityName;
}
/**
* Gets the borrowerCountryCode attribute.
*
* @return Returns the borrowerCountryCode
*/
public String getBorrowerCountryCode() {
return borrowerCountryCode;
}
/**
* Sets the borrowerCountryCode attribute.
*
* @param borrowerCountryCode The borrowerCountryCode to set.
*/
public void setBorrowerCountryCode(String borrowerCountryCode) {
this.borrowerCountryCode = borrowerCountryCode;
}
/**
* Gets the borrowerPhoneNumber attribute.
*
* @return Returns the borrowerPhoneNumber
*/
public String getBorrowerPhoneNumber() {
return borrowerPhoneNumber;
}
/**
* Sets the borrowerPhoneNumber attribute.
*
* @param borrowerPhoneNumber The borrowerPhoneNumber to set.
*/
public void setBorrowerPhoneNumber(String borrowerPhoneNumber) {
this.borrowerPhoneNumber = borrowerPhoneNumber;
}
/**
* Gets the borrowerStateCode attribute.
*
* @return Returns the borrowerStateCode
*/
public String getBorrowerStateCode() {
return borrowerStateCode;
}
/**
* Sets the borrowerStateCode attribute.
*
* @param borrowerStateCode The borrowerStateCode to set.
*/
public void setBorrowerStateCode(String borrowerStateCode) {
this.borrowerStateCode = borrowerStateCode;
}
/**
* Gets the borrowerStorageAddress attribute.
*
* @return Returns the borrowerStorageAddress
*/
public String getBorrowerStorageAddress() {
return borrowerStorageAddress;
}
/**
* Sets the borrowerStorageAddress attribute.
*
* @param borrowerStorageAddress The borrowerStorageAddress to set.
*/
public void setBorrowerStorageAddress(String borrowerStorageAddress) {
this.borrowerStorageAddress = borrowerStorageAddress;
}
/**
* Gets the borrowerStorageCityName attribute.
*
* @return Returns the borrowerStorageCityName
*/
public String getBorrowerStorageCityName() {
return borrowerStorageCityName;
}
/**
* Sets the borrowerStorageCityName attribute.
*
* @param borrowerStorageCityName The borrowerStorageCityName to set.
*/
public void setBorrowerStorageCityName(String borrowerStorageCityName) {
this.borrowerStorageCityName = borrowerStorageCityName;
}
/**
* Gets the borrowerStorageCountryCode attribute.
*
* @return Returns the borrowerStorageCountryCode
*/
public String getBorrowerStorageCountryCode() {
return borrowerStorageCountryCode;
}
/**
* Sets the borrowerStorageCountryCode attribute.
*
* @param borrowerStorageCountryCode The borrowerStorageCountryCode to set.
*/
public void setBorrowerStorageCountryCode(String borrowerStorageCountryCode) {
this.borrowerStorageCountryCode = borrowerStorageCountryCode;
}
/**
* Gets the borrowerStoragePhoneNumber attribute.
*
* @return Returns the borrowerStoragePhoneNumber
*/
public String getBorrowerStoragePhoneNumber() {
return borrowerStoragePhoneNumber;
}
/**
* Sets the borrowerStoragePhoneNumber attribute.
*
* @param borrowerStoragePhoneNumber The borrowerStoragePhoneNumber to set.
*/
public void setBorrowerStoragePhoneNumber(String borrowerStoragePhoneNumber) {
this.borrowerStoragePhoneNumber = borrowerStoragePhoneNumber;
}
/**
* Gets the borrowerStorageStateCode attribute.
*
* @return Returns the borrowerStorageStateCode
*/
public String getBorrowerStorageStateCode() {
return borrowerStorageStateCode;
}
/**
* Sets the borrowerStorageStateCode attribute.
*
* @param borrowerStorageStateCode The borrowerStorageStateCode to set.
*/
public void setBorrowerStorageStateCode(String borrowerStorageStateCode) {
this.borrowerStorageStateCode = borrowerStorageStateCode;
}
/**
* Gets the borrowerStorageZipCode attribute.
*
* @return Returns the borrowerStorageZipCode
*/
public String getBorrowerStorageZipCode() {
return borrowerStorageZipCode;
}
/**
* Sets the borrowerStorageZipCode attribute.
*
* @param borrowerStorageZipCode The borrowerStorageZipCode to set.
*/
public void setBorrowerStorageZipCode(String borrowerStorageZipCode) {
this.borrowerStorageZipCode = borrowerStorageZipCode;
}
/**
* Gets the borrowerPostalZipCode attribute.
*
* @return Returns the borrowerPostalZipCode
*/
public PostalCode getBorrowerPostalZipCode() {
borrowerPostalZipCode = SpringContext.getBean(PostalCodeService.class).getByPrimaryIdIfNecessary(this, borrowerCountryCode, borrowerZipCode, borrowerPostalZipCode);
return borrowerPostalZipCode;
}
/**
* Sets the borrowerPostalZipCode attribute.
*
* @param borrowerPostalZipCode The borrowerPostalZipCode to set.
*/
public void setBorrowerPostalZipCode(PostalCode borrowerPostalZipCode) {
this.borrowerPostalZipCode = borrowerPostalZipCode;
}
/**
* Sets the borrowerStoragePostalZipCode attribute.
*
* @param borrowerStoragePostalZipCode The borrowerStoragePostalZipCode to set.
*/
public PostalCode getBorrowerStoragePostalZipCode() {
borrowerStoragePostalZipCode = SpringContext.getBean(PostalCodeService.class).getByPrimaryIdIfNecessary(this, borrowerStorageCountryCode, borrowerStorageZipCode, borrowerStoragePostalZipCode);
return borrowerStoragePostalZipCode;
}
/**
* Gets the borrowerStoragePostalZipCode attribute.
*
* @return Returns the borrowerStoragePostalZipCode
*/
public void setborrowerStoragePostalZipCode(PostalCode borrowerStoragePostalZipCode) {
this.borrowerStoragePostalZipCode = borrowerStoragePostalZipCode;
}
/**
* Gets the borrowerUniversalIdentifier attribute.
*
* @return Returns the borrowerUniversalIdentifier
*/
public String getBorrowerUniversalIdentifier() {
return borrowerUniversalIdentifier;
}
/**
* Sets the borrowerUniversalIdentifier attribute.
*
* @param borrowerUniversalIdentifier The borrowerUniversalIdentifier to set.
*/
public void setBorrowerUniversalIdentifier(String borrowerUniversalIdentifier) {
this.borrowerUniversalIdentifier = borrowerUniversalIdentifier;
}
/**
* Gets the borrowerZipCode attribute.
*
* @return Returns the borrowerZipCode
*/
public String getBorrowerZipCode() {
return borrowerZipCode;
}
/**
* Sets the borrowerZipCode attribute.
*
* @param borrowerZipCode The borrowerZipCode to set.
*/
public void setBorrowerZipCode(String borrowerZipCode) {
this.borrowerZipCode = borrowerZipCode;
}
/**
* Gets the documentNumber attribute.
*
* @return Returns the documentNumber
*/
public String getDocumentNumber() {
return documentNumber;
}
/**
* Sets the documentNumber attribute.
*
* @param documentNumber The documentNumber to set.
*/
public void setDocumentNumber(String documentNumber) {
this.documentNumber = documentNumber;
}
/**
* Gets the expectedReturnDate attribute.
*
* @return Returns the expectedReturnDate
*/
public Date getExpectedReturnDate() {
return expectedReturnDate;
}
/**
* Sets the expectedReturnDate attribute.
*
* @param expectedReturnDate The expectedReturnDate to set.
*/
public void setExpectedReturnDate(Date expectedReturnDate) {
this.expectedReturnDate = expectedReturnDate;
}
/**
* Gets the loanDate attribute.
*
* @return Returns the loanDate
*/
public Date getLoanDate() {
if (loanDate != null) {
return loanDate;
}
else {
return SpringContext.getBean(DateTimeService.class).getCurrentSqlDate();
}
}
/**
* Sets the loanDate attribute.
*
* @param loanDate The loanDate to set.
*/
public void setLoanDate(Date loanDate) {
this.loanDate = loanDate;
}
/**
* Gets the loanReturnDate attribute.
*
* @return Returns the loanReturnDate
*/
public Date getLoanReturnDate() {
return loanReturnDate;
}
/**
* Sets the loanReturnDate attribute.
*
* @param loanReturnDate The loanReturnDate to set.
*/
public void setLoanReturnDate(Date loanReturnDate) {
this.loanReturnDate = loanReturnDate;
}
/**
* @see org.kuali.rice.kns.document.DocumentBase#postProcessSave(org.kuali.rice.kns.rule.event.KualiDocumentEvent)
*/
@Override
public void postProcessSave(KualiDocumentEvent event) {
super.postProcessSave(event);
if (!(event instanceof SaveDocumentEvent)) { // don't lock until they route
MaintenanceDocumentService maintenanceDocumentService = SpringContext.getBean(MaintenanceDocumentService.class);
AssetService assetService = SpringContext.getBean(AssetService.class);
maintenanceDocumentService.deleteLocks(this.getDocumentNumber());
List<MaintenanceLock> maintenanceLocks = new ArrayList<MaintenanceLock>();
maintenanceLocks.add(assetService.generateAssetLock(documentNumber, capitalAssetNumber));
maintenanceDocumentService.storeLocks(maintenanceLocks);
}
}
/**
* If the document final, unlock the document
*
* @see org.kuali.rice.kns.document.DocumentBase#handleRouteStatusChange()
*/
@Override
public void handleRouteStatusChange() {
super.handleRouteStatusChange();
KualiWorkflowDocument workflowDocument = getDocumentHeader().getWorkflowDocument();
if (workflowDocument.stateIsProcessed()) {
SpringContext.getBean(EquipmentLoanOrReturnService.class).processApprovedEquipmentLoanOrReturn(this);
SpringContext.getBean(MaintenanceDocumentService.class).deleteLocks(getDocumentNumber());
}
if (workflowDocument.stateIsCanceled() || workflowDocument.stateIsDisapproved()) {
SpringContext.getBean(MaintenanceDocumentService.class).deleteLocks(this.getDocumentNumber());
}
}
/**
* @see org.kuali.rice.kns.bo.BusinessObjectBase#toStringMapper()
*/
protected LinkedHashMap<String, String> toStringMapper() {
LinkedHashMap<String, String> m = new LinkedHashMap<String, String>();
m.put("documentNumber", this.documentNumber);
return m;
}
/**
* Gets the capitalAssetNumber attribute.
*
* @return Returns the capitalAssetNumber
*/
public Long getCapitalAssetNumber() {
return capitalAssetNumber;
}
/**
* Sets the capitalAssetNumber attribute.
*
* @param capitalAssetNumber The capitalAssetNumber to set.
*/
public void setCapitalAssetNumber(Long capitalAssetNumber) {
this.capitalAssetNumber = capitalAssetNumber;
}
public boolean isNewLoan() {
return newLoan;
}
public void setNewLoan(boolean newLoan) {
this.newLoan = newLoan;
}
public boolean isReturnLoan() {
return returnLoan;
}
public void setReturnLoan(boolean returnLoan) {
this.returnLoan = returnLoan;
}
} | KULCAP-1051
| work/src/org/kuali/kfs/module/cam/document/EquipmentLoanOrReturnDocument.java | KULCAP-1051 | <ide><path>ork/src/org/kuali/kfs/module/cam/document/EquipmentLoanOrReturnDocument.java
<ide> public class EquipmentLoanOrReturnDocument extends FinancialSystemTransactionalDocumentBase {
<ide> private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(EquipmentLoanOrReturnDocument.class);
<ide>
<add> private String hiddenFieldForError;
<ide> private String documentNumber;
<ide> private Date loanDate;
<ide> private Date expectedReturnDate;
<ide> public void setReturnLoan(boolean returnLoan) {
<ide> this.returnLoan = returnLoan;
<ide> }
<add>
<add> public String getHiddenFieldForError() {
<add> return hiddenFieldForError;
<add> }
<add>
<add> public void setHiddenFieldForError(String hiddenFieldForError) {
<add> this.hiddenFieldForError = hiddenFieldForError;
<add> }
<add>
<ide> } |
|
Java | mit | 2557f6bd9d6a9d248060f842d99ddf13d5a2ccf8 | 0 | EinsamHauer/disthene-reader,EinsamHauer/disthene-reader,EinsamHauer/disthene-reader | package net.iponweb.disthene.reader;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import org.apache.log4j.Logger;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
/**
* @author Andrei Ivanov
*/
public class DistheneServerHandler extends ChannelInboundHandlerAdapter {
final static Logger logger = Logger.getLogger(DistheneServerHandler.class);
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
HttpRequest req = (HttpRequest) msg;
if (DefaultHttpHeaders.is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
}
boolean keepAlive = DefaultHttpHeaders.isKeepAlive(req);
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(getResponse(req).getBytes()));
response.headers().set(CONTENT_TYPE, "application/json");
response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
if (!keepAlive) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else {
response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
ctx.write(response);
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
private String getResponse(HttpRequest request) {
QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
String path = decoder.path();
switch (path) {
case "/metrics":
try {
return MetricsResponseBuilder.buildResponse(
decoder.parameters().get("tenant").get(0),
decoder.parameters().get("path").get(0),
Long.valueOf(decoder.parameters().get("from").get(0)),
Long.valueOf(decoder.parameters().get("to").get(0)));
} catch (Exception e) {
logger.error(e);
return "Error";
}
case "/paths":
try {
return PathsResponseBuilder.buildResponse(decoder.parameters().get("tenant").get(0),
decoder.parameters().get("query").get(0)
);
} catch (Exception e) {
logger.error("Encountered an error fetching paths", e);
return "Error";
}
default:
return "Error";
}
}
}
| src/main/java/net/iponweb/disthene/reader/DistheneServerHandler.java | package net.iponweb.disthene.reader;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import org.apache.log4j.Logger;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
/**
* @author Andrei Ivanov
*/
public class DistheneServerHandler extends ChannelInboundHandlerAdapter {
final static Logger logger = Logger.getLogger(DistheneServerHandler.class);
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
HttpRequest req = (HttpRequest) msg;
if (DefaultHttpHeaders.is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
}
boolean keepAlive = DefaultHttpHeaders.isKeepAlive(req);
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(getResponse(req).getBytes()));
response.headers().set(CONTENT_TYPE, "application/json");
response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
if (!keepAlive) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else {
response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
ctx.write(response);
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
private String getResponse(HttpRequest request) {
QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
String path = decoder.path();
switch (path) {
case "/metrics":
try {
return MetricsResponseBuilder.buildResponse(
decoder.parameters().get("tenant").get(0),
decoder.parameters().get("path").get(0),
Long.valueOf(decoder.parameters().get("from").get(0)),
Long.valueOf(decoder.parameters().get("to").get(0)));
} catch (Exception e) {
logger.error(e);
return "Error";
}
case "/paths":
try {
return PathsResponseBuilder.buildResponse(decoder.parameters().get("tenant").get(0),
decoder.parameters().get("query").get(0)
);
} catch (Exception e) {
logger.error(e);
return "Error";
}
default:
return "Error";
}
}
}
| Added paths handler
| src/main/java/net/iponweb/disthene/reader/DistheneServerHandler.java | Added paths handler | <ide><path>rc/main/java/net/iponweb/disthene/reader/DistheneServerHandler.java
<ide> decoder.parameters().get("query").get(0)
<ide> );
<ide> } catch (Exception e) {
<del> logger.error(e);
<add> logger.error("Encountered an error fetching paths", e);
<ide> return "Error";
<ide> }
<ide> default: |
|
Java | mit | b2c50f9ef42243d057762b05c4fc97d03e78e785 | 0 | jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico | package com.jbalint.bs.bookstore;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import com.complexible.common.openrdf.util.ModelBuilder;
import com.complexible.common.openrdf.util.ResourceBuilder;
import com.complexible.common.rdf.model.StardogValueFactory;
import com.complexible.stardog.api.Connection;
import com.complexible.stardog.api.ConnectionConfiguration;
import com.jbalint.bs.ontology.BsLib;
import com.jbalint.bs.ontology.Nepomuk;
import org.apache.commons.codec.digest.DigestUtils;
import org.openrdf.model.IRI;
import org.openrdf.model.Model;
/**
* Generate metadata structures for Bookstore db.
*/
public class FileMetadataGenerator {
static final StardogValueFactory VF = StardogValueFactory.instance();
Connection conn;
Path root;
IRI context;
public FileMetadataGenerator(Connection conn, Path root, IRI context) {
this.conn = conn;
this.root = root;
this.context = context;
}
/**
* Does an entry for the corresponding path exist in the DB?
*/
boolean existsInDb(Path p) {
return conn.get().context(context).predicate(Nepomuk.NIE.url).object(getIRI(p)).ask();
}
/**
* Turn a Path into a model if it doesn't already exist in the DB and it's a regular file
*/
Model file(Path p) {
try {
Files.getLastModifiedTime(p);
ResourceBuilder mainFile = new ModelBuilder()
.instance(Nepomuk.NFO.RemoteDataObject)
.addProperty(Nepomuk.NIE.url, getIRI(p))
.addProperty(BsLib.relativePath, root.relativize(p).toString())
.addProperty(Nepomuk.NIE.byteSize, Files.size(p))
.addProperty(Nepomuk.NIE.lastRefreshed, new Date())
.addProperty(Nepomuk.NFO.fileCreated, new Date(Files.getLastModifiedTime(p).toMillis()))
.addProperty(Nepomuk.NFO.fileName, p.getFileName().toString())
.addProperty(Nepomuk.NFO.hasHash, new ModelBuilder().instance(Nepomuk.NFO.FileHash)
.addProperty(Nepomuk.NFO.hashAlgorithm, "MD5")
.addProperty(Nepomuk.NFO.hashValue,
DigestUtils.md5Hex(Files.newInputStream(p))));
ResourceBuilder infoElement = new ModelBuilder()
.instance(Nepomuk.NIE.InformationElement)
.addProperty(StardogValueFactory.RDF.TYPE, BsLib.Book)
.addProperty(Nepomuk.NIE.isStoredAs, mainFile);
return infoElement.model();
}
catch (IOException theE) {
throw new RuntimeException(theE);
}
}
void addToDb(Model m) {
conn.begin();
conn.add().graph(m, context);
conn.commit();
}
private IRI getIRI(final Path p) {
try {
// URL escaping, per http://stackoverflow.com/a/25735202/1090617
// was using URLEncoder.encode() but that's form HTTP query parameters (i.e. uses "+" for space instead of "%20")
String urlStr = "https://localhost/bookstore/" + root.relativize(p).toString();
URL url= new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
return VF.createIRI(uri.toASCIIString());
}
catch (Exception theE) {
throw new RuntimeException(theE);
}
}
public static void main(final String args[]) throws Exception {
if (args.length != 3) {
System.err.println("Usage: FileMetadataGenerator <db-url> <fileroot> <graph-iri>");
System.exit(1);
}
FileMetadataGenerator fmg = new FileMetadataGenerator(ConnectionConfiguration.at(args[0]),
Paths.get(args[1]),
VF.createIRI(args[2]));
long booksAdded;
boolean TESTING = false;
if (TESTING) {
booksAdded = Files.walk(fmg.root)
.filter(Files::isRegularFile)
.limit(1)
.map(fmg::file)
.count();
} else {
booksAdded = Files.walk(fmg.root)
.filter(Files::isRegularFile)
.filter(f -> !fmg.existsInDb(f))
.map(fmg::file)
.peek(fmg::addToDb)
.count();
}
System.err.println("Books added: " + booksAdded);
//StatementSources.write(MemoryStatementSource.of(fmg.statements), RDFFormat.TURTLE, new FileOutputStream("/tmp/books.ttl"));
}
}
| bookstore/src/main/java/com/jbalint/bs/bookstore/FileMetadataGenerator.java | package com.jbalint.bs.bookstore;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import com.complexible.common.openrdf.util.ModelBuilder;
import com.complexible.common.openrdf.util.ResourceBuilder;
import com.complexible.common.rdf.model.StardogValueFactory;
import com.complexible.stardog.api.Connection;
import com.complexible.stardog.api.ConnectionConfiguration;
import com.jbalint.bs.ontology.BsLib;
import com.jbalint.bs.ontology.Nepomuk;
import org.apache.commons.codec.digest.DigestUtils;
import org.openrdf.model.IRI;
import org.openrdf.model.Model;
/**
* Generate metadata structures for Bookstore db.
*/
public class FileMetadataGenerator {
static final StardogValueFactory VF = StardogValueFactory.instance();
Connection conn;
Path root;
IRI context;
public FileMetadataGenerator(Connection conn, Path root, IRI context) {
this.conn = conn;
this.root = root;
this.context = context;
}
/**
* Does an entry for the corresponding path exist in the DB?
*/
boolean existsInDb(Path p) {
return conn.get().context(context).predicate(Nepomuk.NIE.url).object(getIRI(p)).statements().findFirst().isPresent();
}
/**
* Turn a Path into a model if it doesn't already exist in the DB and it's a regular file
*/
Model file(Path p) {
try {
Files.getLastModifiedTime(p);
ResourceBuilder mainFile = new ModelBuilder()
.instance(Nepomuk.NFO.RemoteDataObject)
.addProperty(Nepomuk.NIE.url, getIRI(p))
.addProperty(BsLib.relativePath, root.relativize(p).toString())
.addProperty(Nepomuk.NIE.byteSize, Files.size(p))
.addProperty(Nepomuk.NIE.lastRefreshed, new Date())
.addProperty(Nepomuk.NFO.fileCreated, new Date(Files.getLastModifiedTime(p).toMillis()))
.addProperty(Nepomuk.NFO.fileName, p.getFileName().toString())
.addProperty(Nepomuk.NFO.hasHash, new ModelBuilder().instance(Nepomuk.NFO.FileHash)
.addProperty(Nepomuk.NFO.hashAlgorithm, "MD5")
.addProperty(Nepomuk.NFO.hashValue,
DigestUtils.md5Hex(Files.newInputStream(p))));
ResourceBuilder infoElement = new ModelBuilder()
.instance(Nepomuk.NIE.InformationElement)
.addProperty(StardogValueFactory.RDF.TYPE, BsLib.Book)
.addProperty(Nepomuk.NIE.isStoredAs, mainFile);
return infoElement.model();
}
catch (IOException theE) {
throw new RuntimeException(theE);
}
}
void addToDb(Model m) {
conn.begin();
conn.add().graph(m, context);
conn.commit();
}
private IRI getIRI(final Path p) {
try {
// URL escaping, per http://stackoverflow.com/a/25735202/1090617
// was using URLEncoder.encode() but that's form HTTP query parameters (i.e. uses "+" for space instead of "%20")
String urlStr = "https://localhost/bookstore/" + root.relativize(p).toString();
URL url= new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
return VF.createIRI(uri.toASCIIString());
}
catch (Exception theE) {
throw new RuntimeException(theE);
}
}
public static void main(final String args[]) throws Exception {
if (args.length != 3) {
System.err.println("Usage: FileMetadataGenerator <db-url> <fileroot> <graph-iri>");
System.exit(1);
}
FileMetadataGenerator fmg = new FileMetadataGenerator(ConnectionConfiguration.at(args[0]),
Paths.get(args[1]),
VF.createIRI(args[2]));
long booksAdded;
boolean TESTING = false;
if (TESTING) {
booksAdded = Files.walk(fmg.root)
.filter(Files::isRegularFile)
.limit(1)
.map(fmg::file)
.count();
} else {
booksAdded = Files.walk(fmg.root)
.filter(Files::isRegularFile)
.filter(f -> !fmg.existsInDb(f))
.map(fmg::file)
.peek(fmg::addToDb)
.count();
}
System.err.println("Books added: " + booksAdded);
//StatementSources.write(MemoryStatementSource.of(fmg.statements), RDFFormat.TURTLE, new FileOutputStream("/tmp/books.ttl"));
}
}
| Use ask() instead of a truncated statement stream
(fixes [BS-50])
| bookstore/src/main/java/com/jbalint/bs/bookstore/FileMetadataGenerator.java | Use ask() instead of a truncated statement stream (fixes [BS-50]) | <ide><path>ookstore/src/main/java/com/jbalint/bs/bookstore/FileMetadataGenerator.java
<ide> * Does an entry for the corresponding path exist in the DB?
<ide> */
<ide> boolean existsInDb(Path p) {
<del> return conn.get().context(context).predicate(Nepomuk.NIE.url).object(getIRI(p)).statements().findFirst().isPresent();
<add> return conn.get().context(context).predicate(Nepomuk.NIE.url).object(getIRI(p)).ask();
<ide> }
<ide>
<ide> /** |
|
JavaScript | mit | 0ef10e11dad30feb1e42667237b0390561937f0f | 0 | AwesomeJerry/react-native-qrcode-svg | /**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React from "react";
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
} from "react-native";
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from "react-native/Libraries/NewAppScreen";
import QRCode from "react-native-qrcode-svg";
const App: () => React$Node = () => {
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}
>
<Header />
<QRCode value="text" />
{global.HermesInternal == null ? null : (
<View style={styles.engine}>
<Text style={styles.footer}>Engine: Hermes</Text>
</View>
)}
<View style={styles.body}>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Step One</Text>
<Text style={styles.sectionDescription}>
Edit <Text style={styles.highlight}>App.js</Text> to change this
screen and then come back to see your edits.
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>See Your Changes</Text>
<Text style={styles.sectionDescription}>
<ReloadInstructions />
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Debug</Text>
<Text style={styles.sectionDescription}>
<DebugInstructions />
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Learn More</Text>
<Text style={styles.sectionDescription}>
Read the docs to discover what to do next:
</Text>
</View>
<LearnMoreLinks />
</View>
</ScrollView>
</SafeAreaView>
</>
);
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
engine: {
position: "absolute",
right: 0,
},
body: {
backgroundColor: Colors.white,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: "600",
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: "400",
color: Colors.dark,
},
highlight: {
fontWeight: "700",
},
footer: {
color: Colors.dark,
fontSize: 12,
fontWeight: "600",
padding: 4,
paddingRight: 12,
textAlign: "right",
},
});
export default App;
| example/App.js | /**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
} from 'react-native';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
const App: () => React$Node = () => {
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
<Header />
{global.HermesInternal == null ? null : (
<View style={styles.engine}>
<Text style={styles.footer}>Engine: Hermes</Text>
</View>
)}
<View style={styles.body}>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Step One</Text>
<Text style={styles.sectionDescription}>
Edit <Text style={styles.highlight}>App.js</Text> to change this
screen and then come back to see your edits.
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>See Your Changes</Text>
<Text style={styles.sectionDescription}>
<ReloadInstructions />
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Debug</Text>
<Text style={styles.sectionDescription}>
<DebugInstructions />
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Learn More</Text>
<Text style={styles.sectionDescription}>
Read the docs to discover what to do next:
</Text>
</View>
<LearnMoreLinks />
</View>
</ScrollView>
</SafeAreaView>
</>
);
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
engine: {
position: 'absolute',
right: 0,
},
body: {
backgroundColor: Colors.white,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
color: Colors.dark,
},
highlight: {
fontWeight: '700',
},
footer: {
color: Colors.dark,
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
});
export default App;
| Update `Example`
| example/App.js | Update `Example` | <ide><path>xample/App.js
<ide> * @flow strict-local
<ide> */
<ide>
<del>import React from 'react';
<add>import React from "react";
<ide> import {
<ide> SafeAreaView,
<ide> StyleSheet,
<ide> View,
<ide> Text,
<ide> StatusBar,
<del>} from 'react-native';
<add>} from "react-native";
<ide>
<ide> import {
<ide> Header,
<ide> Colors,
<ide> DebugInstructions,
<ide> ReloadInstructions,
<del>} from 'react-native/Libraries/NewAppScreen';
<add>} from "react-native/Libraries/NewAppScreen";
<add>
<add>import QRCode from "react-native-qrcode-svg";
<ide>
<ide> const App: () => React$Node = () => {
<ide> return (
<ide> <SafeAreaView>
<ide> <ScrollView
<ide> contentInsetAdjustmentBehavior="automatic"
<del> style={styles.scrollView}>
<add> style={styles.scrollView}
<add> >
<ide> <Header />
<add> <QRCode value="text" />
<ide> {global.HermesInternal == null ? null : (
<ide> <View style={styles.engine}>
<ide> <Text style={styles.footer}>Engine: Hermes</Text>
<ide> backgroundColor: Colors.lighter,
<ide> },
<ide> engine: {
<del> position: 'absolute',
<add> position: "absolute",
<ide> right: 0,
<ide> },
<ide> body: {
<ide> },
<ide> sectionTitle: {
<ide> fontSize: 24,
<del> fontWeight: '600',
<add> fontWeight: "600",
<ide> color: Colors.black,
<ide> },
<ide> sectionDescription: {
<ide> marginTop: 8,
<ide> fontSize: 18,
<del> fontWeight: '400',
<add> fontWeight: "400",
<ide> color: Colors.dark,
<ide> },
<ide> highlight: {
<del> fontWeight: '700',
<add> fontWeight: "700",
<ide> },
<ide> footer: {
<ide> color: Colors.dark,
<ide> fontSize: 12,
<del> fontWeight: '600',
<add> fontWeight: "600",
<ide> padding: 4,
<ide> paddingRight: 12,
<del> textAlign: 'right',
<add> textAlign: "right",
<ide> },
<ide> });
<ide> |
|
Java | lgpl-2.1 | a72c90e19ee711785ac4c0f695178c10ba1ccd41 | 0 | exedio/copernica,exedio/copernica,exedio/copernica | /*
* Copyright (C) 2004-2008 exedio GmbH (www.exedio.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.exedio.cope;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
/**
* A common super class for all patterns.
* <p>
* Patterns should be constructable in three different ways:
* <dl>
* <dt>1) by an explicit external source</dt>
* <dd>
* This is the most verbose kind of defining a pattern.
* First the source for the pattern is created, such as:
* <pre>static final StringField source = new StringField(OPTIONAL)</pre>
* Then the pattern ist created using the previously defined source:
* <pre>static final Hash hash = new MD5Hash(source)</pre>
* </dd>
* <dt>2) by an implicit external source</dt>
* <dd>
* More concisely the pattern can be constructed by defining the source
* implicitely when the defining the pattern itself:
* <pre>static final Hash hash = new MD5Hash(new StringField(OPTIONAL))</pre>
* </dd>
* <dt>3) by an internal source</dt>
* <dd>
* Finally, the construction of the source can be done the the pattern itself:
* <pre>static final Hash hash = new MD5Hash(OPTIONAL)</pre>
* </dd>
* </dl>
*
* @author Ralf Wiebicke
*/
public abstract class Pattern extends Feature
{
private LinkedHashMap<Field, String> sourceFieldMapGather = new LinkedHashMap<Field, String>();
private LinkedHashMap<Field, String> sourceFieldMap = null;
private List<Field> sourceFieldList = null;
private ArrayList<Type<? extends Item>> sourceTypesWhileGather = new ArrayList<Type<? extends Item>>();
private List<Type<? extends Item>> sourceTypes = null;
protected final void addSource(final Field field, final String postfix)
{
if(postfix==null)
throw new NullPointerException("postfix must not be null");
if(field==null)
throw new NullPointerException("field must not be null for postfix '" + postfix + '\'');
if(sourceFieldMapGather==null)
throw new IllegalStateException("addSource can be called only until initialize() is called, not afterwards");
assert sourceFieldMap== null;
assert sourceFieldList==null;
field.registerPattern(this);
final String collision = sourceFieldMapGather.put(field, postfix);
if(collision!=null)
throw new IllegalStateException("duplicate addSource " + field + '/' + collision);
}
/**
* Here you can do additional initialization not yet done in the constructor.
* In this method you can call methods {@link #getType()} and {@link #getName()}
* for the first time.
*/
public void initialize()
{
// empty default implementation
}
protected final void initialize(final UniqueConstraint uniqueConstraint, final String name)
{
uniqueConstraint.initialize(getType(), name);
}
protected final <X extends Item> Type<X> newSourceType(final Class<X> javaClass, final LinkedHashMap<String, Feature> features)
{
return newSourceType(javaClass, features, "");
}
protected final <X extends Item> Type<X> newSourceType(final Class<X> javaClass, final LinkedHashMap<String, Feature> features, final String postfix)
{
if(sourceTypesWhileGather==null)
throw new IllegalStateException("newSourceType can be called only until initialize() is called, not afterwards");
assert sourceTypes==null;
final String id = getType().getID() + '.' + getName() + postfix;
final Type<X> result = new Type<X>(javaClass, false, id, this, features);
sourceTypesWhileGather.add(result);
return result;
}
@Override
final void initialize(final Type<? extends Item> type, final String name)
{
super.initialize(type, name);
initialize();
for(final Field<?> source : sourceFieldMapGather.keySet())
{
if(!source.isInitialized())
source.initialize(type, name + sourceFieldMapGather.get(source));
final Type<? extends Item> sourceType = source.getType();
//System.out.println("----------check"+source);
if(!sourceType.equals(type))
throw new RuntimeException("Source " + source + " of pattern " + this + " must be declared on the same type, expected " + type + ", but was " + sourceType + '.');
}
this.sourceFieldMap = sourceFieldMapGather;
this.sourceFieldMapGather = null;
this.sourceFieldList =
sourceFieldMap.isEmpty()
? Collections.<Field>emptyList()
: Collections.unmodifiableList(Arrays.asList(sourceFieldMap.keySet().toArray(new Field[sourceFieldMap.size()])));
this.sourceTypesWhileGather.trimToSize();
this.sourceTypes = Collections.unmodifiableList(sourceTypesWhileGather);
this.sourceTypesWhileGather = null;
}
/**
* @see Field#getPatterns()
*/
public List<? extends Field> getSourceFields()
{
if(sourceFieldMap==null)
throw new IllegalStateException("getSourceFields can be called only after initialize() is called");
assert sourceFieldList!=null;
assert sourceFieldMapGather==null;
return sourceFieldList;
}
/**
* @see Type#getPattern()
*/
public List<Type<? extends Item>> getSourceTypes()
{
if(sourceTypes==null)
throw new IllegalStateException("getSourceTypes can be called only after initialize() is called");
assert sourceTypesWhileGather==null;
return sourceTypes;
}
// Make non-final method from super class final
@Override
public final Type<? extends Item> getType()
{
return super.getType();
}
/**
* Common super class for all wrapper classes backed by a real
* item of a type created by {@link #newSourceType(Class, LinkedHashMap, String)};
* TODO: remove, support custom classes for such types.
*/
public abstract class BackedItem
{
protected final Item backingItem;
protected BackedItem(final Item backingItem)
{
this.backingItem = backingItem;
assert backingItem!=null;
}
public final Item getBackingItem()
{
return backingItem;
}
@Override
public final boolean equals(final Object other)
{
return other instanceof BackedItem && backingItem.equals(((BackedItem)other).backingItem);
}
@Override
public final int hashCode()
{
return backingItem.hashCode() ^ 765744;
}
@Override
public final String toString()
{
return backingItem.toString();
}
}
// ------------------- deprecated stuff -------------------
/**
* @deprecated Use {@link #getSourceFields()} instead
*/
@Deprecated
public List<? extends Field> getSources()
{
return getSourceFields();
}
/**
* @deprecated Use {@link #getSourceTypes()} instead
*/
@Deprecated
public List<Type<? extends Item>> getGeneratedTypes()
{
return getSourceTypes();
}
/**
* @deprecated Use {@link #addSource(Field,String)} instead
*/
@Deprecated
protected final void registerSource(final Field field, final String postfix)
{
addSource(field, postfix);
}
/**
* @deprecated Use {@link #newSourceType(Class,LinkedHashMap)} instead
*/
@Deprecated
protected final <X extends Item> Type<X> newType(final Class<X> javaClass, final LinkedHashMap<String, Feature> features)
{
return newSourceType(javaClass, features);
}
/**
* @deprecated Use {@link #newSourceType(Class,LinkedHashMap,String)} instead
*/
@Deprecated
protected final <X extends Item> Type<X> newType(final Class<X> javaClass, final LinkedHashMap<String, Feature> features, final String postfix)
{
return newSourceType(javaClass, features, postfix);
}
}
| runtime/src/com/exedio/cope/Pattern.java | /*
* Copyright (C) 2004-2008 exedio GmbH (www.exedio.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.exedio.cope;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
/**
* A common super class for all patterns.
* <p>
* Patterns should be constructable in three different ways:
* <dl>
* <dt>1) by an explicit external source</dt>
* <dd>
* This is the most verbose kind of defining a pattern.
* First the source for the pattern is created, such as:
* <pre>static final StringField source = new StringField(OPTIONAL)</pre>
* Then the pattern ist created using the previously defined source:
* <pre>static final Hash hash = new MD5Hash(source)</pre>
* </dd>
* <dt>2) by an implicit external source</dt>
* <dd>
* More concisely the pattern can be constructed by defining the source
* implicitely when the defining the pattern itself:
* <pre>static final Hash hash = new MD5Hash(new StringField(OPTIONAL))</pre>
* </dd>
* <dt>3) by an internal source</dt>
* <dd>
* Finally, the construction of the source can be done the the pattern itself:
* <pre>static final Hash hash = new MD5Hash(OPTIONAL)</pre>
* </dd>
* </dl>
*
* @author Ralf Wiebicke
*/
public abstract class Pattern extends Feature
{
private LinkedHashMap<Field, String> sourceFieldMapGather = new LinkedHashMap<Field, String>();
private LinkedHashMap<Field, String> sourceFieldMap = null;
private List<Field> sourceFieldList = null;
private ArrayList<Type<? extends Item>> sourceTypesWhileGather = new ArrayList<Type<? extends Item>>();
private List<Type<? extends Item>> sourceTypes = null;
protected final void addSource(final Field field, final String postfix)
{
if(postfix==null)
throw new NullPointerException("postfix must not be null");
if(field==null)
throw new NullPointerException("field must not be null for postfix '" + postfix + '\'');
if(sourceFieldMapGather==null)
throw new IllegalStateException("registerSource can be called only until initialize() is called, not afterwards");
assert sourceFieldMap== null;
assert sourceFieldList==null;
field.registerPattern(this);
final String collision = sourceFieldMapGather.put(field, postfix);
if(collision!=null)
throw new IllegalStateException("duplicate source registration " + field + '/' + collision);
}
/**
* Here you can do additional initialization not yet done in the constructor.
* In this method you can call methods {@link #getType()} and {@link #getName()}
* for the first time.
*/
public void initialize()
{
// empty default implementation
}
protected final void initialize(final UniqueConstraint uniqueConstraint, final String name)
{
uniqueConstraint.initialize(getType(), name);
}
protected final <X extends Item> Type<X> newSourceType(final Class<X> javaClass, final LinkedHashMap<String, Feature> features)
{
return newSourceType(javaClass, features, "");
}
protected final <X extends Item> Type<X> newSourceType(final Class<X> javaClass, final LinkedHashMap<String, Feature> features, final String postfix)
{
if(sourceTypesWhileGather==null)
throw new IllegalStateException("newType can be called only until initialize() is called, not afterwards");
assert sourceTypes==null;
final String id = getType().getID() + '.' + getName() + postfix;
final Type<X> result = new Type<X>(javaClass, false, id, this, features);
sourceTypesWhileGather.add(result);
return result;
}
@Override
final void initialize(final Type<? extends Item> type, final String name)
{
super.initialize(type, name);
initialize();
for(final Field<?> source : sourceFieldMapGather.keySet())
{
if(!source.isInitialized())
source.initialize(type, name + sourceFieldMapGather.get(source));
final Type<? extends Item> sourceType = source.getType();
//System.out.println("----------check"+source);
if(!sourceType.equals(type))
throw new RuntimeException("Source " + source + " of pattern " + this + " must be declared on the same type, expected " + type + ", but was " + sourceType + '.');
}
this.sourceFieldMap = sourceFieldMapGather;
this.sourceFieldMapGather = null;
this.sourceFieldList =
sourceFieldMap.isEmpty()
? Collections.<Field>emptyList()
: Collections.unmodifiableList(Arrays.asList(sourceFieldMap.keySet().toArray(new Field[sourceFieldMap.size()])));
this.sourceTypesWhileGather.trimToSize();
this.sourceTypes = Collections.unmodifiableList(sourceTypesWhileGather);
this.sourceTypesWhileGather = null;
}
/**
* @see Field#getPatterns()
*/
public List<? extends Field> getSourceFields()
{
if(sourceFieldMap==null)
throw new IllegalStateException("getSourceFields can be called only after initialize() is called");
assert sourceFieldList!=null;
assert sourceFieldMapGather==null;
return sourceFieldList;
}
/**
* @see Type#getPattern()
*/
public List<Type<? extends Item>> getSourceTypes()
{
if(sourceTypes==null)
throw new IllegalStateException("getSourceTypes can be called only after initialize() is called");
assert sourceTypesWhileGather==null;
return sourceTypes;
}
// Make non-final method from super class final
@Override
public final Type<? extends Item> getType()
{
return super.getType();
}
/**
* Common super class for all wrapper classes backed by a real
* item of a type created by {@link #newSourceType(Class, LinkedHashMap, String)};
* TODO: remove, support custom classes for such types.
*/
public abstract class BackedItem
{
protected final Item backingItem;
protected BackedItem(final Item backingItem)
{
this.backingItem = backingItem;
assert backingItem!=null;
}
public final Item getBackingItem()
{
return backingItem;
}
@Override
public final boolean equals(final Object other)
{
return other instanceof BackedItem && backingItem.equals(((BackedItem)other).backingItem);
}
@Override
public final int hashCode()
{
return backingItem.hashCode() ^ 765744;
}
@Override
public final String toString()
{
return backingItem.toString();
}
}
// ------------------- deprecated stuff -------------------
/**
* @deprecated Use {@link #getSourceFields()} instead
*/
@Deprecated
public List<? extends Field> getSources()
{
return getSourceFields();
}
/**
* @deprecated Use {@link #getSourceTypes()} instead
*/
@Deprecated
public List<Type<? extends Item>> getGeneratedTypes()
{
return getSourceTypes();
}
/**
* @deprecated Use {@link #addSource(Field,String)} instead
*/
@Deprecated
protected final void registerSource(final Field field, final String postfix)
{
addSource(field, postfix);
}
/**
* @deprecated Use {@link #newSourceType(Class,LinkedHashMap)} instead
*/
@Deprecated
protected final <X extends Item> Type<X> newType(final Class<X> javaClass, final LinkedHashMap<String, Feature> features)
{
return newSourceType(javaClass, features);
}
/**
* @deprecated Use {@link #newSourceType(Class,LinkedHashMap,String)} instead
*/
@Deprecated
protected final <X extends Item> Type<X> newType(final Class<X> javaClass, final LinkedHashMap<String, Feature> features, final String postfix)
{
return newSourceType(javaClass, features, postfix);
}
}
| fix exception messages after recent renames
git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@10822 e7d4fc99-c606-0410-b9bf-843393a9eab7
| runtime/src/com/exedio/cope/Pattern.java | fix exception messages after recent renames | <ide><path>untime/src/com/exedio/cope/Pattern.java
<ide> if(field==null)
<ide> throw new NullPointerException("field must not be null for postfix '" + postfix + '\'');
<ide> if(sourceFieldMapGather==null)
<del> throw new IllegalStateException("registerSource can be called only until initialize() is called, not afterwards");
<add> throw new IllegalStateException("addSource can be called only until initialize() is called, not afterwards");
<ide> assert sourceFieldMap== null;
<ide> assert sourceFieldList==null;
<ide> field.registerPattern(this);
<ide> final String collision = sourceFieldMapGather.put(field, postfix);
<ide> if(collision!=null)
<del> throw new IllegalStateException("duplicate source registration " + field + '/' + collision);
<add> throw new IllegalStateException("duplicate addSource " + field + '/' + collision);
<ide> }
<ide>
<ide> /**
<ide> protected final <X extends Item> Type<X> newSourceType(final Class<X> javaClass, final LinkedHashMap<String, Feature> features, final String postfix)
<ide> {
<ide> if(sourceTypesWhileGather==null)
<del> throw new IllegalStateException("newType can be called only until initialize() is called, not afterwards");
<add> throw new IllegalStateException("newSourceType can be called only until initialize() is called, not afterwards");
<ide> assert sourceTypes==null;
<ide> final String id = getType().getID() + '.' + getName() + postfix;
<ide> final Type<X> result = new Type<X>(javaClass, false, id, this, features); |
|
JavaScript | mit | 29363ea503c0dd0571a449290abf9eebc8fb55a5 | 0 | fergiemcdowall/stopword | /* global describe */
/* global it */
const should = require('should')
const sw = require('../lib/stopword.js')
describe('general stopwordiness:', function () {
it('should remove stopwords, should default to english, should preserve case', function () {
const oldString = 'a really Interesting string with some words'.split(' ')
const newString = sw.removeStopwords(oldString)
should.exist(sw.removeStopwords(oldString))
newString.should.eql([ 'really', 'Interesting', 'string', 'words' ])
})
it('should remove custom stopwords', function () {
const oldString = 'a really interesting string with some words'.split(' ')
const newString = sw.removeStopwords(oldString, ['interesting'])
newString.should.eql([ 'a', 'really', 'string', 'with', 'some', 'words' ])
})
it('should not remove any stopwords', function () {
const oldString = 'a really interesting string with some words'.split(' ')
const newString = sw.removeStopwords(oldString, [])
newString.should.eql([ 'a', 'really', 'interesting', 'string', 'with', 'some', 'words' ])
})
it('should remove stopwords that have a non standard separator', function () {
const oldString = 'a.really,interesting string.with,some.words'.split(/[\\., ]+/)
const newString = sw.removeStopwords(oldString)
newString.should.eql([ 'really', 'interesting', 'string', 'words' ])
})
it('should specify a custom input separator', function () {
const oldString = 'a-really-interesting-string-with-some words'.split('-')
const newString = sw.removeStopwords(oldString)
newString.should.eql([ 'really', 'interesting', 'string', 'some words' ])
})
it('should remove norwegian stopwords', function () {
const oldString = 'dette er en tekst som har nørske tegn øæåø øæåø æææ'.split(' ')
const newString = sw.removeStopwords(oldString, sw.no)
newString.should.eql([ 'tekst', 'nørske', 'tegn', 'øæåø', 'øæåø', 'æææ' ])
})
it('should remove swedish stopwords and preserve case', function () {
const oldString = 'Trädgårdsägare är beredda att pröva vad som helst för att bli av med de hatade mördarsniglarna åäö'.split(' ')
const newString = sw.removeStopwords(oldString, sw.sv)
newString.should.eql([ 'Trädgårdsägare', 'beredda', 'pröva', 'helst', 'hatade', 'mördarsniglarna', 'åäö' ])
})
it('should remove danish stopwords', function () {
const oldString = 'gæsterne i musikhuset i aarhus bør fremover sende en venlig tanke til den afdøde købmand herman salling når de skal til koncert eller se teater i det aarhusianske kulturhus æøå'.split(' ')
const newString = sw.removeStopwords(oldString, sw.da)
newString.should.eql([ 'gæsterne', 'musikhuset', 'aarhus', 'bør', 'fremover', 'sende', 'venlig', 'tanke', 'afdøde', 'købmand', 'herman', 'salling', 'koncert', 'teater', 'aarhusianske', 'kulturhus', 'æøå' ])
})
it('should remove hindu stopwords', function () {
const oldString = 'केंद्र सरकार पर्यावरण के माकूल घरों ग्रीन होम्स को बढ़ावा देने की दिशा में गंभीरता से सोच रही है। ग्रीन हाउसिंग सोसायटी डिवेलप करने के लिए सरकार सस्ते लोन'.split(' ')
const newString = sw.removeStopwords(oldString, sw.hi)
newString.should.eql([ 'केंद्र', 'सरकार', 'पर्यावरण', 'माकूल', 'घरों', 'ग्रीन', 'होम्स', 'बढ़ावा', 'देने', 'दिशा', 'गंभीरता', 'सोच', 'रही', 'है।', 'ग्रीन', 'हाउसिंग', 'सोसायटी', 'डिवेलप', 'सरकार', 'सस्ते', 'लोन' ])
})
it('should remove spanish stopwords', function () {
const oldString = 'los investigadores han analizado el adn de los restos de unos 200 gatos tomados de momias egipcias yacimientos vikingos y cuevas de la edad de piedra entre otros lugares variopintos'.split(' ')
const newString = sw.removeStopwords(oldString, sw.es)
newString.should.eql([ 'investigadores', 'han', 'analizado', 'adn', 'restos', 'unos', '200', 'gatos', 'tomados', 'momias', 'egipcias', 'yacimientos', 'vikingos', 'cuevas', 'edad', 'piedra', 'entre', 'otros', 'lugares', 'variopintos' ])
})
it('should remove japanese stopwords after being tokenised', function () {
const oldString = '今 回作っ た リスト で は 校正 待ち と なっ て いる 作品 を 抽出 し 作者 や 作品 名 で の 検索 の ほか 作品 の 長さ さまざまな 理由 で 機械 的 に 処理 でき なかっ た もの は に なっ て しまっ て い ます が やいつ から 校正 待ち に なっ て いる か で 並べ替え が できる よう に し まし た'.split(' ')
const newString = sw.removeStopwords(oldString, sw.ja)
newString.should.eql([ '今', '回作っ', 'リスト', '校正', '待ち', '作品', '抽出', '作者', '作品', '名', '検索', '作品', '長さ', 'さまざまな', '理由', '機械', '的', '処理', 'しまっ', 'やいつ', '校正', '待ち', '並べ替え', 'まし' ])
})
it('should remove farsi stopwords and preserve case', function () {
const oldString = 'در این بیانیه آمده است که اتو قادر به صحبت کردن، قادر به دیدن و قادر به عکس العمل نشان دادن به درخواست های شفاهی نبود'.split(' ')
const newString = sw.removeStopwords(oldString, sw.fa)
newString.should.eql([ 'در' ,'این' ,'بیانیه' ,'آمده' ,'است' ,'که' ,'اتو' ,'قادر' ,'به' ,'صحبت' ,'کردن،' ,'قادر' ,'به' ,'دیدن' ,'قادر' ,'به', 'عکس' ,'العمل' ,'نشان' ,'دادن' ,'به' ,'درخواست' ,'های' ,'شفاهی' ,'نبود' ])
})
})
describe('error handling', function () {
it('should return throw an error if specified language is not supported', function () {
(function () {
sw.getStopwords('xx')
}).should.throw()
})
})
| test/test.js | /* global describe */
/* global it */
const should = require('should')
const sw = require('../lib/stopword.js')
describe('general stopwordiness:', function () {
it('should remove stopwords, should default to english, should preserve case', function () {
const oldString = 'a really Interesting string with some words'.split(' ')
const newString = sw.removeStopwords(oldString)
should.exist(sw.removeStopwords(oldString))
newString.should.eql([ 'really', 'Interesting', 'string', 'words' ])
})
it('should remove custom stopwords', function () {
const oldString = 'a really interesting string with some words'.split(' ')
const newString = sw.removeStopwords(oldString, ['interesting'])
newString.should.eql([ 'a', 'really', 'string', 'with', 'some', 'words' ])
})
it('should not remove any stopwords', function () {
const oldString = 'a really interesting string with some words'.split(' ')
const newString = sw.removeStopwords(oldString, [])
newString.should.eql([ 'a', 'really', 'interesting', 'string', 'with', 'some', 'words' ])
})
it('should remove stopwords that have a non standard separator', function () {
const oldString = 'a.really,interesting string.with,some.words'.split(/[\\., ]+/)
const newString = sw.removeStopwords(oldString)
newString.should.eql([ 'really', 'interesting', 'string', 'words' ])
})
it('should specify a custom input separator', function () {
const oldString = 'a-really-interesting-string-with-some words'.split('-')
const newString = sw.removeStopwords(oldString)
newString.should.eql([ 'really', 'interesting', 'string', 'some words' ])
})
it('should remove norwegian stopwords', function () {
const oldString = 'dette er en tekst som har nørske tegn øæåø øæåø æææ'.split(' ')
const newString = sw.removeStopwords(oldString, sw.no)
newString.should.eql([ 'tekst', 'nørske', 'tegn', 'øæåø', 'øæåø', 'æææ' ])
})
it('should remove swedish stopwords and preserve case', function () {
const oldString = 'Trädgårdsägare är beredda att pröva vad som helst för att bli av med de hatade mördarsniglarna åäö'.split(' ')
const newString = sw.removeStopwords(oldString, sw.sv)
newString.should.eql([ 'Trädgårdsägare', 'beredda', 'pröva', 'helst', 'hatade', 'mördarsniglarna', 'åäö' ])
})
it('should remove danish stopwords', function () {
const oldString = 'gæsterne i musikhuset i aarhus bør fremover sende en venlig tanke til den afdøde købmand herman salling når de skal til koncert eller se teater i det aarhusianske kulturhus æøå'.split(' ')
const newString = sw.removeStopwords(oldString, sw.da)
newString.should.eql([ 'gæsterne', 'musikhuset', 'aarhus', 'bør', 'fremover', 'sende', 'venlig', 'tanke', 'afdøde', 'købmand', 'herman', 'salling', 'koncert', 'teater', 'aarhusianske', 'kulturhus', 'æøå' ])
})
it('should remove hindu stopwords', function () {
const oldString = 'केंद्र सरकार पर्यावरण के माकूल घरों ग्रीन होम्स को बढ़ावा देने की दिशा में गंभीरता से सोच रही है। ग्रीन हाउसिंग सोसायटी डिवेलप करने के लिए सरकार सस्ते लोन'.split(' ')
const newString = sw.removeStopwords(oldString, sw.hi)
newString.should.eql([ 'केंद्र', 'सरकार', 'पर्यावरण', 'माकूल', 'घरों', 'ग्रीन', 'होम्स', 'बढ़ावा', 'देने', 'दिशा', 'गंभीरता', 'सोच', 'रही', 'है।', 'ग्रीन', 'हाउसिंग', 'सोसायटी', 'डिवेलप', 'सरकार', 'सस्ते', 'लोन' ])
})
it('should remove spanish stopwords', function () {
const oldString = 'los investigadores han analizado el adn de los restos de unos 200 gatos tomados de momias egipcias yacimientos vikingos y cuevas de la edad de piedra entre otros lugares variopintos'.split(' ')
const newString = sw.removeStopwords(oldString, sw.es)
newString.should.eql([ 'investigadores', 'han', 'analizado', 'adn', 'restos', 'unos', '200', 'gatos', 'tomados', 'momias', 'egipcias', 'yacimientos', 'vikingos', 'cuevas', 'edad', 'piedra', 'entre', 'otros', 'lugares', 'variopintos' ])
})
it('should remove japanese stopwords after being tokenised', function () {
const oldString = '今 回作っ た リスト で は 校正 待ち と なっ て いる 作品 を 抽出 し 作者 や 作品 名 で の 検索 の ほか 作品 の 長さ さまざまな 理由 で 機械 的 に 処理 でき なかっ た もの は に なっ て しまっ て い ます が やいつ から 校正 待ち に なっ て いる か で 並べ替え が できる よう に し まし た'.split(' ')
const newString = sw.removeStopwords(oldString, sw.ja)
newString.should.eql([ '今', '回作っ', 'リスト', '校正', '待ち', '作品', '抽出', '作者', '作品', '名', '検索', '作品', '長さ', 'さまざまな', '理由', '機械', '的', '処理', 'しまっ', 'やいつ', '校正', '待ち', '並べ替え', 'まし' ])
})
})
describe('error handling', function () {
it('should return throw an error if specified language is not supported', function () {
(function () {
sw.getStopwords('xx')
}).should.throw()
})
})
| farsi for test stopword Added
| test/test.js | farsi for test stopword Added | <ide><path>est/test.js
<ide> const newString = sw.removeStopwords(oldString, sw.es)
<ide> newString.should.eql([ 'investigadores', 'han', 'analizado', 'adn', 'restos', 'unos', '200', 'gatos', 'tomados', 'momias', 'egipcias', 'yacimientos', 'vikingos', 'cuevas', 'edad', 'piedra', 'entre', 'otros', 'lugares', 'variopintos' ])
<ide> })
<add>
<ide> it('should remove japanese stopwords after being tokenised', function () {
<ide> const oldString = '今 回作っ た リスト で は 校正 待ち と なっ て いる 作品 を 抽出 し 作者 や 作品 名 で の 検索 の ほか 作品 の 長さ さまざまな 理由 で 機械 的 に 処理 でき なかっ た もの は に なっ て しまっ て い ます が やいつ から 校正 待ち に なっ て いる か で 並べ替え が できる よう に し まし た'.split(' ')
<ide> const newString = sw.removeStopwords(oldString, sw.ja)
<ide> newString.should.eql([ '今', '回作っ', 'リスト', '校正', '待ち', '作品', '抽出', '作者', '作品', '名', '検索', '作品', '長さ', 'さまざまな', '理由', '機械', '的', '処理', 'しまっ', 'やいつ', '校正', '待ち', '並べ替え', 'まし' ])
<add> })
<add>
<add> it('should remove farsi stopwords and preserve case', function () {
<add> const oldString = 'در این بیانیه آمده است که اتو قادر به صحبت کردن، قادر به دیدن و قادر به عکس العمل نشان دادن به درخواست های شفاهی نبود'.split(' ')
<add> const newString = sw.removeStopwords(oldString, sw.fa)
<add> newString.should.eql([ 'در' ,'این' ,'بیانیه' ,'آمده' ,'است' ,'که' ,'اتو' ,'قادر' ,'به' ,'صحبت' ,'کردن،' ,'قادر' ,'به' ,'دیدن' ,'قادر' ,'به', 'عکس' ,'العمل' ,'نشان' ,'دادن' ,'به' ,'درخواست' ,'های' ,'شفاهی' ,'نبود' ])
<ide> })
<ide>
<ide> |
|
Java | mit | 4978a083a768418191a65ee6d71660e8538890e5 | 0 | eric-thelin/fractions | package se.ericthelin.fractions;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.Integer.parseInt;
public class Fraction {
private static final Pattern FRACTION_PATTERN = Pattern.compile("(\\d+)/(\\d+)");
private static final Pattern INTEGER_PATTERN = Pattern.compile("\\d+");
public static Fraction of(String text) {
Matcher fractionMatcher = FRACTION_PATTERN.matcher(text);
if (fractionMatcher.matches()) {
return Fraction.of(
parseInt(fractionMatcher.group(1)),
parseInt(fractionMatcher.group(2)));
}
Matcher integerMatcher = INTEGER_PATTERN.matcher(text);
if (integerMatcher.matches()) {
return Fraction.of(parseInt(integerMatcher.group(0)), 1);
}
throw new InvalidFractionFormatException(text);
}
private static Fraction of(int numerator, int denominator) {
if (denominator == 0) {
throw new ZeroDenominatorException(numerator);
}
if (numerator == 0) {
return new Fraction(numerator, 1);
} else {
return new Fraction(numerator, denominator);
}
}
private final int numerator;
private final int denominator;
private Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
@Override
public String toString() {
return numerator + "/" + denominator;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Fraction)) {
return false;
}
Fraction other = (Fraction) obj;
return numerator == other.numerator
&& denominator == other.denominator;
}
public Fraction plus(Fraction term) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
| production/source/se/ericthelin/fractions/Fraction.java | package se.ericthelin.fractions;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.Integer.parseInt;
public class Fraction {
private static final Pattern FRACTION_PATTERN = Pattern.compile("(\\d+)/(\\d+)");
private static final Pattern INTEGER_PATTERN = Pattern.compile("\\d+");
public static Fraction of(String text) {
Matcher fractionMatcher = FRACTION_PATTERN.matcher(text);
if (fractionMatcher.matches()) {
return Fraction.of(
parseInt(fractionMatcher.group(1)),
parseInt(fractionMatcher.group(2)));
}
Matcher integerMatcher = INTEGER_PATTERN.matcher(text);
if (integerMatcher.matches()) {
return Fraction.of(parseInt(integerMatcher.group(0)), 1);
}
throw new InvalidFractionFormatException(text);
}
private static Fraction of(int numerator, int denominator) {
if (denominator == 0) {
throw new ZeroDenominatorException(numerator);
}
if (numerator == 0) {
return new Fraction(numerator, 1);
} else {
return new Fraction(numerator, denominator);
}
}
private final int numerator;
private final int denominator;
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
@Override
public String toString() {
return numerator + "/" + denominator;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Fraction)) {
return false;
}
Fraction other = (Fraction) obj;
return numerator == other.numerator
&& denominator == other.denominator;
}
public Fraction plus(Fraction term) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
| Fraction constructor is now private
| production/source/se/ericthelin/fractions/Fraction.java | Fraction constructor is now private | <ide><path>roduction/source/se/ericthelin/fractions/Fraction.java
<ide> private final int numerator;
<ide> private final int denominator;
<ide>
<del> public Fraction(int numerator, int denominator) {
<add> private Fraction(int numerator, int denominator) {
<ide> this.numerator = numerator;
<ide> this.denominator = denominator;
<ide> } |
|
Java | mit | aece95c7cc7fc7bb682e3eaf59baddf321ff60dc | 0 | semiotproject/semiot-platform,semiotproject/semiot-platform,semiotproject/semiot-platform,semiotproject/semiot-platform,semiotproject/semiot-platform | package ru.semiot.services.data_archiving_service;
import java.io.StringReader;
import java.util.Calendar;
import java.util.HashMap;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observer;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
public class WriterMetricsListener implements Observer<String> {
private static final Logger logger = LoggerFactory
.getLogger(WriterMetricsListener.class);
private static final String TIMESTAMP = "timestamp";
private static final String VALUE_TYPE = "value_type";
private static final String VALUE = "value";
private static final String PROPERTY = "property";
private static final String ENUM_VALUE = "enum_value";
private static final String FEATURE_OF_INTEREST = "feature_of_interest";
private static final String SOURCE = "source";
private static final String QUDT_ENUMERATION = "http://qudt.org/schema/qudt#Enumeration";
private static final Query METRICS_QUERY = QueryFactory
.create("prefix qudt: <http://www.qudt.org/qudt/owl/1.0.0/qudt/#> "
+ "prefix dcterms: <http://purl.org/dc/terms/#> "
+ "prefix ssn: <http://purl.oclc.org/NET/ssnx/ssn#> "
+ "SELECT ?timestamp ?property ?value_type ?value ?feature_of_interest ?source "
+ "WHERE { ?x a ssn:Observation; "
+ "ssn:observedProperty ?property; "
+ "ssn:observationResultTime ?timestamp; "
+ "ssn:observationResult ?result; "
+ "ssn:observedBy ?sensor. "
+ "?sensor dcterms:identifier ?source. "
+ "?result ssn:hasValue ?res_value. "
+ "?res_value a ?value_type. "
+ "{?res_value ssn:hasValue ?value} "
+ "UNION {?res_value qudt:quantityValue ?value}"
+ "OPTIONAL {?x ssn:featureOfInterest ?feature_of_interest}}");
private final String nameMetric; // временное решение
public WriterMetricsListener(String nameMetric) {
this.nameMetric = nameMetric;
}
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
logger.warn(e.getMessage(), e);
}
@Override
public void onNext(String message) {
try {
Model description = ModelFactory.createDefaultModel().read(
new StringReader(message), null, SubscribeListener.LANG);
if (!description.isEmpty()) {
QueryExecution qe = QueryExecutionFactory.create(METRICS_QUERY,
description);
ResultSet metrics = qe.execSelect();
while (metrics.hasNext()) {
QuerySolution qs = metrics.next();
String timestamp = qs.getLiteral(TIMESTAMP).getString();
String valueType = qs.getResource(VALUE_TYPE).getURI();
String source = qs.getLiteral(SOURCE).getString();
Resource featureOfInterest = qs.getResource(FEATURE_OF_INTEREST);
String value;
if (valueType.equals(QUDT_ENUMERATION)) {
value = qs.getResource(VALUE).getURI(); // instance enum uri
} else {
value = qs.getLiteral(VALUE).getString(); // value simulator
}
String property = qs.getResource(PROPERTY).getURI();
if (StringUtils.isNotBlank(nameMetric)
&& StringUtils.isNotBlank(value)
&& StringUtils.isNotBlank(property)
&& StringUtils.isNotBlank(timestamp)
&& StringUtils.isNoneBlank(source)) {
HashMap<String, String> tags = new HashMap<String, String>();
try {
Calendar calendar = DatatypeConverter
.parseDateTime(timestamp);
tags.put(PROPERTY, property.replaceAll(":", "_").replace("#", "-"));// _ -
tags.put(VALUE_TYPE, valueType.replaceAll(":", "_").replace("#", "-"));
tags.put(SOURCE, source);
if(featureOfInterest != null) {
tags.put(FEATURE_OF_INTEREST, featureOfInterest.getURI().replaceAll(":", "_").replace("#", "-"));
}
if(valueType.equals(QUDT_ENUMERATION)) { // для симуляторов
tags.put(ENUM_VALUE, value.replaceAll(":", "_").replace("#", "-"));
WriterOpenTsdb.getInstance().send(
nameMetric, 0,
calendar.getTimeInMillis(), tags);
}
else {
WriterOpenTsdb.getInstance().send(
nameMetric, value,
calendar.getTimeInMillis(), tags);
}
} catch (IllegalArgumentException e) {
logger.warn("Can't convert " + timestamp
+ " to calendar (xsd:dateTime)");
}
} else {
logger.warn("In the message not found required fields for the metric");
}
}
} else {
logger.warn("Received an empty message or in a wrong format!");
}
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
}
} | data-archiving-service/src/main/java/ru/semiot/services/data_archiving_service/WriterMetricsListener.java | package ru.semiot.services.data_archiving_service;
import java.io.StringReader;
import java.util.Calendar;
import java.util.HashMap;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observer;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
public class WriterMetricsListener implements Observer<String> {
private static final Logger logger = LoggerFactory
.getLogger(WriterMetricsListener.class);
private static final String TIMESTAMP = "timestamp";
private static final String VALUE_TYPE = "value_type";
private static final String VALUE = "value";
private static final String PROPERTY = "property";
private static final String ENUM_VALUE = "enum_value";
private static final String FEATURE_OF_INTEREST = "feature_of_interest";
private static final String SOURCE = "source";
private static final String QUDT_ENUMERATION = "http://www.qudt.org/qudt/owl/1.0.0/qudt/#Enumeration";
private static final Query METRICS_QUERY = QueryFactory
.create("prefix qudt: <http://www.qudt.org/qudt/owl/1.0.0/qudt/#> "
+ "prefix dcterms: <http://purl.org/dc/terms/#> "
+ "prefix ssn: <http://purl.oclc.org/NET/ssnx/ssn#> "
+ "SELECT ?timestamp ?property ?value_type ?value ?feature_of_interest ?source "
+ "WHERE { ?x a ssn:Observation; "
+ "ssn:observedProperty ?property; "
+ "ssn:observationResultTime ?timestamp; "
+ "ssn:observationResult ?result; "
+ "ssn:observedBy ?sensor. "
+ "?sensor dcterms:identifier ?source. "
+ "?result ssn:hasValue ?res_value. "
+ "?res_value a ?value_type. "
+ "{?res_value ssn:hasValue ?value} "
+ "UNION {?res_value qudt:quantityValue ?value}"
+ "OPTIONAL {?x ssn:featureOfInterest ?feature_of_interest}}");
private final String nameMetric; // временное решение
public WriterMetricsListener(String nameMetric) {
this.nameMetric = nameMetric;
}
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
logger.warn(e.getMessage(), e);
}
@Override
public void onNext(String message) {
try {
Model description = ModelFactory.createDefaultModel().read(
new StringReader(message), null, SubscribeListener.LANG);
if (!description.isEmpty()) {
QueryExecution qe = QueryExecutionFactory.create(METRICS_QUERY,
description);
ResultSet metrics = qe.execSelect();
while (metrics.hasNext()) {
QuerySolution qs = metrics.next();
String timestamp = qs.getLiteral(TIMESTAMP).getString();
String valueType = qs.getResource(VALUE_TYPE).getURI();
String source = qs.getLiteral(SOURCE).getString();
Resource featureOfInterest = qs.getResource(FEATURE_OF_INTEREST);
String value;
if (valueType.equals(QUDT_ENUMERATION)) {
value = qs.getResource(VALUE).getURI(); // instance enum uri
} else {
value = qs.getLiteral(VALUE).getString(); // value simulator
}
String property = qs.getResource(PROPERTY).getURI();
if (StringUtils.isNotBlank(nameMetric)
&& StringUtils.isNotBlank(value)
&& StringUtils.isNotBlank(property)
&& StringUtils.isNotBlank(timestamp)
&& StringUtils.isNoneBlank(source)) {
HashMap<String, String> tags = new HashMap<String, String>();
try {
Calendar calendar = DatatypeConverter
.parseDateTime(timestamp);
tags.put(PROPERTY, property.replaceAll(":", "_").replace("#", "-"));// _ -
tags.put(VALUE_TYPE, valueType.replaceAll(":", "_").replace("#", "-"));
tags.put(SOURCE, source);
if(featureOfInterest != null) {
tags.put(FEATURE_OF_INTEREST, featureOfInterest.getURI().replaceAll(":", "_").replace("#", "-"));
}
if(valueType.equals(QUDT_ENUMERATION)) { // для симуляторов
tags.put(ENUM_VALUE, value.replaceAll(":", "_").replace("#", "-"));
WriterOpenTsdb.getInstance().send(
nameMetric, 0,
calendar.getTimeInMillis(), tags);
}
else {
WriterOpenTsdb.getInstance().send(
nameMetric, value,
calendar.getTimeInMillis(), tags);
}
} catch (IllegalArgumentException e) {
logger.warn("Can't convert " + timestamp
+ " to calendar (xsd:dateTime)");
}
} else {
logger.warn("In the message not found required fields for the metric");
}
}
} else {
logger.warn("Received an empty message or in a wrong format!");
}
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
}
} | Changed QUDT_ENUMERATION variable. | data-archiving-service/src/main/java/ru/semiot/services/data_archiving_service/WriterMetricsListener.java | Changed QUDT_ENUMERATION variable. | <ide><path>ata-archiving-service/src/main/java/ru/semiot/services/data_archiving_service/WriterMetricsListener.java
<ide> private static final String FEATURE_OF_INTEREST = "feature_of_interest";
<ide> private static final String SOURCE = "source";
<ide>
<del> private static final String QUDT_ENUMERATION = "http://www.qudt.org/qudt/owl/1.0.0/qudt/#Enumeration";
<add> private static final String QUDT_ENUMERATION = "http://qudt.org/schema/qudt#Enumeration";
<ide> private static final Query METRICS_QUERY = QueryFactory
<ide> .create("prefix qudt: <http://www.qudt.org/qudt/owl/1.0.0/qudt/#> "
<ide> + "prefix dcterms: <http://purl.org/dc/terms/#> " |
|
JavaScript | mit | 3a7c686b3338a6e6e57336de349bd278cb56b43a | 0 | kido1611/Riset_CCC,kido1611/Riset_CCC | import React from 'react';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import axios from 'axios';
class Struktur extends React.Component{
constructor(){
super();
this.state = {
value: '',
list: [],
data: [],
}
}
loadData(data){
var _this = this;
var tahun = data;
console.log("Load data "+tahun);;
axios.get('data/'+tahun+'.json')
.then(function (response) {
_this.setState({
value: tahun,
data: response.data,
});
})
.catch(function (error) {
console.log(error.response);
});
}
componentWillMount(){
var _this = this;
axios.get('data/list.json')
.then(function (response) {
_this.setState({
list: response.data,
});
if(response.data.length>0)
_this.loadData(response.data[response.data.length-1].tahun);
})
.catch(function (error) {
console.log(error);
_this.setState({
value: '',
});
});
}
handleChange = (event, index, value) => {
this.setState({value});
this.loadData(value);
}
render(){
return (
(this.state.value!=='' && this.state.value!==0)?
<div>
<SelectField
floatingLabelText="Struktur Pengurus"
value={this.state.value}
fullWidth={true}
onChange={this.handleChange} >
{
this.state.list.map(item => (
<MenuItem value={item.tahun} primaryText={item.tahun+"-"+(item.tahun+1)} key={item.tahun} />
))
}
</SelectField>
<div>
<table>
<tbody>
{
this.state.data.map((row, index) => (
<tr key={index}>
<td><b>{row.jabatan}</b></td>
<td>:</td>
{
Object.prototype.toString.call(row.nama) !== '[object Array]' ?
<td>{row.nama}</td>
:
<td>
{
row.nama.map((row2, index2) => (
<span key={index2}>{index2+1}. {row2.nama}<br/></span>
))
}
</td>
}
</tr>
))
}
</tbody>
</table>
</div>
</div>
:
<div>
<h1>Cannot load data</h1>
</div>
);
}
}
export default Struktur; | src/components/Struktur.js | import React from 'react';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import axios from 'axios';
class Struktur extends React.Component{
constructor(){
super();
this.state = {
value: '',
list: [],
data: [],
}
}
loadData(data){
var _this = this;
var tahun = data;
console.log("Load data "+tahun);;
axios.get('/data/'+tahun+'.json')
.then(function (response) {
_this.setState({
value: tahun,
data: response.data,
});
})
.catch(function (error) {
console.log(error.response);
});
}
componentWillMount(){
var _this = this;
axios.get('data/list.json')
.then(function (response) {
_this.setState({
list: response.data,
});
if(response.data.length>0)
_this.loadData(response.data[response.data.length-1].tahun);
})
.catch(function (error) {
console.log(error);
_this.setState({
value: '',
});
});
}
handleChange = (event, index, value) => {
this.setState({value});
this.loadData(value);
}
render(){
return (
(this.state.value!=='' && this.state.value!==0)?
<div>
<SelectField
floatingLabelText="Struktur Pengurus"
value={this.state.value}
fullWidth={true}
onChange={this.handleChange} >
{
this.state.list.map(item => (
<MenuItem value={item.tahun} primaryText={item.tahun+"-"+(item.tahun+1)} key={item.tahun} />
))
}
</SelectField>
<div>
<table>
<tbody>
{
this.state.data.map((row, index) => (
<tr key={index}>
<td><b>{row.jabatan}</b></td>
<td>:</td>
{
row.jabatan!=="Pengajar" ?
<td>{row.nama}</td>
:
<td>
{
row.nama.map((row2, index2) => (
<span key={index2}>{index2+1}. {row2.nama}<br/></span>
))
}
</td>
}
</tr>
))
}
</tbody>
</table>
</div>
</div>
:
<div>
<h1>Cannot load data</h1>
</div>
);
}
}
export default Struktur; | Fix deteksi JSON
memperbaiki cara pendeteksian JSON Object berupa array atau bukan. Diimplementasikan pada JSON nama | src/components/Struktur.js | Fix deteksi JSON | <ide><path>rc/components/Struktur.js
<ide> var _this = this;
<ide> var tahun = data;
<ide> console.log("Load data "+tahun);;
<del> axios.get('/data/'+tahun+'.json')
<add> axios.get('data/'+tahun+'.json')
<ide> .then(function (response) {
<ide> _this.setState({
<ide> value: tahun,
<ide> <td><b>{row.jabatan}</b></td>
<ide> <td>:</td>
<ide> {
<del> row.jabatan!=="Pengajar" ?
<add> Object.prototype.toString.call(row.nama) !== '[object Array]' ?
<ide> <td>{row.nama}</td>
<ide> :
<ide> <td> |
|
Java | apache-2.0 | a41ac956a8c9ee8eea200f0b103ffe40cdef9501 | 0 | OpenCollabZA/sakai,OpenCollabZA/sakai,buckett/sakai-gitflow,colczr/sakai,willkara/sakai,puramshetty/sakai,rodriguezdevera/sakai,liubo404/sakai,joserabal/sakai,whumph/sakai,zqian/sakai,udayg/sakai,surya-janani/sakai,ktakacs/sakai,whumph/sakai,joserabal/sakai,joserabal/sakai,frasese/sakai,colczr/sakai,frasese/sakai,bkirschn/sakai,conder/sakai,frasese/sakai,udayg/sakai,kwedoff1/sakai,buckett/sakai-gitflow,clhedrick/sakai,buckett/sakai-gitflow,introp-software/sakai,noondaysun/sakai,joserabal/sakai,introp-software/sakai,zqian/sakai,pushyamig/sakai,ouit0408/sakai,willkara/sakai,clhedrick/sakai,ktakacs/sakai,udayg/sakai,wfuedu/sakai,puramshetty/sakai,bkirschn/sakai,kingmook/sakai,clhedrick/sakai,noondaysun/sakai,ktakacs/sakai,clhedrick/sakai,introp-software/sakai,colczr/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,puramshetty/sakai,udayg/sakai,buckett/sakai-gitflow,Fudan-University/sakai,Fudan-University/sakai,udayg/sakai,kingmook/sakai,puramshetty/sakai,rodriguezdevera/sakai,ouit0408/sakai,whumph/sakai,Fudan-University/sakai,rodriguezdevera/sakai,willkara/sakai,rodriguezdevera/sakai,udayg/sakai,liubo404/sakai,ktakacs/sakai,buckett/sakai-gitflow,surya-janani/sakai,ouit0408/sakai,lorenamgUMU/sakai,surya-janani/sakai,joserabal/sakai,lorenamgUMU/sakai,lorenamgUMU/sakai,bzhouduke123/sakai,introp-software/sakai,liubo404/sakai,bzhouduke123/sakai,willkara/sakai,tl-its-umich-edu/sakai,Fudan-University/sakai,bkirschn/sakai,Fudan-University/sakai,hackbuteer59/sakai,kwedoff1/sakai,tl-its-umich-edu/sakai,OpenCollabZA/sakai,rodriguezdevera/sakai,kingmook/sakai,hackbuteer59/sakai,kingmook/sakai,willkara/sakai,conder/sakai,introp-software/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,zqian/sakai,introp-software/sakai,colczr/sakai,lorenamgUMU/sakai,colczr/sakai,conder/sakai,whumph/sakai,tl-its-umich-edu/sakai,bkirschn/sakai,whumph/sakai,tl-its-umich-edu/sakai,conder/sakai,liubo404/sakai,ktakacs/sakai,surya-janani/sakai,ouit0408/sakai,kwedoff1/sakai,hackbuteer59/sakai,ouit0408/sakai,ktakacs/sakai,duke-compsci290-spring2016/sakai,rodriguezdevera/sakai,ktakacs/sakai,kwedoff1/sakai,conder/sakai,liubo404/sakai,noondaysun/sakai,duke-compsci290-spring2016/sakai,hackbuteer59/sakai,bzhouduke123/sakai,rodriguezdevera/sakai,wfuedu/sakai,joserabal/sakai,frasese/sakai,wfuedu/sakai,kwedoff1/sakai,clhedrick/sakai,buckett/sakai-gitflow,pushyamig/sakai,OpenCollabZA/sakai,bzhouduke123/sakai,zqian/sakai,kingmook/sakai,joserabal/sakai,duke-compsci290-spring2016/sakai,OpenCollabZA/sakai,kingmook/sakai,bkirschn/sakai,OpenCollabZA/sakai,OpenCollabZA/sakai,puramshetty/sakai,bzhouduke123/sakai,noondaysun/sakai,wfuedu/sakai,duke-compsci290-spring2016/sakai,Fudan-University/sakai,bkirschn/sakai,OpenCollabZA/sakai,duke-compsci290-spring2016/sakai,kwedoff1/sakai,whumph/sakai,wfuedu/sakai,frasese/sakai,noondaysun/sakai,liubo404/sakai,lorenamgUMU/sakai,Fudan-University/sakai,tl-its-umich-edu/sakai,ktakacs/sakai,willkara/sakai,bzhouduke123/sakai,Fudan-University/sakai,rodriguezdevera/sakai,whumph/sakai,frasese/sakai,duke-compsci290-spring2016/sakai,colczr/sakai,conder/sakai,pushyamig/sakai,lorenamgUMU/sakai,lorenamgUMU/sakai,bzhouduke123/sakai,willkara/sakai,wfuedu/sakai,bkirschn/sakai,ouit0408/sakai,buckett/sakai-gitflow,duke-compsci290-spring2016/sakai,pushyamig/sakai,colczr/sakai,kwedoff1/sakai,introp-software/sakai,introp-software/sakai,surya-janani/sakai,lorenamgUMU/sakai,joserabal/sakai,bkirschn/sakai,noondaysun/sakai,surya-janani/sakai,zqian/sakai,puramshetty/sakai,hackbuteer59/sakai,buckett/sakai-gitflow,kwedoff1/sakai,udayg/sakai,kingmook/sakai,conder/sakai,kingmook/sakai,pushyamig/sakai,udayg/sakai,zqian/sakai,willkara/sakai,wfuedu/sakai,whumph/sakai,noondaysun/sakai,liubo404/sakai,conder/sakai,frasese/sakai,pushyamig/sakai,hackbuteer59/sakai,surya-janani/sakai,wfuedu/sakai,hackbuteer59/sakai,zqian/sakai,tl-its-umich-edu/sakai,clhedrick/sakai,clhedrick/sakai,puramshetty/sakai,puramshetty/sakai,colczr/sakai,ouit0408/sakai,zqian/sakai,pushyamig/sakai,duke-compsci290-spring2016/sakai,frasese/sakai,bzhouduke123/sakai,hackbuteer59/sakai,pushyamig/sakai,surya-janani/sakai,liubo404/sakai,clhedrick/sakai | /*******************************************************************************
* $URL$
* $Id$
* **********************************************************************************
*
* Copyright (c) 2006, 2007, 2008 Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.
*
******************************************************************************/
package org.sakaiproject.citation.impl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeSet;
import java.util.Vector;
import java.net.URLEncoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osid.repository.Asset;
import org.osid.repository.Part;
import org.osid.repository.PartIterator;
import org.osid.repository.Record;
import org.osid.repository.RecordIterator;
import org.osid.repository.RepositoryException;
import org.sakaiproject.citation.api.ActiveSearch;
import org.sakaiproject.citation.api.Citation;
import org.sakaiproject.citation.api.CitationCollection;
import org.sakaiproject.citation.api.CitationIterator;
import org.sakaiproject.citation.api.CitationService;
import org.sakaiproject.citation.api.ConfigurationService;
import org.sakaiproject.citation.api.Schema;
import org.sakaiproject.citation.api.Schema.Field;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.content.api.ContentEntity;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.InteractionAction;
import org.sakaiproject.content.api.ResourceType;
import org.sakaiproject.content.api.ResourceTypeRegistry;
import org.sakaiproject.content.api.ResourceToolAction;
import org.sakaiproject.content.api.ServiceLevelAction;
import org.sakaiproject.content.api.ResourceToolAction.ActionType;
import org.sakaiproject.content.util.BaseInteractionAction;
import org.sakaiproject.content.util.BaseResourceAction;
import org.sakaiproject.content.util.BasicSiteSelectableResourceType;
//import org.sakaiproject.content.util.BaseResourceAction.Localizer;
import org.sakaiproject.content.util.BaseServiceLevelAction;
import org.sakaiproject.content.util.BasicResourceType;
//import org.sakaiproject.content.util.BasicResourceType.Localizer;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.entity.api.HttpAccess;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.OverQuotaException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.ServerOverloadException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.id.cover.IdManager;
import org.sakaiproject.javax.Filter;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.StringUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
*
*/
public abstract class BaseCitationService implements CitationService
{
protected boolean attemptToMatchSchema = false;
protected static final List<String> AUTHOR_AS_KEY = new Vector<String>();
static
{
AUTHOR_AS_KEY.add( CitationCollection.SORT_BY_AUTHOR );
AUTHOR_AS_KEY.add( CitationCollection.SORT_BY_YEAR );
AUTHOR_AS_KEY.add( CitationCollection.SORT_BY_TITLE );
AUTHOR_AS_KEY.add( CitationCollection.SORT_BY_UUID );
};
protected static final List<String> YEAR_AS_KEY = new Vector<String>();
static
{
YEAR_AS_KEY.add( CitationCollection.SORT_BY_YEAR );
YEAR_AS_KEY.add( CitationCollection.SORT_BY_AUTHOR );
YEAR_AS_KEY.add( CitationCollection.SORT_BY_TITLE );
YEAR_AS_KEY.add( CitationCollection.SORT_BY_UUID );
};
protected static final List<String> TITLE_AS_KEY = new Vector<String>();
static
{
TITLE_AS_KEY.add( CitationCollection.SORT_BY_TITLE );
TITLE_AS_KEY.add( CitationCollection.SORT_BY_AUTHOR );
TITLE_AS_KEY.add( CitationCollection.SORT_BY_YEAR );
TITLE_AS_KEY.add( CitationCollection.SORT_BY_UUID );
};
public static final Map<String, String> GS_TAGS = new Hashtable<String, String>();
static
{
//GS_TAGS.put("rft_val_fmt", "genre");
GS_TAGS.put("rft.title", "title");
GS_TAGS.put("rft.atitle", "title");
GS_TAGS.put("rft.jtitle", "atitle");
GS_TAGS.put("rft.btitle", "atitle");
GS_TAGS.put("rft.aulast", "au");
GS_TAGS.put("rft.aufirst", "au");
GS_TAGS.put("rft.au", "au");
GS_TAGS.put("rft.pub", "publisher");
GS_TAGS.put("rft.volume", "volume");
GS_TAGS.put("rft.issue", "issue");
GS_TAGS.put("rft.pages", "pages");
GS_TAGS.put("rft.date", "date");
GS_TAGS.put("rft.issn", "id");
GS_TAGS.put("rft.isbn", "id");
}
/**
*
*/
public class BasicCitation implements Citation
{
/* for OpenUrl creation */
protected final static String OPENURL_VERSION = "Z39.88-2004";
protected final static String OPENURL_CONTEXT_FORMAT = "info:ofi/fmt:kev:mtx:ctx";
protected final static String OPENURL_JOURNAL_FORMAT = "info:ofi/fmt:kev:mtx:journal";
protected final static String OPENURL_BOOK_FORMAT = "info:ofi/fmt:kev:mtx:book";
protected Map m_citationProperties = null;
protected Map m_urls;
protected String m_citationUrl = null;
protected String m_fullTextUrl = null;
protected String m_id = null;
protected String m_imageUrl = null;
protected Schema m_schema;
protected String m_searchSourceUrl = null;
protected Integer m_serialNumber = null;
protected boolean m_temporary = false;
protected boolean m_isAdded = false;
protected String m_preferredUrl;
/**
* Constructs a temporary citation.
*/
protected BasicCitation()
{
m_serialNumber = nextSerialNumber();
m_temporary = true;
m_citationProperties = new Hashtable();
m_urls = new Hashtable();
setType(CitationService.UNKNOWN_TYPE);
}
/**
* Constructs a temporary citation based on an asset.
*
* @param asset
*/
protected BasicCitation(Asset asset)
{
m_serialNumber = nextSerialNumber();
m_temporary = true;
m_citationProperties = new Hashtable();
m_urls = new Hashtable();
boolean unknownSchema = true;
String preferredUrl = null;
String title = null;
Set validProperties = getValidPropertyNames();
Set multivalued = getMultivalued();
String description;
// assetId = asset.getId().getIdString();
try
{
title = asset.getDisplayName();
if (title != null)
{
m_citationProperties.put(Schema.TITLE, title);
}
description = asset.getDescription();
if (description != null)
{
m_citationProperties.put("abstract", description);
}
RecordIterator rit = asset.getRecords();
try
{
while (rit.hasNextRecord())
{
Record record;
try
{
record = rit.nextRecord();
preferredUrl = null;
try
{
PartIterator pit = record.getParts();
try
{
while (pit.hasNextPart())
{
try
{
Part part = pit.nextPart();
String type = part.getPartStructure().getType()
.getKeyword();
if (type == null)
{
// continue;
}
else if (validProperties.contains(type))
{
if (multivalued.contains(type))
{
List values = (List) m_citationProperties
.get(type);
if (values == null)
{
values = new Vector();
m_citationProperties.put(type, values);
}
values.add(part.getValue());
}
else
{
m_citationProperties.put(type, part.getValue());
}
}
/*
* This type isn't described by the schema. Is
* it a preferred (title link) URL?
*/
else if (type.equals("preferredUrl"))
{
preferredUrl = (String) part.getValue();
}
else if (type.equals("type"))
{
if (m_schema == null
|| m_schema.getIdentifier().equals(
"unknown"))
{
if (getSynonyms("article").contains(
part.getValue().toString()
.toLowerCase()))
{
m_schema = BaseCitationService.this
.getSchema("article");
unknownSchema = false;
}
else if (getSynonyms("book").contains(
part.getValue().toString()
.toLowerCase()))
{
m_schema = BaseCitationService.this
.getSchema("book");
unknownSchema = false;
}
else if (getSynonyms("chapter").contains(
part.getValue().toString()
.toLowerCase()))
{
m_schema = BaseCitationService.this
.getSchema("chapter");
unknownSchema = false;
}
else if (getSynonyms("report").contains(
part.getValue().toString()
.toLowerCase()))
{
m_schema = BaseCitationService.this
.getSchema("report");
unknownSchema = false;
}
else
{
m_schema = BaseCitationService.this
.getSchema("unknown");
unknownSchema = true;
}
}
List values = (List) m_citationProperties.get(type);
if (values == null)
{
values = new Vector();
m_citationProperties.put(type, values);
}
values.add(part.getValue());
}
else
{
}
}
catch (RepositoryException e)
{
M_log.warn("BasicCitation(" + asset + ") ", e);
}
}
}
catch (RepositoryException e)
{
M_log.warn("BasicCitation(" + asset + ") ", e);
}
}
catch (RepositoryException e1)
{
M_log.warn("BasicCitation(" + asset + ") ", e1);
}
}
catch (RepositoryException e2)
{
M_log.warn("BasicCitation(" + asset + ") ", e2);
}
}
}
catch (RepositoryException e)
{
M_log.warn("BasicCitation(" + asset + ") ", e);
}
}
catch (RepositoryException e)
{
M_log.warn("BasicCitation(" + asset + ") ", e);
}
if(unknownSchema && attemptToMatchSchema)
{
matchSchema();
}
setDefaults();
/*
* Did we find a preferred URL?
*/
if (preferredUrl != null)
{
String id;
/*
* Save the URL without a label (it'll get the default label at
* render-time) and set it as the preferred (title) link
*/
id = addCustomUrl("", preferredUrl);
setPreferredUrl(id);
}
}
/**
*
*/
protected void matchSchema()
{
Map pros = new Hashtable();
Map cons = new Hashtable();
List schemas = getSchemas();
Set fieldNames = this.m_citationProperties.keySet();
Iterator schemaIt = schemas.iterator();
while(schemaIt.hasNext())
{
Schema schema = (Schema) schemaIt.next();
if(schema.getIdentifier().equals("unknown"))
{
continue;
}
pros.put(schema.getIdentifier(), new Counter());
cons.put(schema.getIdentifier(), new Counter());
Iterator fieldIt = fieldNames.iterator();
while(fieldIt.hasNext())
{
String fieldName = (String) fieldIt.next();
Field field = schema.getField(fieldName);
if(field == null)
{
// this indicates that data would be lost.
((Counter) cons.get(schema.getIdentifier())).increment();
}
else
{
// this is evidence that this schema might be best fit.
((Counter) pros.get(schema.getIdentifier())).increment();
}
}
}
// elminate schema that lose data
Iterator consIt = cons.keySet().iterator();
while(consIt.hasNext())
{
String schemaId = (String) consIt.next();
boolean blocked = ((Counter) cons.get(schemaId)).intValue() > 0;
if(blocked)
{
pros.remove(schemaId);
}
}
Iterator prosIt = pros.keySet().iterator();
int bestScore = 0;
String bestMatch = null;
// Nominate "article" as first candidate if it's not blocked
Object article = pros.get("article");
if(article != null)
{
bestScore = ((Counter) article).intValue();
bestMatch = "article";
}
while(prosIt.hasNext())
{
String schemaId = (String) prosIt.next();
int score = ((Counter) pros.get(schemaId)).intValue();
if(score > bestScore)
{
bestScore = score;
bestMatch = schemaId;
}
}
if(bestMatch != null)
{
m_schema = BaseCitationService.this.getSchema(bestMatch);
}
}
/**
* @param other
*/
public BasicCitation(BasicCitation other)
{
m_id = other.m_id;
m_serialNumber = other.m_serialNumber;
m_temporary = other.m_temporary;
m_citationProperties = new Hashtable();
m_urls = new Hashtable();
setSchema(other.m_schema);
copy(other);
}
/**
* Construct a citation not marked as temporary of a particular type.
*
* @param mediatype
*/
public BasicCitation(String mediatype)
{
m_id = IdManager.createUuid();
m_citationProperties = new Hashtable();
m_urls = new Hashtable();
setType(mediatype);
}
public BasicCitation(String citationId, Schema schema)
{
m_id = citationId;
m_citationProperties = new Hashtable();
m_urls = new Hashtable();
setSchema(schema);
}
/**
* Construct a citation not marked as temporary of a particular type
* with a particular id.
*
* @param citationId
* @param mediatype
*/
public BasicCitation(String citationId, String mediatype)
{
m_id = citationId;
m_citationProperties = new Hashtable();
m_urls = new Hashtable();
setType(mediatype);
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#addUrl(java.lang.String,
* java.net.URL)
*/
public String addCustomUrl(String label, String url)
{
UrlWrapper wrapper = new UrlWrapper(label, url);
String id = IdManager.createUuid();
m_urls.put(id, wrapper);
return id;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#addPropertyValue(java.lang.String,
* java.lang.Object)
*/
public void addPropertyValue(String name, Object value)
{
if (this.m_citationProperties == null)
{
this.m_citationProperties = new Hashtable();
}
if (isMultivalued(name))
{
List list = (List) this.m_citationProperties.get(name);
if (list == null)
{
list = new Vector();
this.m_citationProperties.put(name, list);
}
list.add(value);
}
else
{
this.m_citationProperties.put(name, value);
}
}
/**
*
* @param citation
*/
public void copy(Citation citation)
{
BasicCitation other = (BasicCitation) citation;
m_citationUrl = other.m_citationUrl;
m_fullTextUrl = other.m_fullTextUrl;
m_imageUrl = other.m_imageUrl;
m_searchSourceUrl = other.m_searchSourceUrl;
m_preferredUrl = other.m_preferredUrl;
m_schema = other.m_schema;
if (m_citationProperties == null)
{
m_citationProperties = new Hashtable();
}
m_citationProperties.clear();
if (other.m_citationProperties != null)
{
Iterator propIt = other.m_citationProperties.keySet().iterator();
while (propIt.hasNext())
{
String name = (String) propIt.next();
Object obj = other.m_citationProperties.get(name);
if (obj == null)
{
}
else if (obj instanceof List)
{
List list = (List) obj;
List copy = new Vector();
Iterator valueIt = list.iterator();
while (valueIt.hasNext())
{
Object val = valueIt.next();
copy.add(val);
}
this.m_citationProperties.put(name, copy);
}
else if (obj instanceof String)
{
this.m_citationProperties.put(name, obj);
}
else
{
M_log.debug("BasicCitation copy constructor: property is not String or List: "
+ name + " (" + obj.getClass().getName() + ") == " + obj);
this.m_citationProperties.put(name, obj);
}
}
}
if (m_urls == null)
{
m_urls = new Hashtable();
}
m_urls.clear();
if (other.m_urls != null)
{
Iterator urlIt = other.m_urls.keySet().iterator();
while (urlIt.hasNext())
{
String id = (String) urlIt.next();
UrlWrapper wrapper = (UrlWrapper) other.m_urls.get(id);
// Do not want to addCustomUrl because that assigns a new, unique id to the customUrl.
// This causes problems when we try to reference the preferredUrl by its id - it was
// created and set in the 'other' citation
//addCustomUrl(wrapper.getLabel(), wrapper.getUrl());
// instead, we store the customUrl along with it's originial id -- since this citation
// is a copy of 'other', there should be no harm in doing this
m_urls.put(id, wrapper);
}
}
}
/*
* Simple helpers to export RIS items
* prefix will most often be empty, and is used to offer an "internal label"
* for stuff that gets shoved into the Notes (N1) field because there isn't
* a dedicated field (e.g., Rights)
*
* Outputs XX - value
* or
* XX - prefix: value
*/
public void exportRisField(String rislabel, String value, StringBuilder buffer, String prefix)
{
// Get rid of the newlines and spaces
value = value.replaceAll("\n", " ");
rislabel = rislabel.trim();
// Adjust the prefix to have a colon-space afterwards, if there *is* a prefix
if (prefix != null && !prefix.trim().equals(""))
{
prefix = prefix + ": ";
}
// Export it only if there's a value, or if it's an ER tag (which is by design empty)
if (value != null && !value.trim().equals("") || rislabel.equals("ER"))
{
buffer.append(rislabel + RIS_DELIM + prefix + value + "\n");
}
}
/*
* Again, without the prefix
*/
public void exportRisField(String rislabel, String value, StringBuilder buffer)
{
exportRisField(rislabel, value, buffer, "");
}
/*
* If the value is a list, iterate over it and recursively call exportRISField
*
*/
public void exportRisField(String rislabel, List propvalues, StringBuilder buffer, String prefix)
{
Iterator propvaliter = propvalues.iterator();
while (propvaliter.hasNext())
{
exportRisField(rislabel, propvaliter.next(), buffer, prefix);
}
}
/*
* And again, to do the dispatch
*/
public void exportRisField(String rislabel, Object val, StringBuilder buffer, String prefix)
{
if (val instanceof List)
{
exportRisField(rislabel, (List) val, buffer, prefix);
} else
{
exportRisField(rislabel, (String) val.toString(), buffer, prefix);
}
}
/*
* And, finally, a dispatcher to deal with items without a prefix
*/
public void exportRisField(String rislabel, Object val, StringBuilder buffer)
{
exportRisField(rislabel, val, buffer, "");
}
/*
*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#exportToRis(java.io.OutputStream)
*/
public void exportRis(StringBuilder buffer) throws IOException
{
// Get the RISType and write a blank line and the TY tag
String type = "article";
if (m_schema != null)
{
type = m_schema.getIdentifier();
}
String ristype = (String) m_RISType.get(type);
if (ristype == null)
{
ristype = (String) m_RISType.get("article");
}
exportRisField("TY", ristype, buffer);
// Cycle through all the properties except for those that need
// pre-processing (as listed in m_RISSpecialFields)
// Deal with the "normal" fields
List fields = m_schema.getFields();
Iterator iter = fields.iterator();
while (iter.hasNext())
{
Field field = (Field) iter.next();
String fieldname = field.getIdentifier();
if (m_RISSpecialFields.contains(fieldname))
{
continue; // Skip if this is a special field
}
String rislabel = field.getIdentifier(RIS_FORMAT);
if (rislabel != null)
{
exportRisField(rislabel, getCitationProperty(fieldname), buffer);
}
}
// Deal with the speical fields.
/**
* Dates need to be of the formt YYYY/MM/DD/other, including the
* slashes even if the data is empty. Hence, we'll mostly be
* producing YYYY// for date formats
*/
// TODO: deal with real dates. Right now, just year
exportRisField("Y1", getCitationProperty(Schema.YEAR) + "//", buffer);
// Other stuff goes into the note field -- including the note
// itself of course.
Iterator specIter = m_RISNoteFields.entrySet().iterator();
while (specIter.hasNext())
{
Map.Entry entry = (Map.Entry) specIter.next();
String fieldname = (String) entry.getKey();
String prefix = (String) entry.getValue();
exportRisField("N1", getCitationProperty(fieldname), buffer, prefix);
}
/**
* Deal with URLs.
*/
Iterator urlIDs = this.getCustomUrlIds().iterator();
while (urlIDs.hasNext())
{
String id = urlIDs.next().toString();
try
{
String url = this.getCustomUrl(id);
String urlLabel = this.getCustomUrlLabel(id);
exportRisField("UR", url, buffer); // URL
exportRisField("NT", url, buffer, urlLabel); // Note
}
catch (IdUnusedException e)
{
// do nothing
}
}
// Write out the end-of-record identifier and an extra newline
exportRisField("ER", "", buffer);
buffer.append("\n");
}
/* (non-Javadoc)
* @see org.sakaiproject.citation.api.Citation#getCitationProperties()
*/
public Map getCitationProperties()
{
if (m_citationProperties == null)
{
m_citationProperties = new Hashtable();
}
return m_citationProperties;
}
/* (non-Javadoc)
* @see org.sakaiproject.citation.api.Citation#getCitationProperty(java.lang.String)
*/
public Object getCitationProperty(String name)
{
if (m_citationProperties == null)
{
m_citationProperties = new Hashtable();
}
Object value = m_citationProperties.get(name);
if (value == null)
{
if (isMultivalued(name))
{
value = new Vector();
((List) value).add("");
}
else
{
value = "";
}
}
return value;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getAuthor()
*/
public String getCreator()
{
List creatorList = null;
Object creatorObj = m_citationProperties.get(Schema.CREATOR);
if (creatorObj == null)
{
creatorList = new Vector();
m_citationProperties.put(Schema.CREATOR, creatorList);
}
else if (creatorObj instanceof List)
{
creatorList = (List) creatorObj;
}
else if (creatorObj instanceof String)
{
creatorList = new Vector();
creatorList.add(creatorObj);
m_citationProperties.put(Schema.CREATOR, creatorList);
}
String creators = "";
int count = 0;
Iterator it = creatorList.iterator();
while (it.hasNext())
{
String creator = (String) it.next();
if (it.hasNext() && count > 0)
{
creators += "; " + creator;
}
else if (it.hasNext())
{
creators += creator;
}
else if (count > 1)
{
creators += "; and " + creator;
}
else if (count > 0)
{
creators += " and " + creator;
}
else
{
creators += creator;
}
count++;
}
if (!creators.trim().equals("") && !creators.trim().endsWith("."))
{
creators = creators.trim() + ". ";
}
return creators;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getUrl(java.lang.String)
*/
public String getCustomUrl(String id) throws IdUnusedException
{
UrlWrapper wrapper = (UrlWrapper) m_urls.get(id);
if (wrapper == null)
{
throw new IdUnusedException(id);
}
return wrapper.getUrl();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getUrlIds()
*/
public List getCustomUrlIds()
{
List rv = new Vector();
if (!m_urls.isEmpty())
{
rv.addAll(m_urls.keySet());
}
return rv;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getUrlLabel(java.lang.String)
*/
public String getCustomUrlLabel(String id) throws IdUnusedException
{
UrlWrapper wrapper = (UrlWrapper) m_urls.get(id);
if (wrapper == null)
{
throw new IdUnusedException(id);
}
return wrapper.getLabel();
}
public String getYear()
{
String yearDate = (String) getCitationProperty(Schema.YEAR);
return yearDate;
}
public String getDisplayName()
{
String displayName = (String) getCitationProperty(Schema.TITLE);
if (displayName == null || displayName.trim() == "")
{
displayName = "untitled";
setCitationProperty(Schema.TITLE, "untitled");
}
displayName = displayName.trim();
if (displayName.length() > 0 && !displayName.endsWith(".") && !displayName.endsWith("?") && !displayName.endsWith("!") && !displayName.endsWith(","))
{
displayName += ".";
}
return new String(displayName);
}
/**
* Get the primary URL for this resource
*
* Normally, this is an OpenURL created from citation properties, but if
* either the Repository OSID or the user has designated a preferred URL,
* we'll use it instead.
*
* @return The primary URL (null if none available)
*/
public String getPrimaryUrl()
{
String url;
/*
* Stop now if we haven't set up any Citation properties
*/
if (m_citationProperties == null)
{
return null;
}
/*
* Custom URL?
*/
if (hasPreferredUrl())
{
String id = getPreferredUrlId();
try
{
return getCustomUrl(id);
}
catch (IdUnusedException exception)
{
M_log.warn("No matching URL for ID: "
+ id
+ ", returning an OpenURL");
}
}
/*
* Use an OpenURL
*/
return getOpenurl();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getFirstAuthor()
*/
public String getFirstAuthor()
{
String firstAuthor = null;
List authors = (List) this.m_citationProperties.get(Schema.CREATOR);
if (authors != null && !authors.isEmpty())
{
firstAuthor = (String) authors.get(0);
}
if (firstAuthor != null)
{
firstAuthor = firstAuthor.trim();
}
return firstAuthor;
}
public String getId()
{
if (isTemporary())
{
return m_serialNumber.toString();
}
return m_id;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getOpenurl()
*/
public String getOpenurl()
{
// check citationProperties
if (m_citationProperties == null)
{
// citation properties do not exist as yet - no OpenUrl
return null;
}
String openUrlParams = getOpenurlParameters();
// return the URL-encoded string
return m_configService.getSiteConfigOpenUrlResolverAddress() + openUrlParams;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getOpenurlParameters()
*/
public String getOpenurlParameters()
{
// check citationProperties
if (m_citationProperties == null)
{
// citation properties do not exist as yet - no OpenUrl
return "";
}
// default to journal
boolean journalOpenUrlType = true;
String referentValueFormat = OPENURL_JOURNAL_FORMAT;
// check to see whether we should construct a journal OpenUrl
// (includes types: article, report, unknown)
// or a book OpenUrl (includes types: book, chapter)
// String type = (String) m_citationProperties.get("type");
String type = "article";
if (m_schema != null)
{
type = m_schema.getIdentifier();
}
if (type != null && !type.trim().equals(""))
{
if (type.equals("article") || type.equals("report") || type.equals("unknown"))
{
journalOpenUrlType = true;
referentValueFormat = OPENURL_JOURNAL_FORMAT;
}
else
{
journalOpenUrlType = false;
referentValueFormat = OPENURL_BOOK_FORMAT;
}
}
// start building the OpenUrl
StringBuilder openUrl = null;
try
{
openUrl = new StringBuilder();
openUrl.append("?url_ver=" + URLEncoder.encode(OPENURL_VERSION, "utf8")
+ "&url_ctx_fmt=" + URLEncoder.encode(OPENURL_CONTEXT_FORMAT, "utf8")
+ "&rft_val_fmt=" + URLEncoder.encode(referentValueFormat, "utf8"));
// flag articles
if (journalOpenUrlType)
{
openUrl.append("&rft.genre=article");
}
// get first author
String author = getFirstAuthor();
// get first author's last/first name
if (author != null)
{
String aulast;
StringBuilder aufirst = new StringBuilder();
String[] authorNames = author.split(",");
if (authorNames.length == 2)
{
aulast = authorNames[0].trim();
aufirst.append(authorNames[1].trim());
}
else
{
authorNames = author.split("\\s");
aulast = authorNames[authorNames.length - 1].trim();
for (int i = 0; i < authorNames.length - 1; i++)
{
aufirst.append(authorNames[i] + " ");
}
if (aufirst.length() > 0)
{
aufirst.deleteCharAt( aufirst.length() - 1 );
}
}
// append to the openUrl
openUrl.append("&rft.aulast=" + URLEncoder.encode(aulast,"utf8"));
if (!aufirst.toString().trim().equals(""))
{
openUrl.append("&rft.aufirst=" + URLEncoder.encode(aufirst.toString().
trim(), "utf8"));
}
}
// append any other authors to the openUrl
java.util.List authors = (java.util.List) m_citationProperties.get(Schema.CREATOR);
if (authors != null && !authors.isEmpty() && authors.size() > 1)
{
for (int i = 1; i < authors.size(); i++)
{
openUrl.append("&rft.au=" + URLEncoder.encode((String) authors.get(i),
"utf8"));
}
}
// titles
String title = (String) m_citationProperties.get( Schema.TITLE );
if( title != null )
{
if( journalOpenUrlType )
{
// article title
openUrl.append("&rft.atitle=" + URLEncoder.encode(title.trim(), "utf8"));
}
else
{
// book title
openUrl.append("&rft.btitle=" + URLEncoder.encode(title.trim(), "utf8"));
}
}
else
{
// want to 'borrow' a title from another field if possible
String sourceTitle = (String) m_citationProperties.get(Schema.SOURCE_TITLE);
if (sourceTitle != null && !sourceTitle.trim().equals(""))
{
openUrl.append("&rft.atitle=" + URLEncoder.encode(sourceTitle, "utf8"));
}
// could add other else ifs for fields to borrow from...
}
// journal title or book title
String sourceTitle = (String) m_citationProperties.get(Schema.SOURCE_TITLE);
if (sourceTitle != null && !sourceTitle.trim().equals(""))
{
if (journalOpenUrlType)
{
openUrl.append("&rft.jtitle=" + URLEncoder.encode(sourceTitle, "utf8"));
}
else
{
openUrl.append("&rft.btitle=" + URLEncoder.encode(sourceTitle, "utf8"));
}
}
// date [ YYYY-MM-DD | YYYY-MM | YYYY ] - need filtering TODO
// -- perhaps do another regular expressions scan...
// currently just using the year
String year = (String) m_citationProperties.get(Schema.YEAR);
if (year != null && !year.trim().equals(""))
{
openUrl.append("&rft.date=" + URLEncoder.encode(year, "utf8"));
}
// volume (edition)
if (journalOpenUrlType)
{
String volume = (String) m_citationProperties.get(Schema.VOLUME);
if (volume != null && !volume.trim().equals(""))
{
openUrl.append("&rft.volume=" + URLEncoder.encode(volume, "utf8"));
}
}
else
{
String edition = (String) m_citationProperties.get("edition");
if (edition != null && !edition.trim().equals(""))
{
openUrl.append("&rft.edition=" + URLEncoder.encode(edition, "utf8"));
}
}
// issue (place)
// (pub)
if (journalOpenUrlType)
{
String issue = (String) m_citationProperties.get(Schema.ISSUE);
if (issue != null && !issue.trim().equals(""))
{
openUrl.append("&rft.issue=" + URLEncoder.encode(issue, "utf8"));
}
}
else
{
String pub = (String) m_citationProperties.get("pub");
if (pub != null && !pub.trim().equals(""))
{
openUrl.append("&rft.pub=" + URLEncoder.encode(pub, "utf8"));
}
String place = (String) m_citationProperties.get("place");
if (place != null && !place.trim().equals(""))
{
openUrl.append("&rft.place=" + URLEncoder.encode(place, "utf8"));
}
}
// spage
String spage = (String) m_citationProperties.get("startPage");
if (spage != null && !spage.trim().equals(""))
{
openUrl.append("&rft.spage=" + URLEncoder.encode(spage, "utf8"));
}
// epage
String epage = (String) m_citationProperties.get("endPage");
if (epage != null && !epage.trim().equals(""))
{
openUrl.append("&rft.epage=" + URLEncoder.encode(epage, "utf8"));
}
// pages
String pages = (String) m_citationProperties.get(Schema.PAGES);
if (pages != null && !pages.trim().equals(""))
{
openUrl.append("&rft.pages=" + URLEncoder.encode(pages, "utf8"));
}
// issn (isbn)
String isn = (String) m_citationProperties.get(Schema.ISN);
if (isn != null && !isn.trim().equals(""))
{
if (journalOpenUrlType)
{
openUrl.append("&rft.issn=" + URLEncoder.encode(isn, "utf8"));
}
else
{
openUrl.append("&rft.isbn=" + URLEncoder.encode(isn, "utf8"));
}
}
}
catch( UnsupportedEncodingException uee )
{
M_log.warn( "getOpenurlParameters -- unsupported encoding argument: utf8" );
}
// genre needs some further work... TODO
return openUrl.toString();
}
public Schema getSchema()
{
return m_schema;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getSource()
*/
public String getSource()
{
String place = (String) getCitationProperty("publicationLocation");
String publisher = (String) getCitationProperty(Schema.PUBLISHER);
String sourceTitle = (String) getCitationProperty(Schema.SOURCE_TITLE);
String year = (String) getCitationProperty(Schema.YEAR);
String volume = (String) getCitationProperty(Schema.VOLUME);
String issue = (String) getCitationProperty(Schema.ISSUE);
String pages = (String) getCitationProperty(Schema.PAGES);
String startPage = (String) getCitationProperty("startPage");
String endPage = (String) getCitationProperty("endPage");
if (pages == null || pages.trim().equals(""))
{
pages = null;
if (startPage != null && ! startPage.trim().equals(""))
{
pages = startPage.trim();
if (endPage != null && ! endPage.trim().equals(""))
{
pages += "-" + endPage;
}
}
}
String source = "";
String schemaId = "unknown";
if (m_schema != null)
{
schemaId = m_schema.getIdentifier();
}
if ("book".equals(schemaId) || "report".equals(schemaId))
{
if (place != null && !place.trim().equals(""))
{
source += place;
}
if (publisher != null && !publisher.trim().equals(""))
{
if (source.length() > 0)
{
source = source.trim() + ": ";
}
source += publisher;
}
if (year != null && ! year.trim().equals(""))
{
if (source.length() > 0)
{
source = source.trim() + ", ";
}
source += year;
}
}
else if ("article".equals(schemaId))
{
if (sourceTitle != null && !sourceTitle.trim().equals(""))
{
source += sourceTitle;
if (volume != null && !volume.trim().equals(""))
{
source += ", " + volume;
if (issue != null && !issue.trim().equals(""))
{
source += "(" + issue + ") ";
}
}
}
if(year != null && ! year.trim().equals(""))
{
source += " " + year;
}
if(source != null && source.length() > 1)
{
source = source.trim();
if(!source.endsWith(".") && !source.endsWith("?") && !source.endsWith("!") && !source.endsWith(","))
{
source += ". ";
}
}
if (pages != null && !pages.trim().equals(""))
{
source += pages;
}
if(source != null && source.length() > 1)
{
source = source.trim();
if(!source.endsWith(".") && !source.endsWith("?") && !source.endsWith("!") && !source.endsWith(","))
{
source += ". ";
}
}
}
else if ("chapter".equals(schemaId))
{
if (sourceTitle != null && !sourceTitle.trim().equals(""))
{
source += "In " + sourceTitle;
if (pages == null)
{
if (startPage != null && !startPage.trim().equals(""))
{
source = source.trim() + ", " + startPage;
if (endPage != null && !endPage.trim().equals(""))
{
source = source.trim() + "-" + endPage;
}
}
}
else
{
source = source.trim() + ", " + pages;
}
if (publisher != null && !publisher.trim().equals(""))
{
if (place != null && !place.trim().equals(""))
{
source += place + ": ";
}
source += publisher;
if (year != null && ! year.trim().equals(""))
{
source += ", " + year;
}
}
else if (year != null && ! year.trim().equals(""))
{
source += " " + year;
}
}
}
else
{
if (sourceTitle != null && ! sourceTitle.trim().equals(""))
{
source += sourceTitle;
if (volume != null && ! volume.trim().equals(""))
{
source += ", " + volume;
if (issue != null && !issue.trim().equals(""))
{
source += "(" + issue + ") ";
}
}
if (pages == null)
{
if (startPage != null && !startPage.trim().equals(""))
{
source += startPage;
if (endPage != null && !endPage.trim().equals(""))
{
source += "-" + endPage;
}
}
}
else
{
if (source.length() > 0)
{
source += ". ";
}
source += pages + ". ";
}
}
else if (publisher != null && ! publisher.trim().equals(""))
{
if (place != null && ! place.trim().equals(""))
{
source += place + ": ";
}
source += publisher;
if (year != null && ! year.trim().equals(""))
{
source += ", " + year;
}
}
}
if (source.length() > 1 && !source.endsWith(".") && !source.endsWith("?") && !source.endsWith("!") && !source.endsWith(","))
{
source = source.trim() + ". ";
}
if( source.trim().endsWith( ".." ) )
{
source = source.substring( 0, source.length()-2 );
}
return source;
}
public String getAbstract() {
if ( m_citationProperties != null && m_citationProperties.get( "abstract" ) != null )
{
return m_citationProperties.get("abstract").toString().trim();
}
else
{
return null;
}
}
public String getSubjectString() {
Object subjects = getCitationProperty( "subject" );
if ( subjects instanceof List )
{
List subjectList = ( List ) subjects;
ListIterator subjectListIterator = subjectList.listIterator();
StringBuilder subjectStringBuf = new StringBuilder();
while ( subjectListIterator.hasNext() )
{
subjectStringBuf.append( ((String)subjectListIterator.next()).trim() + ", " );
}
String subjectString = subjectStringBuf.substring( 0, subjectStringBuf.length() - 2 );
if ( subjectString.equals("") )
{
return null;
}
else
{
return subjectString;
}
}
else
{
return null;
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#hasUrls()
*/
public boolean hasCustomUrls()
{
return m_urls != null && !m_urls.isEmpty();
}
public boolean hasPropertyValue(String fieldId)
{
boolean hasPropertyValue = m_citationProperties.containsKey(fieldId);
Object val = m_citationProperties.get(fieldId);
if (hasPropertyValue && val != null)
{
if (val instanceof List)
{
List list = (List) val;
hasPropertyValue = !list.isEmpty();
}
}
return hasPropertyValue;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#importFromRis(java.io.InputStream)
*/
public void importFromRis(InputStream ris) throws IOException
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#importFromRisList(java.util.List)
*/
public boolean importFromRisList(List risImportList)
{
Log logger = LogFactory.getLog(BasicCitation.class);
String currentLine = null; // The active line being parsed from the list (e.g. "TY - BOOK")
String RIScode = null; // The RIS Code (e.g. "TY" for "TY - BOOK")
String RISvalue = null; // The RIS Value (e.g. "BOOK" for "TY - BOOK")
Schema schema = null; // The Citations Helper Schema to use based on the TY RIS field
String schemaName = null; // The name/string of the schema used to lookup the schema
List Fields = null; // This holds the mapped fields for a particular Schema
Field tempField = null; // This holds the current field being evaluated while iterating through
// Fields
Iterator iter = null; // The iterator used to boogie through the Schema Fields
boolean status = true; // Used to maintain/exit the tag lookup while loop
String[] RIScodes = null; // This holds the RISCodes valid for a given schema
String urlId = null; // Used to set the preferred URL
logger.debug("importFromRisList: In importFromRisList. List size is " + risImportList.size());
// process loop that iterates list size many times
for(int i=0; i< risImportList.size(); i++)
{
// get current RIS line and trim off the spaces
currentLine = (String) risImportList.get(i);
currentLine = currentLine.trim();
logger.debug("importFromRisList: currentLine = " + currentLine);
// If the RIS line is less than 4, it isn't really a valid line. Set some default values
// that we know won't be processed for this line.
if (currentLine.length() < 4)
{
RIScode = "";
RISvalue = "";
}
else
{
// get the RIS code
RIScode = currentLine.substring(0, 2);
logger.debug("importFromRisList: substr code = " + RIScode);
// If the RIS line is of the right minimum length, get the RIS value.
if (currentLine.length() >= 7)
RISvalue = currentLine.substring(6);
else // Just set the value to some default value
RISvalue = "";
logger.debug("importFromRisList: substr value = " + RISvalue);
}
// Trim the value
RISvalue = RISvalue.trim();
// The RIS code TY must be the first entry is a RIS record. This sets the Schema type.
if (i == 0)
{
if (! RIScode.equalsIgnoreCase("TY"))
{
logger.debug("importFromRisList: FALSE - 1st entry in RIS must be TY. It isn't it is " + RISvalue);
return false; // TY MUST be the first entry in a RIS citation
}
else // process the schema
{
// RIS resource type forced mappings
if (RISvalue.equalsIgnoreCase("NEWS"))
{
logger.debug("importFromRisList: force mapping NEWS resource type to JOUR");
RISvalue = "JOUR";
}
logger.debug("importFromRisList: size of m_RISTypeInverse = " + m_RISTypeInverse.size());
logger.debug("importFromRisList: RISvalue before schemaName = " + RISvalue);
// get the Schema String name that we need to use for Schema look up from
// the map m_RISTypeInverse using the RISvalue for RIScode "TY";
schemaName = (String) m_RISTypeInverse.get(RISvalue);
// If we couldn't find a valid schema name mapping, set the name to "unknown"
if (schemaName == null)
{
logger.debug("importFromRisList: Unknown Schema Name = " + RISvalue +
". Setting schemeName to 'unknown'");
schemaName = "unknown";
}
logger.debug("importFromRisList: Schema Name = " + schemaName);
// Lookup the Schema based on the Schema string gotten from the reverse map
schema = org.sakaiproject.citation.cover.CitationService.getSchema(schemaName);
logger.debug("importFromRisList: Retrieved Schema Name = " + schema.getIdentifier());
setSchema(schema);
} // end else (else processes RIScode == "TY")
} // end if i == 0
else // process the RIS entries after the first mandatory TY/Schema code
{
if (RIScode.equalsIgnoreCase("ER")) // RIScode "ER" signifies the end of a citation record
{
logger.debug("importFromRisList: Read an ER. End of citation.");
/*
if (((String) getCitationProperty(Schema.TITLE)).length() == 0 &&
((String) getCitationProperty(Schema.SOURCE_TITLE)).length() > 0)
{
logger.debug("importFromRisList: Setting empty TITLE to non empty SOURCE_TITLE");
setCitationProperty(Schema.TITLE, getCitationProperty(Schema.SOURCE_TITLE));
}
*/
return true; // ER signals end of citation
} // end of citation
// Get all the valid RIS fields for this particular schema type
Fields = schema.getFields();
iter = Fields.iterator();
status = true;
while (iter.hasNext() && status == true)
{
tempField = (Field) iter.next();
// We found that this field is a valid field for this schema
RIScodes = tempField.getIdentifierComplex(RIS_FORMAT);
for(int j=0; j< RIScodes.length && status; j++)
{
// logger.debug("importFromRisList: Seeing if I can find a match that has the " +
// "given code '" + RIScode + "' == '" + RIScodes[j] + "' for Schema " + schema.getIdentifier());
// Need Trim in case RIS complex value has a space after the delimiter
// (e.g. "BT, T1" vs "BT","T1")
if (RIScode.equalsIgnoreCase(RIScodes[j]))
{
status = false;
logger.debug("importFromRisList: Found field mapping");
}
} // end for j (loop through complex RIS codes)
} // end while
if (status) // couldn't find the field mapping
{
/* if (schema.getIdentifier().equalsIgnoreCase("book"))
{
if (RIScode.equalsIgnoreCase("T1")) // Refworks
{
setCitationProperty(Schema.TITLE, RISvalue);
logger.debug("importFromRisList: I manually mapped " + RIScode +
" to " + Schema.TITLE);
}
else
logger.debug("importFromRisList: Cannot find Field mapping");
} // end book schema mapping exceptions
else if (schema.getIdentifier().equalsIgnoreCase("article"))
{
if (RIScode.equalsIgnoreCase("AU")) // EndNote
{
setCitationProperty(Schema.CREATOR, RISvalue);
logger.debug("importFromRisList: I manually mapped " + RIScode +
" to " + Schema.CREATOR);
}
else if (RIScode.equalsIgnoreCase("PY")) // EndNote
{
setCitationProperty(Schema.YEAR, RISvalue);
logger.debug("importFromRisList: I manually mapped " + RIScode +
" to " + Schema.YEAR);
}
else if (RIScode.equalsIgnoreCase("TI")) // EndNote
{
setCitationProperty(Schema.TITLE, RISvalue);
logger.debug("importFromRisList: I manually mapped " + RIScode +
" to " + Schema.TITLE);
}
else
logger.debug("importFromRisList: Cannot find Field mapping");
} // end article schema mapping exceptions
else if (schema.getIdentifier().equalsIgnoreCase("unknown"))
{
if (RIScode.equalsIgnoreCase("AU")) // EndNote
{
setCitationProperty(Schema.CREATOR, RISvalue);
logger.debug("importFromRisList: I manually mapped " + RIScode +
" to " + Schema.CREATOR);
}
else
logger.debug("importFromRisList: Cannot find Field mapping");
} // end unknown schema mapping exceptions
else
*/ logger.debug("importFromRisList: Cannot find field mapping for RIScode " +
RIScode + " for Schema = " + schema);
} // end if status (field not found)
else // ! status. We found a field in the Schema
{
logger.debug("importFromRisList: Field mapping is " + tempField.getIdentifier() +
" => " + RISvalue);
if (RIScode.equalsIgnoreCase("UR"))
{
urlId = addCustomUrl("", RISvalue);
setPreferredUrl(urlId);
logger.debug("importFromRisList: set preferred url to " + urlId + " which is " + RISvalue);
}
else
{
// We found the mapping in the previous while loop. Set the citation property
setCitationProperty(tempField.getIdentifier(), RISvalue);
}
} // end else which means we found the mapping
} // end else of i == 0
} // end for i
// if we got here, the record wasn't properly formatted with an "ER" record (or other issues).
logger.debug("importFromRisList: FALSE - End of Input. Citation not added.");
return false;
} // end ImportFromRisList
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#isAdded()
*/
public boolean isAdded()
{
return this.m_isAdded;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#isMultivalued(java.lang.String)
*/
public boolean isMultivalued(String fieldId)
{
boolean isMultivalued = false;
if (m_schema != null)
{
Field field = m_schema.getField(fieldId);
if (field != null)
{
isMultivalued = field.isMultivalued();
}
}
return isMultivalued;
}
/**
* @return
*/
public boolean isTemporary()
{
return m_temporary;
}
public List listCitationProperties()
{
if (m_citationProperties == null)
{
m_citationProperties = new Hashtable();
}
return new Vector(m_citationProperties.keySet());
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#setAdded()
*/
public void setAdded(boolean added)
{
this.m_isAdded = added;
}
public void setCitationProperty(String name, Object value)
{
if (m_citationProperties == null)
{
m_citationProperties = new Hashtable();
}
if (isMultivalued(name))
{
List list = (List) m_citationProperties.get(name);
if (list == null)
{
list = new Vector();
m_citationProperties.put(name, list);
}
if (value != null)
{
list.add(value);
}
}
else
{
if (value == null)
{
m_citationProperties.remove(name);
}
else
{
m_citationProperties.put(name, value);
}
}
}
protected void setDefaults()
{
if (m_schema != null)
{
List fields = m_schema.getFields();
Iterator it = fields.iterator();
while (it.hasNext())
{
Field field = (Field) it.next();
if (field.isRequired())
{
Object value = field.getDefaultValue();
if (value == null)
{
// do nothing -- there's no value to set
}
else if (field.isMultivalued())
{
List current_values = (List) this.getCitationProperty(field
.getIdentifier());
if (current_values.isEmpty())
{
this.addPropertyValue(field.getIdentifier(), value);
}
}
else if (this.getCitationProperty(field.getIdentifier()) == null)
{
setCitationProperty(field.getIdentifier(), value);
}
}
}
}
}
public void setDisplayName(String name)
{
if (name == null || name.trim().equals(""))
{
setCitationProperty(Schema.TITLE, "untitled");
}
else
{
setCitationProperty(Schema.TITLE, name);
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#setSchema(org.sakaiproject.citation.api.Schema)
*/
public void setSchema(Schema schema)
{
this.m_schema = schema;
setDefaults();
}
protected void setType(String mediatype)
{
Schema schema = m_storage.getSchema(mediatype);
if (schema == null)
{
schema = m_storage.getSchema(CitationService.UNKNOWN_TYPE);
}
setSchema(schema);
}
public String toString()
{
return "BasicCitation: " + this.m_id;
}
public void updateCitationProperty(String name, List values)
{
// what if "name" is not a valid field in the schema??
if (m_citationProperties == null)
{
m_citationProperties = new Hashtable();
}
if (isMultivalued(name))
{
List list = (List) m_citationProperties.get(name);
if (list == null)
{
list = new Vector();
m_citationProperties.put(name, list);
}
list.clear();
if (values != null)
{
list.addAll(values);
}
}
else
{
if (values == null || values.isEmpty())
{
m_citationProperties.remove(name);
}
else
{
m_citationProperties.put(name, values.get(0));
}
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#updateUrl(java.lang.String,
* java.lang.String, java.net.URL)
*/
public void updateCustomUrl(String urlid, String label, String url)
{
UrlWrapper wrapper = new UrlWrapper(label, url);
m_urls.put(urlid, wrapper);
}
/* (non-Javadoc)
* @see org.sakaiproject.citation.api.Citation#getSaveUrl()
*/
public String getSaveUrl(String collectionId)
{
SessionManager sessionManager = (SessionManager) ComponentManager.get("org.sakaiproject.tool.api.SessionManager");
String sessionId = sessionManager.getCurrentSession().getId();
String url = m_serverConfigurationService.getServerUrl() + "/savecite/" + collectionId + "?sakai.session=" + sessionId;
String genre = this.getSchema().getIdentifier();
url += "&genre=" + genre;
String openUrlParams = this.getOpenurlParameters();
String[] params = openUrlParams.split("&");
for(int i = 0; i < params.length; i++)
{
String[] parts = params[i].split("=");
String key = GS_TAGS.get(parts[0]);
if(key != null)
{
url += "&" + key + "=" + parts[1];
}
}
return url;
}
public String getPreferredUrlId()
{
return this.m_preferredUrl;
}
public boolean hasPreferredUrl()
{
return this.m_preferredUrl != null;
}
public void setPreferredUrl(String urlid)
{
if(urlid == null)
{
this.m_preferredUrl = null;
}
else if(this.m_urls.containsKey(urlid))
{
this.m_preferredUrl = urlid;
}
}
} // BaseCitationService.BasicCitation
/**
*
*/
public class BasicCitationCollection implements CitationCollection
{
protected final Comparator DEFAULT_COMPARATOR = new BasicCitationCollection.TitleComparator(true);
public class MultipleKeyComparator implements Comparator
{
protected List<String> m_keys = new Vector<String>();
protected boolean m_ascending = true;
public MultipleKeyComparator(List<String> keys, boolean ascending)
{
m_keys.addAll(keys);
}
public MultipleKeyComparator( MultipleKeyComparator mkc )
{
this.m_keys = mkc.m_keys;
this.m_ascending = mkc.m_ascending;
}
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(Object arg0, Object arg1)
{
int rv = 0;
if (!(arg0 instanceof String) || !(arg1 instanceof String))
{
throw new ClassCastException();
}
Object obj0 = m_citations.get(arg0);
Object obj1 = m_citations.get(arg1);
if (!(obj0 instanceof Citation) || !(obj1 instanceof Citation))
{
throw new ClassCastException();
}
Citation cit0 = (Citation) obj0;
Citation cit1 = (Citation) obj1;
Iterator keyIt = m_keys.iterator();
while(rv == 0 && keyIt.hasNext())
{
String key = (String) keyIt.next();
if(CitationCollection.SORT_BY_TITLE.equalsIgnoreCase(key))
{
/*
String title0 = cit0.getDisplayName().toLowerCase();
String title1 = cit1.getDisplayName().toLowerCase();
*/
String title0 = ((String)cit0.getCitationProperty( Schema.TITLE )).toLowerCase();;
String title1 = ((String)cit1.getCitationProperty( Schema.TITLE )).toLowerCase();;
if (title0 == null)
{
title0 = "";
}
if (title1 == null)
{
title1 = "";
}
rv = m_ascending ? title0.compareTo(title1) : title1.compareTo(title0);
}
else if(CitationCollection.SORT_BY_AUTHOR.equalsIgnoreCase(key))
{
String author0 = cit0.getCreator().toLowerCase();
String author1 = cit1.getCreator().toLowerCase();
if (author0 == null)
{
author0 = "";
}
if (author1 == null)
{
author1 = "";
}
rv = m_ascending ? author0.compareTo(author1) : author1.compareTo(author0);
}
else if(CitationCollection.SORT_BY_YEAR.equalsIgnoreCase(key))
{
String year0 = cit0.getYear();
String year1 = cit1.getYear();
if (year0 == null)
{
year0 = "";
}
if (year1 == null)
{
year1 = "";
}
rv = m_ascending ? year0.compareTo(year1) : year1.compareTo(year0);
}
else if( CitationCollection.SORT_BY_UUID.equalsIgnoreCase( key ) )
{
// not considering m_ascending for ids because they are random alpha-numeric strings
rv = cit0.getId().compareTo(cit1.getId());
}
}
return rv;
}
public void addKey(String key)
{
m_keys.add(key);
}
}
public class AuthorComparator extends MultipleKeyComparator
{
/**
* @param ascending
*/
public AuthorComparator(boolean ascending)
{
super(AUTHOR_AS_KEY, ascending);
}
}
public class YearComparator extends MultipleKeyComparator
{
/**
* @param ascending
*/
public YearComparator(boolean ascending)
{
super(YEAR_AS_KEY, ascending);
}
} // end class DateComparator
public class BasicIterator implements CitationIterator
{
protected List listOfKeys;
// This is the firstItem on a given rendered page
protected int firstItem;
// This is the item where next() returns and increments. At
// the start of rendering a given page nextItem = firstItem and
// increments until lastItem
protected int nextItem;
// This is the lastitem on a given rendered page
protected int lastItem;
public BasicIterator()
{
checkForUpdates();
this.listOfKeys = new Vector(m_order);
this.firstItem = 0;
setIndexes();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#getPageSize()
*/
public int getPageSize()
{
// TODO Auto-generated method stub
return m_pageSize;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#hasNext()
*/
public boolean hasNext()
{
boolean hasNext = false;
if (m_ascending)
{
hasNext = this.nextItem < this.lastItem
&& this.nextItem < this.listOfKeys.size();
}
else
{
hasNext = this.nextItem > this.lastItem && this.nextItem > 0;
}
return hasNext;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#hasNextPage()
*/
public boolean hasNextPage()
{
boolean hasNextPage = false;
if (m_ascending)
hasNextPage = this.firstItem + m_pageSize < this.listOfKeys.size();
else
hasNextPage = this.firstItem - m_pageSize >= 0;
return hasNextPage;
// return m_pageSize * (startPage + 1) < this.listOfKeys.size();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#hasPreviousPage()
*/
public boolean hasPreviousPage()
{
boolean hasPreviousPage = false;
if (m_ascending)
hasPreviousPage = this.firstItem - m_pageSize >= 0;
else
hasPreviousPage = this.firstItem + m_pageSize < this.listOfKeys.size();
return hasPreviousPage;
// return this.startPage > 0;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#next()
*/
public Object next()
{
Object item = null;
if (m_ascending)
{
if (this.nextItem >= this.lastItem || this.nextItem >= listOfKeys.size())
{
throw new NoSuchElementException();
}
item = m_citations.get(listOfKeys.get(this.nextItem++));
}
else
{
if (this.nextItem <= this.lastItem || this.nextItem <= 0)
{
throw new NoSuchElementException();
}
item = m_citations.get(listOfKeys.get(this.nextItem--));
}
return item;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#nextPage()
*/
public void nextPage()
{
if (m_ascending)
{
this.firstItem = this.firstItem + m_pageSize;
}
else
{
this.firstItem = this.firstItem - m_pageSize;
}
setIndexes();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#previousPage()
*/
public void previousPage()
{
if (m_ascending)
{
this.firstItem = this.firstItem - m_pageSize;
}
else
{
this.firstItem = this.firstItem + m_pageSize;
}
setIndexes();
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#remove()
*/
public void remove()
{
throw new UnsupportedOperationException();
}
protected void setIndexes()
{
this.nextItem = this.firstItem;
if (m_ascending)
{
this.lastItem = Math.min(this.listOfKeys.size(), this.nextItem + m_pageSize);
}
else
{
this.lastItem = Math.max(0, this.nextItem - m_pageSize);
}
} // end setIndexes()
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#setSort(java.util.Comparator)
*/
public void setOrder(Comparator comparator)
{
m_comparator = comparator;
if (comparator == null)
{
}
else
{
Collections.sort(this.listOfKeys, m_comparator);
}
this.firstItem = 0;
setIndexes();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#setPageSize(int)
*/
public void setPageSize(int size)
{
if (size > 0)
{
// So that resizing the page at the start of a list (say 11-20)
// with a new size of 20... gives us 1-20 not 11-30
if (this.lastItem <= size)
{
this.firstItem = 0;
}
this.lastItem = this.firstItem + size;
if (this.lastItem >= this.listOfKeys.size())
this.lastItem = this.listOfKeys.size() - 1;
m_pageSize = size;
setIndexes();
} // end if size > 0
} // end setPageSize()
public int getStart()
{
return this.firstItem;
}
public int getEnd()
{
return this.lastItem;
}
public void setStart(int i)
{
if (i >= 0 && i < this.listOfKeys.size())
{
this.firstItem = i;
setIndexes();
}
} // end setStart()
} // end class BasicIterator
public class TitleComparator extends MultipleKeyComparator
{
/**
* @param ascending
*/
public TitleComparator(boolean ascending)
{
super(TITLE_AS_KEY, ascending);
}
}
protected Map<String, Citation> m_citations = new Hashtable<String, Citation>();
protected Comparator m_comparator = DEFAULT_COMPARATOR;
protected String m_sortOrder;
protected SortedSet<String> m_order;
protected int m_pageSize = DEFAULT_PAGE_SIZE;
protected String m_description;
protected String m_id;
protected String m_title;
protected boolean m_temporary = false;
protected Integer m_serialNumber;
protected ActiveSearch m_mySearch;
protected boolean m_ascending = true;
protected long m_mostRecentUpdate = 0L;
public BasicCitationCollection()
{
m_id = IdManager.createUuid();
}
/**
* @param b
*/
public BasicCitationCollection(boolean temporary)
{
m_order = new TreeSet<String>(m_comparator);
m_temporary = temporary;
if (temporary)
{
m_serialNumber = nextSerialNumber();
}
else
{
m_id = IdManager.createUuid();
}
}
public BasicCitationCollection(Map attributes, List citations)
{
m_id = IdManager.createUuid();
m_order = new TreeSet<String>(m_comparator);
if (citations != null)
{
Iterator citationIt = citations.iterator();
while (citationIt.hasNext())
{
Citation citation = (Citation) citationIt.next();
m_citations.put(citation.getId(), citation);
m_order.add(citation.getId());
}
}
}
/**
* @param collectionId
*/
public BasicCitationCollection(String collectionId)
{
m_id = collectionId;
m_order = new TreeSet(m_comparator);
}
public void add(Citation citation)
{
//checkForUpdates();
if (!this.m_citations.keySet().contains(citation.getId()))
{
this.m_citations.put(citation.getId(), citation);
}
if(!this.m_order.contains(citation.getId()))
{
this.m_order.add(citation.getId());
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#addAll(org.sakaiproject.citation.api.CitationCollection)
*/
public void addAll(CitationCollection other)
{
checkForUpdates();
if(this.m_order == null)
{
this.m_order = new TreeSet<String>();
}
for(String key : ((BasicCitationCollection) other).m_order )
{
try
{
Citation citation = other.getCitation(key);
this.add(citation);
}
catch (IdUnusedException e)
{
M_log.debug("BasicCitationCollection.addAll citationId (" + key
+ ") in m_order but not in m_citations; collectionId: "
+ other.getId());
}
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#clear()
*/
public void clear()
{
this.m_order.clear();
this.m_citations.clear();
}
public boolean contains(Citation citation)
{
checkForUpdates();
return this.m_citations.containsKey(citation.getId());
}
protected void copy(BasicCitationCollection other)
{
checkForUpdates();
this.m_ascending = other.m_ascending;
/*
* Get new instance of comparator
*/
if( other.m_comparator instanceof MultipleKeyComparator )
{
this.m_comparator = new MultipleKeyComparator( (MultipleKeyComparator)other.m_comparator );
}
else
{
// default to title, ascending
this.m_comparator = new MultipleKeyComparator( TITLE_AS_KEY, true );
}
set(other);
}
public void exportRis(StringBuilder buffer, List<String> citationIds) throws IOException
{
checkForUpdates();
// output "header" info to buffer
// Iterate over citations and output to ostream
for( String citationId : citationIds )
{
Citation citation = (Citation) this.m_citations.get(citationId);
if (citation != null)
{
citation.exportRis(buffer);
}
}
}
/**
* Compute an alternate root for a reference, based on the root
* property.
*
* @param rootProperty
* The property name.
* @return The alternate root, or "" if there is none.
*/
protected String getAlternateReferenceRoot(String rootProperty)
{
// null means don't do this
if (rootProperty == null || rootProperty.trim().equals(""))
{
return "";
}
// make sure it start with a separator and does not end with one
if (!rootProperty.startsWith(Entity.SEPARATOR))
{
rootProperty = Entity.SEPARATOR + rootProperty;
}
if (rootProperty.endsWith(Entity.SEPARATOR))
{
rootProperty = rootProperty
.substring(0, rootProperty.length() - SEPARATOR.length());
}
return rootProperty;
}
public Citation getCitation(String citationId) throws IdUnusedException
{
checkForUpdates();
Citation citation = (Citation) m_citations.get(citationId);
if (citation == null)
{
throw new IdUnusedException(citationId);
}
return citation;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#getCitations()
*/
public List getCitations()
{
checkForUpdates();
List citations = new Vector();
if (m_citations == null)
{
m_citations = new Hashtable<String, Citation>();
}
if(m_order == null)
{
m_order = new TreeSet<String>();
}
Iterator keyIt = this.m_order.iterator();
while (keyIt.hasNext())
{
String key = (String) keyIt.next();
Object citation = this.m_citations.get(key);
if (citation != null)
{
citations.add(citation);
}
}
return citations;
}
public CitationCollection getCitations(Comparator c)
{
checkForUpdates();
// TODO Auto-generated method stub
return null;
}
public CitationCollection getCitations(Comparator c, Filter f)
{
checkForUpdates();
// TODO Auto-generated method stub
return null;
}
public CitationCollection getCitations(Filter f)
{
checkForUpdates();
// TODO Auto-generated method stub
return null;
}
public CitationCollection getCitations(Map properties)
{
checkForUpdates();
// TODO Auto-generated method stub
return null;
}
// public Citation remove(int index)
// {
// // TODO
// return null;
// }
//
// public Citation remove(Map properties)
// {
// // TODO Auto-generated method stub
// return null;
// }
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#getDescription()
*/
public String getDescription()
{
checkForUpdates();
return m_description;
}
public String getId()
{
return this.m_id;
}
public ResourceProperties getProperties()
{
// TODO Auto-generated method stub
return null;
}
// public void sort(Comparator c)
// {
// // TODO Auto-generated method stub
//
// }
public String getReference()
{
return getReference(null);
}
public String getReference(String rootProperty)
{
return m_relativeAccessPoint + getAlternateReferenceRoot(rootProperty)
+ Entity.SEPARATOR + getId();
}
/* (non-Javadoc)
* @see org.sakaiproject.citation.api.CitationCollection#getSaveUrl()
*/
public String getSort()
{
if (m_sortOrder == null)
m_sortOrder = this.SORT_BY_DEFAULT_ORDER;
return m_sortOrder;
}
/* (non-Javadoc)
* @see org.sakaiproject.citation.api.CitationCollection#getSaveUrl()
*/
public String getSaveUrl()
{
String url = m_serverConfigurationService.getServerUrl() + "/savecite/" + this.getId() + "/";
return url;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#getTitle()
*/
public String getTitle()
{
checkForUpdates();
return m_title;
}
public String getUrl()
{
return getUrl(null);
}
public String getUrl(String rootProperty)
{
return getAccessPoint(false) + getAlternateReferenceRoot(rootProperty)
+ Entity.SEPARATOR + getId();
}
public boolean isEmpty()
{
checkForUpdates();
return this.m_citations.isEmpty();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#iterator()
*/
public CitationIterator iterator()
{
checkForUpdates();
return new BasicIterator();
}
// public Iterator iterator()
// {
// // TODO Auto-generated method stub
// return null;
// }
//
//
// public int lastIndexOf(Citation item)
// {
// // TODO Auto-generated method stub
// return 0;
// }
//
// public boolean move(int from, int to)
// {
// // TODO Auto-generated method stub
// return false;
// }
//
// public boolean moveToBack(int index)
// {
// // TODO Auto-generated method stub
// return false;
// }
//
// public boolean moveToFront(int index)
// {
// // TODO Auto-generated method stub
// return false;
// }
//
public boolean remove(Citation item)
{
checkForUpdates();
boolean success = true;
this.m_order.remove(item.getId());
Object obj = this.m_citations.remove(item.getId());
if (obj == null)
{
success = false;
}
return success;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#saveCitation(org.sakaiproject.citation.api.Citation)
*/
public void saveCitation(Citation citation)
{
//checkForUpdates();
// m_storage.saveCitation(citation);
save(citation);
}
/**
*
* @param comparator
*/
public void setSort(Comparator comparator)
{
checkForUpdates();
this.m_comparator = comparator;
SortedSet oldSet = this.m_order;
this.m_order = new TreeSet<String>(this.m_comparator);
this.m_order.addAll(oldSet);
}
/**
*
* @param sortBy
* @param ascending
*/
public void setSort(String sortBy, boolean ascending)
{
m_ascending = ascending;
String status = "UNSET";
if (sortBy == null || sortBy.equalsIgnoreCase(SORT_BY_DEFAULT_ORDER))
{
this.m_comparator = null;
}
else if (sortBy.equalsIgnoreCase(SORT_BY_AUTHOR))
{
this.m_comparator = new AuthorComparator(ascending);
status = "AUTHOR SET";
}
else if (sortBy.equalsIgnoreCase(SORT_BY_TITLE))
{
this.m_comparator = new TitleComparator(ascending);
status = "TITLE SET";
}
else if (sortBy.equalsIgnoreCase(SORT_BY_YEAR))
{
this.m_comparator = new YearComparator(ascending);
status = "YEAR SET";
}
if (this.m_comparator != null)
{
this.m_sortOrder = sortBy;
SortedSet oldSet = this.m_order;
this.m_order = new TreeSet<String>(this.m_comparator);
this.m_order.addAll(oldSet);
}
} // end setSort(String, boolean)
public int size()
{
checkForUpdates();
return m_order.size();
}
public String toString()
{
return "BasicCitationCollection: " + this.m_id;
}
public Element toXml(Document doc, Stack stack)
{
// TODO Auto-generated method stub
return null;
}
protected void checkForUpdates()
{
if(this.m_mostRecentUpdate < m_storage.mostRecentUpdate(this.m_id))
{
CitationCollection edit = m_storage.getCollection(this.m_id);
if (edit == null)
{
}
else
{
set((BasicCitationCollection) edit);
}
}
}
/**
* copy
* @param other
*/
protected void set(BasicCitationCollection other)
{
this.m_description = other.m_description;
// this.m_comparator = other.m_comparator;
this.m_serialNumber = other.m_serialNumber;
this.m_pageSize = other.m_pageSize;
this.m_temporary = other.m_temporary;
this.m_title = other.m_title;
if(this.m_citations == null)
{
this.m_citations = new Hashtable<String, Citation>();
}
this.m_citations.clear();
if(this.m_order == null)
{
this.m_order = new TreeSet<String>(this.m_comparator);
}
this.m_order.clear();
Iterator it = other.m_citations.keySet().iterator();
while(it.hasNext())
{
String citationId = (String) it.next();
BasicCitation oldCitation = (BasicCitation) other.m_citations.get(citationId);
BasicCitation newCitation = new BasicCitation();
try
{
newCitation.copy(oldCitation);
newCitation.m_id = oldCitation.m_id;
newCitation.m_temporary = false;
this.saveCitation(newCitation);
this.add(newCitation);
}
catch(Exception e)
{
M_log.warn("copy(" + oldCitation.getId() + ") ==> " + newCitation.getId(), e);
}
}
this.m_mostRecentUpdate = TimeService.newTime().getTime();
}
} // BaseCitationService.BasicCitationCollection
/**
*
*/
public class BasicField implements Field
{
protected Object defaultValue;
protected String description;
protected String identifier;
protected String label;
protected int maxCardinality;
protected int minCardinality;
protected String namespace;
protected int order;
protected boolean required;
protected String valueType;
protected Map identifiers;
protected boolean isEditable;
// delimiter used to separate Field identifiers
public final static String DELIMITER = ",";
/**
* @param field
*/
public BasicField(Field other)
{
this.identifier = other.getIdentifier();
this.valueType = other.getValueType();
this.required = other.isRequired();
this.minCardinality = other.getMinCardinality();
this.maxCardinality = other.getMaxCardinality();
this.namespace = other.getNamespaceAbbreviation();
this.description = other.getDescription();
this.identifiers = new Hashtable();
this.isEditable = other.isEditable();
if (other instanceof BasicField)
{
this.order = ((BasicField) other).getOrder();
Iterator it = ((BasicField) other).identifiers.keySet().iterator();
while (it.hasNext())
{
String format = (String) it.next();
this.identifiers.put(format, ((BasicField) other).identifiers.get(format));
}
}
}
public BasicField(String identifier, String valueType, boolean isEditable,
boolean required, int minCardinality, int maxCardinality)
{
this.identifier = identifier;
this.valueType = valueType;
this.required = required;
this.minCardinality = minCardinality;
this.maxCardinality = maxCardinality;
this.namespace = "";
this.label = "";
this.description = "";
this.order = 0;
this.identifiers = new Hashtable();
this.isEditable = true;
}
public Object getDefaultValue()
{
return defaultValue;
}
public String getDescription()
{
return this.description;
}
public String getIdentifier()
{
return identifier;
}
public String getIdentifier(String format)
{
String tempString = null;
String[] tokens = null;
tempString = (String) this.identifiers.get(format);
if (tempString == null)
tempString = "";
tempString = tempString.trim();
// Is this a compound/delimited value?
if (tempString.indexOf(DELIMITER) != -1)
{
// split the string based on the delimiter
tokens = tempString.split(DELIMITER);
// use the first delimiter as the identifier
tempString = tokens[0];
} // end getIdentifier
return tempString;
}
public String[] getIdentifierComplex(String format)
{
String tempString = null;
String[] tokens = null;
tempString = (String) this.identifiers.get(format);
if (tempString == null)
tempString = "";
tempString = tempString.trim();
// Is this a compound/delimited value?
if (tempString.indexOf(DELIMITER) != -1)
{
// split the string based on the delimiter
tokens = tempString.split(DELIMITER);
}
else // it's a simple value
{
tokens = new String[1];
tokens[0] = tempString;
}
return tokens;
} // end getComplexIdentifers
public String getLabel()
{
return this.label;
}
public int getMaxCardinality()
{
return maxCardinality;
}
public int getMinCardinality()
{
return minCardinality;
}
public String getNamespaceAbbreviation()
{
return this.namespace;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Schema.Field#getOrder()
*/
public int getOrder()
{
return order;
}
public String getValueType()
{
return valueType;
}
public boolean isEditable()
{
return isEditable;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Schema.Field#isMultivalued()
*/
public boolean isMultivalued()
{
return this.maxCardinality > 1;
}
public boolean isRequired()
{
return required;
}
public void setDefaultValue(Object value)
{
this.defaultValue = value;
}
/**
* @param label
*/
public void setDescription(String description)
{
this.description = description;
}
public void setEditable(boolean isEditable)
{
this.isEditable = isEditable;
}
public void setIdentifier(String format, String identifier)
{
this.identifiers.put(format, identifier);
}
/**
* @param label
*/
public void setLabel(String label)
{
this.label = label;
}
/**
* @param maxCardinality
* The maxCardinality to set.
*/
public void setMaxCardinality(int maxCardinality)
{
this.maxCardinality = maxCardinality;
}
/**
* @param minCardinality
* The minCardinality to set.
*/
public void setMinCardinality(int minCardinality)
{
this.minCardinality = minCardinality;
}
public void setNamespaceAbbreviation(String namespace)
{
this.namespace = namespace;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Schema.Field#setOrder(int)
*/
public void setOrder(int order)
{
this.order = order;
}
/**
* @param required
* The required to set.
*/
public void setRequired(boolean required)
{
this.required = required;
}
/**
* @param valueType
* The valueType to set.
*/
public void setValueType(String valueType)
{
this.valueType = valueType;
}
public String toString()
{
return "BasicField: " + this.identifier;
}
}
/**
*
*/
protected class BasicSchema implements Schema
{
protected String defaultNamespace;
protected List fields;
protected String identifier;
protected Map index;
protected Map namespaces;
protected Map identifiers;
/**
*
*/
public BasicSchema()
{
this.fields = new Vector();
this.index = new Hashtable();
this.identifiers = new Hashtable();
}
/**
* @param schema
*/
public BasicSchema(Schema other)
{
this.identifier = other.getIdentifier();
this.defaultNamespace = other.getNamespaceAbbrev();
namespaces = new Hashtable();
List nsAbbrevs = other.getNamespaceAbbreviations();
if (nsAbbrevs != null)
{
Iterator nsIt = nsAbbrevs.iterator();
while (nsIt.hasNext())
{
String nsAbbrev = (String) nsIt.next();
String ns = other.getNamespaceUri(nsAbbrev);
namespaces.put(nsAbbrev, ns);
}
}
this.identifiers = new Hashtable();
if (other instanceof BasicSchema)
{
Iterator it = ((BasicSchema) other).identifiers.keySet().iterator();
while (it.hasNext())
{
String format = (String) it.next();
this.identifiers.put(format, ((BasicSchema) other).identifiers.get(format));
}
}
this.fields = new Vector();
this.index = new Hashtable();
List fields = other.getFields();
Iterator fieldIt = fields.iterator();
while (fieldIt.hasNext())
{
Field field = (Field) fieldIt.next();
this.fields.add(new BasicField(field));
index.put(field.getIdentifier(), field);
}
}
/**
* @param schemaId
*/
public BasicSchema(String schemaId)
{
this.identifier = schemaId;
this.fields = new Vector();
this.index = new Hashtable();
this.identifiers = new Hashtable();
}
public void addAlternativeIdentifier(String fieldId, String altFormat, String altIdentifier)
{
BasicField field = (BasicField) this.index.get(fieldId);
if (field != null)
{
field.setIdentifier(altFormat, altIdentifier);
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Schema#addField(org.sakaiproject.citation.api.Schema.Field)
*/
public void addField(Field field)
{
this.index.put(field.getIdentifier(), field);
this.fields.add(field);
}
/**
* @param order
* @param field
*/
public void addField(int order, Field field)
{
fields.add(order, field);
index.put(identifier, field);
}
public BasicField addField(String identifier, String valueType, boolean isEditable,
boolean required, int minCardinality, int maxCardinality)
{
if (fields == null)
{
fields = new Vector();
}
if (index == null)
{
index = new Hashtable();
}
BasicField field = new BasicField(identifier, valueType, isEditable, required,
minCardinality, maxCardinality);
fields.add(field);
index.put(identifier, field);
return field;
}
public BasicField addOptionalField(String identifier, String valueType, int minCardinality,
int maxCardinality)
{
return addField(identifier, valueType, true, false, minCardinality, maxCardinality);
}
public BasicField addRequiredField(String identifier, String valueType, int minCardinality,
int maxCardinality)
{
return addField(identifier, valueType, true, true, minCardinality, maxCardinality);
}
public Field getField(int index)
{
if (fields == null)
{
fields = new Vector();
}
return (Field) fields.get(index);
}
public Field getField(String name)
{
if (index == null)
{
index = new Hashtable();
}
return (Field) index.get(name);
}
public List getFields()
{
if (fields == null)
{
fields = new Vector();
}
return fields;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Schema#getIdentifier()
*/
public String getIdentifier()
{
return this.identifier;
}
public String getIdentifier(String format)
{
return (String) this.identifiers.get(format);
}
public String getNamespaceAbbrev()
{
return defaultNamespace;
}
public List getNamespaceAbbreviations()
{
if (namespaces == null)
{
namespaces = new Hashtable();
}
Collection keys = namespaces.keySet();
List rv = new Vector();
if (keys != null)
{
rv.addAll(keys);
}
return rv;
}
public String getNamespaceUri(String abbrev)
{
if (namespaces == null)
{
namespaces = new Hashtable();
}
return (String) namespaces.get(abbrev);
}
public List getRequiredFields()
{
if (fields == null)
{
fields = new Vector();
}
List required = new Vector();
Iterator it = fields.iterator();
while (it.hasNext())
{
Field field = (Field) it.next();
if (field.isRequired())
{
required.add(field);
}
}
return required;
}
/**
* @param identifier
*/
public void setIdentifier(String identifier)
{
this.identifier = identifier;
}
public void setIdentifier(String format, String identifier)
{
this.identifiers.put(format, identifier);
}
/**
*
*/
public void sortFields()
{
Collections.sort(fields, new Comparator()
{
public int compare(Object arg0, Object arg1)
{
if (arg0 instanceof BasicField && arg1 instanceof BasicField)
{
Integer int0 = new Integer(((BasicField) arg0).getOrder());
Integer int1 = new Integer(((BasicField) arg1).getOrder());
return int0.compareTo(int1);
}
else if (arg0 instanceof Field && arg1 instanceof Field)
{
String lbl0 = ((Field) arg0).getLabel();
String lbl1 = ((Field) arg1).getLabel();
return lbl0.compareTo(lbl1);
}
else
{
throw new ClassCastException(arg0.toString() + " " + arg1.toString());
}
}
});
}
public String toString()
{
return "BasicSchema: " + this.identifier;
}
}
/**
*
*/
protected interface Storage
{
/**
* @param mediatype
* @return
*/
public Citation addCitation(String mediatype);
public CitationCollection addCollection(Map attributes, List citations);
public Schema addSchema(Schema schema);
public boolean checkCitation(String citationId);
public boolean checkCollection(String collectionId);
public boolean checkSchema(String schemaId);
public long mostRecentUpdate(String collectionId);
/**
* Close.
*/
public void close();
public CitationCollection copyAll(String collectionId);
public Citation getCitation(String citationId);
public CitationCollection getCollection(String collectionId);
public Schema getSchema(String schemaId);
public List getSchemas();
/**
* @return
*/
public List listSchemas();
/**
* Open and be ready to read / write.
*/
public void open();
public void putSchemas(Collection schemas);
public void removeCitation(Citation edit);
public void removeCollection(CitationCollection edit);
public void removeSchema(Schema schema);
public void saveCitation(Citation edit);
public void saveCollection(CitationCollection collection);
public void updateSchema(Schema schema);
public void updateSchemas(Collection schemas);
} // interface Storage
/**
*
*/
public class UrlWrapper
{
protected String m_label;
protected String m_url;
/**
* @param label
* @param url
*/
public UrlWrapper(String label, String url)
{
m_label = label;
m_url = url;
}
/**
* @return the label
*/
public String getLabel()
{
return m_label;
}
/**
* @return the url
*/
public String getUrl()
{
return m_url;
}
/**
* @param label
* the label to set
*/
public void setLabel(String label)
{
m_label = label;
}
/**
* @param url
* the url to set
*/
public void setUrl(String url)
{
m_url = url;
}
}
public static ResourceLoader rb;
/** Our logger. */
private static Log M_log = LogFactory.getLog(BaseCitationService.class);
protected static final String PROPERTY_DEFAULTVALUE = "sakai:defaultValue";
protected static final String PROPERTY_DESCRIPTION = "sakai:description";
protected static final String PROPERTY_HAS_ABBREVIATION = "sakai:hasAbbreviation";
protected static final String PROPERTY_HAS_CITATION = "sakai:hasCitation";
protected static final String PROPERTY_HAS_FIELD = "sakai:hasField";
protected static final String PROPERTY_HAS_NAMESPACE = "sakai:hasNamespace";
protected static final String PROPERTY_HAS_ORDER = "sakai:hasOrder";
protected static final String PROPERTY_HAS_SCHEMA = "sakai:hasSchema";
protected static final String PROPERTY_LABEL = "sakai:label";
protected static final String PROPERTY_MAXCARDINALITY = "sakai:maxCardinality";
protected static final String PROPERTY_MINCARDINALITY = "sakai:minCardinality";
protected static final String PROPERTY_NAMESPACE = "sakai:namespace";
protected static final String PROPERTY_REQUIRED = "sakai:required";
protected static final String PROPERTY_VALUETYPE = "sakai:valueType";
public static final String SCHEMA_PREFIX = "schema.";
protected static Integer m_nextSerialNumber;
/*
* RIS MAPPINGS below
*/
protected static final String RIS_DELIM = " - ";
/**
* Set up a mapping of our type to RIS 'TY - ' values
*/
protected static final Map m_RISType = new Hashtable();
protected static final Map m_RISTypeInverse = new Hashtable();
/**
* Which fields map onto the RIS Notes field? Include a prefix for the data,
* if necessary.
*/
protected static final Map m_RISNoteFields = new Hashtable();
/**
* Which fields need special processing for RIS export?
*/
protected static final Set m_RISSpecialFields = new java.util.HashSet();
static
{
m_RISType.put("unknown", "JOUR"); // Default to journal article
m_RISType.put("article", "JOUR");
m_RISType.put("book", "BOOK");
m_RISType.put("chapter", "CHAP");
m_RISType.put("report", "RPRT");
m_RISTypeInverse.put("BOOK", "book");
m_RISTypeInverse.put("CHAP", "chapter");
m_RISTypeInverse.put("JOUR", "article");
m_RISTypeInverse.put("RPRT", "report");
}
static
{
m_RISNoteFields.put("language", "Language: ");
m_RISNoteFields.put("doi", "DOI: ");
m_RISNoteFields.put("rights", "Rights: ");
}
static
{
m_RISSpecialFields.add("date");
m_RISSpecialFields.add("doi");
}
public static String escapeFieldName(String original)
{
if (original == null)
{
return "";
}
original = original.trim();
try
{
// convert the string to bytes in UTF-8
byte[] bytes = original.getBytes("UTF-8");
StringBuilder buf = new StringBuilder();
for (int i = 0; i < bytes.length; i++)
{
byte b = bytes[i];
// escape ascii control characters, ascii high bits, specials
if (Schema.ESCAPE_FIELD_NAME.indexOf((char) b) != -1)
{
buf.append(Schema.ESCAPE_CHAR); // special funky way to
// encode bad URL characters
// - ParameterParser will
// decode it
}
else
{
buf.append((char) b);
}
}
String rv = buf.toString();
return rv;
}
catch (Exception e)
{
M_log.warn("BaseCitationService.escapeFieldName: ", e);
return original;
}
}
/** Dependency: CitationsConfigurationService. */
protected ConfigurationService m_configService = null;
/** Dependency: ServerConfigurationService. */
protected ServerConfigurationService m_serverConfigurationService = null;
/** Dependency: ContentHostingService. */
protected ContentHostingService m_contentHostingService = null;
/** Dependency: EntityManager. */
protected EntityManager m_entityManager = null;
protected String m_defaultSchema;
/** A Storage object for persistent storage. */
protected Storage m_storage = null;
protected String m_relativeAccessPoint;
/**
* Dependency: the ResourceTypeRegistry
*/
protected ResourceTypeRegistry m_resourceTypeRegistry;
/**
* Dependency: inject the ResourceTypeRegistry
* @param registry
*/
public void setResourceTypeRegistry(ResourceTypeRegistry registry)
{
m_resourceTypeRegistry = registry;
}
/**
* @return the ResourceTypeRegistry
*/
public ResourceTypeRegistry getResourceTypeRegistry()
{
return m_resourceTypeRegistry;
}
public static final String PROP_TEMPORARY_CITATION_LIST = "citations.temporary_citation_list";
/**
* Checks permissions to add a CitationList. Returns true if the user
* has permission to add a resource in the collection identified by the
* parameter.
* @param contentCollectionId
* @return
*/
public boolean allowAddCitationList(String contentCollectionId)
{
return m_contentHostingService.allowAddResource(contentCollectionId + "testing");
}
/**
* Checks permission to revise a CitationList, including permissions
* to add, remove or revise citations within the CitationList. Returns
* true if the user has permission to revise the resource identified by
* the parameter. Also returns true if all of these conditions are met:
* (1) the user is the creator of the specified resource, (2) the specified
* resource is a temporary CitationList (as identified by the value of
* the PROP_TEMPORARY_CITATION_LIST property), and (3) the user has
* permission to add resources in the collection containing the
* resource.
* @param contentResourceId
* @return
*/
public boolean allowReviseCitationList(String contentResourceId)
{
boolean allowed = m_contentHostingService.allowUpdateResource(contentResourceId);
if(!allowed)
{
try
{
ResourceProperties props = m_contentHostingService.getProperties(contentResourceId);
String temp_res = props.getProperty(CitationService.PROP_TEMPORARY_CITATION_LIST);
String creator = props.getProperty(ResourceProperties.PROP_CREATOR);
String contentCollectionId = m_contentHostingService.getContainingCollectionId(contentResourceId);
SessionManager sessionManager = (SessionManager) ComponentManager.get("org.sakaiproject.tool.api.SessionManager");
String currentUser = sessionManager.getCurrentSessionUserId();
allowed = this.allowAddCitationList(contentCollectionId) && (temp_res != null) && currentUser.equals(creator);
}
catch(PermissionException e)
{
// do nothing: return false
}
catch (IdUnusedException e)
{
// do nothing: return false
}
}
return allowed;
}
/**
*
* @return
*/
public boolean allowRemoveCitationList(String contentResourceId)
{
boolean allowed = m_contentHostingService.allowUpdateResource(contentResourceId);
if(!allowed)
{
try
{
ResourceProperties props = m_contentHostingService.getProperties(contentResourceId);
String temp_res = props.getProperty(CitationService.PROP_TEMPORARY_CITATION_LIST);
String creator = props.getProperty(ResourceProperties.PROP_CREATOR);
String contentCollectionId = m_contentHostingService.getContainingCollectionId(contentResourceId);
SessionManager sessionManager = (SessionManager) ComponentManager.get("org.sakaiproject.tool.api.SessionManager");
String currentUser = sessionManager.getCurrentSessionUserId();
allowed = this.allowAddCitationList(contentCollectionId) && (temp_res != null) && currentUser.equals(creator);
}
catch(PermissionException e)
{
// do nothing: return false
}
catch (IdUnusedException e)
{
// do nothing: return false
}
}
return allowed;
}
public Citation addCitation(String mediatype)
{
Citation edit = m_storage.addCitation(mediatype);
return edit;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#addCollection()
*/
public CitationCollection addCollection()
{
CitationCollection edit = m_storage.addCollection(null, null);
return edit;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#archive(java.lang.String,
* org.w3c.dom.Document, java.util.Stack, java.lang.String,
* java.util.List)
*/
public String archive(String siteId, Document doc, Stack stack, String archivePath,
List attachments)
{
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#copyAll(java.lang.String)
*/
public CitationCollection copyAll(String collectionId)
{
return m_storage.copyAll(collectionId);
}
/**
* Returns to uninitialized state.
*/
public void destroy()
{
if(m_storage != null)
{
m_storage.close();
m_storage = null;
}
}
/**
* Access the partial URL that forms the root of calendar URLs.
*
* @param relative
* if true, form within the access path only (i.e. starting with
* /content)
* @return the partial URL that forms the root of calendar URLs.
*/
protected String getAccessPoint(boolean relative)
{
return (relative ? "" : m_serverConfigurationService.getAccessUrl())
+ m_relativeAccessPoint;
} // getAccessPoint
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#getCollection(java.lang.String)
*/
public CitationCollection getCollection(String collectionId) throws IdUnusedException
{
CitationCollection edit = m_storage.getCollection(collectionId);
if (edit == null)
{
throw new IdUnusedException(collectionId);
}
return edit;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#getDefaultSchema()
*/
public Schema getDefaultSchema()
{
Schema rv = null;
if (m_defaultSchema != null)
{
rv = m_storage.getSchema(m_defaultSchema);
}
return rv;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getEntity(org.sakaiproject.entity.api.Reference)
*/
public Entity getEntity(Reference ref)
{
Entity entity = null;
if (APPLICATION_ID.equals(ref.getType()))
{
if ( REF_TYPE_EXPORT_RIS_SEL.equals(ref.getSubType()) ||
REF_TYPE_EXPORT_RIS_ALL.equals(ref.getSubType()) )
{
// these entities are citation collections
String id = ref.getId();
if (id == null || id.trim().equals(""))
{
String reference = ref.getReference();
if (reference != null && reference.startsWith(REFERENCE_ROOT))
{
id = reference.substring(REFERENCE_ROOT.length(), reference.length());
}
}
if (id != null && !id.trim().equals(""))
{
entity = m_storage.getCollection(id);
}
}
else if (REF_TYPE_VIEW_LIST.equals(ref.getSubType()))
{
// these entities are actually in /content
String id = ref.getId();
if (id == null || id.trim().equals(""))
{
String reference = ref.getReference();
if (reference.startsWith(REFERENCE_ROOT))
{
reference = reference
.substring(REFERENCE_ROOT.length(), reference.length());
}
if (reference.startsWith(m_contentHostingService.REFERENCE_ROOT))
{
id = reference.substring(m_contentHostingService.REFERENCE_ROOT.length(),
reference.length());
}
}
if (id != null && !id.trim().equals(""))
{
try
{
entity = m_contentHostingService.getResource(id);
}
catch (PermissionException e)
{
M_log.warn("getEntity(" + id + ") ", e);
}
catch (IdUnusedException e)
{
M_log.warn("getEntity(" + id + ") ", e);
}
catch (TypeException e)
{
M_log.warn("getEntity(" + id + ") ", e);
}
}
}
}
// and maybe others are in /citation
return entity;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getEntityAuthzGroups(org.sakaiproject.entity.api.Reference,
* java.lang.String)
*/
public Collection getEntityAuthzGroups(Reference ref, String userId)
{
// entities that are actually in /content use the /content authz groups
// those in /citation are open?
return null;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getEntityDescription(org.sakaiproject.entity.api.Reference)
*/
public String getEntityDescription(Reference ref)
{
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getEntityResourceProperties(org.sakaiproject.entity.api.Reference)
*/
public ResourceProperties getEntityResourceProperties(Reference ref)
{
// if it's a /content item, return its props
// otherwise return null
return null;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getEntityUrl(org.sakaiproject.entity.api.Reference)
*/
public String getEntityUrl(Reference ref)
{
return null;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getHttpAccess()
*/
public HttpAccess getHttpAccess()
{
// if it's a /content item, the access is via CitationListAccessServlet
return new CitationListAccessServlet();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getLabel()
*/
public String getLabel()
{
// TODO Auto-generated method stub
return null;
}
/**
* @return
*/
public Set getMultivalued()
{
Set multivalued = new TreeSet();
Iterator schemaIt = m_storage.getSchemas().iterator();
while (schemaIt.hasNext())
{
Schema schema = (Schema) schemaIt.next();
{
Iterator fieldIt = schema.getFields().iterator();
while (fieldIt.hasNext())
{
Field field = (Field) fieldIt.next();
if (field.getMaxCardinality() > 1)
{
multivalued.add(field.getIdentifier());
}
}
}
}
return multivalued;
}
/**
* @return
*/
public Set getMultivalued(String type)
{
Set multivalued = new TreeSet();
Schema schema = m_storage.getSchema(type);
{
Iterator fieldIt = schema.getFields().iterator();
while (fieldIt.hasNext())
{
Field field = (Field) fieldIt.next();
if (field.getMaxCardinality() > 1)
{
multivalued.add(field.getIdentifier());
}
}
}
return multivalued;
}
public Schema getSchema(String name)
{
Schema schema = m_storage.getSchema(name);
return schema;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#getSchemas()
*/
public List getSchemas()
{
List schemas = new Vector(m_storage.getSchemas());
return schemas;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Schema#getSynonyms(java.lang.String)
*/
protected Set getSynonyms(String mediatype)
{
Set synonyms = new TreeSet();
if (mediatype.equalsIgnoreCase("article"))
{
synonyms.add("article");
synonyms.add("journal article");
synonyms.add("journal");
synonyms.add("periodical");
synonyms.add("newspaper article");
synonyms.add("magazine article");
synonyms.add("editorial");
synonyms.add("peer reviewed article");
synonyms.add("peer reviewed journal article");
synonyms.add("book review");
synonyms.add("review");
synonyms.add("meeting");
synonyms.add("wire feed");
synonyms.add("wire story");
synonyms.add("journal article (cije)");
}
else if (mediatype.equalsIgnoreCase("book"))
{
synonyms.add("book");
synonyms.add("bk");
}
else if (mediatype.equalsIgnoreCase("chapter"))
{
synonyms.add("chapter");
synonyms.add("book chapter");
synonyms.add("book section");
}
else if (mediatype.equalsIgnoreCase("report"))
{
synonyms.add("report");
synonyms.add("editorial material");
synonyms.add("technical report");
synonyms.add("se");
synonyms.add("document (rie)");
}
return synonyms;
}
public Citation getTemporaryCitation()
{
return new BasicCitation();
}
public Citation getTemporaryCitation(Asset asset)
{
return new BasicCitation(asset);
}
public CitationCollection getTemporaryCollection()
{
return new BasicCitationCollection(true);
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#getValidPropertyNames()
*/
public Set getValidPropertyNames()
{
Set names = new TreeSet();
Iterator schemaIt = m_storage.getSchemas().iterator();
while (schemaIt.hasNext())
{
Schema schema = (Schema) schemaIt.next();
{
Iterator fieldIt = schema.getFields().iterator();
while (fieldIt.hasNext())
{
Field field = (Field) fieldIt.next();
names.add(field.getIdentifier());
}
}
}
return names;
} // getValidPropertyNames
public class CitationListCreateAction extends BaseInteractionAction
{
/**
* @param id
* @param actionType
* @param typeId
* @param helperId
* @param requiredPropertyKeys
*/
public CitationListCreateAction(String id, ActionType actionType, String typeId, String helperId, List requiredPropertyKeys)
{
super(id, actionType, typeId, helperId, requiredPropertyKeys);
}
/* (non-Javadoc)
* @see org.sakaiproject.content.util.BaseResourceAction#available(org.sakaiproject.content.api.ContentEntity)
*/
@Override
public boolean available(ContentEntity entity)
{
return super.available(entity);
}
}
/**
*
*
*/
public void init()
{
m_storage = newStorage();
m_nextSerialNumber = new Integer(0);
m_relativeAccessPoint = CitationService.REFERENCE_ROOT;
rb = new ResourceLoader("citations");
//initializeSchemas();
m_defaultSchema = "article";
// register as an entity producer
m_entityManager.registerEntityProducer(this, REFERENCE_ROOT);
if(m_configService.isCitationsEnabledByDefault() ||
m_configService.isAllowSiteBySiteOverride() )
{
registerResourceType();
}
}
/**
*
*/
protected void registerResourceType()
{
ResourceTypeRegistry registry = getResourceTypeRegistry();
List requiredPropertyKeys = new Vector();
requiredPropertyKeys.add(ContentHostingService.PROP_ALTERNATE_REFERENCE);
requiredPropertyKeys.add(ResourceProperties.PROP_CONTENT_TYPE);
BaseInteractionAction createAction = new CitationListCreateAction(ResourceToolAction.CREATE,
ResourceToolAction.ActionType.CREATE,
CitationService.CITATION_LIST_ID,
CitationService.HELPER_ID,
new Vector());
createAction.setLocalizer(
new BaseResourceAction.Localizer()
{
public String getLabel()
{
return rb.getString("action.create");
}
});
BaseInteractionAction reviseAction = new BaseInteractionAction(ResourceToolAction.REVISE_CONTENT,
ResourceToolAction.ActionType.REVISE_CONTENT,
CitationService.CITATION_LIST_ID,
CitationService.HELPER_ID,
new Vector());
reviseAction.setLocalizer(
new BaseResourceAction.Localizer()
{
public String getLabel()
{
return rb.getString("action.revise");
}
});
BaseServiceLevelAction moveAction = new BaseServiceLevelAction(ResourceToolAction.MOVE,
ResourceToolAction.ActionType.MOVE,
CitationService.CITATION_LIST_ID,
true );
BaseServiceLevelAction revisePropsAction = new BaseServiceLevelAction(ResourceToolAction.REVISE_METADATA,
ResourceToolAction.ActionType.REVISE_METADATA,
CitationService.CITATION_LIST_ID,
false );
BasicSiteSelectableResourceType typedef = new BasicSiteSelectableResourceType(CitationService.CITATION_LIST_ID);
typedef.setSizeLabeler(new CitationSizeLabeler());
typedef.setLocalizer(new CitationLocalizer());
typedef.addAction(createAction);
typedef.addAction(reviseAction);
typedef.addAction(new CitationListDeleteAction());
typedef.addAction(new CitationListCopyAction());
typedef.addAction(new CitationListPasteCopyAction());
typedef.addAction(new CitationListPasteMoveAction());
typedef.addAction(new CitationListDuplicateAction());
typedef.addAction(revisePropsAction);
typedef.addAction(moveAction);
typedef.setEnabledByDefault(m_configService.isCitationsEnabledByDefault());
typedef.setIconLocation("sakai/citationlist.gif");
typedef.setHasRightsDialog(false);
registry.register(typedef);
}
/**
*
*/
protected void initializeSchemas()
{
BasicSchema unknown = new BasicSchema();
unknown.setIdentifier(CitationService.UNKNOWN_TYPE);
BasicSchema article = new BasicSchema();
article.setIdentifier("article");
BasicSchema book = new BasicSchema();
book.setIdentifier("book");
BasicSchema chapter = new BasicSchema();
chapter.setIdentifier("chapter");
BasicSchema report = new BasicSchema();
report.setIdentifier("report");
/* schema ordering is different for different types */
/*
* UNKNOWN (GENERIC)
*/
unknown.addField(Schema.CREATOR, Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
unknown.addAlternativeIdentifier(Schema.CREATOR, RIS_FORMAT, "A1");
unknown.addField(Schema.TITLE, Schema.SHORTTEXT, true, true, 1, 1);
unknown.addAlternativeIdentifier(Schema.TITLE, RIS_FORMAT, "T1");
unknown.addField(Schema.YEAR, Schema.NUMBER, true, false, 0, 1);
unknown.addField("date", Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier("date", RIS_FORMAT, "Y1");
unknown.addField(Schema.PUBLISHER, Schema.SHORTTEXT, true, false, 0, 1);
unknown.addAlternativeIdentifier(Schema.PUBLISHER, RIS_FORMAT, "PB");
unknown.addField("publicationLocation", Schema.SHORTTEXT, true, false, 0, 1);
unknown.addAlternativeIdentifier("publicationLocation", RIS_FORMAT, "CY");
unknown.addField(Schema.VOLUME, Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier(Schema.VOLUME, RIS_FORMAT, "VL");
unknown.addField(Schema.ISSUE, Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier(Schema.ISSUE, RIS_FORMAT, "IS");
unknown.addField(Schema.PAGES, Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier(Schema.PAGES, RIS_FORMAT, "SP");
unknown.addField("startPage", Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier("startPage", RIS_FORMAT, "SP");
unknown.addField("endPage", Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier("endPage", RIS_FORMAT, "EP");
unknown.addField("edition", Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier("edition", RIS_FORMAT, "VL");
unknown.addField("editor", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
unknown.addAlternativeIdentifier("editor", RIS_FORMAT, "A3");
unknown.addField(Schema.SOURCE_TITLE, Schema.SHORTTEXT, true, false, 0, 1);
unknown.addAlternativeIdentifier(Schema.SOURCE_TITLE, RIS_FORMAT, "T3");
unknown.addField("Language", Schema.NUMBER, true, false, 0, 1);
unknown.addField("abstract", Schema.LONGTEXT, true, false, 0, 1);
unknown.addAlternativeIdentifier("abstract", RIS_FORMAT, "N2");
unknown.addField("note", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
unknown.addAlternativeIdentifier("note", RIS_FORMAT, "N1");
unknown.addField(Schema.ISN, Schema.SHORTTEXT, true, false, 0, 1);
unknown.addAlternativeIdentifier(Schema.ISN, RIS_FORMAT, "SN");
unknown.addField("subject", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
unknown.addAlternativeIdentifier("subject", RIS_FORMAT, "KW");
unknown.addField("locIdentifier", Schema.SHORTTEXT, true, false, 0, 1);
unknown.addAlternativeIdentifier("locIdentifier", RIS_FORMAT, "M1");
unknown.addField("dateRetrieved", Schema.DATE, false, false, 0, 1);
unknown.addField("openURL", Schema.SHORTTEXT, false, false, 0, 1);
unknown.addField("doi", Schema.NUMBER, true, false, 0, 1);
unknown.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
/*
* ARTICLE
*/
article.addField(Schema.CREATOR, Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
article.addAlternativeIdentifier(Schema.CREATOR, RIS_FORMAT, "A1");
article.addField(Schema.TITLE, Schema.SHORTTEXT, true, true, 1, 1);
article.addAlternativeIdentifier(Schema.TITLE, RIS_FORMAT, "T1");
article.addField(Schema.SOURCE_TITLE, Schema.SHORTTEXT, true, false, 0, 1);
article.addAlternativeIdentifier(Schema.SOURCE_TITLE, RIS_FORMAT, "JF");
article.addField(Schema.YEAR, Schema.NUMBER, true, false, 0, 1);
article.addField("date", Schema.NUMBER, true, false, 0, 1);
article.addAlternativeIdentifier("date", RIS_FORMAT, "Y1");
article.addField(Schema.VOLUME, Schema.NUMBER, true, false, 0, 1);
article.addAlternativeIdentifier(Schema.VOLUME, RIS_FORMAT, "VL");
article.addField(Schema.ISSUE, Schema.NUMBER, true, false, 0, 1);
article.addAlternativeIdentifier(Schema.ISSUE, RIS_FORMAT, "IS");
article.addField(Schema.PAGES, Schema.NUMBER, true, false, 0, 1);
article.addField("startPage", Schema.NUMBER, true, false, 0, 1);
article.addAlternativeIdentifier("startPage", RIS_FORMAT, "SP");
article.addField("endPage", Schema.NUMBER, true, false, 0, 1);
article.addAlternativeIdentifier("endPage", RIS_FORMAT, "EP");
article.addField("abstract", Schema.LONGTEXT, true, false, 0, 1);
article.addAlternativeIdentifier("abstract", RIS_FORMAT, "N2");
article.addField("note", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
article.addAlternativeIdentifier("note", RIS_FORMAT, "N1");
article.addField(Schema.ISN, Schema.SHORTTEXT, true, false, 0, 1);
article.addAlternativeIdentifier(Schema.ISN, RIS_FORMAT, "SN");
article.addField("subject", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
article.addAlternativeIdentifier("subject", RIS_FORMAT, "KW");
article.addField("Language", Schema.NUMBER, true, false, 0, 1);
article.addField("locIdentifier", Schema.SHORTTEXT, true, false, 0, 1);
article.addAlternativeIdentifier("locIdentifier", RIS_FORMAT, "M1");
article.addField("dateRetrieved", Schema.DATE, false, false, 0, 1);
article.addField("openURL", Schema.SHORTTEXT, false, false, 0, 1);
article.addField("doi", Schema.NUMBER, true, false, 0, 1);
article.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
/*
* BOOK
*/
book.addField(Schema.CREATOR, Schema.SHORTTEXT, true, true, 1, Schema.UNLIMITED);
book.addAlternativeIdentifier(Schema.CREATOR, RIS_FORMAT, "A1");
book.addField(Schema.TITLE, Schema.SHORTTEXT, true, true, 1, 1);
book.addAlternativeIdentifier(Schema.TITLE, RIS_FORMAT, "BT");
book.addField(Schema.YEAR, Schema.NUMBER, true, false, 0, 1);
book.addField("date", Schema.NUMBER, true, false, 0, 1);
book.addAlternativeIdentifier("date", RIS_FORMAT, "Y1");
book.addField(Schema.PUBLISHER, Schema.SHORTTEXT, true, false, 0, 1);
book.addAlternativeIdentifier(Schema.PUBLISHER, RIS_FORMAT, "PB");
book.addField("publicationLocation", Schema.SHORTTEXT, true, false, 0, 1);
book.addAlternativeIdentifier("publicationLocation", RIS_FORMAT, "CY");
book.addField("edition", Schema.NUMBER, true, false, 0, 1);
book.addAlternativeIdentifier("edition", RIS_FORMAT, "VL");
book.addField("editor", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
book.addAlternativeIdentifier("editor", RIS_FORMAT, "A3");
book.addField(Schema.SOURCE_TITLE, Schema.SHORTTEXT, true, false, 0, 1);
book.addAlternativeIdentifier(Schema.SOURCE_TITLE, RIS_FORMAT, "T3");
book.addField("abstract", Schema.LONGTEXT, true, false, 0, 1);
book.addAlternativeIdentifier("abstract", RIS_FORMAT, "N2");
book.addField("note", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
book.addAlternativeIdentifier("note", RIS_FORMAT, "N1");
book.addField(Schema.ISN, Schema.SHORTTEXT, true, false, 0, 1);
book.addAlternativeIdentifier(Schema.ISN, RIS_FORMAT, "SN");
book.addField("subject", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
book.addAlternativeIdentifier("subject", RIS_FORMAT, "KW");
book.addField("Language", Schema.NUMBER, true, false, 0, 1);
book.addField("locIdentifier", Schema.SHORTTEXT, true, false, 0, 1);
book.addAlternativeIdentifier("locIdentifier", RIS_FORMAT, "M1");
book.addField("dateRetrieved", Schema.DATE, false, false, 0, 1);
book.addField("openURL", Schema.SHORTTEXT, false, false, 0, 1);
book.addField("doi", Schema.NUMBER, true, false, 0, 1);
book.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
book.addAlternativeIdentifier(Schema.PAGES, RIS_FORMAT, "SP");
/*
* CHAPTER
*/
chapter.addField(Schema.CREATOR, Schema.SHORTTEXT, true, true, 1, Schema.UNLIMITED);
chapter.addAlternativeIdentifier(Schema.CREATOR, RIS_FORMAT, "A1");
chapter.addField(Schema.TITLE, Schema.SHORTTEXT, true, true, 1, 1);
chapter.addAlternativeIdentifier(Schema.TITLE, RIS_FORMAT, "CT");
chapter.addField(Schema.YEAR, Schema.NUMBER, true, false, 0, 1);
chapter.addField("date", Schema.NUMBER, true, false, 0, 1);
chapter.addAlternativeIdentifier("date", RIS_FORMAT, "Y1");
chapter.addField(Schema.PUBLISHER, Schema.SHORTTEXT, true, false, 0, 1);
chapter.addAlternativeIdentifier(Schema.PUBLISHER, RIS_FORMAT, "PB");
chapter.addField("publicationLocation", Schema.SHORTTEXT, true, false, 0, 1);
chapter.addAlternativeIdentifier("publicationLocation", RIS_FORMAT, "CY");
chapter.addField("edition", Schema.NUMBER, true, false, 0, 1);
chapter.addAlternativeIdentifier("edition", RIS_FORMAT, "VL");
chapter.addField("editor", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
chapter.addAlternativeIdentifier("editor", RIS_FORMAT, "ED");
chapter.addField(Schema.SOURCE_TITLE, Schema.SHORTTEXT, true, false, 0, 1);
chapter.addAlternativeIdentifier(Schema.SOURCE_TITLE, RIS_FORMAT, "BT");
chapter.addField(Schema.PAGES, Schema.NUMBER, true, false, 0, 1);
chapter.addAlternativeIdentifier(Schema.PAGES, RIS_FORMAT, "SP");
chapter.addField("startPage", Schema.NUMBER, true, false, 0, 1);
chapter.addAlternativeIdentifier("startPage", RIS_FORMAT, "SP");
chapter.addField("endPage", Schema.NUMBER, true, false, 0, 1);
chapter.addAlternativeIdentifier("endPage", RIS_FORMAT, "EP");
chapter.addField("abstract", Schema.LONGTEXT, true, false, 0, 1);
chapter.addAlternativeIdentifier("abstract", RIS_FORMAT, "N2");
chapter.addField("note", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
chapter.addAlternativeIdentifier("note", RIS_FORMAT, "N1");
chapter.addField(Schema.ISN, Schema.SHORTTEXT, true, false, 0, 1);
chapter.addAlternativeIdentifier(Schema.ISN, RIS_FORMAT, "SN");
chapter.addField("subject", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
chapter.addAlternativeIdentifier("subject", RIS_FORMAT, "KW");
chapter.addField("Language", Schema.NUMBER, true, false, 0, 1);
chapter.addField("locIdentifier", Schema.SHORTTEXT, true, false, 0, 1);
chapter.addAlternativeIdentifier("locIdentifier", RIS_FORMAT, "M1");
chapter.addField("dateRetrieved", Schema.DATE, false, false, 0, 1);
chapter.addField("openURL", Schema.SHORTTEXT, false, false, 0, 1);
chapter.addField("doi", Schema.NUMBER, true, false, 0, 1);
chapter.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
/*
* REPORT
*/
report.addField(Schema.CREATOR, Schema.SHORTTEXT, true, true, 1, Schema.UNLIMITED);
report.addAlternativeIdentifier(Schema.CREATOR, RIS_FORMAT, "A1");
report.addField(Schema.TITLE, Schema.SHORTTEXT, true, true, 1, 1);
report.addAlternativeIdentifier(Schema.TITLE, RIS_FORMAT, "T1");
report.addField(Schema.YEAR, Schema.NUMBER, true, false, 0, 1);
report.addField("date", Schema.NUMBER, true, false, 0, 1);
report.addAlternativeIdentifier("date", RIS_FORMAT, "Y1");
report.addField(Schema.PUBLISHER, Schema.SHORTTEXT, true, false, 0, 1);
report.addAlternativeIdentifier(Schema.PUBLISHER, RIS_FORMAT, "PB");
report.addField("publicationLocation", Schema.SHORTTEXT, true, false, 0, 1);
report.addAlternativeIdentifier("publicationLocation", RIS_FORMAT, "CY");
report.addField("editor", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
report.addAlternativeIdentifier("editor", RIS_FORMAT, "A3");
report.addField("edition", Schema.NUMBER, true, false, 0, 1);
report.addAlternativeIdentifier("edition", RIS_FORMAT, "VL");
report.addField(Schema.SOURCE_TITLE, Schema.SHORTTEXT, true, false, 0, 1);
report.addAlternativeIdentifier(Schema.SOURCE_TITLE, RIS_FORMAT, "T3");
report.addField(Schema.PAGES, Schema.NUMBER, true, false, 0, 1);
report.addAlternativeIdentifier(Schema.PAGES, RIS_FORMAT, "SP");
report.addField("abstract", Schema.LONGTEXT, true, false, 0, 1);
report.addAlternativeIdentifier("abstract", RIS_FORMAT, "N2");
report.addField(Schema.ISN, Schema.SHORTTEXT, true, false, 0, 1);
report.addAlternativeIdentifier(Schema.ISN, RIS_FORMAT, "SN");
report.addField("note", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
report.addAlternativeIdentifier("note", RIS_FORMAT, "N1");
report.addField("subject", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
report.addAlternativeIdentifier("subject", RIS_FORMAT, "KW");
report.addField("Language", Schema.NUMBER, true, false, 0, 1);
report.addField("locIdentifier", Schema.SHORTTEXT, true, false, 0, 1);
report.addAlternativeIdentifier("locIdentifier", RIS_FORMAT, "M1");
report.addField("dateRetrieved", Schema.DATE, false, false, 0, 1);
report.addField("openURL", Schema.SHORTTEXT, false, false, 0, 1);
report.addField("doi", Schema.NUMBER, true, false, 0, 1);
report.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
/* IGNORING 'Citation' field for now...
unknown.addField("inlineCitation", Schema.SHORTTEXT, false, false, 0, Schema.UNLIMITED);
article.addField("inlineCitation", Schema.SHORTTEXT, false, false, 0, Schema.UNLIMITED);
book.addField("inlineCitation", Schema.SHORTTEXT, false, false, 0, Schema.UNLIMITED);
chapter.addField("inlineCitation", Schema.SHORTTEXT, false, false, 0, Schema.UNLIMITED);
report.addField("inlineCitation", Schema.SHORTTEXT, false, false, 0, Schema.UNLIMITED);
*/
if (m_storage.checkSchema(unknown.getIdentifier()))
{
m_storage.updateSchema(unknown);
}
else
{
m_storage.addSchema(unknown);
}
if (m_storage.checkSchema(article.getIdentifier()))
{
m_storage.updateSchema(article);
}
else
{
m_storage.addSchema(article);
}
if (m_storage.checkSchema(book.getIdentifier()))
{
m_storage.updateSchema(book);
}
else
{
m_storage.addSchema(book);
}
if (m_storage.checkSchema(chapter.getIdentifier()))
{
m_storage.updateSchema(chapter);
}
else
{
m_storage.addSchema(chapter);
}
if (m_storage.checkSchema(report.getIdentifier()))
{
m_storage.updateSchema(report);
}
else
{
m_storage.addSchema(report);
}
}
public class CitationListDeleteAction extends BaseServiceLevelAction
{
public CitationListDeleteAction()
{
super(ResourceToolAction.DELETE, ResourceToolAction.ActionType.DELETE, CitationService.CITATION_LIST_ID, true);
}
public void finalizeAction(Reference reference)
{
try
{
ContentResource resource = (ContentResource) reference.getEntity();
String collectionId = new String(resource.getContent());
CitationCollection collection = getCollection(collectionId);
removeCollection(collection);
}
catch(IdUnusedException e)
{
M_log.warn("IdUnusedException ", e);
}
catch(ServerOverloadException e)
{
M_log.warn("ServerOverloadException ", e);
}
}
}
public class CitationLocalizer implements BasicResourceType.Localizer
{
/**
*
* @return
*/
public String getLabel()
{
return rb.getString("list.title");
}
/**
*
* @param member
* @return
*/
public String getLocalizedHoverText(ContentEntity member)
{
return rb.getString("list.title");
}
}
public class CitationSizeLabeler implements BasicResourceType.SizeLabeler
{
public String getLongSizeLabel(ContentEntity entity)
{
return getSizeLabel(entity);
}
public String getSizeLabel(ContentEntity entity)
{
String label = null;
if(entity instanceof ContentResource)
{
byte[] collectionId = null;
ContentResource resource = (ContentResource) entity;
try
{
collectionId = resource.getContent();
if(collectionId != null)
{
CitationCollection collection = getCollection(new String(collectionId));
String[] args = new String[]{ Integer.toString(collection.size())};
label = rb.getFormattedMessage("citation.count", args);
}
}
catch(Exception e)
{
String citationCollectionId = "null";
if(collectionId != null)
{
citationCollectionId = collectionId.toString();
}
M_log.warn("Unable to determine size of CitationCollection for entity: entityId == " + entity.getId() + " citationCollectionId == " + collectionId + " exception == " + e.toString());
}
}
return label;
}
}
public class CitationListCopyAction extends BaseServiceLevelAction
{
public CitationListCopyAction()
{
super(ResourceToolAction.COPY, ResourceToolAction.ActionType.COPY, CitationService.CITATION_LIST_ID, true);
}
@Override
public void finalizeAction(Reference reference)
{
copyCitationCollection(reference);
}
}
public class CitationListPasteMoveAction extends BaseServiceLevelAction
{
public CitationListPasteMoveAction()
{
super(ResourceToolAction.PASTE_COPIED, ResourceToolAction.ActionType.PASTE_MOVED, CitationService.CITATION_LIST_ID, true);
}
@Override
public void finalizeAction(Reference reference)
{
copyCitationCollection(reference);
}
}
public class CitationListPasteCopyAction extends BaseServiceLevelAction
{
public CitationListPasteCopyAction()
{
super(ResourceToolAction.PASTE_COPIED, ResourceToolAction.ActionType.PASTE_COPIED, CitationService.CITATION_LIST_ID, true);
}
@Override
public void finalizeAction(Reference reference)
{
copyCitationCollection(reference);
}
}
public class CitationListDuplicateAction extends BaseServiceLevelAction
{
public CitationListDuplicateAction()
{
super(ResourceToolAction.DUPLICATE, ResourceToolAction.ActionType.DUPLICATE, CitationService.CITATION_LIST_ID, false);
}
@Override
public void finalizeAction(Reference reference)
{
copyCitationCollection(reference);
}
}
/**
* @param schemaId
* @param fieldId
* @return
*/
public boolean isMultivalued(String schemaId, String fieldId)
{
Schema schema = getSchema(schemaId.toLowerCase());
if (schema == null)
{
if (getSynonyms("article").contains(schemaId.toLowerCase()))
{
schema = getSchema("article");
}
else if (getSynonyms("book").contains(schemaId.toLowerCase()))
{
schema = getSchema("book");
}
else if (getSynonyms("chapter").contains(schemaId.toLowerCase()))
{
schema = getSchema("chapter");
}
else if (getSynonyms("report").contains(schemaId.toLowerCase()))
{
schema = getSchema("report");
}
else
{
schema = this.getSchema("unknown");
}
}
Field field = schema.getField(fieldId);
if (field == null)
{
return false;
}
return (field.isMultivalued());
}
/**
* Access a list of all schemas that have been defined (other than the
* "unknown" type).
*
* @return A list of Strings representing the identifiers for known schemas.
*/
public List listSchemas()
{
Set names = (Set) m_storage.listSchemas();
return new Vector(names);
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#merge(java.lang.String,
* org.w3c.dom.Element, java.lang.String, java.lang.String,
* java.util.Map, java.util.Map, java.util.Set)
*/
public String merge(String siteId, Element root, String archivePath, String fromSiteId,
Map attachmentNames, Map userIdTrans, Set userListAllowImport)
{
// TODO Auto-generated method stub
return null;
}
/**
* Construct a Storage object.
*
* @return The new storage object.
*/
public abstract Storage newStorage();
/**
* @return
*/
protected Integer nextSerialNumber()
{
Integer number;
synchronized (m_nextSerialNumber)
{
number = m_nextSerialNumber;
m_nextSerialNumber = new Integer(number.intValue() + 1);
}
return number;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#parseEntityReference(java.lang.String,
* org.sakaiproject.entity.api.Reference)
*/
public boolean parseEntityReference(String reference, Reference ref)
{
boolean citationEntity = false;
if (reference.startsWith(CitationService.REFERENCE_ROOT))
{
citationEntity = true;
String[] parts = StringUtil.split(reference, Entity.SEPARATOR);
String subType = null;
String context = null;
String id = null;
String container = null;
// the first part will be null, then next the service, the third
// will be "export_ris", "content" or "list"
if (parts.length > 2)
{
subType = parts[2];
if (CitationService.REF_TYPE_EXPORT_RIS_ALL.equals(subType) ||
CitationService.REF_TYPE_EXPORT_RIS_SEL.equals(subType))
{
context = parts[3];
id = parts[3];
ref.set(APPLICATION_ID, subType, id, container, context);
}
else if ("content".equals(subType))
{
String wrappedRef = reference.substring(REFERENCE_ROOT.length(), reference
.length());
Reference wrapped = m_entityManager.newReference(wrappedRef);
ref.set(APPLICATION_ID, REF_TYPE_VIEW_LIST, wrapped.getId(), wrapped
.getContainer(), wrapped.getContext());
}
else
{
M_log.warn(".parseEntityReference(): unknown citation subtype: " + subType
+ " in ref: " + reference);
citationEntity = false;
}
}
else
{
citationEntity = false;
}
}
return citationEntity;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#removeCollection(org.sakaiproject.citation.api.CitationCollection)
*/
public void removeCollection(CitationCollection edit)
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#save(org.sakaiproject.citation.api.Citation)
*/
public void save(Citation citation)
{
if (citation instanceof BasicCitation && ((BasicCitation) citation).isTemporary())
{
((BasicCitation) citation).m_id = IdManager.createUuid();
((BasicCitation) citation).m_temporary = false;
((BasicCitation) citation).m_serialNumber = null;
}
this.m_storage.saveCitation(citation);
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#save(org.sakaiproject.citation.api.CitationCollection)
*/
public void save(CitationCollection collection)
{
this.m_storage.saveCollection(collection);
}
/**
* Dependency: ConfigurationService.
*
* @param service
* The ConfigurationService.
*/
public void setConfigurationService(ConfigurationService service)
{
m_configService = service;
}
/**
* Dependency: ContentHostingService.
*
* @param service
* The ContentHostingService.
*/
public void setContentHostingService(ContentHostingService service)
{
m_contentHostingService = service;
}
/**
* Dependency: EntityManager.
*
* @param service
* The EntityManager.
*/
public void setEntityManager(EntityManager service)
{
m_entityManager = service;
}
/**
* Dependency: ServerConfigurationService.
*
* @param service
* The ServerConfigurationService.
*/
public void setServerConfigurationService(ServerConfigurationService service)
{
m_serverConfigurationService = service;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#willArchiveMerge()
*/
public boolean willArchiveMerge()
{
// TODO Auto-generated method stub
return false;
}
public final class Counter
{
private int value;
private Integer lock = new Integer(0);
public Counter()
{
value = 0;
}
public Counter(int val)
{
value = val;
}
public void increment()
{
synchronized(lock)
{
value++;
}
}
public void decrement()
{
synchronized(lock)
{
value--;
}
}
public int intValue()
{
return value;
}
}
/**
* @return the attemptToMatchSchema
*/
public boolean isAttemptToMatchSchema()
{
return attemptToMatchSchema;
}
/**
* @param attemptToMatchSchema the attemptToMatchSchema to set
*/
public void setAttemptToMatchSchema(boolean attemptToMatchSchema)
{
this.attemptToMatchSchema = attemptToMatchSchema;
}
/**
* @param reference
*/
private void copyCitationCollection(Reference reference)
{
ContentHostingService contentService = (ContentHostingService) ComponentManager.get(ContentHostingService.class);
try
{
ContentResourceEdit edit = contentService.editResource(reference.getId());
String collectionId = new String(edit.getContent());
CitationCollection oldCollection = getCollection(collectionId);
BasicCitationCollection newCollection = new BasicCitationCollection();
newCollection.copy((BasicCitationCollection) oldCollection);
save(newCollection);
edit.setContent(newCollection.getId().getBytes());
contentService.commitResource(edit);
}
catch(IdUnusedException e)
{
M_log.warn("IdUnusedException ", e);
}
catch(ServerOverloadException e)
{
M_log.warn("ServerOverloadException ", e);
}
catch (PermissionException e)
{
M_log.warn("PermissionException ", e);
}
catch (TypeException e)
{
M_log.warn("TypeException ", e);
}
catch (InUseException e)
{
M_log.warn("InUseException ", e);
}
catch (OverQuotaException e)
{
M_log.warn("OverQuotaException ", e);
}
}
} // BaseCitationService
| citations/citations-impl/impl/src/java/org/sakaiproject/citation/impl/BaseCitationService.java | /*******************************************************************************
* $URL$
* $Id$
* **********************************************************************************
*
* Copyright (c) 2006, 2007, 2008 Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.
*
******************************************************************************/
package org.sakaiproject.citation.impl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeSet;
import java.util.Vector;
import java.net.URLEncoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osid.repository.Asset;
import org.osid.repository.Part;
import org.osid.repository.PartIterator;
import org.osid.repository.Record;
import org.osid.repository.RecordIterator;
import org.osid.repository.RepositoryException;
import org.sakaiproject.citation.api.ActiveSearch;
import org.sakaiproject.citation.api.Citation;
import org.sakaiproject.citation.api.CitationCollection;
import org.sakaiproject.citation.api.CitationIterator;
import org.sakaiproject.citation.api.CitationService;
import org.sakaiproject.citation.api.ConfigurationService;
import org.sakaiproject.citation.api.Schema;
import org.sakaiproject.citation.api.Schema.Field;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.content.api.ContentEntity;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.InteractionAction;
import org.sakaiproject.content.api.ResourceType;
import org.sakaiproject.content.api.ResourceTypeRegistry;
import org.sakaiproject.content.api.ResourceToolAction;
import org.sakaiproject.content.api.ServiceLevelAction;
import org.sakaiproject.content.api.ResourceToolAction.ActionType;
import org.sakaiproject.content.util.BaseInteractionAction;
import org.sakaiproject.content.util.BaseResourceAction;
import org.sakaiproject.content.util.BasicSiteSelectableResourceType;
//import org.sakaiproject.content.util.BaseResourceAction.Localizer;
import org.sakaiproject.content.util.BaseServiceLevelAction;
import org.sakaiproject.content.util.BasicResourceType;
//import org.sakaiproject.content.util.BasicResourceType.Localizer;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.entity.api.HttpAccess;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.OverQuotaException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.ServerOverloadException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.id.cover.IdManager;
import org.sakaiproject.javax.Filter;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.StringUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
*
*/
public abstract class BaseCitationService implements CitationService
{
protected boolean attemptToMatchSchema = false;
protected static final List<String> AUTHOR_AS_KEY = new Vector<String>();
static
{
AUTHOR_AS_KEY.add( CitationCollection.SORT_BY_AUTHOR );
AUTHOR_AS_KEY.add( CitationCollection.SORT_BY_YEAR );
AUTHOR_AS_KEY.add( CitationCollection.SORT_BY_TITLE );
AUTHOR_AS_KEY.add( CitationCollection.SORT_BY_UUID );
};
protected static final List<String> YEAR_AS_KEY = new Vector<String>();
static
{
YEAR_AS_KEY.add( CitationCollection.SORT_BY_YEAR );
YEAR_AS_KEY.add( CitationCollection.SORT_BY_AUTHOR );
YEAR_AS_KEY.add( CitationCollection.SORT_BY_TITLE );
YEAR_AS_KEY.add( CitationCollection.SORT_BY_UUID );
};
protected static final List<String> TITLE_AS_KEY = new Vector<String>();
static
{
TITLE_AS_KEY.add( CitationCollection.SORT_BY_TITLE );
TITLE_AS_KEY.add( CitationCollection.SORT_BY_AUTHOR );
TITLE_AS_KEY.add( CitationCollection.SORT_BY_YEAR );
TITLE_AS_KEY.add( CitationCollection.SORT_BY_UUID );
};
public static final Map<String, String> GS_TAGS = new Hashtable<String, String>();
static
{
//GS_TAGS.put("rft_val_fmt", "genre");
GS_TAGS.put("rft.title", "title");
GS_TAGS.put("rft.atitle", "title");
GS_TAGS.put("rft.jtitle", "atitle");
GS_TAGS.put("rft.btitle", "atitle");
GS_TAGS.put("rft.aulast", "au");
GS_TAGS.put("rft.aufirst", "au");
GS_TAGS.put("rft.au", "au");
GS_TAGS.put("rft.pub", "publisher");
GS_TAGS.put("rft.volume", "volume");
GS_TAGS.put("rft.issue", "issue");
GS_TAGS.put("rft.pages", "pages");
GS_TAGS.put("rft.date", "date");
GS_TAGS.put("rft.issn", "id");
GS_TAGS.put("rft.isbn", "id");
}
/**
*
*/
public class BasicCitation implements Citation
{
/* for OpenUrl creation */
protected final static String OPENURL_VERSION = "Z39.88-2004";
protected final static String OPENURL_CONTEXT_FORMAT = "info:ofi/fmt:kev:mtx:ctx";
protected final static String OPENURL_JOURNAL_FORMAT = "info:ofi/fmt:kev:mtx:journal";
protected final static String OPENURL_BOOK_FORMAT = "info:ofi/fmt:kev:mtx:book";
protected Map m_citationProperties = null;
protected Map m_urls;
protected String m_citationUrl = null;
protected String m_fullTextUrl = null;
protected String m_id = null;
protected String m_imageUrl = null;
protected Schema m_schema;
protected String m_searchSourceUrl = null;
protected Integer m_serialNumber = null;
protected boolean m_temporary = false;
protected boolean m_isAdded = false;
protected String m_preferredUrl;
/**
* Constructs a temporary citation.
*/
protected BasicCitation()
{
m_serialNumber = nextSerialNumber();
m_temporary = true;
m_citationProperties = new Hashtable();
m_urls = new Hashtable();
setType(CitationService.UNKNOWN_TYPE);
}
/**
* Constructs a temporary citation based on an asset.
*
* @param asset
*/
protected BasicCitation(Asset asset)
{
m_serialNumber = nextSerialNumber();
m_temporary = true;
m_citationProperties = new Hashtable();
m_urls = new Hashtable();
boolean unknownSchema = true;
String preferredUrl = null;
String title = null;
Set validProperties = getValidPropertyNames();
Set multivalued = getMultivalued();
String description;
// assetId = asset.getId().getIdString();
try
{
title = asset.getDisplayName();
if (title != null)
{
m_citationProperties.put(Schema.TITLE, title);
}
description = asset.getDescription();
if (description != null)
{
m_citationProperties.put("abstract", description);
}
RecordIterator rit = asset.getRecords();
try
{
while (rit.hasNextRecord())
{
Record record;
try
{
record = rit.nextRecord();
preferredUrl = null;
try
{
PartIterator pit = record.getParts();
try
{
while (pit.hasNextPart())
{
try
{
Part part = pit.nextPart();
String type = part.getPartStructure().getType()
.getKeyword();
if (type == null)
{
// continue;
}
else if (validProperties.contains(type))
{
if (multivalued.contains(type))
{
List values = (List) m_citationProperties
.get(type);
if (values == null)
{
values = new Vector();
m_citationProperties.put(type, values);
}
values.add(part.getValue());
}
else
{
m_citationProperties.put(type, part.getValue());
}
}
/*
* This type isn't described by the schema. Is
* it a preferred (title link) URL?
*/
else if (type.equals("preferredUrl"))
{
preferredUrl = (String) part.getValue();
}
else if (type.equals("type"))
{
if (m_schema == null
|| m_schema.getIdentifier().equals(
"unknown"))
{
if (getSynonyms("article").contains(
part.getValue().toString()
.toLowerCase()))
{
m_schema = BaseCitationService.this
.getSchema("article");
unknownSchema = false;
}
else if (getSynonyms("book").contains(
part.getValue().toString()
.toLowerCase()))
{
m_schema = BaseCitationService.this
.getSchema("book");
unknownSchema = false;
}
else if (getSynonyms("chapter").contains(
part.getValue().toString()
.toLowerCase()))
{
m_schema = BaseCitationService.this
.getSchema("chapter");
unknownSchema = false;
}
else if (getSynonyms("report").contains(
part.getValue().toString()
.toLowerCase()))
{
m_schema = BaseCitationService.this
.getSchema("report");
unknownSchema = false;
}
else
{
m_schema = BaseCitationService.this
.getSchema("unknown");
unknownSchema = true;
}
}
List values = (List) m_citationProperties.get(type);
if (values == null)
{
values = new Vector();
m_citationProperties.put(type, values);
}
values.add(part.getValue());
}
else
{
}
}
catch (RepositoryException e)
{
M_log.warn("BasicCitation(" + asset + ") ", e);
}
}
}
catch (RepositoryException e)
{
M_log.warn("BasicCitation(" + asset + ") ", e);
}
}
catch (RepositoryException e1)
{
M_log.warn("BasicCitation(" + asset + ") ", e1);
}
}
catch (RepositoryException e2)
{
M_log.warn("BasicCitation(" + asset + ") ", e2);
}
}
}
catch (RepositoryException e)
{
M_log.warn("BasicCitation(" + asset + ") ", e);
}
}
catch (RepositoryException e)
{
M_log.warn("BasicCitation(" + asset + ") ", e);
}
if(unknownSchema && attemptToMatchSchema)
{
matchSchema();
}
setDefaults();
/*
* Did we find a preferred URL?
*/
if (preferredUrl != null)
{
String id;
/*
* Save the URL without a label (it'll get the default label at
* render-time) and set it as the preferred (title) link
*/
id = addCustomUrl("", preferredUrl);
setPreferredUrl(id);
}
}
/**
*
*/
protected void matchSchema()
{
Map pros = new Hashtable();
Map cons = new Hashtable();
List schemas = getSchemas();
Set fieldNames = this.m_citationProperties.keySet();
Iterator schemaIt = schemas.iterator();
while(schemaIt.hasNext())
{
Schema schema = (Schema) schemaIt.next();
if(schema.getIdentifier().equals("unknown"))
{
continue;
}
pros.put(schema.getIdentifier(), new Counter());
cons.put(schema.getIdentifier(), new Counter());
Iterator fieldIt = fieldNames.iterator();
while(fieldIt.hasNext())
{
String fieldName = (String) fieldIt.next();
Field field = schema.getField(fieldName);
if(field == null)
{
// this indicates that data would be lost.
((Counter) cons.get(schema.getIdentifier())).increment();
}
else
{
// this is evidence that this schema might be best fit.
((Counter) pros.get(schema.getIdentifier())).increment();
}
}
}
// elminate schema that lose data
Iterator consIt = cons.keySet().iterator();
while(consIt.hasNext())
{
String schemaId = (String) consIt.next();
boolean blocked = ((Counter) cons.get(schemaId)).intValue() > 0;
if(blocked)
{
pros.remove(schemaId);
}
}
Iterator prosIt = pros.keySet().iterator();
int bestScore = 0;
String bestMatch = null;
// Nominate "article" as first candidate if it's not blocked
Object article = pros.get("article");
if(article != null)
{
bestScore = ((Counter) article).intValue();
bestMatch = "article";
}
while(prosIt.hasNext())
{
String schemaId = (String) prosIt.next();
int score = ((Counter) pros.get(schemaId)).intValue();
if(score > bestScore)
{
bestScore = score;
bestMatch = schemaId;
}
}
if(bestMatch != null)
{
m_schema = BaseCitationService.this.getSchema(bestMatch);
}
}
/**
* @param other
*/
public BasicCitation(BasicCitation other)
{
m_id = other.m_id;
m_serialNumber = other.m_serialNumber;
m_temporary = other.m_temporary;
m_citationProperties = new Hashtable();
m_urls = new Hashtable();
setSchema(other.m_schema);
copy(other);
}
/**
* Construct a citation not marked as temporary of a particular type.
*
* @param mediatype
*/
public BasicCitation(String mediatype)
{
m_id = IdManager.createUuid();
m_citationProperties = new Hashtable();
m_urls = new Hashtable();
setType(mediatype);
}
public BasicCitation(String citationId, Schema schema)
{
m_id = citationId;
m_citationProperties = new Hashtable();
m_urls = new Hashtable();
setSchema(schema);
}
/**
* Construct a citation not marked as temporary of a particular type
* with a particular id.
*
* @param citationId
* @param mediatype
*/
public BasicCitation(String citationId, String mediatype)
{
m_id = citationId;
m_citationProperties = new Hashtable();
m_urls = new Hashtable();
setType(mediatype);
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#addUrl(java.lang.String,
* java.net.URL)
*/
public String addCustomUrl(String label, String url)
{
UrlWrapper wrapper = new UrlWrapper(label, url);
String id = IdManager.createUuid();
m_urls.put(id, wrapper);
return id;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#addPropertyValue(java.lang.String,
* java.lang.Object)
*/
public void addPropertyValue(String name, Object value)
{
if (this.m_citationProperties == null)
{
this.m_citationProperties = new Hashtable();
}
if (isMultivalued(name))
{
List list = (List) this.m_citationProperties.get(name);
if (list == null)
{
list = new Vector();
this.m_citationProperties.put(name, list);
}
list.add(value);
}
else
{
this.m_citationProperties.put(name, value);
}
}
/**
*
* @param citation
*/
public void copy(Citation citation)
{
BasicCitation other = (BasicCitation) citation;
m_citationUrl = other.m_citationUrl;
m_fullTextUrl = other.m_fullTextUrl;
m_imageUrl = other.m_imageUrl;
m_searchSourceUrl = other.m_searchSourceUrl;
m_preferredUrl = other.m_preferredUrl;
m_schema = other.m_schema;
if (m_citationProperties == null)
{
m_citationProperties = new Hashtable();
}
m_citationProperties.clear();
if (other.m_citationProperties != null)
{
Iterator propIt = other.m_citationProperties.keySet().iterator();
while (propIt.hasNext())
{
String name = (String) propIt.next();
Object obj = other.m_citationProperties.get(name);
if (obj == null)
{
}
else if (obj instanceof List)
{
List list = (List) obj;
List copy = new Vector();
Iterator valueIt = list.iterator();
while (valueIt.hasNext())
{
Object val = valueIt.next();
copy.add(val);
}
this.m_citationProperties.put(name, copy);
}
else if (obj instanceof String)
{
this.m_citationProperties.put(name, obj);
}
else
{
M_log.debug("BasicCitation copy constructor: property is not String or List: "
+ name + " (" + obj.getClass().getName() + ") == " + obj);
this.m_citationProperties.put(name, obj);
}
}
}
if (m_urls == null)
{
m_urls = new Hashtable();
}
m_urls.clear();
if (other.m_urls != null)
{
Iterator urlIt = other.m_urls.keySet().iterator();
while (urlIt.hasNext())
{
String id = (String) urlIt.next();
UrlWrapper wrapper = (UrlWrapper) other.m_urls.get(id);
// Do not want to addCustomUrl because that assigns a new, unique id to the customUrl.
// This causes problems when we try to reference the preferredUrl by its id - it was
// created and set in the 'other' citation
//addCustomUrl(wrapper.getLabel(), wrapper.getUrl());
// instead, we store the customUrl along with it's originial id -- since this citation
// is a copy of 'other', there should be no harm in doing this
m_urls.put(id, wrapper);
}
}
}
/*
* Simple helpers to export RIS items
* prefix will most often be empty, and is used to offer an "internal label"
* for stuff that gets shoved into the Notes (N1) field because there isn't
* a dedicated field (e.g., Rights)
*
* Outputs XX - value
* or
* XX - prefix: value
*/
public void exportRisField(String rislabel, String value, StringBuilder buffer, String prefix)
{
// Get rid of the newlines and spaces
value = value.replaceAll("\n", " ");
rislabel = rislabel.trim();
// Adjust the prefix to have a colon-space afterwards, if there *is* a prefix
if (prefix != null && !prefix.trim().equals(""))
{
prefix = prefix + ": ";
}
// Export it only if there's a value, or if it's an ER tag (which is by design empty)
if (value != null && !value.trim().equals("") || rislabel.equals("ER"))
{
buffer.append(rislabel + RIS_DELIM + prefix + value + "\n");
}
}
/*
* Again, without the prefix
*/
public void exportRisField(String rislabel, String value, StringBuilder buffer)
{
exportRisField(rislabel, value, buffer, "");
}
/*
* If the value is a list, iterate over it and recursively call exportRISField
*
*/
public void exportRisField(String rislabel, List propvalues, StringBuilder buffer, String prefix)
{
Iterator propvaliter = propvalues.iterator();
while (propvaliter.hasNext())
{
exportRisField(rislabel, propvaliter.next(), buffer, prefix);
}
}
/*
* And again, to do the dispatch
*/
public void exportRisField(String rislabel, Object val, StringBuilder buffer, String prefix)
{
if (val instanceof List)
{
exportRisField(rislabel, (List) val, buffer, prefix);
} else
{
exportRisField(rislabel, (String) val.toString(), buffer, prefix);
}
}
/*
* And, finally, a dispatcher to deal with items without a prefix
*/
public void exportRisField(String rislabel, Object val, StringBuilder buffer)
{
exportRisField(rislabel, val, buffer, "");
}
/*
*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#exportToRis(java.io.OutputStream)
*/
public void exportRis(StringBuilder buffer) throws IOException
{
// Get the RISType and write a blank line and the TY tag
String type = "article";
if (m_schema != null)
{
type = m_schema.getIdentifier();
}
String ristype = (String) m_RISType.get(type);
if (ristype == null)
{
ristype = (String) m_RISType.get("article");
}
exportRisField("TY", ristype, buffer);
// Cycle through all the properties except for those that need
// pre-processing (as listed in m_RISSpecialFields)
// Deal with the "normal" fields
List fields = m_schema.getFields();
Iterator iter = fields.iterator();
while (iter.hasNext())
{
Field field = (Field) iter.next();
String fieldname = field.getIdentifier();
if (m_RISSpecialFields.contains(fieldname))
{
continue; // Skip if this is a special field
}
String rislabel = field.getIdentifier(RIS_FORMAT);
if (rislabel != null)
{
exportRisField(rislabel, getCitationProperty(fieldname), buffer);
}
}
// Deal with the speical fields.
/**
* Dates need to be of the formt YYYY/MM/DD/other, including the
* slashes even if the data is empty. Hence, we'll mostly be
* producing YYYY// for date formats
*/
// TODO: deal with real dates. Right now, just year
exportRisField("Y1", getCitationProperty(Schema.YEAR) + "//", buffer);
// Other stuff goes into the note field -- including the note
// itself of course.
Iterator specIter = m_RISNoteFields.entrySet().iterator();
while (specIter.hasNext())
{
Map.Entry entry = (Map.Entry) specIter.next();
String fieldname = (String) entry.getKey();
String prefix = (String) entry.getValue();
exportRisField("N1", getCitationProperty(fieldname), buffer, prefix);
}
/**
* Deal with URLs.
*/
Iterator urlIDs = this.getCustomUrlIds().iterator();
while (urlIDs.hasNext())
{
String id = urlIDs.next().toString();
try
{
String url = this.getCustomUrl(id);
String urlLabel = this.getCustomUrlLabel(id);
exportRisField("UR", url, buffer); // URL
exportRisField("NT", url, buffer, urlLabel); // Note
}
catch (IdUnusedException e)
{
// do nothing
}
}
// Write out the end-of-record identifier and an extra newline
exportRisField("ER", "", buffer);
buffer.append("\n");
}
/* (non-Javadoc)
* @see org.sakaiproject.citation.api.Citation#getCitationProperties()
*/
public Map getCitationProperties()
{
if (m_citationProperties == null)
{
m_citationProperties = new Hashtable();
}
return m_citationProperties;
}
/* (non-Javadoc)
* @see org.sakaiproject.citation.api.Citation#getCitationProperty(java.lang.String)
*/
public Object getCitationProperty(String name)
{
if (m_citationProperties == null)
{
m_citationProperties = new Hashtable();
}
Object value = m_citationProperties.get(name);
if (value == null)
{
if (isMultivalued(name))
{
value = new Vector();
((List) value).add("");
}
else
{
value = "";
}
}
return value;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getAuthor()
*/
public String getCreator()
{
List creatorList = null;
Object creatorObj = m_citationProperties.get(Schema.CREATOR);
if (creatorObj == null)
{
creatorList = new Vector();
m_citationProperties.put(Schema.CREATOR, creatorList);
}
else if (creatorObj instanceof List)
{
creatorList = (List) creatorObj;
}
else if (creatorObj instanceof String)
{
creatorList = new Vector();
creatorList.add(creatorObj);
m_citationProperties.put(Schema.CREATOR, creatorList);
}
String creators = "";
int count = 0;
Iterator it = creatorList.iterator();
while (it.hasNext())
{
String creator = (String) it.next();
if (it.hasNext() && count > 0)
{
creators += "; " + creator;
}
else if (it.hasNext())
{
creators += creator;
}
else if (count > 1)
{
creators += "; and " + creator;
}
else if (count > 0)
{
creators += " and " + creator;
}
else
{
creators += creator;
}
count++;
}
if (!creators.trim().equals("") && !creators.trim().endsWith("."))
{
creators = creators.trim() + ". ";
}
return creators;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getUrl(java.lang.String)
*/
public String getCustomUrl(String id) throws IdUnusedException
{
UrlWrapper wrapper = (UrlWrapper) m_urls.get(id);
if (wrapper == null)
{
throw new IdUnusedException(id);
}
return wrapper.getUrl();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getUrlIds()
*/
public List getCustomUrlIds()
{
List rv = new Vector();
if (!m_urls.isEmpty())
{
rv.addAll(m_urls.keySet());
}
return rv;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getUrlLabel(java.lang.String)
*/
public String getCustomUrlLabel(String id) throws IdUnusedException
{
UrlWrapper wrapper = (UrlWrapper) m_urls.get(id);
if (wrapper == null)
{
throw new IdUnusedException(id);
}
return wrapper.getLabel();
}
public String getYear()
{
String yearDate = (String) getCitationProperty(Schema.YEAR);
return yearDate;
}
public String getDisplayName()
{
String displayName = (String) getCitationProperty(Schema.TITLE);
if (displayName == null || displayName.trim() == "")
{
displayName = "untitled";
setCitationProperty(Schema.TITLE, "untitled");
}
displayName = displayName.trim();
if (displayName.length() > 0 && !displayName.endsWith(".") && !displayName.endsWith("?") && !displayName.endsWith("!") && !displayName.endsWith(","))
{
displayName += ".";
}
return new String(displayName);
}
/**
* Get the primary URL for this resource
*
* Normally, this is an OpenURL created from citation properties, but if
* either the Repository OSID or the user has designated a preferred URL,
* we'll use it instead.
*
* @return The primary URL (null if none available)
*/
public String getPrimaryUrl()
{
String url;
/*
* Stop now if we haven't set up any Citation properties
*/
if (m_citationProperties == null)
{
return null;
}
/*
* Custom URL?
*/
if (hasPreferredUrl())
{
String id = getPreferredUrlId();
try
{
return getCustomUrl(id);
}
catch (IdUnusedException exception)
{
M_log.warn("No matching URL for ID: "
+ id
+ ", returning an OpenURL");
}
}
/*
* Use an OpenURL
*/
return getOpenurl();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getFirstAuthor()
*/
public String getFirstAuthor()
{
String firstAuthor = null;
List authors = (List) this.m_citationProperties.get(Schema.CREATOR);
if (authors != null && !authors.isEmpty())
{
firstAuthor = (String) authors.get(0);
}
if (firstAuthor != null)
{
firstAuthor = firstAuthor.trim();
}
return firstAuthor;
}
public String getId()
{
if (isTemporary())
{
return m_serialNumber.toString();
}
return m_id;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getOpenurl()
*/
public String getOpenurl()
{
// check citationProperties
if (m_citationProperties == null)
{
// citation properties do not exist as yet - no OpenUrl
return null;
}
String openUrlParams = getOpenurlParameters();
// return the URL-encoded string
return m_configService.getSiteConfigOpenUrlResolverAddress() + openUrlParams;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getOpenurlParameters()
*/
public String getOpenurlParameters()
{
// check citationProperties
if (m_citationProperties == null)
{
// citation properties do not exist as yet - no OpenUrl
return "";
}
// default to journal
boolean journalOpenUrlType = true;
String referentValueFormat = OPENURL_JOURNAL_FORMAT;
// check to see whether we should construct a journal OpenUrl
// (includes types: article, report, unknown)
// or a book OpenUrl (includes types: book, chapter)
// String type = (String) m_citationProperties.get("type");
String type = "article";
if (m_schema != null)
{
type = m_schema.getIdentifier();
}
if (type != null && !type.trim().equals(""))
{
if (type.equals("article") || type.equals("report") || type.equals("unknown"))
{
journalOpenUrlType = true;
referentValueFormat = OPENURL_JOURNAL_FORMAT;
}
else
{
journalOpenUrlType = false;
referentValueFormat = OPENURL_BOOK_FORMAT;
}
}
// start building the OpenUrl
StringBuilder openUrl = null;
try
{
openUrl = new StringBuilder();
openUrl.append("?url_ver=" + URLEncoder.encode(OPENURL_VERSION, "utf8")
+ "&url_ctx_fmt=" + URLEncoder.encode(OPENURL_CONTEXT_FORMAT, "utf8")
+ "&rft_val_fmt=" + URLEncoder.encode(referentValueFormat, "utf8"));
// flag articles
if (journalOpenUrlType)
{
openUrl.append("&rft.genre=article");
}
// get first author
String author = getFirstAuthor();
// get first author's last/first name
if (author != null)
{
String aulast;
StringBuilder aufirst = new StringBuilder();
String[] authorNames = author.split(",");
if (authorNames.length == 2)
{
aulast = authorNames[0].trim();
aufirst.append(authorNames[1].trim());
}
else
{
authorNames = author.split("\\s");
aulast = authorNames[authorNames.length - 1].trim();
for (int i = 0; i < authorNames.length - 1; i++)
{
aufirst.append(authorNames[i] + " ");
}
if (aufirst.length() > 0)
{
aufirst.deleteCharAt( aufirst.length() - 1 );
}
}
// append to the openUrl
openUrl.append("&rft.aulast=" + URLEncoder.encode(aulast,"utf8"));
if (!aufirst.toString().trim().equals(""))
{
openUrl.append("&rft.aufirst=" + URLEncoder.encode(aufirst.toString().
trim(), "utf8"));
}
}
// append any other authors to the openUrl
java.util.List authors = (java.util.List) m_citationProperties.get(Schema.CREATOR);
if (authors != null && !authors.isEmpty() && authors.size() > 1)
{
for (int i = 1; i < authors.size(); i++)
{
openUrl.append("&rft.au=" + URLEncoder.encode((String) authors.get(i),
"utf8"));
}
}
// titles
String title = (String) m_citationProperties.get( Schema.TITLE );
if( title != null )
{
if( journalOpenUrlType )
{
// article title
openUrl.append("&rft.atitle=" + URLEncoder.encode(title.trim(), "utf8"));
}
else
{
// book title
openUrl.append("&rft.btitle=" + URLEncoder.encode(title.trim(), "utf8"));
}
}
else
{
// want to 'borrow' a title from another field if possible
String sourceTitle = (String) m_citationProperties.get(Schema.SOURCE_TITLE);
if (sourceTitle != null && !sourceTitle.trim().equals(""))
{
openUrl.append("&rft.atitle=" + URLEncoder.encode(sourceTitle, "utf8"));
}
// could add other else ifs for fields to borrow from...
}
// journal title or book title
String sourceTitle = (String) m_citationProperties.get(Schema.SOURCE_TITLE);
if (sourceTitle != null && !sourceTitle.trim().equals(""))
{
if (journalOpenUrlType)
{
openUrl.append("&rft.jtitle=" + URLEncoder.encode(sourceTitle, "utf8"));
}
else
{
openUrl.append("&rft.btitle=" + URLEncoder.encode(sourceTitle, "utf8"));
}
}
// date [ YYYY-MM-DD | YYYY-MM | YYYY ] - need filtering TODO
// -- perhaps do another regular expressions scan...
// currently just using the year
String year = (String) m_citationProperties.get(Schema.YEAR);
if (year != null && !year.trim().equals(""))
{
openUrl.append("&rft.date=" + URLEncoder.encode(year, "utf8"));
}
// volume (edition)
if (journalOpenUrlType)
{
String volume = (String) m_citationProperties.get(Schema.VOLUME);
if (volume != null && !volume.trim().equals(""))
{
openUrl.append("&rft.volume=" + URLEncoder.encode(volume, "utf8"));
}
}
else
{
String edition = (String) m_citationProperties.get("edition");
if (edition != null && !edition.trim().equals(""))
{
openUrl.append("&rft.edition=" + URLEncoder.encode(edition, "utf8"));
}
}
// issue (place)
// (pub)
if (journalOpenUrlType)
{
String issue = (String) m_citationProperties.get(Schema.ISSUE);
if (issue != null && !issue.trim().equals(""))
{
openUrl.append("&rft.issue=" + URLEncoder.encode(issue, "utf8"));
}
}
else
{
String pub = (String) m_citationProperties.get("pub");
if (pub != null && !pub.trim().equals(""))
{
openUrl.append("&rft.pub=" + URLEncoder.encode(pub, "utf8"));
}
String place = (String) m_citationProperties.get("place");
if (place != null && !place.trim().equals(""))
{
openUrl.append("&rft.place=" + URLEncoder.encode(place, "utf8"));
}
}
// spage
String spage = (String) m_citationProperties.get("startPage");
if (spage != null && !spage.trim().equals(""))
{
openUrl.append("&rft.spage=" + URLEncoder.encode(spage, "utf8"));
}
// epage
String epage = (String) m_citationProperties.get("endPage");
if (epage != null && !epage.trim().equals(""))
{
openUrl.append("&rft.epage=" + URLEncoder.encode(epage, "utf8"));
}
// pages
String pages = (String) m_citationProperties.get(Schema.PAGES);
if (pages != null && !pages.trim().equals(""))
{
openUrl.append("&rft.pages=" + URLEncoder.encode(pages, "utf8"));
}
// issn (isbn)
String isn = (String) m_citationProperties.get(Schema.ISN);
if (isn != null && !isn.trim().equals(""))
{
if (journalOpenUrlType)
{
openUrl.append("&rft.issn=" + URLEncoder.encode(isn, "utf8"));
}
else
{
openUrl.append("&rft.isbn=" + URLEncoder.encode(isn, "utf8"));
}
}
}
catch( UnsupportedEncodingException uee )
{
M_log.warn( "getOpenurlParameters -- unsupported encoding argument: utf8" );
}
// genre needs some further work... TODO
return openUrl.toString();
}
public Schema getSchema()
{
return m_schema;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#getSource()
*/
public String getSource()
{
String place = (String) getCitationProperty("publicationLocation");
String publisher = (String) getCitationProperty(Schema.PUBLISHER);
String sourceTitle = (String) getCitationProperty(Schema.SOURCE_TITLE);
String year = (String) getCitationProperty(Schema.YEAR);
String volume = (String) getCitationProperty(Schema.VOLUME);
String issue = (String) getCitationProperty(Schema.ISSUE);
String pages = (String) getCitationProperty(Schema.PAGES);
String startPage = (String) getCitationProperty("startPage");
String endPage = (String) getCitationProperty("endPage");
if (pages == null || pages.trim().equals(""))
{
pages = null;
if (startPage != null && ! startPage.trim().equals(""))
{
pages = startPage.trim();
if (endPage != null && ! endPage.trim().equals(""))
{
pages += "-" + endPage;
}
}
}
String source = "";
String schemaId = "unknown";
if (m_schema != null)
{
schemaId = m_schema.getIdentifier();
}
if ("book".equals(schemaId) || "report".equals(schemaId))
{
if (place != null && !place.trim().equals(""))
{
source += place;
}
if (publisher != null && !publisher.trim().equals(""))
{
if (source.length() > 0)
{
source = source.trim() + ": ";
}
source += publisher;
}
if (year != null && ! year.trim().equals(""))
{
if (source.length() > 0)
{
source = source.trim() + ", ";
}
source += year;
}
}
else if ("article".equals(schemaId))
{
if (sourceTitle != null && !sourceTitle.trim().equals(""))
{
source += sourceTitle;
if (volume != null && !volume.trim().equals(""))
{
source += ", " + volume;
if (issue != null && !issue.trim().equals(""))
{
source += "(" + issue + ") ";
}
}
}
if(year != null && ! year.trim().equals(""))
{
source += " " + year;
}
if(source != null && source.length() > 1)
{
source = source.trim();
if(!source.endsWith(".") && !source.endsWith("?") && !source.endsWith("!") && !source.endsWith(","))
{
source += ". ";
}
}
if (pages != null && !pages.trim().equals(""))
{
source += pages;
}
if(source != null && source.length() > 1)
{
source = source.trim();
if(!source.endsWith(".") && !source.endsWith("?") && !source.endsWith("!") && !source.endsWith(","))
{
source += ". ";
}
}
}
else if ("chapter".equals(schemaId))
{
if (sourceTitle != null && !sourceTitle.trim().equals(""))
{
source += "In " + sourceTitle;
if (pages == null)
{
if (startPage != null && !startPage.trim().equals(""))
{
source = source.trim() + ", " + startPage;
if (endPage != null && !endPage.trim().equals(""))
{
source = source.trim() + "-" + endPage;
}
}
}
else
{
source = source.trim() + ", " + pages;
}
if (publisher != null && !publisher.trim().equals(""))
{
if (place != null && !place.trim().equals(""))
{
source += place + ": ";
}
source += publisher;
if (year != null && ! year.trim().equals(""))
{
source += ", " + year;
}
}
else if (year != null && ! year.trim().equals(""))
{
source += " " + year;
}
}
}
else
{
if (sourceTitle != null && ! sourceTitle.trim().equals(""))
{
source += sourceTitle;
if (volume != null && ! volume.trim().equals(""))
{
source += ", " + volume;
if (issue != null && !issue.trim().equals(""))
{
source += "(" + issue + ") ";
}
}
if (pages == null)
{
if (startPage != null && !startPage.trim().equals(""))
{
source += startPage;
if (endPage != null && !endPage.trim().equals(""))
{
source += "-" + endPage;
}
}
}
else
{
if (source.length() > 0)
{
source += ". ";
}
source += pages + ". ";
}
}
else if (publisher != null && ! publisher.trim().equals(""))
{
if (place != null && ! place.trim().equals(""))
{
source += place + ": ";
}
source += publisher;
if (year != null && ! year.trim().equals(""))
{
source += ", " + year;
}
}
}
if (source.length() > 1 && !source.endsWith(".") && !source.endsWith("?") && !source.endsWith("!") && !source.endsWith(","))
{
source = source.trim() + ". ";
}
if( source.trim().endsWith( ".." ) )
{
source = source.substring( 0, source.length()-2 );
}
return source;
}
public String getAbstract() {
if ( m_citationProperties != null && m_citationProperties.get( "abstract" ) != null )
{
return m_citationProperties.get("abstract").toString().trim();
}
else
{
return null;
}
}
public String getSubjectString() {
Object subjects = getCitationProperty( "subject" );
if ( subjects instanceof List )
{
List subjectList = ( List ) subjects;
ListIterator subjectListIterator = subjectList.listIterator();
StringBuilder subjectStringBuf = new StringBuilder();
while ( subjectListIterator.hasNext() )
{
subjectStringBuf.append( ((String)subjectListIterator.next()).trim() + ", " );
}
String subjectString = subjectStringBuf.substring( 0, subjectStringBuf.length() - 2 );
if ( subjectString.equals("") )
{
return null;
}
else
{
return subjectString;
}
}
else
{
return null;
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#hasUrls()
*/
public boolean hasCustomUrls()
{
return m_urls != null && !m_urls.isEmpty();
}
public boolean hasPropertyValue(String fieldId)
{
boolean hasPropertyValue = m_citationProperties.containsKey(fieldId);
Object val = m_citationProperties.get(fieldId);
if (hasPropertyValue && val != null)
{
if (val instanceof List)
{
List list = (List) val;
hasPropertyValue = !list.isEmpty();
}
}
return hasPropertyValue;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#importFromRis(java.io.InputStream)
*/
public void importFromRis(InputStream ris) throws IOException
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#importFromRisList(java.util.List)
*/
public boolean importFromRisList(List risImportList)
{
Log logger = LogFactory.getLog(BasicCitation.class);
String currentLine = null; // The active line being parsed from the list (e.g. "TY - BOOK")
String RIScode = null; // The RIS Code (e.g. "TY" for "TY - BOOK")
String RISvalue = null; // The RIS Value (e.g. "BOOK" for "TY - BOOK")
Schema schema = null; // The Citations Helper Schema to use based on the TY RIS field
String schemaName = null; // The name/string of the schema used to lookup the schema
List Fields = null; // This holds the mapped fields for a particular Schema
Field tempField = null; // This holds the current field being evaluated while iterating through
// Fields
Iterator iter = null; // The iterator used to boogie through the Schema Fields
boolean status = true; // Used to maintain/exit the tag lookup while loop
String[] RIScodes = null; // This holds the RISCodes valid for a given schema
logger.debug("importFromRisList: In importFromRisList. List size is " + risImportList.size());
// process loop that iterates list size many times
for(int i=0; i< risImportList.size(); i++)
{
// get current RIS line and trim off the spaces
currentLine = (String) risImportList.get(i);
currentLine = currentLine.trim();
logger.debug("importFromRisList: currentLine = " + currentLine);
// If the RIS line is less than 4, it isn't really a valid line. Set some default values
// that we know won't be processed for this line.
if (currentLine.length() < 4)
{
RIScode = "";
RISvalue = "";
}
else
{
// get the RIS code
RIScode = currentLine.substring(0, 2);
logger.debug("importFromRisList: substr code = " + RIScode);
// If the RIS line is of the right minimum length, get the RIS value.
if (currentLine.length() >= 7)
RISvalue = currentLine.substring(6);
else // Just set the value to some default value
RISvalue = "";
logger.debug("importFromRisList: substr value = " + RISvalue);
}
// Trim the value
RISvalue = RISvalue.trim();
// The RIS code TY must be the first entry is a RIS record. This sets the Schema type.
if (i == 0)
{
if (! RIScode.equalsIgnoreCase("TY"))
{
logger.debug("importFromRisList: FALSE - 1st entry in RIS must be TY. It isn't it is " + RISvalue);
return false; // TY MUST be the first entry in a RIS citation
}
else // process the schema
{
// RIS resource type forced mappings
if (RISvalue.equalsIgnoreCase("NEWS"))
{
logger.debug("importFromRisList: force mapping NEWS resource type to JOUR");
RISvalue = "JOUR";
}
logger.debug("importFromRisList: size of m_RISTypeInverse = " + m_RISTypeInverse.size());
logger.debug("importFromRisList: RISvalue before schemaName = " + RISvalue);
// get the Schema String name that we need to use for Schema look up from
// the map m_RISTypeInverse using the RISvalue for RIScode "TY";
schemaName = (String) m_RISTypeInverse.get(RISvalue);
// If we couldn't find a valid schema name mapping, set the name to "unknown"
if (schemaName == null)
{
logger.debug("importFromRisList: Unknown Schema Name = " + RISvalue +
". Setting schemeName to 'unknown'");
schemaName = "unknown";
}
logger.debug("importFromRisList: Schema Name = " + schemaName);
// Lookup the Schema based on the Schema string gotten from the reverse map
schema = org.sakaiproject.citation.cover.CitationService.getSchema(schemaName);
logger.debug("importFromRisList: Retrieved Schema Name = " + schema.getIdentifier());
setSchema(schema);
} // end else (else processes RIScode == "TY")
} // end if i == 0
else // process the RIS entries after the first mandatory TY/Schema code
{
if (RIScode.equalsIgnoreCase("ER")) // RIScode "ER" signifies the end of a citation record
{
logger.debug("importFromRisList: Read an ER. End of citation.");
/*
if (((String) getCitationProperty(Schema.TITLE)).length() == 0 &&
((String) getCitationProperty(Schema.SOURCE_TITLE)).length() > 0)
{
logger.debug("importFromRisList: Setting empty TITLE to non empty SOURCE_TITLE");
setCitationProperty(Schema.TITLE, getCitationProperty(Schema.SOURCE_TITLE));
}
*/
return true; // ER signals end of citation
} // end of citation
// Get all the valid RIS fields for this particular schema type
Fields = schema.getFields();
iter = Fields.iterator();
status = true;
while (iter.hasNext() && status == true)
{
tempField = (Field) iter.next();
// We found that this field is a valid field for this schema
RIScodes = tempField.getIdentifierComplex(RIS_FORMAT);
for(int j=0; j< RIScodes.length && status; j++)
{
// logger.debug("importFromRisList: Seeing if I can find a match that has the " +
// "given code '" + RIScode + "' == '" + RIScodes[j] + "' for Schema " + schema.getIdentifier());
// Need Trim in case RIS complex value has a space after the delimiter
// (e.g. "BT, T1" vs "BT","T1")
if (RIScode.equalsIgnoreCase(RIScodes[j]))
{
status = false;
logger.debug("importFromRisList: Found field mapping");
}
} // end for j (loop through complex RIS codes)
} // end while
if (status) // couldn't find the field mapping
{
/* if (schema.getIdentifier().equalsIgnoreCase("book"))
{
if (RIScode.equalsIgnoreCase("T1")) // Refworks
{
setCitationProperty(Schema.TITLE, RISvalue);
logger.debug("importFromRisList: I manually mapped " + RIScode +
" to " + Schema.TITLE);
}
else
logger.debug("importFromRisList: Cannot find Field mapping");
} // end book schema mapping exceptions
else if (schema.getIdentifier().equalsIgnoreCase("article"))
{
if (RIScode.equalsIgnoreCase("AU")) // EndNote
{
setCitationProperty(Schema.CREATOR, RISvalue);
logger.debug("importFromRisList: I manually mapped " + RIScode +
" to " + Schema.CREATOR);
}
else if (RIScode.equalsIgnoreCase("PY")) // EndNote
{
setCitationProperty(Schema.YEAR, RISvalue);
logger.debug("importFromRisList: I manually mapped " + RIScode +
" to " + Schema.YEAR);
}
else if (RIScode.equalsIgnoreCase("TI")) // EndNote
{
setCitationProperty(Schema.TITLE, RISvalue);
logger.debug("importFromRisList: I manually mapped " + RIScode +
" to " + Schema.TITLE);
}
else
logger.debug("importFromRisList: Cannot find Field mapping");
} // end article schema mapping exceptions
else if (schema.getIdentifier().equalsIgnoreCase("unknown"))
{
if (RIScode.equalsIgnoreCase("AU")) // EndNote
{
setCitationProperty(Schema.CREATOR, RISvalue);
logger.debug("importFromRisList: I manually mapped " + RIScode +
" to " + Schema.CREATOR);
}
else
logger.debug("importFromRisList: Cannot find Field mapping");
} // end unknown schema mapping exceptions
else
*/ logger.debug("importFromRisList: Cannot find field mapping for RIScode " +
RIScode + " for Schema = " + schema);
} // end if status (field not found)
else // ! status. We found a field in the Schema
{
logger.debug("importFromRisList: Field mapping is " + tempField.getIdentifier() +
" => " + RISvalue);
// We found the mapping in the previous while loop. Set the citation property
setCitationProperty(tempField.getIdentifier(), RISvalue);
} // end we found the mapping
} // end else of i == 0
} // end for i
// if we got here, the record wasn't properly formatted with an "ER" record (or other issues).
logger.debug("importFromRisList: FALSE - End of Input. Citation not added.");
return false;
} // end ImportFromRisList
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#isAdded()
*/
public boolean isAdded()
{
return this.m_isAdded;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#isMultivalued(java.lang.String)
*/
public boolean isMultivalued(String fieldId)
{
boolean isMultivalued = false;
if (m_schema != null)
{
Field field = m_schema.getField(fieldId);
if (field != null)
{
isMultivalued = field.isMultivalued();
}
}
return isMultivalued;
}
/**
* @return
*/
public boolean isTemporary()
{
return m_temporary;
}
public List listCitationProperties()
{
if (m_citationProperties == null)
{
m_citationProperties = new Hashtable();
}
return new Vector(m_citationProperties.keySet());
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#setAdded()
*/
public void setAdded(boolean added)
{
this.m_isAdded = added;
}
public void setCitationProperty(String name, Object value)
{
if (m_citationProperties == null)
{
m_citationProperties = new Hashtable();
}
if (isMultivalued(name))
{
List list = (List) m_citationProperties.get(name);
if (list == null)
{
list = new Vector();
m_citationProperties.put(name, list);
}
if (value != null)
{
list.add(value);
}
}
else
{
if (value == null)
{
m_citationProperties.remove(name);
}
else
{
m_citationProperties.put(name, value);
}
}
}
protected void setDefaults()
{
if (m_schema != null)
{
List fields = m_schema.getFields();
Iterator it = fields.iterator();
while (it.hasNext())
{
Field field = (Field) it.next();
if (field.isRequired())
{
Object value = field.getDefaultValue();
if (value == null)
{
// do nothing -- there's no value to set
}
else if (field.isMultivalued())
{
List current_values = (List) this.getCitationProperty(field
.getIdentifier());
if (current_values.isEmpty())
{
this.addPropertyValue(field.getIdentifier(), value);
}
}
else if (this.getCitationProperty(field.getIdentifier()) == null)
{
setCitationProperty(field.getIdentifier(), value);
}
}
}
}
}
public void setDisplayName(String name)
{
if (name == null || name.trim().equals(""))
{
setCitationProperty(Schema.TITLE, "untitled");
}
else
{
setCitationProperty(Schema.TITLE, name);
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#setSchema(org.sakaiproject.citation.api.Schema)
*/
public void setSchema(Schema schema)
{
this.m_schema = schema;
setDefaults();
}
protected void setType(String mediatype)
{
Schema schema = m_storage.getSchema(mediatype);
if (schema == null)
{
schema = m_storage.getSchema(CitationService.UNKNOWN_TYPE);
}
setSchema(schema);
}
public String toString()
{
return "BasicCitation: " + this.m_id;
}
public void updateCitationProperty(String name, List values)
{
// what if "name" is not a valid field in the schema??
if (m_citationProperties == null)
{
m_citationProperties = new Hashtable();
}
if (isMultivalued(name))
{
List list = (List) m_citationProperties.get(name);
if (list == null)
{
list = new Vector();
m_citationProperties.put(name, list);
}
list.clear();
if (values != null)
{
list.addAll(values);
}
}
else
{
if (values == null || values.isEmpty())
{
m_citationProperties.remove(name);
}
else
{
m_citationProperties.put(name, values.get(0));
}
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Citation#updateUrl(java.lang.String,
* java.lang.String, java.net.URL)
*/
public void updateCustomUrl(String urlid, String label, String url)
{
UrlWrapper wrapper = new UrlWrapper(label, url);
m_urls.put(urlid, wrapper);
}
/* (non-Javadoc)
* @see org.sakaiproject.citation.api.Citation#getSaveUrl()
*/
public String getSaveUrl(String collectionId)
{
SessionManager sessionManager = (SessionManager) ComponentManager.get("org.sakaiproject.tool.api.SessionManager");
String sessionId = sessionManager.getCurrentSession().getId();
String url = m_serverConfigurationService.getServerUrl() + "/savecite/" + collectionId + "?sakai.session=" + sessionId;
String genre = this.getSchema().getIdentifier();
url += "&genre=" + genre;
String openUrlParams = this.getOpenurlParameters();
String[] params = openUrlParams.split("&");
for(int i = 0; i < params.length; i++)
{
String[] parts = params[i].split("=");
String key = GS_TAGS.get(parts[0]);
if(key != null)
{
url += "&" + key + "=" + parts[1];
}
}
return url;
}
public String getPreferredUrlId()
{
return this.m_preferredUrl;
}
public boolean hasPreferredUrl()
{
return this.m_preferredUrl != null;
}
public void setPreferredUrl(String urlid)
{
if(urlid == null)
{
this.m_preferredUrl = null;
}
else if(this.m_urls.containsKey(urlid))
{
this.m_preferredUrl = urlid;
}
}
} // BaseCitationService.BasicCitation
/**
*
*/
public class BasicCitationCollection implements CitationCollection
{
protected final Comparator DEFAULT_COMPARATOR = new BasicCitationCollection.TitleComparator(true);
public class MultipleKeyComparator implements Comparator
{
protected List<String> m_keys = new Vector<String>();
protected boolean m_ascending = true;
public MultipleKeyComparator(List<String> keys, boolean ascending)
{
m_keys.addAll(keys);
}
public MultipleKeyComparator( MultipleKeyComparator mkc )
{
this.m_keys = mkc.m_keys;
this.m_ascending = mkc.m_ascending;
}
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(Object arg0, Object arg1)
{
int rv = 0;
if (!(arg0 instanceof String) || !(arg1 instanceof String))
{
throw new ClassCastException();
}
Object obj0 = m_citations.get(arg0);
Object obj1 = m_citations.get(arg1);
if (!(obj0 instanceof Citation) || !(obj1 instanceof Citation))
{
throw new ClassCastException();
}
Citation cit0 = (Citation) obj0;
Citation cit1 = (Citation) obj1;
Iterator keyIt = m_keys.iterator();
while(rv == 0 && keyIt.hasNext())
{
String key = (String) keyIt.next();
if(CitationCollection.SORT_BY_TITLE.equalsIgnoreCase(key))
{
/*
String title0 = cit0.getDisplayName().toLowerCase();
String title1 = cit1.getDisplayName().toLowerCase();
*/
String title0 = ((String)cit0.getCitationProperty( Schema.TITLE )).toLowerCase();;
String title1 = ((String)cit1.getCitationProperty( Schema.TITLE )).toLowerCase();;
if (title0 == null)
{
title0 = "";
}
if (title1 == null)
{
title1 = "";
}
rv = m_ascending ? title0.compareTo(title1) : title1.compareTo(title0);
}
else if(CitationCollection.SORT_BY_AUTHOR.equalsIgnoreCase(key))
{
String author0 = cit0.getCreator().toLowerCase();
String author1 = cit1.getCreator().toLowerCase();
if (author0 == null)
{
author0 = "";
}
if (author1 == null)
{
author1 = "";
}
rv = m_ascending ? author0.compareTo(author1) : author1.compareTo(author0);
}
else if(CitationCollection.SORT_BY_YEAR.equalsIgnoreCase(key))
{
String year0 = cit0.getYear();
String year1 = cit1.getYear();
if (year0 == null)
{
year0 = "";
}
if (year1 == null)
{
year1 = "";
}
rv = m_ascending ? year0.compareTo(year1) : year1.compareTo(year0);
}
else if( CitationCollection.SORT_BY_UUID.equalsIgnoreCase( key ) )
{
// not considering m_ascending for ids because they are random alpha-numeric strings
rv = cit0.getId().compareTo(cit1.getId());
}
}
return rv;
}
public void addKey(String key)
{
m_keys.add(key);
}
}
public class AuthorComparator extends MultipleKeyComparator
{
/**
* @param ascending
*/
public AuthorComparator(boolean ascending)
{
super(AUTHOR_AS_KEY, ascending);
}
}
public class YearComparator extends MultipleKeyComparator
{
/**
* @param ascending
*/
public YearComparator(boolean ascending)
{
super(YEAR_AS_KEY, ascending);
}
} // end class DateComparator
public class BasicIterator implements CitationIterator
{
protected List listOfKeys;
// This is the firstItem on a given rendered page
protected int firstItem;
// This is the item where next() returns and increments. At
// the start of rendering a given page nextItem = firstItem and
// increments until lastItem
protected int nextItem;
// This is the lastitem on a given rendered page
protected int lastItem;
public BasicIterator()
{
checkForUpdates();
this.listOfKeys = new Vector(m_order);
this.firstItem = 0;
setIndexes();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#getPageSize()
*/
public int getPageSize()
{
// TODO Auto-generated method stub
return m_pageSize;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#hasNext()
*/
public boolean hasNext()
{
boolean hasNext = false;
if (m_ascending)
{
hasNext = this.nextItem < this.lastItem
&& this.nextItem < this.listOfKeys.size();
}
else
{
hasNext = this.nextItem > this.lastItem && this.nextItem > 0;
}
return hasNext;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#hasNextPage()
*/
public boolean hasNextPage()
{
boolean hasNextPage = false;
if (m_ascending)
hasNextPage = this.firstItem + m_pageSize < this.listOfKeys.size();
else
hasNextPage = this.firstItem - m_pageSize >= 0;
return hasNextPage;
// return m_pageSize * (startPage + 1) < this.listOfKeys.size();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#hasPreviousPage()
*/
public boolean hasPreviousPage()
{
boolean hasPreviousPage = false;
if (m_ascending)
hasPreviousPage = this.firstItem - m_pageSize >= 0;
else
hasPreviousPage = this.firstItem + m_pageSize < this.listOfKeys.size();
return hasPreviousPage;
// return this.startPage > 0;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#next()
*/
public Object next()
{
Object item = null;
if (m_ascending)
{
if (this.nextItem >= this.lastItem || this.nextItem >= listOfKeys.size())
{
throw new NoSuchElementException();
}
item = m_citations.get(listOfKeys.get(this.nextItem++));
}
else
{
if (this.nextItem <= this.lastItem || this.nextItem <= 0)
{
throw new NoSuchElementException();
}
item = m_citations.get(listOfKeys.get(this.nextItem--));
}
return item;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#nextPage()
*/
public void nextPage()
{
if (m_ascending)
{
this.firstItem = this.firstItem + m_pageSize;
}
else
{
this.firstItem = this.firstItem - m_pageSize;
}
setIndexes();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#previousPage()
*/
public void previousPage()
{
if (m_ascending)
{
this.firstItem = this.firstItem - m_pageSize;
}
else
{
this.firstItem = this.firstItem + m_pageSize;
}
setIndexes();
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#remove()
*/
public void remove()
{
throw new UnsupportedOperationException();
}
protected void setIndexes()
{
this.nextItem = this.firstItem;
if (m_ascending)
{
this.lastItem = Math.min(this.listOfKeys.size(), this.nextItem + m_pageSize);
}
else
{
this.lastItem = Math.max(0, this.nextItem - m_pageSize);
}
} // end setIndexes()
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#setSort(java.util.Comparator)
*/
public void setOrder(Comparator comparator)
{
m_comparator = comparator;
if (comparator == null)
{
}
else
{
Collections.sort(this.listOfKeys, m_comparator);
}
this.firstItem = 0;
setIndexes();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationIterator#setPageSize(int)
*/
public void setPageSize(int size)
{
if (size > 0)
{
// So that resizing the page at the start of a list (say 11-20)
// with a new size of 20... gives us 1-20 not 11-30
if (this.lastItem <= size)
{
this.firstItem = 0;
}
this.lastItem = this.firstItem + size;
if (this.lastItem >= this.listOfKeys.size())
this.lastItem = this.listOfKeys.size() - 1;
m_pageSize = size;
setIndexes();
} // end if size > 0
} // end setPageSize()
public int getStart()
{
return this.firstItem;
}
public int getEnd()
{
return this.lastItem;
}
public void setStart(int i)
{
if (i >= 0 && i < this.listOfKeys.size())
{
this.firstItem = i;
setIndexes();
}
} // end setStart()
} // end class BasicIterator
public class TitleComparator extends MultipleKeyComparator
{
/**
* @param ascending
*/
public TitleComparator(boolean ascending)
{
super(TITLE_AS_KEY, ascending);
}
}
protected Map<String, Citation> m_citations = new Hashtable<String, Citation>();
protected Comparator m_comparator = DEFAULT_COMPARATOR;
protected String m_sortOrder;
protected SortedSet<String> m_order;
protected int m_pageSize = DEFAULT_PAGE_SIZE;
protected String m_description;
protected String m_id;
protected String m_title;
protected boolean m_temporary = false;
protected Integer m_serialNumber;
protected ActiveSearch m_mySearch;
protected boolean m_ascending = true;
protected long m_mostRecentUpdate = 0L;
public BasicCitationCollection()
{
m_id = IdManager.createUuid();
}
/**
* @param b
*/
public BasicCitationCollection(boolean temporary)
{
m_order = new TreeSet<String>(m_comparator);
m_temporary = temporary;
if (temporary)
{
m_serialNumber = nextSerialNumber();
}
else
{
m_id = IdManager.createUuid();
}
}
public BasicCitationCollection(Map attributes, List citations)
{
m_id = IdManager.createUuid();
m_order = new TreeSet<String>(m_comparator);
if (citations != null)
{
Iterator citationIt = citations.iterator();
while (citationIt.hasNext())
{
Citation citation = (Citation) citationIt.next();
m_citations.put(citation.getId(), citation);
m_order.add(citation.getId());
}
}
}
/**
* @param collectionId
*/
public BasicCitationCollection(String collectionId)
{
m_id = collectionId;
m_order = new TreeSet(m_comparator);
}
public void add(Citation citation)
{
//checkForUpdates();
if (!this.m_citations.keySet().contains(citation.getId()))
{
this.m_citations.put(citation.getId(), citation);
}
if(!this.m_order.contains(citation.getId()))
{
this.m_order.add(citation.getId());
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#addAll(org.sakaiproject.citation.api.CitationCollection)
*/
public void addAll(CitationCollection other)
{
checkForUpdates();
if(this.m_order == null)
{
this.m_order = new TreeSet<String>();
}
for(String key : ((BasicCitationCollection) other).m_order )
{
try
{
Citation citation = other.getCitation(key);
this.add(citation);
}
catch (IdUnusedException e)
{
M_log.debug("BasicCitationCollection.addAll citationId (" + key
+ ") in m_order but not in m_citations; collectionId: "
+ other.getId());
}
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#clear()
*/
public void clear()
{
this.m_order.clear();
this.m_citations.clear();
}
public boolean contains(Citation citation)
{
checkForUpdates();
return this.m_citations.containsKey(citation.getId());
}
protected void copy(BasicCitationCollection other)
{
checkForUpdates();
this.m_ascending = other.m_ascending;
/*
* Get new instance of comparator
*/
if( other.m_comparator instanceof MultipleKeyComparator )
{
this.m_comparator = new MultipleKeyComparator( (MultipleKeyComparator)other.m_comparator );
}
else
{
// default to title, ascending
this.m_comparator = new MultipleKeyComparator( TITLE_AS_KEY, true );
}
set(other);
}
public void exportRis(StringBuilder buffer, List<String> citationIds) throws IOException
{
checkForUpdates();
// output "header" info to buffer
// Iterate over citations and output to ostream
for( String citationId : citationIds )
{
Citation citation = (Citation) this.m_citations.get(citationId);
if (citation != null)
{
citation.exportRis(buffer);
}
}
}
/**
* Compute an alternate root for a reference, based on the root
* property.
*
* @param rootProperty
* The property name.
* @return The alternate root, or "" if there is none.
*/
protected String getAlternateReferenceRoot(String rootProperty)
{
// null means don't do this
if (rootProperty == null || rootProperty.trim().equals(""))
{
return "";
}
// make sure it start with a separator and does not end with one
if (!rootProperty.startsWith(Entity.SEPARATOR))
{
rootProperty = Entity.SEPARATOR + rootProperty;
}
if (rootProperty.endsWith(Entity.SEPARATOR))
{
rootProperty = rootProperty
.substring(0, rootProperty.length() - SEPARATOR.length());
}
return rootProperty;
}
public Citation getCitation(String citationId) throws IdUnusedException
{
checkForUpdates();
Citation citation = (Citation) m_citations.get(citationId);
if (citation == null)
{
throw new IdUnusedException(citationId);
}
return citation;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#getCitations()
*/
public List getCitations()
{
checkForUpdates();
List citations = new Vector();
if (m_citations == null)
{
m_citations = new Hashtable<String, Citation>();
}
if(m_order == null)
{
m_order = new TreeSet<String>();
}
Iterator keyIt = this.m_order.iterator();
while (keyIt.hasNext())
{
String key = (String) keyIt.next();
Object citation = this.m_citations.get(key);
if (citation != null)
{
citations.add(citation);
}
}
return citations;
}
public CitationCollection getCitations(Comparator c)
{
checkForUpdates();
// TODO Auto-generated method stub
return null;
}
public CitationCollection getCitations(Comparator c, Filter f)
{
checkForUpdates();
// TODO Auto-generated method stub
return null;
}
public CitationCollection getCitations(Filter f)
{
checkForUpdates();
// TODO Auto-generated method stub
return null;
}
public CitationCollection getCitations(Map properties)
{
checkForUpdates();
// TODO Auto-generated method stub
return null;
}
// public Citation remove(int index)
// {
// // TODO
// return null;
// }
//
// public Citation remove(Map properties)
// {
// // TODO Auto-generated method stub
// return null;
// }
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#getDescription()
*/
public String getDescription()
{
checkForUpdates();
return m_description;
}
public String getId()
{
return this.m_id;
}
public ResourceProperties getProperties()
{
// TODO Auto-generated method stub
return null;
}
// public void sort(Comparator c)
// {
// // TODO Auto-generated method stub
//
// }
public String getReference()
{
return getReference(null);
}
public String getReference(String rootProperty)
{
return m_relativeAccessPoint + getAlternateReferenceRoot(rootProperty)
+ Entity.SEPARATOR + getId();
}
/* (non-Javadoc)
* @see org.sakaiproject.citation.api.CitationCollection#getSaveUrl()
*/
public String getSort()
{
if (m_sortOrder == null)
m_sortOrder = this.SORT_BY_DEFAULT_ORDER;
return m_sortOrder;
}
/* (non-Javadoc)
* @see org.sakaiproject.citation.api.CitationCollection#getSaveUrl()
*/
public String getSaveUrl()
{
String url = m_serverConfigurationService.getServerUrl() + "/savecite/" + this.getId() + "/";
return url;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#getTitle()
*/
public String getTitle()
{
checkForUpdates();
return m_title;
}
public String getUrl()
{
return getUrl(null);
}
public String getUrl(String rootProperty)
{
return getAccessPoint(false) + getAlternateReferenceRoot(rootProperty)
+ Entity.SEPARATOR + getId();
}
public boolean isEmpty()
{
checkForUpdates();
return this.m_citations.isEmpty();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#iterator()
*/
public CitationIterator iterator()
{
checkForUpdates();
return new BasicIterator();
}
// public Iterator iterator()
// {
// // TODO Auto-generated method stub
// return null;
// }
//
//
// public int lastIndexOf(Citation item)
// {
// // TODO Auto-generated method stub
// return 0;
// }
//
// public boolean move(int from, int to)
// {
// // TODO Auto-generated method stub
// return false;
// }
//
// public boolean moveToBack(int index)
// {
// // TODO Auto-generated method stub
// return false;
// }
//
// public boolean moveToFront(int index)
// {
// // TODO Auto-generated method stub
// return false;
// }
//
public boolean remove(Citation item)
{
checkForUpdates();
boolean success = true;
this.m_order.remove(item.getId());
Object obj = this.m_citations.remove(item.getId());
if (obj == null)
{
success = false;
}
return success;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationCollection#saveCitation(org.sakaiproject.citation.api.Citation)
*/
public void saveCitation(Citation citation)
{
//checkForUpdates();
// m_storage.saveCitation(citation);
save(citation);
}
/**
*
* @param comparator
*/
public void setSort(Comparator comparator)
{
checkForUpdates();
this.m_comparator = comparator;
SortedSet oldSet = this.m_order;
this.m_order = new TreeSet<String>(this.m_comparator);
this.m_order.addAll(oldSet);
}
/**
*
* @param sortBy
* @param ascending
*/
public void setSort(String sortBy, boolean ascending)
{
m_ascending = ascending;
String status = "UNSET";
if (sortBy == null || sortBy.equalsIgnoreCase(SORT_BY_DEFAULT_ORDER))
{
this.m_comparator = null;
}
else if (sortBy.equalsIgnoreCase(SORT_BY_AUTHOR))
{
this.m_comparator = new AuthorComparator(ascending);
status = "AUTHOR SET";
}
else if (sortBy.equalsIgnoreCase(SORT_BY_TITLE))
{
this.m_comparator = new TitleComparator(ascending);
status = "TITLE SET";
}
else if (sortBy.equalsIgnoreCase(SORT_BY_YEAR))
{
this.m_comparator = new YearComparator(ascending);
status = "YEAR SET";
}
if (this.m_comparator != null)
{
this.m_sortOrder = sortBy;
SortedSet oldSet = this.m_order;
this.m_order = new TreeSet<String>(this.m_comparator);
this.m_order.addAll(oldSet);
}
} // end setSort(String, boolean)
public int size()
{
checkForUpdates();
return m_order.size();
}
public String toString()
{
return "BasicCitationCollection: " + this.m_id;
}
public Element toXml(Document doc, Stack stack)
{
// TODO Auto-generated method stub
return null;
}
protected void checkForUpdates()
{
if(this.m_mostRecentUpdate < m_storage.mostRecentUpdate(this.m_id))
{
CitationCollection edit = m_storage.getCollection(this.m_id);
if (edit == null)
{
}
else
{
set((BasicCitationCollection) edit);
}
}
}
/**
* copy
* @param other
*/
protected void set(BasicCitationCollection other)
{
this.m_description = other.m_description;
// this.m_comparator = other.m_comparator;
this.m_serialNumber = other.m_serialNumber;
this.m_pageSize = other.m_pageSize;
this.m_temporary = other.m_temporary;
this.m_title = other.m_title;
if(this.m_citations == null)
{
this.m_citations = new Hashtable<String, Citation>();
}
this.m_citations.clear();
if(this.m_order == null)
{
this.m_order = new TreeSet<String>(this.m_comparator);
}
this.m_order.clear();
Iterator it = other.m_citations.keySet().iterator();
while(it.hasNext())
{
String citationId = (String) it.next();
BasicCitation oldCitation = (BasicCitation) other.m_citations.get(citationId);
BasicCitation newCitation = new BasicCitation();
try
{
newCitation.copy(oldCitation);
newCitation.m_id = oldCitation.m_id;
newCitation.m_temporary = false;
this.saveCitation(newCitation);
this.add(newCitation);
}
catch(Exception e)
{
M_log.warn("copy(" + oldCitation.getId() + ") ==> " + newCitation.getId(), e);
}
}
this.m_mostRecentUpdate = TimeService.newTime().getTime();
}
} // BaseCitationService.BasicCitationCollection
/**
*
*/
public class BasicField implements Field
{
protected Object defaultValue;
protected String description;
protected String identifier;
protected String label;
protected int maxCardinality;
protected int minCardinality;
protected String namespace;
protected int order;
protected boolean required;
protected String valueType;
protected Map identifiers;
protected boolean isEditable;
// delimiter used to separate Field identifiers
public final static String DELIMITER = ",";
/**
* @param field
*/
public BasicField(Field other)
{
this.identifier = other.getIdentifier();
this.valueType = other.getValueType();
this.required = other.isRequired();
this.minCardinality = other.getMinCardinality();
this.maxCardinality = other.getMaxCardinality();
this.namespace = other.getNamespaceAbbreviation();
this.description = other.getDescription();
this.identifiers = new Hashtable();
this.isEditable = other.isEditable();
if (other instanceof BasicField)
{
this.order = ((BasicField) other).getOrder();
Iterator it = ((BasicField) other).identifiers.keySet().iterator();
while (it.hasNext())
{
String format = (String) it.next();
this.identifiers.put(format, ((BasicField) other).identifiers.get(format));
}
}
}
public BasicField(String identifier, String valueType, boolean isEditable,
boolean required, int minCardinality, int maxCardinality)
{
this.identifier = identifier;
this.valueType = valueType;
this.required = required;
this.minCardinality = minCardinality;
this.maxCardinality = maxCardinality;
this.namespace = "";
this.label = "";
this.description = "";
this.order = 0;
this.identifiers = new Hashtable();
this.isEditable = true;
}
public Object getDefaultValue()
{
return defaultValue;
}
public String getDescription()
{
return this.description;
}
public String getIdentifier()
{
return identifier;
}
public String getIdentifier(String format)
{
String tempString = null;
String[] tokens = null;
tempString = (String) this.identifiers.get(format);
if (tempString == null)
tempString = "";
tempString = tempString.trim();
// Is this a compound/delimited value?
if (tempString.indexOf(DELIMITER) != -1)
{
// split the string based on the delimiter
tokens = tempString.split(DELIMITER);
// use the first delimiter as the identifier
tempString = tokens[0];
} // end getIdentifier
return tempString;
}
public String[] getIdentifierComplex(String format)
{
String tempString = null;
String[] tokens = null;
tempString = (String) this.identifiers.get(format);
if (tempString == null)
tempString = "";
tempString = tempString.trim();
// Is this a compound/delimited value?
if (tempString.indexOf(DELIMITER) != -1)
{
// split the string based on the delimiter
tokens = tempString.split(DELIMITER);
}
else // it's a simple value
{
tokens = new String[1];
tokens[0] = tempString;
}
return tokens;
} // end getComplexIdentifers
public String getLabel()
{
return this.label;
}
public int getMaxCardinality()
{
return maxCardinality;
}
public int getMinCardinality()
{
return minCardinality;
}
public String getNamespaceAbbreviation()
{
return this.namespace;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Schema.Field#getOrder()
*/
public int getOrder()
{
return order;
}
public String getValueType()
{
return valueType;
}
public boolean isEditable()
{
return isEditable;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Schema.Field#isMultivalued()
*/
public boolean isMultivalued()
{
return this.maxCardinality > 1;
}
public boolean isRequired()
{
return required;
}
public void setDefaultValue(Object value)
{
this.defaultValue = value;
}
/**
* @param label
*/
public void setDescription(String description)
{
this.description = description;
}
public void setEditable(boolean isEditable)
{
this.isEditable = isEditable;
}
public void setIdentifier(String format, String identifier)
{
this.identifiers.put(format, identifier);
}
/**
* @param label
*/
public void setLabel(String label)
{
this.label = label;
}
/**
* @param maxCardinality
* The maxCardinality to set.
*/
public void setMaxCardinality(int maxCardinality)
{
this.maxCardinality = maxCardinality;
}
/**
* @param minCardinality
* The minCardinality to set.
*/
public void setMinCardinality(int minCardinality)
{
this.minCardinality = minCardinality;
}
public void setNamespaceAbbreviation(String namespace)
{
this.namespace = namespace;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Schema.Field#setOrder(int)
*/
public void setOrder(int order)
{
this.order = order;
}
/**
* @param required
* The required to set.
*/
public void setRequired(boolean required)
{
this.required = required;
}
/**
* @param valueType
* The valueType to set.
*/
public void setValueType(String valueType)
{
this.valueType = valueType;
}
public String toString()
{
return "BasicField: " + this.identifier;
}
}
/**
*
*/
protected class BasicSchema implements Schema
{
protected String defaultNamespace;
protected List fields;
protected String identifier;
protected Map index;
protected Map namespaces;
protected Map identifiers;
/**
*
*/
public BasicSchema()
{
this.fields = new Vector();
this.index = new Hashtable();
this.identifiers = new Hashtable();
}
/**
* @param schema
*/
public BasicSchema(Schema other)
{
this.identifier = other.getIdentifier();
this.defaultNamespace = other.getNamespaceAbbrev();
namespaces = new Hashtable();
List nsAbbrevs = other.getNamespaceAbbreviations();
if (nsAbbrevs != null)
{
Iterator nsIt = nsAbbrevs.iterator();
while (nsIt.hasNext())
{
String nsAbbrev = (String) nsIt.next();
String ns = other.getNamespaceUri(nsAbbrev);
namespaces.put(nsAbbrev, ns);
}
}
this.identifiers = new Hashtable();
if (other instanceof BasicSchema)
{
Iterator it = ((BasicSchema) other).identifiers.keySet().iterator();
while (it.hasNext())
{
String format = (String) it.next();
this.identifiers.put(format, ((BasicSchema) other).identifiers.get(format));
}
}
this.fields = new Vector();
this.index = new Hashtable();
List fields = other.getFields();
Iterator fieldIt = fields.iterator();
while (fieldIt.hasNext())
{
Field field = (Field) fieldIt.next();
this.fields.add(new BasicField(field));
index.put(field.getIdentifier(), field);
}
}
/**
* @param schemaId
*/
public BasicSchema(String schemaId)
{
this.identifier = schemaId;
this.fields = new Vector();
this.index = new Hashtable();
this.identifiers = new Hashtable();
}
public void addAlternativeIdentifier(String fieldId, String altFormat, String altIdentifier)
{
BasicField field = (BasicField) this.index.get(fieldId);
if (field != null)
{
field.setIdentifier(altFormat, altIdentifier);
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Schema#addField(org.sakaiproject.citation.api.Schema.Field)
*/
public void addField(Field field)
{
this.index.put(field.getIdentifier(), field);
this.fields.add(field);
}
/**
* @param order
* @param field
*/
public void addField(int order, Field field)
{
fields.add(order, field);
index.put(identifier, field);
}
public BasicField addField(String identifier, String valueType, boolean isEditable,
boolean required, int minCardinality, int maxCardinality)
{
if (fields == null)
{
fields = new Vector();
}
if (index == null)
{
index = new Hashtable();
}
BasicField field = new BasicField(identifier, valueType, isEditable, required,
minCardinality, maxCardinality);
fields.add(field);
index.put(identifier, field);
return field;
}
public BasicField addOptionalField(String identifier, String valueType, int minCardinality,
int maxCardinality)
{
return addField(identifier, valueType, true, false, minCardinality, maxCardinality);
}
public BasicField addRequiredField(String identifier, String valueType, int minCardinality,
int maxCardinality)
{
return addField(identifier, valueType, true, true, minCardinality, maxCardinality);
}
public Field getField(int index)
{
if (fields == null)
{
fields = new Vector();
}
return (Field) fields.get(index);
}
public Field getField(String name)
{
if (index == null)
{
index = new Hashtable();
}
return (Field) index.get(name);
}
public List getFields()
{
if (fields == null)
{
fields = new Vector();
}
return fields;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Schema#getIdentifier()
*/
public String getIdentifier()
{
return this.identifier;
}
public String getIdentifier(String format)
{
return (String) this.identifiers.get(format);
}
public String getNamespaceAbbrev()
{
return defaultNamespace;
}
public List getNamespaceAbbreviations()
{
if (namespaces == null)
{
namespaces = new Hashtable();
}
Collection keys = namespaces.keySet();
List rv = new Vector();
if (keys != null)
{
rv.addAll(keys);
}
return rv;
}
public String getNamespaceUri(String abbrev)
{
if (namespaces == null)
{
namespaces = new Hashtable();
}
return (String) namespaces.get(abbrev);
}
public List getRequiredFields()
{
if (fields == null)
{
fields = new Vector();
}
List required = new Vector();
Iterator it = fields.iterator();
while (it.hasNext())
{
Field field = (Field) it.next();
if (field.isRequired())
{
required.add(field);
}
}
return required;
}
/**
* @param identifier
*/
public void setIdentifier(String identifier)
{
this.identifier = identifier;
}
public void setIdentifier(String format, String identifier)
{
this.identifiers.put(format, identifier);
}
/**
*
*/
public void sortFields()
{
Collections.sort(fields, new Comparator()
{
public int compare(Object arg0, Object arg1)
{
if (arg0 instanceof BasicField && arg1 instanceof BasicField)
{
Integer int0 = new Integer(((BasicField) arg0).getOrder());
Integer int1 = new Integer(((BasicField) arg1).getOrder());
return int0.compareTo(int1);
}
else if (arg0 instanceof Field && arg1 instanceof Field)
{
String lbl0 = ((Field) arg0).getLabel();
String lbl1 = ((Field) arg1).getLabel();
return lbl0.compareTo(lbl1);
}
else
{
throw new ClassCastException(arg0.toString() + " " + arg1.toString());
}
}
});
}
public String toString()
{
return "BasicSchema: " + this.identifier;
}
}
/**
*
*/
protected interface Storage
{
/**
* @param mediatype
* @return
*/
public Citation addCitation(String mediatype);
public CitationCollection addCollection(Map attributes, List citations);
public Schema addSchema(Schema schema);
public boolean checkCitation(String citationId);
public boolean checkCollection(String collectionId);
public boolean checkSchema(String schemaId);
public long mostRecentUpdate(String collectionId);
/**
* Close.
*/
public void close();
public CitationCollection copyAll(String collectionId);
public Citation getCitation(String citationId);
public CitationCollection getCollection(String collectionId);
public Schema getSchema(String schemaId);
public List getSchemas();
/**
* @return
*/
public List listSchemas();
/**
* Open and be ready to read / write.
*/
public void open();
public void putSchemas(Collection schemas);
public void removeCitation(Citation edit);
public void removeCollection(CitationCollection edit);
public void removeSchema(Schema schema);
public void saveCitation(Citation edit);
public void saveCollection(CitationCollection collection);
public void updateSchema(Schema schema);
public void updateSchemas(Collection schemas);
} // interface Storage
/**
*
*/
public class UrlWrapper
{
protected String m_label;
protected String m_url;
/**
* @param label
* @param url
*/
public UrlWrapper(String label, String url)
{
m_label = label;
m_url = url;
}
/**
* @return the label
*/
public String getLabel()
{
return m_label;
}
/**
* @return the url
*/
public String getUrl()
{
return m_url;
}
/**
* @param label
* the label to set
*/
public void setLabel(String label)
{
m_label = label;
}
/**
* @param url
* the url to set
*/
public void setUrl(String url)
{
m_url = url;
}
}
public static ResourceLoader rb;
/** Our logger. */
private static Log M_log = LogFactory.getLog(BaseCitationService.class);
protected static final String PROPERTY_DEFAULTVALUE = "sakai:defaultValue";
protected static final String PROPERTY_DESCRIPTION = "sakai:description";
protected static final String PROPERTY_HAS_ABBREVIATION = "sakai:hasAbbreviation";
protected static final String PROPERTY_HAS_CITATION = "sakai:hasCitation";
protected static final String PROPERTY_HAS_FIELD = "sakai:hasField";
protected static final String PROPERTY_HAS_NAMESPACE = "sakai:hasNamespace";
protected static final String PROPERTY_HAS_ORDER = "sakai:hasOrder";
protected static final String PROPERTY_HAS_SCHEMA = "sakai:hasSchema";
protected static final String PROPERTY_LABEL = "sakai:label";
protected static final String PROPERTY_MAXCARDINALITY = "sakai:maxCardinality";
protected static final String PROPERTY_MINCARDINALITY = "sakai:minCardinality";
protected static final String PROPERTY_NAMESPACE = "sakai:namespace";
protected static final String PROPERTY_REQUIRED = "sakai:required";
protected static final String PROPERTY_VALUETYPE = "sakai:valueType";
public static final String SCHEMA_PREFIX = "schema.";
protected static Integer m_nextSerialNumber;
/*
* RIS MAPPINGS below
*/
protected static final String RIS_DELIM = " - ";
/**
* Set up a mapping of our type to RIS 'TY - ' values
*/
protected static final Map m_RISType = new Hashtable();
protected static final Map m_RISTypeInverse = new Hashtable();
/**
* Which fields map onto the RIS Notes field? Include a prefix for the data,
* if necessary.
*/
protected static final Map m_RISNoteFields = new Hashtable();
/**
* Which fields need special processing for RIS export?
*/
protected static final Set m_RISSpecialFields = new java.util.HashSet();
static
{
m_RISType.put("unknown", "JOUR"); // Default to journal article
m_RISType.put("article", "JOUR");
m_RISType.put("book", "BOOK");
m_RISType.put("chapter", "CHAP");
m_RISType.put("report", "RPRT");
m_RISTypeInverse.put("BOOK", "book");
m_RISTypeInverse.put("CHAP", "chapter");
m_RISTypeInverse.put("JOUR", "article");
m_RISTypeInverse.put("RPRT", "report");
}
static
{
m_RISNoteFields.put("language", "Language: ");
m_RISNoteFields.put("doi", "DOI: ");
m_RISNoteFields.put("rights", "Rights: ");
}
static
{
m_RISSpecialFields.add("date");
m_RISSpecialFields.add("doi");
}
public static String escapeFieldName(String original)
{
if (original == null)
{
return "";
}
original = original.trim();
try
{
// convert the string to bytes in UTF-8
byte[] bytes = original.getBytes("UTF-8");
StringBuilder buf = new StringBuilder();
for (int i = 0; i < bytes.length; i++)
{
byte b = bytes[i];
// escape ascii control characters, ascii high bits, specials
if (Schema.ESCAPE_FIELD_NAME.indexOf((char) b) != -1)
{
buf.append(Schema.ESCAPE_CHAR); // special funky way to
// encode bad URL characters
// - ParameterParser will
// decode it
}
else
{
buf.append((char) b);
}
}
String rv = buf.toString();
return rv;
}
catch (Exception e)
{
M_log.warn("BaseCitationService.escapeFieldName: ", e);
return original;
}
}
/** Dependency: CitationsConfigurationService. */
protected ConfigurationService m_configService = null;
/** Dependency: ServerConfigurationService. */
protected ServerConfigurationService m_serverConfigurationService = null;
/** Dependency: ContentHostingService. */
protected ContentHostingService m_contentHostingService = null;
/** Dependency: EntityManager. */
protected EntityManager m_entityManager = null;
protected String m_defaultSchema;
/** A Storage object for persistent storage. */
protected Storage m_storage = null;
protected String m_relativeAccessPoint;
/**
* Dependency: the ResourceTypeRegistry
*/
protected ResourceTypeRegistry m_resourceTypeRegistry;
/**
* Dependency: inject the ResourceTypeRegistry
* @param registry
*/
public void setResourceTypeRegistry(ResourceTypeRegistry registry)
{
m_resourceTypeRegistry = registry;
}
/**
* @return the ResourceTypeRegistry
*/
public ResourceTypeRegistry getResourceTypeRegistry()
{
return m_resourceTypeRegistry;
}
public static final String PROP_TEMPORARY_CITATION_LIST = "citations.temporary_citation_list";
/**
* Checks permissions to add a CitationList. Returns true if the user
* has permission to add a resource in the collection identified by the
* parameter.
* @param contentCollectionId
* @return
*/
public boolean allowAddCitationList(String contentCollectionId)
{
return m_contentHostingService.allowAddResource(contentCollectionId + "testing");
}
/**
* Checks permission to revise a CitationList, including permissions
* to add, remove or revise citations within the CitationList. Returns
* true if the user has permission to revise the resource identified by
* the parameter. Also returns true if all of these conditions are met:
* (1) the user is the creator of the specified resource, (2) the specified
* resource is a temporary CitationList (as identified by the value of
* the PROP_TEMPORARY_CITATION_LIST property), and (3) the user has
* permission to add resources in the collection containing the
* resource.
* @param contentResourceId
* @return
*/
public boolean allowReviseCitationList(String contentResourceId)
{
boolean allowed = m_contentHostingService.allowUpdateResource(contentResourceId);
if(!allowed)
{
try
{
ResourceProperties props = m_contentHostingService.getProperties(contentResourceId);
String temp_res = props.getProperty(CitationService.PROP_TEMPORARY_CITATION_LIST);
String creator = props.getProperty(ResourceProperties.PROP_CREATOR);
String contentCollectionId = m_contentHostingService.getContainingCollectionId(contentResourceId);
SessionManager sessionManager = (SessionManager) ComponentManager.get("org.sakaiproject.tool.api.SessionManager");
String currentUser = sessionManager.getCurrentSessionUserId();
allowed = this.allowAddCitationList(contentCollectionId) && (temp_res != null) && currentUser.equals(creator);
}
catch(PermissionException e)
{
// do nothing: return false
}
catch (IdUnusedException e)
{
// do nothing: return false
}
}
return allowed;
}
/**
*
* @return
*/
public boolean allowRemoveCitationList(String contentResourceId)
{
boolean allowed = m_contentHostingService.allowUpdateResource(contentResourceId);
if(!allowed)
{
try
{
ResourceProperties props = m_contentHostingService.getProperties(contentResourceId);
String temp_res = props.getProperty(CitationService.PROP_TEMPORARY_CITATION_LIST);
String creator = props.getProperty(ResourceProperties.PROP_CREATOR);
String contentCollectionId = m_contentHostingService.getContainingCollectionId(contentResourceId);
SessionManager sessionManager = (SessionManager) ComponentManager.get("org.sakaiproject.tool.api.SessionManager");
String currentUser = sessionManager.getCurrentSessionUserId();
allowed = this.allowAddCitationList(contentCollectionId) && (temp_res != null) && currentUser.equals(creator);
}
catch(PermissionException e)
{
// do nothing: return false
}
catch (IdUnusedException e)
{
// do nothing: return false
}
}
return allowed;
}
public Citation addCitation(String mediatype)
{
Citation edit = m_storage.addCitation(mediatype);
return edit;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#addCollection()
*/
public CitationCollection addCollection()
{
CitationCollection edit = m_storage.addCollection(null, null);
return edit;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#archive(java.lang.String,
* org.w3c.dom.Document, java.util.Stack, java.lang.String,
* java.util.List)
*/
public String archive(String siteId, Document doc, Stack stack, String archivePath,
List attachments)
{
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#copyAll(java.lang.String)
*/
public CitationCollection copyAll(String collectionId)
{
return m_storage.copyAll(collectionId);
}
/**
* Returns to uninitialized state.
*/
public void destroy()
{
if(m_storage != null)
{
m_storage.close();
m_storage = null;
}
}
/**
* Access the partial URL that forms the root of calendar URLs.
*
* @param relative
* if true, form within the access path only (i.e. starting with
* /content)
* @return the partial URL that forms the root of calendar URLs.
*/
protected String getAccessPoint(boolean relative)
{
return (relative ? "" : m_serverConfigurationService.getAccessUrl())
+ m_relativeAccessPoint;
} // getAccessPoint
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#getCollection(java.lang.String)
*/
public CitationCollection getCollection(String collectionId) throws IdUnusedException
{
CitationCollection edit = m_storage.getCollection(collectionId);
if (edit == null)
{
throw new IdUnusedException(collectionId);
}
return edit;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#getDefaultSchema()
*/
public Schema getDefaultSchema()
{
Schema rv = null;
if (m_defaultSchema != null)
{
rv = m_storage.getSchema(m_defaultSchema);
}
return rv;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getEntity(org.sakaiproject.entity.api.Reference)
*/
public Entity getEntity(Reference ref)
{
Entity entity = null;
if (APPLICATION_ID.equals(ref.getType()))
{
if ( REF_TYPE_EXPORT_RIS_SEL.equals(ref.getSubType()) ||
REF_TYPE_EXPORT_RIS_ALL.equals(ref.getSubType()) )
{
// these entities are citation collections
String id = ref.getId();
if (id == null || id.trim().equals(""))
{
String reference = ref.getReference();
if (reference != null && reference.startsWith(REFERENCE_ROOT))
{
id = reference.substring(REFERENCE_ROOT.length(), reference.length());
}
}
if (id != null && !id.trim().equals(""))
{
entity = m_storage.getCollection(id);
}
}
else if (REF_TYPE_VIEW_LIST.equals(ref.getSubType()))
{
// these entities are actually in /content
String id = ref.getId();
if (id == null || id.trim().equals(""))
{
String reference = ref.getReference();
if (reference.startsWith(REFERENCE_ROOT))
{
reference = reference
.substring(REFERENCE_ROOT.length(), reference.length());
}
if (reference.startsWith(m_contentHostingService.REFERENCE_ROOT))
{
id = reference.substring(m_contentHostingService.REFERENCE_ROOT.length(),
reference.length());
}
}
if (id != null && !id.trim().equals(""))
{
try
{
entity = m_contentHostingService.getResource(id);
}
catch (PermissionException e)
{
M_log.warn("getEntity(" + id + ") ", e);
}
catch (IdUnusedException e)
{
M_log.warn("getEntity(" + id + ") ", e);
}
catch (TypeException e)
{
M_log.warn("getEntity(" + id + ") ", e);
}
}
}
}
// and maybe others are in /citation
return entity;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getEntityAuthzGroups(org.sakaiproject.entity.api.Reference,
* java.lang.String)
*/
public Collection getEntityAuthzGroups(Reference ref, String userId)
{
// entities that are actually in /content use the /content authz groups
// those in /citation are open?
return null;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getEntityDescription(org.sakaiproject.entity.api.Reference)
*/
public String getEntityDescription(Reference ref)
{
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getEntityResourceProperties(org.sakaiproject.entity.api.Reference)
*/
public ResourceProperties getEntityResourceProperties(Reference ref)
{
// if it's a /content item, return its props
// otherwise return null
return null;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getEntityUrl(org.sakaiproject.entity.api.Reference)
*/
public String getEntityUrl(Reference ref)
{
return null;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getHttpAccess()
*/
public HttpAccess getHttpAccess()
{
// if it's a /content item, the access is via CitationListAccessServlet
return new CitationListAccessServlet();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#getLabel()
*/
public String getLabel()
{
// TODO Auto-generated method stub
return null;
}
/**
* @return
*/
public Set getMultivalued()
{
Set multivalued = new TreeSet();
Iterator schemaIt = m_storage.getSchemas().iterator();
while (schemaIt.hasNext())
{
Schema schema = (Schema) schemaIt.next();
{
Iterator fieldIt = schema.getFields().iterator();
while (fieldIt.hasNext())
{
Field field = (Field) fieldIt.next();
if (field.getMaxCardinality() > 1)
{
multivalued.add(field.getIdentifier());
}
}
}
}
return multivalued;
}
/**
* @return
*/
public Set getMultivalued(String type)
{
Set multivalued = new TreeSet();
Schema schema = m_storage.getSchema(type);
{
Iterator fieldIt = schema.getFields().iterator();
while (fieldIt.hasNext())
{
Field field = (Field) fieldIt.next();
if (field.getMaxCardinality() > 1)
{
multivalued.add(field.getIdentifier());
}
}
}
return multivalued;
}
public Schema getSchema(String name)
{
Schema schema = m_storage.getSchema(name);
return schema;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#getSchemas()
*/
public List getSchemas()
{
List schemas = new Vector(m_storage.getSchemas());
return schemas;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.Schema#getSynonyms(java.lang.String)
*/
protected Set getSynonyms(String mediatype)
{
Set synonyms = new TreeSet();
if (mediatype.equalsIgnoreCase("article"))
{
synonyms.add("article");
synonyms.add("journal article");
synonyms.add("journal");
synonyms.add("periodical");
synonyms.add("newspaper article");
synonyms.add("magazine article");
synonyms.add("editorial");
synonyms.add("peer reviewed article");
synonyms.add("peer reviewed journal article");
synonyms.add("book review");
synonyms.add("review");
synonyms.add("meeting");
synonyms.add("wire feed");
synonyms.add("wire story");
synonyms.add("journal article (cije)");
}
else if (mediatype.equalsIgnoreCase("book"))
{
synonyms.add("book");
synonyms.add("bk");
}
else if (mediatype.equalsIgnoreCase("chapter"))
{
synonyms.add("chapter");
synonyms.add("book chapter");
synonyms.add("book section");
}
else if (mediatype.equalsIgnoreCase("report"))
{
synonyms.add("report");
synonyms.add("editorial material");
synonyms.add("technical report");
synonyms.add("se");
synonyms.add("document (rie)");
}
return synonyms;
}
public Citation getTemporaryCitation()
{
return new BasicCitation();
}
public Citation getTemporaryCitation(Asset asset)
{
return new BasicCitation(asset);
}
public CitationCollection getTemporaryCollection()
{
return new BasicCitationCollection(true);
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#getValidPropertyNames()
*/
public Set getValidPropertyNames()
{
Set names = new TreeSet();
Iterator schemaIt = m_storage.getSchemas().iterator();
while (schemaIt.hasNext())
{
Schema schema = (Schema) schemaIt.next();
{
Iterator fieldIt = schema.getFields().iterator();
while (fieldIt.hasNext())
{
Field field = (Field) fieldIt.next();
names.add(field.getIdentifier());
}
}
}
return names;
} // getValidPropertyNames
public class CitationListCreateAction extends BaseInteractionAction
{
/**
* @param id
* @param actionType
* @param typeId
* @param helperId
* @param requiredPropertyKeys
*/
public CitationListCreateAction(String id, ActionType actionType, String typeId, String helperId, List requiredPropertyKeys)
{
super(id, actionType, typeId, helperId, requiredPropertyKeys);
}
/* (non-Javadoc)
* @see org.sakaiproject.content.util.BaseResourceAction#available(org.sakaiproject.content.api.ContentEntity)
*/
@Override
public boolean available(ContentEntity entity)
{
return super.available(entity);
}
}
/**
*
*
*/
public void init()
{
m_storage = newStorage();
m_nextSerialNumber = new Integer(0);
m_relativeAccessPoint = CitationService.REFERENCE_ROOT;
rb = new ResourceLoader("citations");
//initializeSchemas();
m_defaultSchema = "article";
// register as an entity producer
m_entityManager.registerEntityProducer(this, REFERENCE_ROOT);
if(m_configService.isCitationsEnabledByDefault() ||
m_configService.isAllowSiteBySiteOverride() )
{
registerResourceType();
}
}
/**
*
*/
protected void registerResourceType()
{
ResourceTypeRegistry registry = getResourceTypeRegistry();
List requiredPropertyKeys = new Vector();
requiredPropertyKeys.add(ContentHostingService.PROP_ALTERNATE_REFERENCE);
requiredPropertyKeys.add(ResourceProperties.PROP_CONTENT_TYPE);
BaseInteractionAction createAction = new CitationListCreateAction(ResourceToolAction.CREATE,
ResourceToolAction.ActionType.CREATE,
CitationService.CITATION_LIST_ID,
CitationService.HELPER_ID,
new Vector());
createAction.setLocalizer(
new BaseResourceAction.Localizer()
{
public String getLabel()
{
return rb.getString("action.create");
}
});
BaseInteractionAction reviseAction = new BaseInteractionAction(ResourceToolAction.REVISE_CONTENT,
ResourceToolAction.ActionType.REVISE_CONTENT,
CitationService.CITATION_LIST_ID,
CitationService.HELPER_ID,
new Vector());
reviseAction.setLocalizer(
new BaseResourceAction.Localizer()
{
public String getLabel()
{
return rb.getString("action.revise");
}
});
BaseServiceLevelAction moveAction = new BaseServiceLevelAction(ResourceToolAction.MOVE,
ResourceToolAction.ActionType.MOVE,
CitationService.CITATION_LIST_ID,
true );
BaseServiceLevelAction revisePropsAction = new BaseServiceLevelAction(ResourceToolAction.REVISE_METADATA,
ResourceToolAction.ActionType.REVISE_METADATA,
CitationService.CITATION_LIST_ID,
false );
BasicSiteSelectableResourceType typedef = new BasicSiteSelectableResourceType(CitationService.CITATION_LIST_ID);
typedef.setSizeLabeler(new CitationSizeLabeler());
typedef.setLocalizer(new CitationLocalizer());
typedef.addAction(createAction);
typedef.addAction(reviseAction);
typedef.addAction(new CitationListDeleteAction());
typedef.addAction(new CitationListCopyAction());
typedef.addAction(new CitationListPasteCopyAction());
typedef.addAction(new CitationListPasteMoveAction());
typedef.addAction(new CitationListDuplicateAction());
typedef.addAction(revisePropsAction);
typedef.addAction(moveAction);
typedef.setEnabledByDefault(m_configService.isCitationsEnabledByDefault());
typedef.setIconLocation("sakai/citationlist.gif");
typedef.setHasRightsDialog(false);
registry.register(typedef);
}
/**
*
*/
protected void initializeSchemas()
{
BasicSchema unknown = new BasicSchema();
unknown.setIdentifier(CitationService.UNKNOWN_TYPE);
BasicSchema article = new BasicSchema();
article.setIdentifier("article");
BasicSchema book = new BasicSchema();
book.setIdentifier("book");
BasicSchema chapter = new BasicSchema();
chapter.setIdentifier("chapter");
BasicSchema report = new BasicSchema();
report.setIdentifier("report");
/* schema ordering is different for different types */
/*
* UNKNOWN (GENERIC)
*/
unknown.addField(Schema.CREATOR, Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
unknown.addAlternativeIdentifier(Schema.CREATOR, RIS_FORMAT, "A1");
unknown.addField(Schema.TITLE, Schema.SHORTTEXT, true, true, 1, 1);
unknown.addAlternativeIdentifier(Schema.TITLE, RIS_FORMAT, "T1");
unknown.addField(Schema.YEAR, Schema.NUMBER, true, false, 0, 1);
unknown.addField("date", Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier("date", RIS_FORMAT, "Y1");
unknown.addField(Schema.PUBLISHER, Schema.SHORTTEXT, true, false, 0, 1);
unknown.addAlternativeIdentifier(Schema.PUBLISHER, RIS_FORMAT, "PB");
unknown.addField("publicationLocation", Schema.SHORTTEXT, true, false, 0, 1);
unknown.addAlternativeIdentifier("publicationLocation", RIS_FORMAT, "CY");
unknown.addField(Schema.VOLUME, Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier(Schema.VOLUME, RIS_FORMAT, "VL");
unknown.addField(Schema.ISSUE, Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier(Schema.ISSUE, RIS_FORMAT, "IS");
unknown.addField(Schema.PAGES, Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier(Schema.PAGES, RIS_FORMAT, "SP");
unknown.addField("startPage", Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier("startPage", RIS_FORMAT, "SP");
unknown.addField("endPage", Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier("endPage", RIS_FORMAT, "EP");
unknown.addField("edition", Schema.NUMBER, true, false, 0, 1);
unknown.addAlternativeIdentifier("edition", RIS_FORMAT, "VL");
unknown.addField("editor", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
unknown.addAlternativeIdentifier("editor", RIS_FORMAT, "A3");
unknown.addField(Schema.SOURCE_TITLE, Schema.SHORTTEXT, true, false, 0, 1);
unknown.addAlternativeIdentifier(Schema.SOURCE_TITLE, RIS_FORMAT, "T3");
unknown.addField("Language", Schema.NUMBER, true, false, 0, 1);
unknown.addField("abstract", Schema.LONGTEXT, true, false, 0, 1);
unknown.addAlternativeIdentifier("abstract", RIS_FORMAT, "N2");
unknown.addField("note", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
unknown.addAlternativeIdentifier("note", RIS_FORMAT, "N1");
unknown.addField(Schema.ISN, Schema.SHORTTEXT, true, false, 0, 1);
unknown.addAlternativeIdentifier(Schema.ISN, RIS_FORMAT, "SN");
unknown.addField("subject", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
unknown.addAlternativeIdentifier("subject", RIS_FORMAT, "KW");
unknown.addField("locIdentifier", Schema.SHORTTEXT, true, false, 0, 1);
unknown.addAlternativeIdentifier("locIdentifier", RIS_FORMAT, "M1");
unknown.addField("dateRetrieved", Schema.DATE, false, false, 0, 1);
unknown.addField("openURL", Schema.SHORTTEXT, false, false, 0, 1);
unknown.addField("doi", Schema.NUMBER, true, false, 0, 1);
unknown.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
/*
* ARTICLE
*/
article.addField(Schema.CREATOR, Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
article.addAlternativeIdentifier(Schema.CREATOR, RIS_FORMAT, "A1");
article.addField(Schema.TITLE, Schema.SHORTTEXT, true, true, 1, 1);
article.addAlternativeIdentifier(Schema.TITLE, RIS_FORMAT, "T1");
article.addField(Schema.SOURCE_TITLE, Schema.SHORTTEXT, true, false, 0, 1);
article.addAlternativeIdentifier(Schema.SOURCE_TITLE, RIS_FORMAT, "JF");
article.addField(Schema.YEAR, Schema.NUMBER, true, false, 0, 1);
article.addField("date", Schema.NUMBER, true, false, 0, 1);
article.addAlternativeIdentifier("date", RIS_FORMAT, "Y1");
article.addField(Schema.VOLUME, Schema.NUMBER, true, false, 0, 1);
article.addAlternativeIdentifier(Schema.VOLUME, RIS_FORMAT, "VL");
article.addField(Schema.ISSUE, Schema.NUMBER, true, false, 0, 1);
article.addAlternativeIdentifier(Schema.ISSUE, RIS_FORMAT, "IS");
article.addField(Schema.PAGES, Schema.NUMBER, true, false, 0, 1);
article.addField("startPage", Schema.NUMBER, true, false, 0, 1);
article.addAlternativeIdentifier("startPage", RIS_FORMAT, "SP");
article.addField("endPage", Schema.NUMBER, true, false, 0, 1);
article.addAlternativeIdentifier("endPage", RIS_FORMAT, "EP");
article.addField("abstract", Schema.LONGTEXT, true, false, 0, 1);
article.addAlternativeIdentifier("abstract", RIS_FORMAT, "N2");
article.addField("note", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
article.addAlternativeIdentifier("note", RIS_FORMAT, "N1");
article.addField(Schema.ISN, Schema.SHORTTEXT, true, false, 0, 1);
article.addAlternativeIdentifier(Schema.ISN, RIS_FORMAT, "SN");
article.addField("subject", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
article.addAlternativeIdentifier("subject", RIS_FORMAT, "KW");
article.addField("Language", Schema.NUMBER, true, false, 0, 1);
article.addField("locIdentifier", Schema.SHORTTEXT, true, false, 0, 1);
article.addAlternativeIdentifier("locIdentifier", RIS_FORMAT, "M1");
article.addField("dateRetrieved", Schema.DATE, false, false, 0, 1);
article.addField("openURL", Schema.SHORTTEXT, false, false, 0, 1);
article.addField("doi", Schema.NUMBER, true, false, 0, 1);
article.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
/*
* BOOK
*/
book.addField(Schema.CREATOR, Schema.SHORTTEXT, true, true, 1, Schema.UNLIMITED);
book.addAlternativeIdentifier(Schema.CREATOR, RIS_FORMAT, "A1");
book.addField(Schema.TITLE, Schema.SHORTTEXT, true, true, 1, 1);
book.addAlternativeIdentifier(Schema.TITLE, RIS_FORMAT, "BT");
book.addField(Schema.YEAR, Schema.NUMBER, true, false, 0, 1);
book.addField("date", Schema.NUMBER, true, false, 0, 1);
book.addAlternativeIdentifier("date", RIS_FORMAT, "Y1");
book.addField(Schema.PUBLISHER, Schema.SHORTTEXT, true, false, 0, 1);
book.addAlternativeIdentifier(Schema.PUBLISHER, RIS_FORMAT, "PB");
book.addField("publicationLocation", Schema.SHORTTEXT, true, false, 0, 1);
book.addAlternativeIdentifier("publicationLocation", RIS_FORMAT, "CY");
book.addField("edition", Schema.NUMBER, true, false, 0, 1);
book.addAlternativeIdentifier("edition", RIS_FORMAT, "VL");
book.addField("editor", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
book.addAlternativeIdentifier("editor", RIS_FORMAT, "A3");
book.addField(Schema.SOURCE_TITLE, Schema.SHORTTEXT, true, false, 0, 1);
book.addAlternativeIdentifier(Schema.SOURCE_TITLE, RIS_FORMAT, "T3");
book.addField("abstract", Schema.LONGTEXT, true, false, 0, 1);
book.addAlternativeIdentifier("abstract", RIS_FORMAT, "N2");
book.addField("note", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
book.addAlternativeIdentifier("note", RIS_FORMAT, "N1");
book.addField(Schema.ISN, Schema.SHORTTEXT, true, false, 0, 1);
book.addAlternativeIdentifier(Schema.ISN, RIS_FORMAT, "SN");
book.addField("subject", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
book.addAlternativeIdentifier("subject", RIS_FORMAT, "KW");
book.addField("Language", Schema.NUMBER, true, false, 0, 1);
book.addField("locIdentifier", Schema.SHORTTEXT, true, false, 0, 1);
book.addAlternativeIdentifier("locIdentifier", RIS_FORMAT, "M1");
book.addField("dateRetrieved", Schema.DATE, false, false, 0, 1);
book.addField("openURL", Schema.SHORTTEXT, false, false, 0, 1);
book.addField("doi", Schema.NUMBER, true, false, 0, 1);
book.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
book.addAlternativeIdentifier(Schema.PAGES, RIS_FORMAT, "SP");
/*
* CHAPTER
*/
chapter.addField(Schema.CREATOR, Schema.SHORTTEXT, true, true, 1, Schema.UNLIMITED);
chapter.addAlternativeIdentifier(Schema.CREATOR, RIS_FORMAT, "A1");
chapter.addField(Schema.TITLE, Schema.SHORTTEXT, true, true, 1, 1);
chapter.addAlternativeIdentifier(Schema.TITLE, RIS_FORMAT, "CT");
chapter.addField(Schema.YEAR, Schema.NUMBER, true, false, 0, 1);
chapter.addField("date", Schema.NUMBER, true, false, 0, 1);
chapter.addAlternativeIdentifier("date", RIS_FORMAT, "Y1");
chapter.addField(Schema.PUBLISHER, Schema.SHORTTEXT, true, false, 0, 1);
chapter.addAlternativeIdentifier(Schema.PUBLISHER, RIS_FORMAT, "PB");
chapter.addField("publicationLocation", Schema.SHORTTEXT, true, false, 0, 1);
chapter.addAlternativeIdentifier("publicationLocation", RIS_FORMAT, "CY");
chapter.addField("edition", Schema.NUMBER, true, false, 0, 1);
chapter.addAlternativeIdentifier("edition", RIS_FORMAT, "VL");
chapter.addField("editor", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
chapter.addAlternativeIdentifier("editor", RIS_FORMAT, "ED");
chapter.addField(Schema.SOURCE_TITLE, Schema.SHORTTEXT, true, false, 0, 1);
chapter.addAlternativeIdentifier(Schema.SOURCE_TITLE, RIS_FORMAT, "BT");
chapter.addField(Schema.PAGES, Schema.NUMBER, true, false, 0, 1);
chapter.addAlternativeIdentifier(Schema.PAGES, RIS_FORMAT, "SP");
chapter.addField("startPage", Schema.NUMBER, true, false, 0, 1);
chapter.addAlternativeIdentifier("startPage", RIS_FORMAT, "SP");
chapter.addField("endPage", Schema.NUMBER, true, false, 0, 1);
chapter.addAlternativeIdentifier("endPage", RIS_FORMAT, "EP");
chapter.addField("abstract", Schema.LONGTEXT, true, false, 0, 1);
chapter.addAlternativeIdentifier("abstract", RIS_FORMAT, "N2");
chapter.addField("note", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
chapter.addAlternativeIdentifier("note", RIS_FORMAT, "N1");
chapter.addField(Schema.ISN, Schema.SHORTTEXT, true, false, 0, 1);
chapter.addAlternativeIdentifier(Schema.ISN, RIS_FORMAT, "SN");
chapter.addField("subject", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
chapter.addAlternativeIdentifier("subject", RIS_FORMAT, "KW");
chapter.addField("Language", Schema.NUMBER, true, false, 0, 1);
chapter.addField("locIdentifier", Schema.SHORTTEXT, true, false, 0, 1);
chapter.addAlternativeIdentifier("locIdentifier", RIS_FORMAT, "M1");
chapter.addField("dateRetrieved", Schema.DATE, false, false, 0, 1);
chapter.addField("openURL", Schema.SHORTTEXT, false, false, 0, 1);
chapter.addField("doi", Schema.NUMBER, true, false, 0, 1);
chapter.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
/*
* REPORT
*/
report.addField(Schema.CREATOR, Schema.SHORTTEXT, true, true, 1, Schema.UNLIMITED);
report.addAlternativeIdentifier(Schema.CREATOR, RIS_FORMAT, "A1");
report.addField(Schema.TITLE, Schema.SHORTTEXT, true, true, 1, 1);
report.addAlternativeIdentifier(Schema.TITLE, RIS_FORMAT, "T1");
report.addField(Schema.YEAR, Schema.NUMBER, true, false, 0, 1);
report.addField("date", Schema.NUMBER, true, false, 0, 1);
report.addAlternativeIdentifier("date", RIS_FORMAT, "Y1");
report.addField(Schema.PUBLISHER, Schema.SHORTTEXT, true, false, 0, 1);
report.addAlternativeIdentifier(Schema.PUBLISHER, RIS_FORMAT, "PB");
report.addField("publicationLocation", Schema.SHORTTEXT, true, false, 0, 1);
report.addAlternativeIdentifier("publicationLocation", RIS_FORMAT, "CY");
report.addField("editor", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
report.addAlternativeIdentifier("editor", RIS_FORMAT, "A3");
report.addField("edition", Schema.NUMBER, true, false, 0, 1);
report.addAlternativeIdentifier("edition", RIS_FORMAT, "VL");
report.addField(Schema.SOURCE_TITLE, Schema.SHORTTEXT, true, false, 0, 1);
report.addAlternativeIdentifier(Schema.SOURCE_TITLE, RIS_FORMAT, "T3");
report.addField(Schema.PAGES, Schema.NUMBER, true, false, 0, 1);
report.addAlternativeIdentifier(Schema.PAGES, RIS_FORMAT, "SP");
report.addField("abstract", Schema.LONGTEXT, true, false, 0, 1);
report.addAlternativeIdentifier("abstract", RIS_FORMAT, "N2");
report.addField(Schema.ISN, Schema.SHORTTEXT, true, false, 0, 1);
report.addAlternativeIdentifier(Schema.ISN, RIS_FORMAT, "SN");
report.addField("note", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
report.addAlternativeIdentifier("note", RIS_FORMAT, "N1");
report.addField("subject", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
report.addAlternativeIdentifier("subject", RIS_FORMAT, "KW");
report.addField("Language", Schema.NUMBER, true, false, 0, 1);
report.addField("locIdentifier", Schema.SHORTTEXT, true, false, 0, 1);
report.addAlternativeIdentifier("locIdentifier", RIS_FORMAT, "M1");
report.addField("dateRetrieved", Schema.DATE, false, false, 0, 1);
report.addField("openURL", Schema.SHORTTEXT, false, false, 0, 1);
report.addField("doi", Schema.NUMBER, true, false, 0, 1);
report.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
/* IGNORING 'Citation' field for now...
unknown.addField("inlineCitation", Schema.SHORTTEXT, false, false, 0, Schema.UNLIMITED);
article.addField("inlineCitation", Schema.SHORTTEXT, false, false, 0, Schema.UNLIMITED);
book.addField("inlineCitation", Schema.SHORTTEXT, false, false, 0, Schema.UNLIMITED);
chapter.addField("inlineCitation", Schema.SHORTTEXT, false, false, 0, Schema.UNLIMITED);
report.addField("inlineCitation", Schema.SHORTTEXT, false, false, 0, Schema.UNLIMITED);
*/
if (m_storage.checkSchema(unknown.getIdentifier()))
{
m_storage.updateSchema(unknown);
}
else
{
m_storage.addSchema(unknown);
}
if (m_storage.checkSchema(article.getIdentifier()))
{
m_storage.updateSchema(article);
}
else
{
m_storage.addSchema(article);
}
if (m_storage.checkSchema(book.getIdentifier()))
{
m_storage.updateSchema(book);
}
else
{
m_storage.addSchema(book);
}
if (m_storage.checkSchema(chapter.getIdentifier()))
{
m_storage.updateSchema(chapter);
}
else
{
m_storage.addSchema(chapter);
}
if (m_storage.checkSchema(report.getIdentifier()))
{
m_storage.updateSchema(report);
}
else
{
m_storage.addSchema(report);
}
}
public class CitationListDeleteAction extends BaseServiceLevelAction
{
public CitationListDeleteAction()
{
super(ResourceToolAction.DELETE, ResourceToolAction.ActionType.DELETE, CitationService.CITATION_LIST_ID, true);
}
public void finalizeAction(Reference reference)
{
try
{
ContentResource resource = (ContentResource) reference.getEntity();
String collectionId = new String(resource.getContent());
CitationCollection collection = getCollection(collectionId);
removeCollection(collection);
}
catch(IdUnusedException e)
{
M_log.warn("IdUnusedException ", e);
}
catch(ServerOverloadException e)
{
M_log.warn("ServerOverloadException ", e);
}
}
}
public class CitationLocalizer implements BasicResourceType.Localizer
{
/**
*
* @return
*/
public String getLabel()
{
return rb.getString("list.title");
}
/**
*
* @param member
* @return
*/
public String getLocalizedHoverText(ContentEntity member)
{
return rb.getString("list.title");
}
}
public class CitationSizeLabeler implements BasicResourceType.SizeLabeler
{
public String getLongSizeLabel(ContentEntity entity)
{
return getSizeLabel(entity);
}
public String getSizeLabel(ContentEntity entity)
{
String label = null;
if(entity instanceof ContentResource)
{
byte[] collectionId = null;
ContentResource resource = (ContentResource) entity;
try
{
collectionId = resource.getContent();
if(collectionId != null)
{
CitationCollection collection = getCollection(new String(collectionId));
String[] args = new String[]{ Integer.toString(collection.size())};
label = rb.getFormattedMessage("citation.count", args);
}
}
catch(Exception e)
{
String citationCollectionId = "null";
if(collectionId != null)
{
citationCollectionId = collectionId.toString();
}
M_log.warn("Unable to determine size of CitationCollection for entity: entityId == " + entity.getId() + " citationCollectionId == " + collectionId + " exception == " + e.toString());
}
}
return label;
}
}
public class CitationListCopyAction extends BaseServiceLevelAction
{
public CitationListCopyAction()
{
super(ResourceToolAction.COPY, ResourceToolAction.ActionType.COPY, CitationService.CITATION_LIST_ID, true);
}
@Override
public void finalizeAction(Reference reference)
{
copyCitationCollection(reference);
}
}
public class CitationListPasteMoveAction extends BaseServiceLevelAction
{
public CitationListPasteMoveAction()
{
super(ResourceToolAction.PASTE_COPIED, ResourceToolAction.ActionType.PASTE_MOVED, CitationService.CITATION_LIST_ID, true);
}
@Override
public void finalizeAction(Reference reference)
{
copyCitationCollection(reference);
}
}
public class CitationListPasteCopyAction extends BaseServiceLevelAction
{
public CitationListPasteCopyAction()
{
super(ResourceToolAction.PASTE_COPIED, ResourceToolAction.ActionType.PASTE_COPIED, CitationService.CITATION_LIST_ID, true);
}
@Override
public void finalizeAction(Reference reference)
{
copyCitationCollection(reference);
}
}
public class CitationListDuplicateAction extends BaseServiceLevelAction
{
public CitationListDuplicateAction()
{
super(ResourceToolAction.DUPLICATE, ResourceToolAction.ActionType.DUPLICATE, CitationService.CITATION_LIST_ID, false);
}
@Override
public void finalizeAction(Reference reference)
{
copyCitationCollection(reference);
}
}
/**
* @param schemaId
* @param fieldId
* @return
*/
public boolean isMultivalued(String schemaId, String fieldId)
{
Schema schema = getSchema(schemaId.toLowerCase());
if (schema == null)
{
if (getSynonyms("article").contains(schemaId.toLowerCase()))
{
schema = getSchema("article");
}
else if (getSynonyms("book").contains(schemaId.toLowerCase()))
{
schema = getSchema("book");
}
else if (getSynonyms("chapter").contains(schemaId.toLowerCase()))
{
schema = getSchema("chapter");
}
else if (getSynonyms("report").contains(schemaId.toLowerCase()))
{
schema = getSchema("report");
}
else
{
schema = this.getSchema("unknown");
}
}
Field field = schema.getField(fieldId);
if (field == null)
{
return false;
}
return (field.isMultivalued());
}
/**
* Access a list of all schemas that have been defined (other than the
* "unknown" type).
*
* @return A list of Strings representing the identifiers for known schemas.
*/
public List listSchemas()
{
Set names = (Set) m_storage.listSchemas();
return new Vector(names);
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#merge(java.lang.String,
* org.w3c.dom.Element, java.lang.String, java.lang.String,
* java.util.Map, java.util.Map, java.util.Set)
*/
public String merge(String siteId, Element root, String archivePath, String fromSiteId,
Map attachmentNames, Map userIdTrans, Set userListAllowImport)
{
// TODO Auto-generated method stub
return null;
}
/**
* Construct a Storage object.
*
* @return The new storage object.
*/
public abstract Storage newStorage();
/**
* @return
*/
protected Integer nextSerialNumber()
{
Integer number;
synchronized (m_nextSerialNumber)
{
number = m_nextSerialNumber;
m_nextSerialNumber = new Integer(number.intValue() + 1);
}
return number;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#parseEntityReference(java.lang.String,
* org.sakaiproject.entity.api.Reference)
*/
public boolean parseEntityReference(String reference, Reference ref)
{
boolean citationEntity = false;
if (reference.startsWith(CitationService.REFERENCE_ROOT))
{
citationEntity = true;
String[] parts = StringUtil.split(reference, Entity.SEPARATOR);
String subType = null;
String context = null;
String id = null;
String container = null;
// the first part will be null, then next the service, the third
// will be "export_ris", "content" or "list"
if (parts.length > 2)
{
subType = parts[2];
if (CitationService.REF_TYPE_EXPORT_RIS_ALL.equals(subType) ||
CitationService.REF_TYPE_EXPORT_RIS_SEL.equals(subType))
{
context = parts[3];
id = parts[3];
ref.set(APPLICATION_ID, subType, id, container, context);
}
else if ("content".equals(subType))
{
String wrappedRef = reference.substring(REFERENCE_ROOT.length(), reference
.length());
Reference wrapped = m_entityManager.newReference(wrappedRef);
ref.set(APPLICATION_ID, REF_TYPE_VIEW_LIST, wrapped.getId(), wrapped
.getContainer(), wrapped.getContext());
}
else
{
M_log.warn(".parseEntityReference(): unknown citation subtype: " + subType
+ " in ref: " + reference);
citationEntity = false;
}
}
else
{
citationEntity = false;
}
}
return citationEntity;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#removeCollection(org.sakaiproject.citation.api.CitationCollection)
*/
public void removeCollection(CitationCollection edit)
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#save(org.sakaiproject.citation.api.Citation)
*/
public void save(Citation citation)
{
if (citation instanceof BasicCitation && ((BasicCitation) citation).isTemporary())
{
((BasicCitation) citation).m_id = IdManager.createUuid();
((BasicCitation) citation).m_temporary = false;
((BasicCitation) citation).m_serialNumber = null;
}
this.m_storage.saveCitation(citation);
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.citation.api.CitationService#save(org.sakaiproject.citation.api.CitationCollection)
*/
public void save(CitationCollection collection)
{
this.m_storage.saveCollection(collection);
}
/**
* Dependency: ConfigurationService.
*
* @param service
* The ConfigurationService.
*/
public void setConfigurationService(ConfigurationService service)
{
m_configService = service;
}
/**
* Dependency: ContentHostingService.
*
* @param service
* The ContentHostingService.
*/
public void setContentHostingService(ContentHostingService service)
{
m_contentHostingService = service;
}
/**
* Dependency: EntityManager.
*
* @param service
* The EntityManager.
*/
public void setEntityManager(EntityManager service)
{
m_entityManager = service;
}
/**
* Dependency: ServerConfigurationService.
*
* @param service
* The ServerConfigurationService.
*/
public void setServerConfigurationService(ServerConfigurationService service)
{
m_serverConfigurationService = service;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.entity.api.EntityProducer#willArchiveMerge()
*/
public boolean willArchiveMerge()
{
// TODO Auto-generated method stub
return false;
}
public final class Counter
{
private int value;
private Integer lock = new Integer(0);
public Counter()
{
value = 0;
}
public Counter(int val)
{
value = val;
}
public void increment()
{
synchronized(lock)
{
value++;
}
}
public void decrement()
{
synchronized(lock)
{
value--;
}
}
public int intValue()
{
return value;
}
}
/**
* @return the attemptToMatchSchema
*/
public boolean isAttemptToMatchSchema()
{
return attemptToMatchSchema;
}
/**
* @param attemptToMatchSchema the attemptToMatchSchema to set
*/
public void setAttemptToMatchSchema(boolean attemptToMatchSchema)
{
this.attemptToMatchSchema = attemptToMatchSchema;
}
/**
* @param reference
*/
private void copyCitationCollection(Reference reference)
{
ContentHostingService contentService = (ContentHostingService) ComponentManager.get(ContentHostingService.class);
try
{
ContentResourceEdit edit = contentService.editResource(reference.getId());
String collectionId = new String(edit.getContent());
CitationCollection oldCollection = getCollection(collectionId);
BasicCitationCollection newCollection = new BasicCitationCollection();
newCollection.copy((BasicCitationCollection) oldCollection);
save(newCollection);
edit.setContent(newCollection.getId().getBytes());
contentService.commitResource(edit);
}
catch(IdUnusedException e)
{
M_log.warn("IdUnusedException ", e);
}
catch(ServerOverloadException e)
{
M_log.warn("ServerOverloadException ", e);
}
catch (PermissionException e)
{
M_log.warn("PermissionException ", e);
}
catch (TypeException e)
{
M_log.warn("TypeException ", e);
}
catch (InUseException e)
{
M_log.warn("InUseException ", e);
}
catch (OverQuotaException e)
{
M_log.warn("OverQuotaException ", e);
}
}
} // BaseCitationService
| SAK-14282 - added an if test to importFromRisList() to handle the UR RIS tag. If it is a UR tag, it creates an id out of via addcustomUrl() for the RISvalue and sets the citation's preferred URL to this urlId.
git-svn-id: dce76f8a399c671fe9c0e23b6e81ff8638f82523@51411 66ffb92e-73f9-0310-93c1-f5514f145a0a
| citations/citations-impl/impl/src/java/org/sakaiproject/citation/impl/BaseCitationService.java | SAK-14282 - added an if test to importFromRisList() to handle the UR RIS tag. If it is a UR tag, it creates an id out of via addcustomUrl() for the RISvalue and sets the citation's preferred URL to this urlId. | <ide><path>itations/citations-impl/impl/src/java/org/sakaiproject/citation/impl/BaseCitationService.java
<ide> Iterator iter = null; // The iterator used to boogie through the Schema Fields
<ide> boolean status = true; // Used to maintain/exit the tag lookup while loop
<ide> String[] RIScodes = null; // This holds the RISCodes valid for a given schema
<add> String urlId = null; // Used to set the preferred URL
<ide>
<ide> logger.debug("importFromRisList: In importFromRisList. List size is " + risImportList.size());
<ide>
<ide> logger.debug("importFromRisList: Field mapping is " + tempField.getIdentifier() +
<ide> " => " + RISvalue);
<ide>
<del> // We found the mapping in the previous while loop. Set the citation property
<del> setCitationProperty(tempField.getIdentifier(), RISvalue);
<del> } // end we found the mapping
<add> if (RIScode.equalsIgnoreCase("UR"))
<add> {
<add> urlId = addCustomUrl("", RISvalue);
<add> setPreferredUrl(urlId);
<add> logger.debug("importFromRisList: set preferred url to " + urlId + " which is " + RISvalue);
<add> }
<add> else
<add> {
<add> // We found the mapping in the previous while loop. Set the citation property
<add> setCitationProperty(tempField.getIdentifier(), RISvalue);
<add> }
<add> } // end else which means we found the mapping
<ide>
<ide> } // end else of i == 0
<ide> } // end for i
<ide> article.addField("doi", Schema.NUMBER, true, false, 0, 1);
<ide>
<ide> article.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
<add>
<ide>
<ide> /*
<ide> * BOOK
<ide> chapter.addField("doi", Schema.NUMBER, true, false, 0, 1);
<ide>
<ide> chapter.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
<add>
<ide>
<ide> /*
<ide> * REPORT
<ide> report.addField("doi", Schema.NUMBER, true, false, 0, 1);
<ide>
<ide> report.addField("rights", Schema.SHORTTEXT, true, false, 0, Schema.UNLIMITED);
<add>
<ide>
<ide> /* IGNORING 'Citation' field for now...
<ide> unknown.addField("inlineCitation", Schema.SHORTTEXT, false, false, 0, Schema.UNLIMITED); |
|
Java | apache-2.0 | a0bf66a5cbc30f837704e6cd8632beeb198f61ab | 0 | sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.cvc5;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import io.github.cvc5.api.CVC5ApiException;
import io.github.cvc5.api.Kind;
import io.github.cvc5.api.Op;
import io.github.cvc5.api.Result;
import io.github.cvc5.api.RoundingMode;
import io.github.cvc5.api.Solver;
import io.github.cvc5.api.Sort;
import io.github.cvc5.api.Term;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.AssumptionViolatedException;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.sosy_lab.common.NativeLibraries;
/*
* Please note that CVC5 does not have a native variable cache!
* Each variable created is a new one with a new internal id, even if they are named the same.
* As a result, checking equality on 2 formulas that are build with new variables
* that are named the same results in false!
* Additionally, CVC5 only supports quantifier elimination for LIA and LRA.
* However, it might run endlessly in some cases if you try quantifier elimination on array
* theories!
*/
public class CVC5NativeAPITest {
private static final String INVALID_GETVALUE_STRING_SAT =
"Cannot get value unless after a SAT or UNKNOWN response.";
private static final String INVALID_GETVALUE_STRING_BOUND_VAR =
"Cannot get value of term containing free variables";
private static final String INVALID_MODEL_STRING =
"Cannot get model unless after a SAT or UNKNOWN response.";
@BeforeClass
public static void loadCVC4() {
try {
NativeLibraries.loadLibrary("cvc5jni");
} catch (UnsatisfiedLinkError e) {
throw new AssumptionViolatedException("CVC5 is not available", e);
}
}
private Term x;
private Term array;
private Term aAtxEq0;
private Term aAtxEq1;
private Solver solver;
@Before
public void createEnvironment() throws CVC5ApiException {
// CVC5 loads its own library statically
solver = new Solver();
// Set the logic
solver.setLogic("ALL");
// options
solver.setOption("produce-models", "true");
solver.setOption("finite-model-find", "true");
solver.setOption("sets-ext", "true");
solver.setOption("output-language", "smtlib2");
}
@After
public void freeEnvironment() {
solver.close();
}
/*
* Check how to get types/values etc. from constants, variables etc. in CVC5.
*/
@Test
public void checkGetValueAndType() throws CVC5ApiException {
// Constant values (NOT Kind,CONSTANT!)
assertThat(solver.mkBoolean(false).isBooleanValue()).isTrue();
assertThat(solver.mkInteger(0).isIntegerValue()).isTrue();
assertThat(solver.mkInteger(999).isIntegerValue()).isTrue();
assertThat(solver.mkInteger(-1).isIntegerValue()).isTrue();
assertThat(solver.mkInteger("0").isIntegerValue()).isTrue();
// Variables (named const, because thats not confusing....)
// Variables (Consts) return false if checked for value!
assertThat(solver.mkConst(solver.getBooleanSort()).isBooleanValue()).isFalse();
assertThat(solver.mkConst(solver.getIntegerSort()).isIntegerValue()).isFalse();
// To check for variables we have to check for value and type
assertThat(solver.mkConst(solver.getBooleanSort()).getSort().isBoolean()).isTrue();
// Test consts (variables). Consts are always false when checked for isTypedValue(), if you try
// getTypedValue() on it anyway an exception is raised. This persists after sat. The only way of
// checking and geting the values is via Kind.CONSTANT, type = sort and getValue()
Term intVar = solver.mkConst(solver.getIntegerSort(), "int_const");
assertThat(intVar.isIntegerValue()).isFalse();
assertThat(intVar.getSort().isInteger()).isTrue();
Exception e =
assertThrows(io.github.cvc5.api.CVC5ApiException.class, () -> intVar.getIntegerValue());
assertThat(e.toString())
.contains(
"Invalid argument 'int_const' for '*d_node', expected Term to be an integer value when calling getIntegerValue()");
// Build a formula such that is has a value, assert and check sat and then check again
solver.assertFormula(solver.mkTerm(Kind.EQUAL, intVar, solver.mkInteger(1)));
// Is sat, no need to check
solver.checkSat();
assertThat(intVar.isIntegerValue()).isFalse();
assertThat(intVar.getSort().isInteger()).isTrue();
assertThat(intVar.getKind()).isEqualTo(Kind.CONSTANT);
assertThat(intVar.getKind()).isNotEqualTo(Kind.VARIABLE);
assertThat(solver.getValue(intVar).toString()).isEqualTo("1");
// Note that variables (Kind.VARIABLES) are bound variables!
assertThat(solver.mkVar(solver.getIntegerSort()).getKind()).isEqualTo(Kind.VARIABLE);
assertThat(solver.mkVar(solver.getIntegerSort()).getKind()).isNotEqualTo(Kind.CONSTANT);
// Uf unapplied are CONSTANT
Sort intToBoolSort = solver.mkFunctionSort(solver.getIntegerSort(), solver.getBooleanSort());
Term uf1 = solver.mkConst(intToBoolSort);
assertThat(uf1.getKind()).isNotEqualTo(Kind.VARIABLE);
assertThat(uf1.getKind()).isEqualTo(Kind.CONSTANT);
assertThat(uf1.getKind()).isNotEqualTo(Kind.APPLY_UF);
assertThat(intToBoolSort.isFunction()).isTrue();
assertThat(uf1.getSort().isFunction()).isTrue();
// arity 1
assertThat(uf1.getSort().getFunctionArity()).isEqualTo(1);
// apply the uf, the kind is now APPLY_UF
Term appliedUf1 = solver.mkTerm(Kind.APPLY_UF, new Term[] {uf1, intVar});
assertThat(appliedUf1.getKind()).isNotEqualTo(Kind.VARIABLE);
assertThat(appliedUf1.getKind()).isNotEqualTo(Kind.CONSTANT);
assertThat(appliedUf1.getKind()).isEqualTo(Kind.APPLY_UF);
assertThat(appliedUf1.getSort().isFunction()).isFalse();
// The ufs sort is always the returntype
assertThat(appliedUf1.getSort()).isEqualTo(solver.getBooleanSort());
assertThat(appliedUf1.getNumChildren()).isEqualTo(2);
// The first child is the UF
assertThat(appliedUf1.getChild(0).getSort()).isEqualTo(intToBoolSort);
// The second child onwards are the arguments
assertThat(appliedUf1.getChild(1).getSort()).isEqualTo(solver.getIntegerSort());
}
/*
* Try to convert real -> int -> bv -> fp; which fails at the fp step. Use Kind.FLOATINGPOINT_TO_FP_REAL instead!
*/
@Test
public void checkFPConversion() throws CVC5ApiException {
Term oneFourth = solver.mkReal("1/4");
Term intOneFourth = solver.mkTerm(Kind.TO_INTEGER, oneFourth);
Term bvOneFourth = solver.mkTerm(solver.mkOp(Kind.INT_TO_BITVECTOR, 32), intOneFourth);
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiException.class,
() -> solver.mkFloatingPoint(8, 24, bvOneFourth));
assertThat(e.toString())
.contains(
"Invalid argument '((_ int2bv 32) (to_int (/ 1 4)))' for 'val', expected bit-vector constant");
}
@Test
public void checkSimpleUnsat() {
solver.assertFormula(solver.mkBoolean(false));
Result satCheck = solver.checkSat();
assertThat(satCheck.isUnsat()).isTrue();
}
@Test
public void checkSimpleSat() {
solver.assertFormula(solver.mkBoolean(true));
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleEqualitySat() {
Term one = solver.mkInteger(1);
Term assertion = solver.mkTerm(Kind.EQUAL, one, one);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleEqualityUnsat() {
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
Term assertion = solver.mkTerm(Kind.EQUAL, zero, one);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleInequalityUnsat() {
Term one = solver.mkInteger(1);
Term assertion = solver.mkTerm(Kind.NOT, solver.mkTerm(Kind.EQUAL, one, one));
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleInequalitySat() {
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
Term assertion = solver.mkTerm(Kind.NOT, solver.mkTerm(Kind.EQUAL, zero, one));
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleLIAEqualitySat() {
Term one = solver.mkInteger(1);
Term two = solver.mkInteger(2);
Term assertion = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, one, one), two);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleLIAEqualityUnsat() {
Term one = solver.mkInteger(1);
Term assertion = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, one, one), one);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleLIASat() {
// x + y = 4 AND x * y = 4
Term four = solver.mkInteger(4);
Term varX = solver.mkConst(solver.getIntegerSort(), "x");
Term varY = solver.mkConst(solver.getIntegerSort(), "y");
Term assertion1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), four);
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, varX, varY), four);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
assertThat(getInt(varX) + getInt(varY)).isEqualTo(4);
assertThat(getInt(varX) * getInt(varY)).isEqualTo(4);
}
/** Helper to get to int values faster. */
private int getInt(Term cvc5Term) {
String string = solver.getValue(cvc5Term).toString();
return Integer.parseInt(string);
}
@Test
public void checkSimpleLIAUnsat() {
// x + y = 1 AND x * y = 1
Term one = solver.mkInteger(1);
Term varX = solver.mkConst(solver.getIntegerSort(), "x");
Term varY = solver.mkConst(solver.getIntegerSort(), "y");
Term assertion1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), one);
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, varX, varY), one);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkLIAModel() {
// 1 + 2 = var
// it follows that var = 3
Term one = solver.mkInteger(1);
Term two = solver.mkInteger(2);
Term var = solver.mkConst(solver.getIntegerSort());
Term assertion = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, one, two), var);
solver.assertFormula(assertion);
Result result = solver.checkSat();
assertThat(result.isSat()).isTrue();
Term assertionValue = solver.getValue(assertion);
assertThat(assertionValue.toString()).isEqualTo("true");
assertThat(solver.getValue(var).toString()).isEqualTo("3");
}
@Test
public void checkSimpleLIRAUnsat2() {
// x + y = 4 AND x * y = 4
Term threeHalf = solver.mkReal(3, 2);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term varY = solver.mkConst(solver.getRealSort(), "y");
Term assertion1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), threeHalf);
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, varX, varY), threeHalf);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleLIRASat() {
// x + y = 8/5 AND x > 0 AND y > 0 AND x < 8/5 AND y < 8/5
Term zero = solver.mkReal(0);
Term eightFifth = solver.mkReal(8, 5);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term varY = solver.mkConst(solver.getRealSort(), "y");
Term assertion1 = solver.mkTerm(Kind.GT, varX, zero);
Term assertion2 = solver.mkTerm(Kind.GT, varY, zero);
Term assertion3 = solver.mkTerm(Kind.LT, varX, eightFifth);
Term assertion4 = solver.mkTerm(Kind.LT, varY, eightFifth);
Term assertion5 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, varX, varY), eightFifth);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
solver.assertFormula(assertion3);
solver.assertFormula(assertion4);
solver.assertFormula(assertion5);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
/** Real uses the same operators as int (plain plus, mult etc.) */
@Test
public void checkSimpleLRASat() {
// x * y = 8/5 AND x < 4/5
Term fourFifth = solver.mkReal(4, 5);
Term eightFifth = solver.mkReal(8, 5);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term varY = solver.mkConst(solver.getRealSort(), "y");
Term assertion1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), eightFifth);
Term assertion2 = solver.mkTerm(Kind.LT, varX, fourFifth);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
/** Exponents may only be natural number constants. */
@Test
public void checkSimplePow() {
// x ^ 2 = 4 AND x ^ 3 = 8
Term two = solver.mkReal(2);
Term three = solver.mkReal(3);
Term four = solver.mkReal(4);
Term eight = solver.mkReal(8);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term assertion1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.POW, varX, two), four);
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.POW, varX, three), eight);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleFPSat() throws CVC5ApiException {
// x * y = 1/4
Term rmTerm = solver.mkRoundingMode(RoundingMode.ROUND_NEAREST_TIES_TO_AWAY);
Op mkRealOp = solver.mkOp(Kind.FLOATINGPOINT_TO_FP_REAL, 8, 24);
Term oneFourth = solver.mkTerm(mkRealOp, rmTerm, solver.mkReal(1, 4));
Term varX = solver.mkConst(solver.mkFloatingPointSort(8, 24), "x");
Term varY = solver.mkConst(solver.mkFloatingPointSort(8, 24), "y");
Term assertion1 =
solver.mkTerm(
Kind.FLOATINGPOINT_EQ,
solver.mkTerm(Kind.FLOATINGPOINT_MULT, rmTerm, varX, varY),
oneFourth);
solver.assertFormula(assertion1);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleFPUnsat() throws CVC5ApiException {
// x * y = 1/4 AND x > 0 AND y < 0
Term rmTerm = solver.mkRoundingMode(RoundingMode.ROUND_NEAREST_TIES_TO_AWAY);
Op mkRealOp = solver.mkOp(Kind.FLOATINGPOINT_TO_FP_REAL, 8, 24);
Term oneFourth = solver.mkTerm(mkRealOp, rmTerm, solver.mkReal(1, 4));
Term zero = solver.mkTerm(mkRealOp, rmTerm, solver.mkReal(0));
Term varX = solver.mkConst(solver.mkFloatingPointSort(8, 24), "x");
Term varY = solver.mkConst(solver.mkFloatingPointSort(8, 24), "y");
Term assertion1 =
solver.mkTerm(
Kind.FLOATINGPOINT_EQ,
solver.mkTerm(Kind.FLOATINGPOINT_MULT, rmTerm, varX, varY),
oneFourth);
Term assertion2 = solver.mkTerm(Kind.FLOATINGPOINT_GT, varX, zero);
Term assertion3 = solver.mkTerm(Kind.FLOATINGPOINT_LT, varY, zero);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
solver.assertFormula(assertion3);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleLRAUnsat() {
// x + y = x * y AND x - 1 = 0
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term varY = solver.mkConst(solver.getRealSort(), "y");
Term assertion1 =
solver.mkTerm(
Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), solver.mkTerm(Kind.PLUS, varX, varY));
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MINUS, varX, one), zero);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleLRAUnsat2() {
// x + y = 3/2 AND x * y = 3/2
Term threeHalf = solver.mkReal(3, 2);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term varY = solver.mkConst(solver.getRealSort(), "y");
Term assertion1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), threeHalf);
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, varX, varY), threeHalf);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleIncrementalSolving() throws CVC5ApiException {
// x + y = 3/2 AND x * y = 3/2 (AND x - 1 = 0)
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
Term threeHalf = solver.mkReal(3, 2);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term varY = solver.mkConst(solver.getRealSort(), "y");
// this alone is SAT
Term assertion1 =
solver.mkTerm(
Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), solver.mkTerm(Kind.PLUS, varX, varY));
// both 2 and 3 make it UNSAT (either one)
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, varX, varY), threeHalf);
Term assertion3 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MINUS, varX, one), zero);
solver.push();
solver.assertFormula(assertion1);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
solver.push();
solver.assertFormula(assertion2);
satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
solver.pop();
satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
solver.push();
solver.assertFormula(assertion3);
satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
solver.pop();
satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
/** Note that model and getValue are seperate! */
@Test
public void checkInvalidModelGetValue() {
Term assertion = solver.mkBoolean(false);
solver.assertFormula(assertion);
Result result = solver.checkSat();
assertThat(result.isSat()).isFalse();
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiRecoverableException.class, () -> solver.getValue(assertion));
assertThat(e.toString()).contains(INVALID_GETVALUE_STRING_SAT);
}
/** The getModel() call needs an array of sorts and terms. */
@Test
public void checkGetModelUnsat() {
Term assertion = solver.mkBoolean(false);
solver.assertFormula(assertion);
Sort[] sorts = new Sort[] {solver.getBooleanSort()};
Term[] terms = new Term[] {assertion};
Result result = solver.checkSat();
assertThat(result.isSat()).isFalse();
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiRecoverableException.class,
() -> solver.getModel(sorts, terms));
assertThat(e.toString()).contains(INVALID_MODEL_STRING);
}
/**
* The getModel() call needs an array of sorts and terms. This tests invalid sort parameters.
* Sort: The list of uninterpreted sorts that should be printed in the model. Vars: The list of
* free constants that should be printed in the model. A subset of these may be printed based on
* isModelCoreSymbol.
*/
@Test
public void checkGetModelSatInvalidSort() {
Term assertion = solver.mkBoolean(true);
solver.assertFormula(assertion);
Sort[] sorts = new Sort[] {solver.getBooleanSort()};
Term[] terms = new Term[] {assertion};
Result result = solver.checkSat();
assertThat(result.isSat()).isTrue();
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiRecoverableException.class,
() -> solver.getModel(sorts, terms));
assertThat(e.toString()).contains("Expecting an uninterpreted sort as argument to getModel.");
}
/** Same as checkGetModelSatInvalidSort but with invalid term. */
@Test
public void checkGetModelSatInvalidTerm() {
Term assertion = solver.mkBoolean(true);
solver.assertFormula(assertion);
Sort[] sorts = new Sort[] {};
Term[] terms = new Term[] {assertion};
Result result = solver.checkSat();
assertThat(result.isSat()).isTrue();
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiRecoverableException.class,
() -> solver.getModel(sorts, terms));
assertThat(e.toString()).contains("Expecting a free constant as argument to getModel.");
}
@Test
public void checkGetModelSat() {
Term assertion = solver.mkConst(solver.getBooleanSort());
solver.assertFormula(assertion);
Sort[] sorts = new Sort[] {};
Term[] terms = new Term[] {assertion};
Result result = solver.checkSat();
assertThat(result.isSat()).isTrue();
String model = solver.getModel(sorts, terms);
// The toString of vars (consts) is the internal variable id
assertThat(model).contains("(\n" + "(define-fun " + assertion + " () Bool true)\n" + ")");
}
/**
* The getModel() call needs an array of sorts and terms. This tests what happens if you put empty
* arrays into it.
*/
@Test
public void checkInvalidGetModel() {
Term assertion = solver.mkBoolean(false);
solver.assertFormula(assertion);
Result result = solver.checkSat();
assertThat(result.isSat()).isFalse();
Sort[] sorts = new Sort[1];
Term[] terms = new Term[1];
assertThrows(NullPointerException.class, () -> solver.getModel(sorts, terms));
}
/** It does not matter if you take an int or array or bv here, all result in the same error. */
@Test
public void checkInvalidTypeOperationsAssert() throws CVC5ApiException {
Sort bvSort = solver.mkBitVectorSort(16);
Term bvVar = solver.mkConst(bvSort, "bla");
Term assertion = solver.mkTerm(Kind.BITVECTOR_AND, bvVar, bvVar);
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiException.class, () -> solver.assertFormula(assertion));
assertThat(e.toString()).contains("Expected term with sort Bool");
}
/** It does not matter if you take an int or array or bv here, all result in the same error. */
@Test
public void checkInvalidTypeOperationsCheckSat() throws CVC5ApiException {
Sort bvSort = solver.mkBitVectorSort(16);
Term bvVar = solver.mkConst(bvSort);
Term intVar = solver.mkConst(solver.getIntegerSort());
Term arrayVar = solver.mkConst(solver.mkArraySort(solver.getIntegerSort(), solver.getIntegerSort()));
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiException.class, () -> solver.mkTerm(Kind.AND, bvVar, bvVar));
assertThat(e.toString()).contains("expecting a Boolean subexpression");
e =
assertThrows(
io.github.cvc5.api.CVC5ApiException.class,
() -> solver.mkTerm(Kind.AND, intVar, intVar));
assertThat(e.toString()).contains("expecting a Boolean subexpression");
e =
assertThrows(
io.github.cvc5.api.CVC5ApiException.class,
() -> solver.mkTerm(Kind.AND, arrayVar, arrayVar));
assertThat(e.toString()).contains("expecting a Boolean subexpression");
}
@Test
public void checkBvInvalidZeroWidthAssertion() {
Exception e =
assertThrows(io.github.cvc5.api.CVC5ApiException.class, () -> solver.mkBitVector(0, 1));
assertThat(e.toString()).contains("Invalid argument '0' for 'size', expected a bit-width > 0");
}
@Test
public void checkBvInvalidNegativeWidthCheckAssertion() {
Exception e =
assertThrows(io.github.cvc5.api.CVC5ApiException.class, () -> solver.mkBitVector(-1, 1));
assertThat(e.toString()).contains("Expected size '-1' to be non negative.");
}
@Test
public void checkSimpleBvEqualitySat() throws CVC5ApiException {
// 1 + 0 = 1 with bitvectors
Term bvOne = solver.mkBitVector(16, 1);
Term bvZero = solver.mkBitVector(16, 0);
Term assertion =
solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.BITVECTOR_ADD, bvZero, bvOne), bvOne);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleBvEqualityUnsat() throws CVC5ApiException {
// 0 + 1 = 2 UNSAT with bitvectors
Term bvZero = solver.mkBitVector(16, 0);
Term bvOne = solver.mkBitVector(16, 1);
Term bvTwo = solver.mkBitVector(16, 2);
Term assertion =
solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.BITVECTOR_ADD, bvZero, bvOne), bvTwo);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleBvUnsat() throws CVC5ApiException {
// var + 1 = 0 & var < max bitvector & var > 0; both < and > signed
// Because of bitvector nature its UNSAT now
Term bvVar = solver.mkConst(solver.mkBitVectorSort(16), "bvVar");
Term bvOne = solver.mkBitVector(16, 1);
Term bvZero = solver.mkBitVector(16, 0);
Term assertion1 =
solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.BITVECTOR_ADD, bvVar, bvOne), bvZero);
// mkMaxSigned(16);
Term assertion2 = solver.mkTerm(Kind.BITVECTOR_SLT, bvVar, makeMaxCVC5Bitvector(16, true));
Term assertion3 = solver.mkTerm(Kind.BITVECTOR_SGT, bvVar, bvZero);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
solver.assertFormula(assertion3);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkBvDistinct() throws CVC5ApiException {
Sort bvSort = solver.mkBitVectorSort(6);
List<Term> bvs = new ArrayList<>();
for (int i = 0; i < 64; i++) {
bvs.add(solver.mkConst(bvSort, "a" + i + "_"));
}
Term distinct2 = solver.mkTerm(Kind.DISTINCT, bvs.toArray(new Term[0]));
solver.assertFormula(distinct2);
assertThat(solver.checkSat().isSat()).isTrue();
solver.resetAssertions();
// TODO: The following runs endlessly; recheck for new versions!
/*
bvs.add(solver.mkConst(bvSort, "b" + "_"));
Term distinct3 = solver.mkTerm(Kind.DISTINCT, bvs.toArray(new Term[0]));
solver.assertFormula(distinct3);
assertThat(solver.checkSat().isSat()).isFalse();
*/
}
/*
* CVC5 fails some easy quantifier tests.
*/
@Test
public void checkQuantifierExistsIncomplete() {
// (not exists x . not b[x] = 0) AND (b[123] = 0) is SAT
setupArrayQuant();
Term zero = solver.mkInteger(0);
Term xBound = solver.mkVar(solver.getIntegerSort(), "x");
Term quantifiedVars = solver.mkTerm(Kind.VARIABLE_LIST, xBound);
Term aAtxEq0s = aAtxEq0.substitute(x, xBound);
Term exists = solver.mkTerm(Kind.EXISTS, quantifiedVars, solver.mkTerm(Kind.NOT, aAtxEq0s));
Term notExists = solver.mkTerm(Kind.NOT, exists);
Term select123 = solver.mkTerm(Kind.SELECT, array, solver.mkInteger(123));
Term selectEq0 = solver.mkTerm(Kind.EQUAL, select123, zero);
Term assertion = solver.mkTerm(Kind.AND, notExists, selectEq0);
// assertFormula has a return value, check?
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
// CVC5 fails this test as incomplete
assertThat(satCheck.isSatUnknown()).isTrue();
assertThat(satCheck.getUnknownExplanation()).isEqualTo(Result.UnknownExplanation.INCOMPLETE);
}
@Test
public void checkQuantifierEliminationLIA() {
// build formula: (forall x . ((x < 5) | (7 < x + y)))
// quantifier-free equivalent: (2 < y) or (>= y 3)
setupArrayQuant();
Term three = solver.mkInteger(3);
Term five = solver.mkInteger(5);
Term seven = solver.mkInteger(7);
Term y = solver.mkConst(solver.getIntegerSort(), "y");
Term first = solver.mkTerm(Kind.LT, x, five);
Term second = solver.mkTerm(Kind.LT, seven, solver.mkTerm(Kind.PLUS, x, y));
Term body = solver.mkTerm(Kind.OR, first, second);
Term xBound = solver.mkVar(solver.getIntegerSort(), "xBound");
Term quantifiedVars = solver.mkTerm(Kind.VARIABLE_LIST, xBound);
Term bodySubst = body.substitute(x, xBound);
Term assertion = solver.mkTerm(Kind.FORALL, quantifiedVars, bodySubst);
Term result = solver.getQuantifierElimination(assertion);
Term resultCheck = solver.mkTerm(Kind.GEQ, y, three);
assertThat(result.toString()).isEqualTo(resultCheck.toString());
}
@Test
public void checkQuantifierWithUf() {
Term var = solver.mkConst(solver.getIntegerSort(), "var");
// start with a normal, free variable!
Term boundVar = solver.mkConst(solver.getIntegerSort(), "boundVar");
Term varIsOne = solver.mkTerm(Kind.EQUAL, var, solver.mkInteger(1));
// try not to use 0 as this is the default value for CVC5 models
Term boundVarIsTwo = solver.mkTerm(Kind.EQUAL, boundVar, solver.mkInteger(2));
Term boundVarIsOne = solver.mkTerm(Kind.EQUAL, boundVar, solver.mkInteger(1));
String func = "func";
Sort intSort = solver.getIntegerSort();
Sort ufSort = solver.mkFunctionSort(intSort, intSort);
Term uf = solver.mkConst(ufSort, func);
Term funcAtBoundVar = solver.mkTerm(Kind.APPLY_UF, uf, boundVar);
Term body =
solver.mkTerm(Kind.AND, boundVarIsTwo, solver.mkTerm(Kind.EQUAL, var, funcAtBoundVar));
// This is the bound variable used for boundVar
Term boundVarBound = solver.mkVar(solver.getIntegerSort(), "boundVarBound");
Term quantifiedVars = solver.mkTerm(Kind.VARIABLE_LIST, boundVarBound);
// Subst all boundVar variables with the bound version
Term bodySubst = body.substitute(boundVar, boundVarBound);
Term quantFormula = solver.mkTerm(Kind.EXISTS, quantifiedVars, bodySubst);
// var = 1 & boundVar = 1 & exists boundVar . ( boundVar = 2 & f(boundVar) = var )
Term overallFormula = solver.mkTerm(Kind.AND, varIsOne, boundVarIsOne, quantFormula);
solver.assertFormula(overallFormula);
Result satCheck = solver.checkSat();
// SAT
assertThat(satCheck.isSat()).isTrue();
// check Model
// var = 1 & boundVar = 1 & exists boundVar . ( boundVar = 2 & f(2) = 1 )
// It seems like CVC5 can't return quantified variables,
// therefore we can't get a value for the uf!
assertThat(solver.getValue(var).toString()).isEqualTo("1");
assertThat(solver.getValue(boundVar).toString()).isEqualTo("1");
// funcAtBoundVar and body do not have boundVars in them!
assertThat(solver.getValue(funcAtBoundVar).toString()).isEqualTo("1");
assertThat(solver.getValue(body).toString()).isEqualTo("false");
// CVC5 does not allow the usage of getValue() on bound vars!
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiRecoverableException.class,
() -> solver.getValue(boundVarBound));
assertThat(e.toString()).contains(INVALID_GETVALUE_STRING_BOUND_VAR);
e =
assertThrows(
io.github.cvc5.api.CVC5ApiRecoverableException.class, () -> solver.getValue(bodySubst));
assertThat(e.toString()).contains(INVALID_GETVALUE_STRING_BOUND_VAR);
}
/** CVC5 does not support Array quantifier elimination. This would run endlessly! */
@Ignore
@Test
public void checkArrayQuantElim() {
setupArrayQuant();
Term body = solver.mkTerm(Kind.OR, aAtxEq0, aAtxEq1);
Term xBound = solver.mkVar(solver.getIntegerSort(), "x_b");
Term quantifiedVars = solver.mkTerm(Kind.VARIABLE_LIST, xBound);
Term bodySubst = body.substitute(x, xBound);
Term assertion = solver.mkTerm(Kind.FORALL, quantifiedVars, bodySubst);
Term result = solver.getQuantifierElimination(assertion);
String resultString =
"(forall ((x_b Int)) (let ((_let_0 (select a x_b))) (or (= _let_0 0) (= _let_0 1))) )";
assertThat(result.toString()).isEqualTo(resultString);
}
/** CVC5 does support Bv quantifier elim.! */
@Test
public void checkQuantifierEliminationBV() throws CVC5ApiException {
// build formula: exists y : bv[2]. x * y = 1
// quantifier-free equivalent: x = 1 | x = 3
// or extract_0_0 x = 1
// Note from CVC5: a witness expression; first parameter is a BOUND_VAR_LIST, second is the
// witness body"
int width = 2;
Term xBv = solver.mkConst(solver.mkBitVectorSort(width), "x_bv");
Term yBv = solver.mkConst(solver.mkBitVectorSort(width), "y_bv");
Term mult = solver.mkTerm(Kind.BITVECTOR_MULT, xBv, yBv);
Term body = solver.mkTerm(Kind.EQUAL, mult, solver.mkBitVector(2, 1));
Term xBound = solver.mkVar(solver.mkBitVectorSort(width), "y_bv");
Term quantifiedVars = solver.mkTerm(Kind.VARIABLE_LIST, xBound);
Term bodySubst = body.substitute(yBv, xBound);
Term assertion = solver.mkTerm(Kind.EXISTS, quantifiedVars, bodySubst);
Term quantElim = solver.getQuantifierElimination(assertion);
assertThat(solver.getValue(quantElim).toString())
.isEqualTo(
"(= (concat ((_ extract 0 0) (witness ((x0 (_ BitVec 2))) (or (= (bvmul x_bv x0) #b01) (not (= (concat #b0 ((_ extract 0 0) (bvor x_bv (bvneg x_bv)))) #b01))))) #b0) #b01)");
assertThat(quantElim.toString())
.isEqualTo(
"(= (bvmul x_bv (witness ((x0 (_ BitVec 2))) (or (= (bvmul x_bv x0) #b01) (not (= (concat #b0 ((_ extract 0 0) (bvor x_bv (bvneg x_bv)))) #b01))))) #b01)");
}
@Test
public void checkArraySat() {
// ((x = 123) & (select(arr, 5) = 123)) => ((select(arr, 5) = x) & (x = 123))
Term five = solver.mkInteger(5);
Term oneTwoThree = solver.mkInteger(123);
Term xInt = solver.mkVar(solver.getIntegerSort(), "x_int");
Sort arraySort = solver.mkArraySort(solver.getIntegerSort(), solver.getIntegerSort());
Term arr = solver.mkVar(arraySort, "arr");
Term xEq123 = solver.mkTerm(Kind.EQUAL, xInt, oneTwoThree);
Term selAat5Eq123 =
solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.SELECT, arr, five), oneTwoThree);
Term selAat5EqX = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.SELECT, arr, five), xInt);
Term leftAnd = solver.mkTerm(Kind.AND, xEq123, selAat5Eq123);
Term rightAnd = solver.mkTerm(Kind.AND, xEq123, selAat5EqX);
Term impl = solver.mkTerm(Kind.IMPLIES, leftAnd, rightAnd);
solver.assertFormula(impl);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkArrayUnsat() {
// (x = 123) & (select(arr, 5) = 123) & (select(arr, 5) != x)
Term five = solver.mkInteger(5);
Term oneTwoThree = solver.mkInteger(123);
Term xInt = solver.mkVar(solver.getIntegerSort(), "x_int");
Sort arraySort = solver.mkArraySort(solver.getIntegerSort(), solver.getIntegerSort());
Term arr = solver.mkVar(arraySort, "arr");
Term xEq123 = solver.mkTerm(Kind.EQUAL, xInt, oneTwoThree);
Term selAat5Eq123 =
solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.SELECT, arr, five), oneTwoThree);
Term selAat5NotEqX =
solver.mkTerm(
Kind.NOT, solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.SELECT, arr, five), xInt));
Term assertion = solver.mkTerm(Kind.AND, xEq123, selAat5Eq123, selAat5NotEqX);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkUnsatCore() {
// (a & b) & (not(a OR b))
// Enable UNSAT Core first!
solver.setOption("produce-unsat-cores", "true");
Sort boolSort = solver.getBooleanSort();
Term a = solver.mkVar(boolSort, "a");
Term b = solver.mkVar(boolSort, "b");
Term aAndb = solver.mkTerm(Kind.AND, a, b);
Term notaOrb = solver.mkTerm(Kind.NOT, solver.mkTerm(Kind.OR, a, b));
solver.assertFormula(aAndb);
solver.assertFormula(notaOrb);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
Term[] unsatCore = solver.getUnsatCore();
// UnsatCores are iterable
for (Term e : unsatCore) {
assertThat(e.toString()).isIn(Arrays.asList("(not (or a b))", "(and a b)"));
}
}
@Test
public void checkCustomTypesAndUFs() {
// 0 <= f(x)
// 0 <= f(y)
// f(x) + f(y) <= 1
// not p(0)
// p(f(y))
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
Sort boolSort = solver.getBooleanSort();
Sort intSort = solver.getIntegerSort();
// You may use custom sorts just like bool or int
Sort mySort = solver.mkParamSort("f");
// Sort for UFs later
Sort mySortToInt = solver.mkFunctionSort(mySort, intSort);
Sort intToBool = solver.mkFunctionSort(intSort, boolSort);
Term xTyped = solver.mkVar(mySort, "x");
Term yTyped = solver.mkVar(mySort, "y");
// declare UFs
Term f = solver.mkConst(mySortToInt, "f");
Term p = solver.mkConst(intToBool, "p");
// Apply UFs
Term fx = solver.mkTerm(Kind.APPLY_UF, f, xTyped);
Term fy = solver.mkTerm(Kind.APPLY_UF, f, yTyped);
Term sum = solver.mkTerm(Kind.PLUS, fx, fy);
Term p0 = solver.mkTerm(Kind.APPLY_UF, p, zero);
Term pfy = solver.mkTerm(Kind.APPLY_UF, p, fy);
// Make some assumptions
Term assumptions1 =
solver.mkTerm(
Kind.AND,
solver.mkTerm(Kind.LEQ, zero, fx),
solver.mkTerm(Kind.LEQ, zero, fy),
solver.mkTerm(Kind.LEQ, sum, one));
Term assumptions2 = solver.mkTerm(Kind.AND, p0.notTerm(), pfy);
solver.assertFormula(assumptions1);
solver.assertFormula(assumptions2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkBooleanUFDeclaration() {
Sort boolSort = solver.getBooleanSort();
Sort intSort = solver.getIntegerSort();
// arg is bool, return is int
Sort ufSort = solver.mkFunctionSort(boolSort, intSort);
Term uf = solver.mkConst(ufSort, "fun_bi");
Term ufTrue = solver.mkTerm(Kind.APPLY_UF, uf, solver.mkTrue());
Term ufFalse = solver.mkTerm(Kind.APPLY_UF, uf, solver.mkFalse());
Term assumptions = solver.mkTerm(Kind.NOT, solver.mkTerm(Kind.EQUAL, ufTrue, ufFalse));
solver.assertFormula(assumptions);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkLIAUfsUnsat() {
// 0 <= f(x)
// 0 <= f(y)
// f(x) + f(y) = x
// f(x) + f(y) = y
// f(x) = x + 1
// f(y) = y - 1
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
Sort intSort = solver.getIntegerSort();
// Sort for UFs later
Sort intToInt = solver.mkFunctionSort(intSort, intSort);
Term xInt = solver.mkConst(intSort, "x");
Term yInt = solver.mkConst(intSort, "y");
// declare UFs
Term f = solver.mkConst(intToInt, "f");
// Apply UFs
Term fx = solver.mkTerm(Kind.APPLY_UF, f, xInt);
Term fy = solver.mkTerm(Kind.APPLY_UF, f, yInt);
Term plus = solver.mkTerm(Kind.PLUS, fx, fy);
// Make some assumptions
Term assumptions1 =
solver.mkTerm(
Kind.AND,
solver.mkTerm(Kind.LEQ, zero, fx),
solver.mkTerm(Kind.EQUAL, plus, xInt),
solver.mkTerm(Kind.LEQ, zero, fy));
Term assumptions2 =
solver.mkTerm(
Kind.AND,
solver.mkTerm(Kind.EQUAL, fx, solver.mkTerm(Kind.PLUS, xInt, one)),
solver.mkTerm(Kind.EQUAL, fy, solver.mkTerm(Kind.MINUS, yInt, one)),
solver.mkTerm(Kind.EQUAL, plus, yInt));
solver.assertFormula(assumptions1);
solver.assertFormula(assumptions2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkLIAUfsSat() {
// f(x) = x + 1
// f(y) = y - 1
// x = y -> f(x) + f(y) = x AND f(x) + f(y) = y
Term one = solver.mkInteger(1);
Sort intSort = solver.getIntegerSort();
// Sort for UFs later
Sort intToInt = solver.mkFunctionSort(intSort, intSort);
Term xInt = solver.mkConst(intSort, "x");
Term yInt = solver.mkConst(intSort, "y");
// declare UFs
Term f = solver.mkConst(intToInt, "f");
// Apply UFs
Term fx = solver.mkTerm(Kind.APPLY_UF, f, xInt);
Term fy = solver.mkTerm(Kind.APPLY_UF, f, yInt);
Term plus = solver.mkTerm(Kind.PLUS, fx, fy);
Term plusEqx = solver.mkTerm(Kind.EQUAL, plus, xInt);
Term plusEqy = solver.mkTerm(Kind.EQUAL, plus, yInt);
Term xEqy = solver.mkTerm(Kind.EQUAL, yInt, xInt);
Term xEqyImplplusEqxAndy =
solver.mkTerm(Kind.IMPLIES, xEqy, solver.mkTerm(Kind.AND, plusEqx, plusEqy));
Term assumptions =
solver.mkTerm(
Kind.AND,
solver.mkTerm(Kind.EQUAL, fx, solver.mkTerm(Kind.PLUS, xInt, one)),
solver.mkTerm(Kind.EQUAL, fy, solver.mkTerm(Kind.MINUS, yInt, one)),
xEqyImplplusEqxAndy);
solver.assertFormula(assumptions);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
/** Sets up array and quantifier based formulas for tests. */
public void setupArrayQuant() {
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
x = solver.mkVar(solver.getIntegerSort(), "x");
Sort arraySort = solver.mkArraySort(solver.getIntegerSort(), solver.getIntegerSort());
array = solver.mkVar(arraySort, "a");
aAtxEq0 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.SELECT, array, x), zero);
aAtxEq1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.SELECT, array, x), one);
}
/**
* For some reason CVC5 does not provide API to create max (or min) size signed/unsiged
* bitvectors.
*
* @param width of the bitvector term.
* @param signed true if signed. false for unsigned.
* @return Max size bitvector term.
*/
public Term makeMaxCVC5Bitvector(int width, boolean signed) throws CVC5ApiException {
String bitvecString;
if (signed) {
bitvecString = new String(new char[width - 1]).replace("\0", "1");
bitvecString = "0" + bitvecString;
} else {
bitvecString = new String(new char[width]).replace("\0", "1");
}
return solver.mkBitVector(width, bitvecString, 2);
}
}
| src/org/sosy_lab/java_smt/solvers/cvc5/CVC5NativeAPITest.java | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.solvers.cvc5;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import io.github.cvc5.api.CVC5ApiException;
import io.github.cvc5.api.Kind;
import io.github.cvc5.api.Op;
import io.github.cvc5.api.Result;
import io.github.cvc5.api.RoundingMode;
import io.github.cvc5.api.Solver;
import io.github.cvc5.api.Sort;
import io.github.cvc5.api.Term;
import java.util.Arrays;
import org.junit.After;
import org.junit.AssumptionViolatedException;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.sosy_lab.common.NativeLibraries;
/*
* Please note that CVC5 does not have a native variable cache!
* Each variable created is a new one with a new internal id, even if they are named the same.
* As a result, checking equality on 2 formulas that are build with new variables
* that are named the same results in false!
* Additionally, CVC5 only supports quantifier elimination for LIA and LRA.
* However, it might run endlessly in some cases if you try quantifier elimination on array
* theories!
*/
public class CVC5NativeAPITest {
private static final String INVALID_GETVALUE_STRING_SAT =
"Cannot get value unless after a SAT or UNKNOWN response.";
private static final String INVALID_GETVALUE_STRING_BOUND_VAR =
"Cannot get value of term containing free variables";
private static final String INVALID_MODEL_STRING =
"Cannot get model unless after a SAT or UNKNOWN response.";
@BeforeClass
public static void loadCVC4() {
try {
NativeLibraries.loadLibrary("cvc5jni");
} catch (UnsatisfiedLinkError e) {
throw new AssumptionViolatedException("CVC5 is not available", e);
}
}
private Term x;
private Term array;
private Term aAtxEq0;
private Term aAtxEq1;
private Solver solver;
@Before
public void createEnvironment() throws CVC5ApiException {
// CVC5 loads its own library statically
solver = new Solver();
// Set the logic
solver.setLogic("ALL");
// options
solver.setOption("produce-models", "true");
solver.setOption("finite-model-find", "true");
solver.setOption("sets-ext", "true");
solver.setOption("output-language", "smtlib2");
}
@After
public void freeEnvironment() {
solver.close();
}
/*
* Check how to get types/values etc. from constants, variables etc. in CVC5.
*/
@Test
public void checkGetValueAndType() throws CVC5ApiException {
// Constant values (NOT Kind,CONSTANT!)
assertThat(solver.mkBoolean(false).isBooleanValue()).isTrue();
assertThat(solver.mkInteger(0).isIntegerValue()).isTrue();
assertThat(solver.mkInteger(999).isIntegerValue()).isTrue();
assertThat(solver.mkInteger(-1).isIntegerValue()).isTrue();
assertThat(solver.mkInteger("0").isIntegerValue()).isTrue();
// Variables (named const, because thats not confusing....)
// Variables (Consts) return false if checked for value!
assertThat(solver.mkConst(solver.getBooleanSort()).isBooleanValue()).isFalse();
assertThat(solver.mkConst(solver.getIntegerSort()).isIntegerValue()).isFalse();
// To check for variables we have to check for value and type
assertThat(solver.mkConst(solver.getBooleanSort()).getSort().isBoolean()).isTrue();
// Test consts (variables). Consts are always false when checked for isTypedValue(), if you try
// getTypedValue() on it anyway an exception is raised. This persists after sat. The only way of
// checking and geting the values is via Kind.CONSTANT, type = sort and getValue()
Term intVar = solver.mkConst(solver.getIntegerSort(), "int_const");
assertThat(intVar.isIntegerValue()).isFalse();
assertThat(intVar.getSort().isInteger()).isTrue();
Exception e =
assertThrows(io.github.cvc5.api.CVC5ApiException.class, () -> intVar.getIntegerValue());
assertThat(e.toString())
.contains(
"Invalid argument 'int_const' for '*d_node', expected Term to be an integer value when calling getIntegerValue()");
// Build a formula such that is has a value, assert and check sat and then check again
solver.assertFormula(solver.mkTerm(Kind.EQUAL, intVar, solver.mkInteger(1)));
// Is sat, no need to check
solver.checkSat();
assertThat(intVar.isIntegerValue()).isFalse();
assertThat(intVar.getSort().isInteger()).isTrue();
assertThat(intVar.getKind()).isEqualTo(Kind.CONSTANT);
assertThat(intVar.getKind()).isNotEqualTo(Kind.VARIABLE);
assertThat(solver.getValue(intVar).toString()).isEqualTo("1");
// Note that variables (Kind.VARIABLES) are bound variables!
assertThat(solver.mkVar(solver.getIntegerSort()).getKind()).isEqualTo(Kind.VARIABLE);
assertThat(solver.mkVar(solver.getIntegerSort()).getKind()).isNotEqualTo(Kind.CONSTANT);
// Uf unapplied are CONSTANT
Sort intToBoolSort = solver.mkFunctionSort(solver.getIntegerSort(), solver.getBooleanSort());
Term uf1 = solver.mkConst(intToBoolSort);
assertThat(uf1.getKind()).isNotEqualTo(Kind.VARIABLE);
assertThat(uf1.getKind()).isEqualTo(Kind.CONSTANT);
assertThat(uf1.getKind()).isNotEqualTo(Kind.APPLY_UF);
assertThat(intToBoolSort.isFunction()).isTrue();
assertThat(uf1.getSort().isFunction()).isTrue();
// arity 1
assertThat(uf1.getSort().getFunctionArity()).isEqualTo(1);
// apply the uf, the kind is now APPLY_UF
Term appliedUf1 = solver.mkTerm(Kind.APPLY_UF, new Term[] {uf1, intVar});
assertThat(appliedUf1.getKind()).isNotEqualTo(Kind.VARIABLE);
assertThat(appliedUf1.getKind()).isNotEqualTo(Kind.CONSTANT);
assertThat(appliedUf1.getKind()).isEqualTo(Kind.APPLY_UF);
assertThat(appliedUf1.getSort().isFunction()).isFalse();
// The ufs sort is always the returntype
assertThat(appliedUf1.getSort()).isEqualTo(solver.getBooleanSort());
assertThat(appliedUf1.getNumChildren()).isEqualTo(2);
// The first child is the UF
assertThat(appliedUf1.getChild(0).getSort()).isEqualTo(intToBoolSort);
// The second child onwards are the arguments
assertThat(appliedUf1.getChild(1).getSort()).isEqualTo(solver.getIntegerSort());
}
/*
* Try to convert real -> int -> bv -> fp; which fails at the fp step. Use Kind.FLOATINGPOINT_TO_FP_REAL instead!
*/
@Test
public void checkFPConversion() throws CVC5ApiException {
Term oneFourth = solver.mkReal("1/4");
Term intOneFourth = solver.mkTerm(Kind.TO_INTEGER, oneFourth);
Term bvOneFourth = solver.mkTerm(solver.mkOp(Kind.INT_TO_BITVECTOR, 32), intOneFourth);
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiException.class,
() -> solver.mkFloatingPoint(8, 24, bvOneFourth));
assertThat(e.toString())
.contains(
"Invalid argument '((_ int2bv 32) (to_int (/ 1 4)))' for 'val', expected bit-vector constant");
}
@Test
public void checkSimpleUnsat() {
solver.assertFormula(solver.mkBoolean(false));
Result satCheck = solver.checkSat();
assertThat(satCheck.isUnsat()).isTrue();
}
@Test
public void checkSimpleSat() {
solver.assertFormula(solver.mkBoolean(true));
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleEqualitySat() {
Term one = solver.mkInteger(1);
Term assertion = solver.mkTerm(Kind.EQUAL, one, one);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleEqualityUnsat() {
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
Term assertion = solver.mkTerm(Kind.EQUAL, zero, one);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleInequalityUnsat() {
Term one = solver.mkInteger(1);
Term assertion = solver.mkTerm(Kind.NOT, solver.mkTerm(Kind.EQUAL, one, one));
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleInequalitySat() {
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
Term assertion = solver.mkTerm(Kind.NOT, solver.mkTerm(Kind.EQUAL, zero, one));
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleLIAEqualitySat() {
Term one = solver.mkInteger(1);
Term two = solver.mkInteger(2);
Term assertion = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, one, one), two);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleLIAEqualityUnsat() {
Term one = solver.mkInteger(1);
Term assertion = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, one, one), one);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleLIASat() {
// x + y = 4 AND x * y = 4
Term four = solver.mkInteger(4);
Term varX = solver.mkConst(solver.getIntegerSort(), "x");
Term varY = solver.mkConst(solver.getIntegerSort(), "y");
Term assertion1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), four);
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, varX, varY), four);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
assertThat(getInt(varX) + getInt(varY)).isEqualTo(4);
assertThat(getInt(varX) * getInt(varY)).isEqualTo(4);
}
/** Helper to get to int values faster. */
private int getInt(Term cvc5Term) {
String string = solver.getValue(cvc5Term).toString();
return Integer.parseInt(string);
}
@Test
public void checkSimpleLIAUnsat() {
// x + y = 1 AND x * y = 1
Term one = solver.mkInteger(1);
Term varX = solver.mkConst(solver.getIntegerSort(), "x");
Term varY = solver.mkConst(solver.getIntegerSort(), "y");
Term assertion1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), one);
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, varX, varY), one);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkLIAModel() {
// 1 + 2 = var
// it follows that var = 3
Term one = solver.mkInteger(1);
Term two = solver.mkInteger(2);
Term var = solver.mkConst(solver.getIntegerSort());
Term assertion = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, one, two), var);
solver.assertFormula(assertion);
Result result = solver.checkSat();
assertThat(result.isSat()).isTrue();
Term assertionValue = solver.getValue(assertion);
assertThat(assertionValue.toString()).isEqualTo("true");
assertThat(solver.getValue(var).toString()).isEqualTo("3");
}
@Test
public void checkSimpleLIRAUnsat2() {
// x + y = 4 AND x * y = 4
Term threeHalf = solver.mkReal(3, 2);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term varY = solver.mkConst(solver.getRealSort(), "y");
Term assertion1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), threeHalf);
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, varX, varY), threeHalf);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleLIRASat() {
// x + y = 8/5 AND x > 0 AND y > 0 AND x < 8/5 AND y < 8/5
Term zero = solver.mkReal(0);
Term eightFifth = solver.mkReal(8, 5);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term varY = solver.mkConst(solver.getRealSort(), "y");
Term assertion1 = solver.mkTerm(Kind.GT, varX, zero);
Term assertion2 = solver.mkTerm(Kind.GT, varY, zero);
Term assertion3 = solver.mkTerm(Kind.LT, varX, eightFifth);
Term assertion4 = solver.mkTerm(Kind.LT, varY, eightFifth);
Term assertion5 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, varX, varY), eightFifth);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
solver.assertFormula(assertion3);
solver.assertFormula(assertion4);
solver.assertFormula(assertion5);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
/** Real uses the same operators as int (plain plus, mult etc.) */
@Test
public void checkSimpleLRASat() {
// x * y = 8/5 AND x < 4/5
Term fourFifth = solver.mkReal(4, 5);
Term eightFifth = solver.mkReal(8, 5);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term varY = solver.mkConst(solver.getRealSort(), "y");
Term assertion1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), eightFifth);
Term assertion2 = solver.mkTerm(Kind.LT, varX, fourFifth);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
/** Exponents may only be natural number constants. */
@Test
public void checkSimplePow() {
// x ^ 2 = 4 AND x ^ 3 = 8
Term two = solver.mkReal(2);
Term three = solver.mkReal(3);
Term four = solver.mkReal(4);
Term eight = solver.mkReal(8);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term assertion1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.POW, varX, two), four);
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.POW, varX, three), eight);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleFPSat() throws CVC5ApiException {
// x * y = 1/4
Term rmTerm = solver.mkRoundingMode(RoundingMode.ROUND_NEAREST_TIES_TO_AWAY);
Op mkRealOp = solver.mkOp(Kind.FLOATINGPOINT_TO_FP_REAL, 8, 24);
Term oneFourth = solver.mkTerm(mkRealOp, rmTerm, solver.mkReal(1, 4));
Term varX = solver.mkConst(solver.mkFloatingPointSort(8, 24), "x");
Term varY = solver.mkConst(solver.mkFloatingPointSort(8, 24), "y");
Term assertion1 =
solver.mkTerm(
Kind.FLOATINGPOINT_EQ,
solver.mkTerm(Kind.FLOATINGPOINT_MULT, rmTerm, varX, varY),
oneFourth);
solver.assertFormula(assertion1);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleFPUnsat() throws CVC5ApiException {
// x * y = 1/4 AND x > 0 AND y < 0
Term rmTerm = solver.mkRoundingMode(RoundingMode.ROUND_NEAREST_TIES_TO_AWAY);
Op mkRealOp = solver.mkOp(Kind.FLOATINGPOINT_TO_FP_REAL, 8, 24);
Term oneFourth = solver.mkTerm(mkRealOp, rmTerm, solver.mkReal(1, 4));
Term zero = solver.mkTerm(mkRealOp, rmTerm, solver.mkReal(0));
Term varX = solver.mkConst(solver.mkFloatingPointSort(8, 24), "x");
Term varY = solver.mkConst(solver.mkFloatingPointSort(8, 24), "y");
Term assertion1 =
solver.mkTerm(
Kind.FLOATINGPOINT_EQ,
solver.mkTerm(Kind.FLOATINGPOINT_MULT, rmTerm, varX, varY),
oneFourth);
Term assertion2 = solver.mkTerm(Kind.FLOATINGPOINT_GT, varX, zero);
Term assertion3 = solver.mkTerm(Kind.FLOATINGPOINT_LT, varY, zero);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
solver.assertFormula(assertion3);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleLRAUnsat() {
// x + y = x * y AND x - 1 = 0
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term varY = solver.mkConst(solver.getRealSort(), "y");
Term assertion1 =
solver.mkTerm(
Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), solver.mkTerm(Kind.PLUS, varX, varY));
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MINUS, varX, one), zero);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleLRAUnsat2() {
// x + y = 3/2 AND x * y = 3/2
Term threeHalf = solver.mkReal(3, 2);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term varY = solver.mkConst(solver.getRealSort(), "y");
Term assertion1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), threeHalf);
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, varX, varY), threeHalf);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleIncrementalSolving() throws CVC5ApiException {
// x + y = 3/2 AND x * y = 3/2 (AND x - 1 = 0)
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
Term threeHalf = solver.mkReal(3, 2);
Term varX = solver.mkConst(solver.getRealSort(), "x");
Term varY = solver.mkConst(solver.getRealSort(), "y");
// this alone is SAT
Term assertion1 =
solver.mkTerm(
Kind.EQUAL, solver.mkTerm(Kind.MULT, varX, varY), solver.mkTerm(Kind.PLUS, varX, varY));
// both 2 and 3 make it UNSAT (either one)
Term assertion2 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.PLUS, varX, varY), threeHalf);
Term assertion3 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.MINUS, varX, one), zero);
solver.push();
solver.assertFormula(assertion1);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
solver.push();
solver.assertFormula(assertion2);
satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
solver.pop();
satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
solver.push();
solver.assertFormula(assertion3);
satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
solver.pop();
satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
/** Note that model and getValue are seperate! */
@Test
public void checkInvalidModelGetValue() {
Term assertion = solver.mkBoolean(false);
solver.assertFormula(assertion);
Result result = solver.checkSat();
assertThat(result.isSat()).isFalse();
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiRecoverableException.class, () -> solver.getValue(assertion));
assertThat(e.toString()).contains(INVALID_GETVALUE_STRING_SAT);
}
/** The getModel() call needs an array of sorts and terms. */
@Test
public void checkGetModelUnsat() {
Term assertion = solver.mkBoolean(false);
solver.assertFormula(assertion);
Sort[] sorts = new Sort[] {solver.getBooleanSort()};
Term[] terms = new Term[] {assertion};
Result result = solver.checkSat();
assertThat(result.isSat()).isFalse();
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiRecoverableException.class,
() -> solver.getModel(sorts, terms));
assertThat(e.toString()).contains(INVALID_MODEL_STRING);
}
/**
* The getModel() call needs an array of sorts and terms. This tests invalid sort parameters.
* Sort: The list of uninterpreted sorts that should be printed in the model. Vars: The list of
* free constants that should be printed in the model. A subset of these may be printed based on
* isModelCoreSymbol.
*/
@Test
public void checkGetModelSatInvalidSort() {
Term assertion = solver.mkBoolean(true);
solver.assertFormula(assertion);
Sort[] sorts = new Sort[] {solver.getBooleanSort()};
Term[] terms = new Term[] {assertion};
Result result = solver.checkSat();
assertThat(result.isSat()).isTrue();
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiRecoverableException.class,
() -> solver.getModel(sorts, terms));
assertThat(e.toString()).contains("Expecting an uninterpreted sort as argument to getModel.");
}
/** Same as checkGetModelSatInvalidSort but with invalid term. */
@Test
public void checkGetModelSatInvalidTerm() {
Term assertion = solver.mkBoolean(true);
solver.assertFormula(assertion);
Sort[] sorts = new Sort[] {};
Term[] terms = new Term[] {assertion};
Result result = solver.checkSat();
assertThat(result.isSat()).isTrue();
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiRecoverableException.class,
() -> solver.getModel(sorts, terms));
assertThat(e.toString()).contains("Expecting a free constant as argument to getModel.");
}
@Test
public void checkGetModelSat() {
Term assertion = solver.mkConst(solver.getBooleanSort());
solver.assertFormula(assertion);
Sort[] sorts = new Sort[] {};
Term[] terms = new Term[] {assertion};
Result result = solver.checkSat();
assertThat(result.isSat()).isTrue();
String model = solver.getModel(sorts, terms);
// The toString of vars (consts) is the internal variable id
assertThat(model).contains("(\n" + "(define-fun " + assertion + " () Bool true)\n" + ")");
}
/**
* The getModel() call needs an array of sorts and terms. This tests what happens if you put empty
* arrays into it.
*/
@Test
public void checkInvalidGetModel() {
Term assertion = solver.mkBoolean(false);
solver.assertFormula(assertion);
Result result = solver.checkSat();
assertThat(result.isSat()).isFalse();
Sort[] sorts = new Sort[1];
Term[] terms = new Term[1];
assertThrows(NullPointerException.class, () -> solver.getModel(sorts, terms));
}
/** It does not matter if you take an int or array or bv here, all result in the same error. */
@Test
public void checkInvalidTypeOperationsAssert() throws CVC5ApiException {
Sort bvSort = solver.mkBitVectorSort(16);
Term bvVar = solver.mkConst(bvSort, "bla");
Term assertion = solver.mkTerm(Kind.BITVECTOR_AND, bvVar, bvVar);
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiException.class, () -> solver.assertFormula(assertion));
assertThat(e.toString()).contains("Expected term with sort Bool");
}
/** It does not matter if you take an int or array or bv here, all result in the same error. */
@Test
public void checkInvalidTypeOperationsCheckSat() throws CVC5ApiException {
Sort bvSort = solver.mkBitVectorSort(16);
Term bvVar = solver.mkConst(bvSort);
Term intVar = solver.mkConst(solver.getIntegerSort());
Term arrayVar = solver.mkConst(solver.mkArraySort(solver.getIntegerSort(), solver.getIntegerSort()));
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiException.class, () -> solver.mkTerm(Kind.AND, bvVar, bvVar));
assertThat(e.toString()).contains("expecting a Boolean subexpression");
e =
assertThrows(
io.github.cvc5.api.CVC5ApiException.class,
() -> solver.mkTerm(Kind.AND, intVar, intVar));
assertThat(e.toString()).contains("expecting a Boolean subexpression");
e =
assertThrows(
io.github.cvc5.api.CVC5ApiException.class,
() -> solver.mkTerm(Kind.AND, arrayVar, arrayVar));
assertThat(e.toString()).contains("expecting a Boolean subexpression");
}
@Test
public void checkBvInvalidZeroWidthAssertion() {
Exception e =
assertThrows(io.github.cvc5.api.CVC5ApiException.class, () -> solver.mkBitVector(0, 1));
assertThat(e.toString()).contains("Invalid argument '0' for 'size', expected a bit-width > 0");
}
@Test
public void checkBvInvalidNegativeWidthCheckAssertion() {
Exception e =
assertThrows(io.github.cvc5.api.CVC5ApiException.class, () -> solver.mkBitVector(-1, 1));
assertThat(e.toString()).contains("Expected size '-1' to be non negative.");
}
@Test
public void checkSimpleBvEqualitySat() throws CVC5ApiException {
// 1 + 0 = 1 with bitvectors
Term bvOne = solver.mkBitVector(16, 1);
Term bvZero = solver.mkBitVector(16, 0);
Term assertion =
solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.BITVECTOR_ADD, bvZero, bvOne), bvOne);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkSimpleBvEqualityUnsat() throws CVC5ApiException {
// 0 + 1 = 2 UNSAT with bitvectors
Term bvZero = solver.mkBitVector(16, 0);
Term bvOne = solver.mkBitVector(16, 1);
Term bvTwo = solver.mkBitVector(16, 2);
Term assertion =
solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.BITVECTOR_ADD, bvZero, bvOne), bvTwo);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkSimpleBvUnsat() throws CVC5ApiException {
// var + 1 = 0 & var < max bitvector & var > 0; both < and > signed
// Because of bitvector nature its UNSAT now
Term bvVar = solver.mkConst(solver.mkBitVectorSort(16), "bvVar");
Term bvOne = solver.mkBitVector(16, 1);
Term bvZero = solver.mkBitVector(16, 0);
Term assertion1 =
solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.BITVECTOR_ADD, bvVar, bvOne), bvZero);
// mkMaxSigned(16);
Term assertion2 = solver.mkTerm(Kind.BITVECTOR_SLT, bvVar, makeMaxCVC5Bitvector(16, true));
Term assertion3 = solver.mkTerm(Kind.BITVECTOR_SGT, bvVar, bvZero);
solver.assertFormula(assertion1);
solver.assertFormula(assertion2);
solver.assertFormula(assertion3);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
/*
* CVC5 fails some easy quantifier tests.
*/
@Test
public void checkQuantifierExistsIncomplete() {
// (not exists x . not b[x] = 0) AND (b[123] = 0) is SAT
setupArrayQuant();
Term zero = solver.mkInteger(0);
Term xBound = solver.mkVar(solver.getIntegerSort(), "x");
Term quantifiedVars = solver.mkTerm(Kind.VARIABLE_LIST, xBound);
Term aAtxEq0s = aAtxEq0.substitute(x, xBound);
Term exists = solver.mkTerm(Kind.EXISTS, quantifiedVars, solver.mkTerm(Kind.NOT, aAtxEq0s));
Term notExists = solver.mkTerm(Kind.NOT, exists);
Term select123 = solver.mkTerm(Kind.SELECT, array, solver.mkInteger(123));
Term selectEq0 = solver.mkTerm(Kind.EQUAL, select123, zero);
Term assertion = solver.mkTerm(Kind.AND, notExists, selectEq0);
// assertFormula has a return value, check?
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
// CVC5 fails this test as incomplete
assertThat(satCheck.isSatUnknown()).isTrue();
assertThat(satCheck.getUnknownExplanation()).isEqualTo(Result.UnknownExplanation.INCOMPLETE);
}
@Test
public void checkQuantifierEliminationLIA() {
// build formula: (forall x . ((x < 5) | (7 < x + y)))
// quantifier-free equivalent: (2 < y) or (>= y 3)
setupArrayQuant();
Term three = solver.mkInteger(3);
Term five = solver.mkInteger(5);
Term seven = solver.mkInteger(7);
Term y = solver.mkConst(solver.getIntegerSort(), "y");
Term first = solver.mkTerm(Kind.LT, x, five);
Term second = solver.mkTerm(Kind.LT, seven, solver.mkTerm(Kind.PLUS, x, y));
Term body = solver.mkTerm(Kind.OR, first, second);
Term xBound = solver.mkVar(solver.getIntegerSort(), "xBound");
Term quantifiedVars = solver.mkTerm(Kind.VARIABLE_LIST, xBound);
Term bodySubst = body.substitute(x, xBound);
Term assertion = solver.mkTerm(Kind.FORALL, quantifiedVars, bodySubst);
Term result = solver.getQuantifierElimination(assertion);
Term resultCheck = solver.mkTerm(Kind.GEQ, y, three);
assertThat(result.toString()).isEqualTo(resultCheck.toString());
}
@Test
public void checkQuantifierWithUf() {
Term var = solver.mkConst(solver.getIntegerSort(), "var");
// start with a normal, free variable!
Term boundVar = solver.mkConst(solver.getIntegerSort(), "boundVar");
Term varIsOne = solver.mkTerm(Kind.EQUAL, var, solver.mkInteger(1));
// try not to use 0 as this is the default value for CVC5 models
Term boundVarIsTwo = solver.mkTerm(Kind.EQUAL, boundVar, solver.mkInteger(2));
Term boundVarIsOne = solver.mkTerm(Kind.EQUAL, boundVar, solver.mkInteger(1));
String func = "func";
Sort intSort = solver.getIntegerSort();
Sort ufSort = solver.mkFunctionSort(intSort, intSort);
Term uf = solver.mkConst(ufSort, func);
Term funcAtBoundVar = solver.mkTerm(Kind.APPLY_UF, uf, boundVar);
Term body =
solver.mkTerm(Kind.AND, boundVarIsTwo, solver.mkTerm(Kind.EQUAL, var, funcAtBoundVar));
// This is the bound variable used for boundVar
Term boundVarBound = solver.mkVar(solver.getIntegerSort(), "boundVarBound");
Term quantifiedVars = solver.mkTerm(Kind.VARIABLE_LIST, boundVarBound);
// Subst all boundVar variables with the bound version
Term bodySubst = body.substitute(boundVar, boundVarBound);
Term quantFormula = solver.mkTerm(Kind.EXISTS, quantifiedVars, bodySubst);
// var = 1 & boundVar = 1 & exists boundVar . ( boundVar = 2 & f(boundVar) = var )
Term overallFormula = solver.mkTerm(Kind.AND, varIsOne, boundVarIsOne, quantFormula);
solver.assertFormula(overallFormula);
Result satCheck = solver.checkSat();
// SAT
assertThat(satCheck.isSat()).isTrue();
// check Model
// var = 1 & boundVar = 1 & exists boundVar . ( boundVar = 2 & f(2) = 1 )
// It seems like CVC5 can't return quantified variables,
// therefore we can't get a value for the uf!
assertThat(solver.getValue(var).toString()).isEqualTo("1");
assertThat(solver.getValue(boundVar).toString()).isEqualTo("1");
// funcAtBoundVar and body do not have boundVars in them!
assertThat(solver.getValue(funcAtBoundVar).toString()).isEqualTo("1");
assertThat(solver.getValue(body).toString()).isEqualTo("false");
// CVC5 does not allow the usage of getValue() on bound vars!
Exception e =
assertThrows(
io.github.cvc5.api.CVC5ApiRecoverableException.class,
() -> solver.getValue(boundVarBound));
assertThat(e.toString()).contains(INVALID_GETVALUE_STRING_BOUND_VAR);
e =
assertThrows(
io.github.cvc5.api.CVC5ApiRecoverableException.class, () -> solver.getValue(bodySubst));
assertThat(e.toString()).contains(INVALID_GETVALUE_STRING_BOUND_VAR);
}
/** CVC5 does not support Array quantifier elimination. This would run endlessly! */
@Ignore
@Test
public void checkArrayQuantElim() {
setupArrayQuant();
Term body = solver.mkTerm(Kind.OR, aAtxEq0, aAtxEq1);
Term xBound = solver.mkVar(solver.getIntegerSort(), "x_b");
Term quantifiedVars = solver.mkTerm(Kind.VARIABLE_LIST, xBound);
Term bodySubst = body.substitute(x, xBound);
Term assertion = solver.mkTerm(Kind.FORALL, quantifiedVars, bodySubst);
Term result = solver.getQuantifierElimination(assertion);
String resultString =
"(forall ((x_b Int)) (let ((_let_0 (select a x_b))) (or (= _let_0 0) (= _let_0 1))) )";
assertThat(result.toString()).isEqualTo(resultString);
}
/** CVC5 does support Bv quantifier elim.! */
@Test
public void checkQuantifierEliminationBV() throws CVC5ApiException {
// build formula: exists y : bv[2]. x * y = 1
// quantifier-free equivalent: x = 1 | x = 3
// or extract_0_0 x = 1
// Note from CVC5: a witness expression; first parameter is a BOUND_VAR_LIST, second is the
// witness body"
int width = 2;
Term xBv = solver.mkConst(solver.mkBitVectorSort(width), "x_bv");
Term yBv = solver.mkConst(solver.mkBitVectorSort(width), "y_bv");
Term mult = solver.mkTerm(Kind.BITVECTOR_MULT, xBv, yBv);
Term body = solver.mkTerm(Kind.EQUAL, mult, solver.mkBitVector(2, 1));
Term xBound = solver.mkVar(solver.mkBitVectorSort(width), "y_bv");
Term quantifiedVars = solver.mkTerm(Kind.VARIABLE_LIST, xBound);
Term bodySubst = body.substitute(yBv, xBound);
Term assertion = solver.mkTerm(Kind.EXISTS, quantifiedVars, bodySubst);
Term quantElim = solver.getQuantifierElimination(assertion);
assertThat(solver.getValue(quantElim).toString())
.isEqualTo(
"(= (concat ((_ extract 0 0) (witness ((x0 (_ BitVec 2))) (or (= (bvmul x_bv x0) #b01) (not (= (concat #b0 ((_ extract 0 0) (bvor x_bv (bvneg x_bv)))) #b01))))) #b0) #b01)");
assertThat(quantElim.toString())
.isEqualTo(
"(= (bvmul x_bv (witness ((x0 (_ BitVec 2))) (or (= (bvmul x_bv x0) #b01) (not (= (concat #b0 ((_ extract 0 0) (bvor x_bv (bvneg x_bv)))) #b01))))) #b01)");
}
@Test
public void checkArraySat() {
// ((x = 123) & (select(arr, 5) = 123)) => ((select(arr, 5) = x) & (x = 123))
Term five = solver.mkInteger(5);
Term oneTwoThree = solver.mkInteger(123);
Term xInt = solver.mkVar(solver.getIntegerSort(), "x_int");
Sort arraySort = solver.mkArraySort(solver.getIntegerSort(), solver.getIntegerSort());
Term arr = solver.mkVar(arraySort, "arr");
Term xEq123 = solver.mkTerm(Kind.EQUAL, xInt, oneTwoThree);
Term selAat5Eq123 =
solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.SELECT, arr, five), oneTwoThree);
Term selAat5EqX = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.SELECT, arr, five), xInt);
Term leftAnd = solver.mkTerm(Kind.AND, xEq123, selAat5Eq123);
Term rightAnd = solver.mkTerm(Kind.AND, xEq123, selAat5EqX);
Term impl = solver.mkTerm(Kind.IMPLIES, leftAnd, rightAnd);
solver.assertFormula(impl);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkArrayUnsat() {
// (x = 123) & (select(arr, 5) = 123) & (select(arr, 5) != x)
Term five = solver.mkInteger(5);
Term oneTwoThree = solver.mkInteger(123);
Term xInt = solver.mkVar(solver.getIntegerSort(), "x_int");
Sort arraySort = solver.mkArraySort(solver.getIntegerSort(), solver.getIntegerSort());
Term arr = solver.mkVar(arraySort, "arr");
Term xEq123 = solver.mkTerm(Kind.EQUAL, xInt, oneTwoThree);
Term selAat5Eq123 =
solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.SELECT, arr, five), oneTwoThree);
Term selAat5NotEqX =
solver.mkTerm(
Kind.NOT, solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.SELECT, arr, five), xInt));
Term assertion = solver.mkTerm(Kind.AND, xEq123, selAat5Eq123, selAat5NotEqX);
solver.assertFormula(assertion);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkUnsatCore() {
// (a & b) & (not(a OR b))
// Enable UNSAT Core first!
solver.setOption("produce-unsat-cores", "true");
Sort boolSort = solver.getBooleanSort();
Term a = solver.mkVar(boolSort, "a");
Term b = solver.mkVar(boolSort, "b");
Term aAndb = solver.mkTerm(Kind.AND, a, b);
Term notaOrb = solver.mkTerm(Kind.NOT, solver.mkTerm(Kind.OR, a, b));
solver.assertFormula(aAndb);
solver.assertFormula(notaOrb);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
Term[] unsatCore = solver.getUnsatCore();
// UnsatCores are iterable
for (Term e : unsatCore) {
assertThat(e.toString()).isIn(Arrays.asList("(not (or a b))", "(and a b)"));
}
}
@Test
public void checkCustomTypesAndUFs() {
// 0 <= f(x)
// 0 <= f(y)
// f(x) + f(y) <= 1
// not p(0)
// p(f(y))
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
Sort boolSort = solver.getBooleanSort();
Sort intSort = solver.getIntegerSort();
// You may use custom sorts just like bool or int
Sort mySort = solver.mkParamSort("f");
// Sort for UFs later
Sort mySortToInt = solver.mkFunctionSort(mySort, intSort);
Sort intToBool = solver.mkFunctionSort(intSort, boolSort);
Term xTyped = solver.mkVar(mySort, "x");
Term yTyped = solver.mkVar(mySort, "y");
// declare UFs
Term f = solver.mkConst(mySortToInt, "f");
Term p = solver.mkConst(intToBool, "p");
// Apply UFs
Term fx = solver.mkTerm(Kind.APPLY_UF, f, xTyped);
Term fy = solver.mkTerm(Kind.APPLY_UF, f, yTyped);
Term sum = solver.mkTerm(Kind.PLUS, fx, fy);
Term p0 = solver.mkTerm(Kind.APPLY_UF, p, zero);
Term pfy = solver.mkTerm(Kind.APPLY_UF, p, fy);
// Make some assumptions
Term assumptions1 =
solver.mkTerm(
Kind.AND,
solver.mkTerm(Kind.LEQ, zero, fx),
solver.mkTerm(Kind.LEQ, zero, fy),
solver.mkTerm(Kind.LEQ, sum, one));
Term assumptions2 = solver.mkTerm(Kind.AND, p0.notTerm(), pfy);
solver.assertFormula(assumptions1);
solver.assertFormula(assumptions2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkBooleanUFDeclaration() {
Sort boolSort = solver.getBooleanSort();
Sort intSort = solver.getIntegerSort();
// arg is bool, return is int
Sort ufSort = solver.mkFunctionSort(boolSort, intSort);
Term uf = solver.mkConst(ufSort, "fun_bi");
Term ufTrue = solver.mkTerm(Kind.APPLY_UF, uf, solver.mkTrue());
Term ufFalse = solver.mkTerm(Kind.APPLY_UF, uf, solver.mkFalse());
Term assumptions = solver.mkTerm(Kind.NOT, solver.mkTerm(Kind.EQUAL, ufTrue, ufFalse));
solver.assertFormula(assumptions);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
@Test
public void checkLIAUfsUnsat() {
// 0 <= f(x)
// 0 <= f(y)
// f(x) + f(y) = x
// f(x) + f(y) = y
// f(x) = x + 1
// f(y) = y - 1
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
Sort intSort = solver.getIntegerSort();
// Sort for UFs later
Sort intToInt = solver.mkFunctionSort(intSort, intSort);
Term xInt = solver.mkConst(intSort, "x");
Term yInt = solver.mkConst(intSort, "y");
// declare UFs
Term f = solver.mkConst(intToInt, "f");
// Apply UFs
Term fx = solver.mkTerm(Kind.APPLY_UF, f, xInt);
Term fy = solver.mkTerm(Kind.APPLY_UF, f, yInt);
Term plus = solver.mkTerm(Kind.PLUS, fx, fy);
// Make some assumptions
Term assumptions1 =
solver.mkTerm(
Kind.AND,
solver.mkTerm(Kind.LEQ, zero, fx),
solver.mkTerm(Kind.EQUAL, plus, xInt),
solver.mkTerm(Kind.LEQ, zero, fy));
Term assumptions2 =
solver.mkTerm(
Kind.AND,
solver.mkTerm(Kind.EQUAL, fx, solver.mkTerm(Kind.PLUS, xInt, one)),
solver.mkTerm(Kind.EQUAL, fy, solver.mkTerm(Kind.MINUS, yInt, one)),
solver.mkTerm(Kind.EQUAL, plus, yInt));
solver.assertFormula(assumptions1);
solver.assertFormula(assumptions2);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isFalse();
}
@Test
public void checkLIAUfsSat() {
// f(x) = x + 1
// f(y) = y - 1
// x = y -> f(x) + f(y) = x AND f(x) + f(y) = y
Term one = solver.mkInteger(1);
Sort intSort = solver.getIntegerSort();
// Sort for UFs later
Sort intToInt = solver.mkFunctionSort(intSort, intSort);
Term xInt = solver.mkConst(intSort, "x");
Term yInt = solver.mkConst(intSort, "y");
// declare UFs
Term f = solver.mkConst(intToInt, "f");
// Apply UFs
Term fx = solver.mkTerm(Kind.APPLY_UF, f, xInt);
Term fy = solver.mkTerm(Kind.APPLY_UF, f, yInt);
Term plus = solver.mkTerm(Kind.PLUS, fx, fy);
Term plusEqx = solver.mkTerm(Kind.EQUAL, plus, xInt);
Term plusEqy = solver.mkTerm(Kind.EQUAL, plus, yInt);
Term xEqy = solver.mkTerm(Kind.EQUAL, yInt, xInt);
Term xEqyImplplusEqxAndy =
solver.mkTerm(Kind.IMPLIES, xEqy, solver.mkTerm(Kind.AND, plusEqx, plusEqy));
Term assumptions =
solver.mkTerm(
Kind.AND,
solver.mkTerm(Kind.EQUAL, fx, solver.mkTerm(Kind.PLUS, xInt, one)),
solver.mkTerm(Kind.EQUAL, fy, solver.mkTerm(Kind.MINUS, yInt, one)),
xEqyImplplusEqxAndy);
solver.assertFormula(assumptions);
Result satCheck = solver.checkSat();
assertThat(satCheck.isSat()).isTrue();
}
/** Sets up array and quantifier based formulas for tests. */
public void setupArrayQuant() {
Term zero = solver.mkInteger(0);
Term one = solver.mkInteger(1);
x = solver.mkVar(solver.getIntegerSort(), "x");
Sort arraySort = solver.mkArraySort(solver.getIntegerSort(), solver.getIntegerSort());
array = solver.mkVar(arraySort, "a");
aAtxEq0 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.SELECT, array, x), zero);
aAtxEq1 = solver.mkTerm(Kind.EQUAL, solver.mkTerm(Kind.SELECT, array, x), one);
}
/**
* For some reason CVC5 does not provide API to create max (or min) size signed/unsiged
* bitvectors.
*
* @param width of the bitvector term.
* @param signed true if signed. false for unsigned.
* @return Max size bitvector term.
*/
public Term makeMaxCVC5Bitvector(int width, boolean signed) throws CVC5ApiException {
String bitvecString;
if (signed) {
bitvecString = new String(new char[width - 1]).replace("\0", "1");
bitvecString = "0" + bitvecString;
} else {
bitvecString = new String(new char[width]).replace("\0", "1");
}
return solver.mkBitVector(width, bitvecString, 2);
}
}
| Add a native API test for bv distinct | src/org/sosy_lab/java_smt/solvers/cvc5/CVC5NativeAPITest.java | Add a native API test for bv distinct | <ide><path>rc/org/sosy_lab/java_smt/solvers/cvc5/CVC5NativeAPITest.java
<ide> import io.github.cvc5.api.Solver;
<ide> import io.github.cvc5.api.Sort;
<ide> import io.github.cvc5.api.Term;
<add>import java.util.ArrayList;
<ide> import java.util.Arrays;
<add>import java.util.List;
<ide> import org.junit.After;
<ide> import org.junit.AssumptionViolatedException;
<ide> import org.junit.Before;
<ide> assertThat(satCheck.isSat()).isFalse();
<ide> }
<ide>
<add> @Test
<add> public void checkBvDistinct() throws CVC5ApiException {
<add> Sort bvSort = solver.mkBitVectorSort(6);
<add> List<Term> bvs = new ArrayList<>();
<add> for (int i = 0; i < 64; i++) {
<add> bvs.add(solver.mkConst(bvSort, "a" + i + "_"));
<add> }
<add>
<add> Term distinct2 = solver.mkTerm(Kind.DISTINCT, bvs.toArray(new Term[0]));
<add> solver.assertFormula(distinct2);
<add> assertThat(solver.checkSat().isSat()).isTrue();
<add> solver.resetAssertions();
<add>
<add> // TODO: The following runs endlessly; recheck for new versions!
<add> /*
<add> bvs.add(solver.mkConst(bvSort, "b" + "_"));
<add> Term distinct3 = solver.mkTerm(Kind.DISTINCT, bvs.toArray(new Term[0]));
<add> solver.assertFormula(distinct3);
<add> assertThat(solver.checkSat().isSat()).isFalse();
<add> */
<add> }
<add>
<ide> /*
<ide> * CVC5 fails some easy quantifier tests.
<ide> */ |
|
Java | apache-2.0 | aae5e7a84bde749539dac442a81bd617cc1a1ec9 | 0 | antoinesd/weld-core,weld/core,manovotn/core,antoinesd/weld-core,weld/core,manovotn/core,antoinesd/weld-core,manovotn/core | /*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.
*/
package org.jboss.webbeans.bootstrap;
import static org.jboss.webbeans.bean.BeanFactory.createEnterpriseBean;
import static org.jboss.webbeans.bean.BeanFactory.createEventBean;
import static org.jboss.webbeans.bean.BeanFactory.createInstanceBean;
import static org.jboss.webbeans.bean.BeanFactory.createObserver;
import static org.jboss.webbeans.bean.BeanFactory.createProducerFieldBean;
import static org.jboss.webbeans.bean.BeanFactory.createProducerMethodBean;
import static org.jboss.webbeans.bean.BeanFactory.createSimpleBean;
import static org.jboss.webbeans.ejb.EJB.ENTERPRISE_BEAN_CLASS;
import static org.jboss.webbeans.jsf.JSF.UICOMPONENT_CLASS;
import static org.jboss.webbeans.servlet.Servlet.FILTER_CLASS;
import static org.jboss.webbeans.servlet.Servlet.HTTP_SESSION_LISTENER_CLASS;
import static org.jboss.webbeans.servlet.Servlet.SERVLET_CLASS;
import static org.jboss.webbeans.servlet.Servlet.SERVLET_CONTEXT_LISTENER_CLASS;
import static org.jboss.webbeans.servlet.Servlet.SERVLET_REQUEST_LISTENER_CLASS;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.webbeans.DefinitionException;
import javax.webbeans.Initializer;
import javax.webbeans.Observable;
import javax.webbeans.Observer;
import javax.webbeans.Observes;
import javax.webbeans.Obtainable;
import org.jboss.webbeans.CurrentManager;
import org.jboss.webbeans.ManagerImpl;
import org.jboss.webbeans.bean.AbstractBean;
import org.jboss.webbeans.bean.AbstractClassBean;
import org.jboss.webbeans.bean.BeanFactory;
import org.jboss.webbeans.bean.EventBean;
import org.jboss.webbeans.bean.InstanceBean;
import org.jboss.webbeans.bean.ProducerFieldBean;
import org.jboss.webbeans.bean.ProducerMethodBean;
import org.jboss.webbeans.bindings.InitializedBinding;
import org.jboss.webbeans.bootstrap.spi.WebBeanDiscovery;
import org.jboss.webbeans.contexts.DependentContext;
import org.jboss.webbeans.ejb.DefaultEnterpriseBeanLookup;
import org.jboss.webbeans.event.ObserverImpl;
import org.jboss.webbeans.introspector.AnnotatedField;
import org.jboss.webbeans.introspector.AnnotatedItem;
import org.jboss.webbeans.introspector.AnnotatedMethod;
import org.jboss.webbeans.introspector.AnnotatedParameter;
import org.jboss.webbeans.log.LogProvider;
import org.jboss.webbeans.log.Logging;
import org.jboss.webbeans.transaction.Transaction;
import org.jboss.webbeans.util.JNDI;
import org.jboss.webbeans.util.Reflections;
/**
* Bootstrapping functionality that is run at application startup and detects
* and register beans
*
* @author Pete Muir
*/
public class WebBeansBootstrap
{
// The property name of the discovery class
public static String WEB_BEAN_DISCOVERY_PROPERTY_NAME = "org.jboss.webbeans.bootstrap.webBeanDiscovery";
// The log provider
private static LogProvider log = Logging.getLogProvider(WebBeansBootstrap.class);
// The Web Beans manager
protected ManagerImpl manager;
/**
* Constructor
*
* Starts up with the singleton Manager
*/
public WebBeansBootstrap(ManagerImpl manager)
{
this.manager = manager;
registerManager();
manager.addContext(DependentContext.INSTANCE);
}
protected void registerManager()
{
JNDI.bind(ManagerImpl.JNDI_KEY, manager);
CurrentManager.setRootManager(manager);
}
public WebBeansBootstrap()
{
this(new ManagerImpl());
}
/**
* Register any beans defined by the provided classes with the manager
*
* @param classes The classes to register
*/
protected void registerBeans(Class<?>... classes)
{
registerBeans(new HashSet<Class<?>>(Arrays.asList(classes)));
}
/**
* Register the bean with the manager, including any standard (built in) beans
*
* @param classes The classes to register as Web Beans
*/
protected void registerBeans(Iterable<Class<?>> classes)
{
Set<AbstractBean<?, ?>> beans = createBeans(classes);
beans.addAll(createStandardBeans());
manager.setBeans(beans);
}
/**
* Creates the standard beans used internally by the RI
*
* @return A set containing the created beans
*/
protected Set<AbstractBean<?, ?>> createStandardBeans()
{
Set<AbstractBean<?, ?>> beans = new HashSet<AbstractBean<?, ?>>();
createBean(BeanFactory.createSimpleBean(Transaction.class, manager), beans);
createBean(BeanFactory.createSimpleBean(ManagerImpl.class, manager), beans);
createBean(BeanFactory.createSimpleBean(DefaultEnterpriseBeanLookup.class, manager), beans);
return beans;
}
/**
* Creates Web Beans from a set of classes
*
* Iterates over the classes and creates a Web Bean of the corresponding
* type. Also register the beans injection points with the resolver. If the
* bean has producer methods, producer beans are created for these and those
* injection points are also registered.
*
* @param classes The classes to adapt
* @return A set of adapted Web Beans
*/
protected Set<AbstractBean<?, ?>> createBeans(Iterable<Class<?>> classes)
{
Set<AbstractBean<?, ?>> beans = new HashSet<AbstractBean<?, ?>>();
for (Class<?> clazz : classes)
{
if (manager.getEjbDescriptorCache().containsKey(clazz))
{
createBean(createEnterpriseBean(clazz, manager), beans);
}
else if (isTypeSimpleWebBean(clazz))
{
createBean(createSimpleBean(clazz, manager), beans);
}
}
return beans;
}
/**
* Creates a Web Bean from a bean abstraction and adds it to the set of created beans
*
* Also creates the implicit field- and method-level beans, if present
*
* @param bean The bean representation
* @param beans The set of created beans
*/
@SuppressWarnings("unchecked")
protected void createBean(AbstractClassBean<?> bean, Set<AbstractBean<?, ?>> beans)
{
beans.add(bean);
manager.getResolver().addInjectionPoints(bean.getInjectionPoints());
for (AnnotatedMethod<Object> producerMethod : bean.getProducerMethods())
{
ProducerMethodBean<?> producerMethodBean = createProducerMethodBean(producerMethod, bean, manager);
beans.add(producerMethodBean);
manager.getResolver().addInjectionPoints(producerMethodBean.getInjectionPoints());
registerEvents(producerMethodBean.getInjectionPoints(), beans);
log.info("Web Bean: " + producerMethodBean);
}
for (AnnotatedField<Object> producerField : bean.getProducerFields())
{
ProducerFieldBean<?> producerFieldBean = createProducerFieldBean(producerField, bean, manager);
beans.add(producerFieldBean);
log.info("Web Bean: " + producerFieldBean);
}
for (AnnotatedMethod<Object> initializerMethod : bean.getInitializerMethods())
{
for (AnnotatedParameter<Object> parameter : initializerMethod.getAnnotatedParameters(Observable.class))
{
registerEvent(parameter, beans);
}
}
for (AnnotatedItem injectionPoint : bean.getInjectionPoints())
{
if ( injectionPoint.isAnnotationPresent(Observable.class) )
{
registerEvent(injectionPoint, beans);
}
if ( injectionPoint.isAnnotationPresent(Obtainable.class) )
{
InstanceBean<Object, Field> instanceBean = createInstanceBean(injectionPoint, manager);
beans.add(instanceBean);
log.info("Web Bean: " + instanceBean);
}
}
for (AnnotatedMethod<Object> observerMethod : bean.getObserverMethods())
{
ObserverImpl<?> observer = createObserver(observerMethod, bean, manager);
if (observerMethod.getAnnotatedParameters(Observes.class).size() == 1)
{
registerObserver(observer, observerMethod.getAnnotatedParameters(Observes.class).get(0).getType(), observerMethod.getAnnotatedParameters(Observes.class).get(0).getBindingTypesAsArray());
}
else
{
throw new DefinitionException("Observer method can only have one parameter annotated @Observes " + observer);
}
}
log.info("Web Bean: " + bean);
}
/**
* Starts the boot process.
*
* Discovers the beans and registers them with the manager. Also resolves the
* injection points.
*
* @param webBeanDiscovery The discovery implementation
*/
public synchronized void boot(WebBeanDiscovery webBeanDiscovery)
{
log.info("Starting Web Beans RI " + getVersion());
if (webBeanDiscovery == null)
{
throw new IllegalStateException("No WebBeanDiscovery provider found, you need to implement the org.jboss.webbeans.bootstrap.spi.WebBeanDiscovery interface, and tell the RI to use it by specifying -D" + WebBeansBootstrap.WEB_BEAN_DISCOVERY_PROPERTY_NAME + "=<classname>");
}
// Must populate EJB cache first, as we need it to detect whether a bean is an EJB!
manager.getEjbDescriptorCache().addAll(webBeanDiscovery.discoverEjbs());
registerBeans(webBeanDiscovery.discoverWebBeanClasses());
log.info("Validing Web Bean injection points");
manager.getResolver().resolveInjectionPoints();
manager.fireEvent(manager, new InitializedBinding());
log.info("Web Beans RI initialized");
}
/**
* Gets version information
*
* @return The implementation version from the Bootstrap class package.
*/
public static String getVersion()
{
Package pkg = WebBeansBootstrap.class.getPackage();
return pkg != null ? pkg.getImplementationVersion() : null;
}
/**
* Gets the available discovery implementations
*
* Parses the web-beans-ri.properties file and for each row describing a
* discover class, instantiate that class and add it to the set
*
* @return A set of discovery implementations
* @see org.jboss.webbeans.bootstrap.DeploymentProperties
*/
@SuppressWarnings("unchecked")
public static Set<Class<? extends WebBeanDiscovery>> getWebBeanDiscoveryClasses()
{
Set<Class<? extends WebBeanDiscovery>> webBeanDiscoveryClasses = new HashSet<Class<? extends WebBeanDiscovery>>();
for (String className : new DeploymentProperties(Thread.currentThread().getContextClassLoader()).getPropertyValues(WEB_BEAN_DISCOVERY_PROPERTY_NAME))
{
try
{
webBeanDiscoveryClasses.add((Class<WebBeanDiscovery>) Class.forName(className));
}
catch (ClassNotFoundException e)
{
log.debug("Unable to load WebBeanDiscovery provider " + className, e);
}
catch (NoClassDefFoundError e)
{
log.warn("Unable to load WebBeanDiscovery provider " + className + " due classDependencyProblem", e);
}
}
return webBeanDiscoveryClasses;
}
/**
* Registers an observer with the manager
*
* @param observer The observer
* @param eventType The event type to observe
* @param bindings The binding types to observe on
*/
@SuppressWarnings("unchecked")
private <T> void registerObserver(Observer<T> observer, Class<?> eventType, Annotation[] bindings)
{
manager.addObserver(observer, (Class<T>) eventType, bindings);
}
/**
* Iterates through the injection points and creates and registers any Event
* observables specified with the @Observable annotation
*
* @param injectionPoints A set of injection points to inspect
* @param beans A set of beans to add the Event beans to
*/
@SuppressWarnings("unchecked")
private void registerEvents(Set<AnnotatedItem<?,?>> injectionPoints, Set<AbstractBean<?, ?>> beans)
{
for (AnnotatedItem injectionPoint : injectionPoints)
{
registerEvent(injectionPoint, beans);
}
}
@SuppressWarnings("unchecked")
private void registerEvent(AnnotatedItem injectionPoint, Set<AbstractBean<?, ?>> beans)
{
if ( injectionPoint.isAnnotationPresent(Observable.class) )
{
EventBean<Object, Method> eventBean = createEventBean(injectionPoint, manager);
beans.add(eventBean);
log.info("Web Bean: " + eventBean);
}
}
/**
* Indicates if the type is a simple Web Bean
*
* @param type The type to inspect
* @return True if simple Web Bean, false otherwise
*/
protected static boolean isTypeSimpleWebBean(Class<?> type)
{
//TODO: check 3.2.1 for more rules!!!!!!
return !type.isAnnotation() &&
!Reflections.isAbstract(type) &&
!SERVLET_CLASS.isAssignableFrom(type) &&
!FILTER_CLASS.isAssignableFrom(type) &&
!SERVLET_CONTEXT_LISTENER_CLASS.isAssignableFrom(type) &&
!HTTP_SESSION_LISTENER_CLASS.isAssignableFrom(type) &&
!SERVLET_REQUEST_LISTENER_CLASS.isAssignableFrom(type) &&
!ENTERPRISE_BEAN_CLASS.isAssignableFrom(type) &&
!UICOMPONENT_CLASS.isAssignableFrom(type) &&
hasSimpleWebBeanConstructor(type);
}
private static boolean hasSimpleWebBeanConstructor(Class<?> type) {
try {
type.getDeclaredConstructor();
return true;
}
catch (NoSuchMethodException nsme)
{
for (Constructor<?> c: type.getDeclaredConstructors())
{
if (c.isAnnotationPresent(Initializer.class)) return true;
}
return false;
}
}
}
| webbeans-ri/src/main/java/org/jboss/webbeans/bootstrap/WebBeansBootstrap.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.
*/
package org.jboss.webbeans.bootstrap;
import static org.jboss.webbeans.bean.BeanFactory.createEnterpriseBean;
import static org.jboss.webbeans.bean.BeanFactory.createEventBean;
import static org.jboss.webbeans.bean.BeanFactory.createInstanceBean;
import static org.jboss.webbeans.bean.BeanFactory.createObserver;
import static org.jboss.webbeans.bean.BeanFactory.createProducerFieldBean;
import static org.jboss.webbeans.bean.BeanFactory.createProducerMethodBean;
import static org.jboss.webbeans.bean.BeanFactory.createSimpleBean;
import static org.jboss.webbeans.ejb.EJB.ENTERPRISE_BEAN_CLASS;
import static org.jboss.webbeans.jsf.JSF.UICOMPONENT_CLASS;
import static org.jboss.webbeans.servlet.Servlet.FILTER_CLASS;
import static org.jboss.webbeans.servlet.Servlet.HTTP_SESSION_LISTENER_CLASS;
import static org.jboss.webbeans.servlet.Servlet.SERVLET_CLASS;
import static org.jboss.webbeans.servlet.Servlet.SERVLET_CONTEXT_LISTENER_CLASS;
import static org.jboss.webbeans.servlet.Servlet.SERVLET_REQUEST_LISTENER_CLASS;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.webbeans.DefinitionException;
import javax.webbeans.Observable;
import javax.webbeans.Observer;
import javax.webbeans.Observes;
import javax.webbeans.Obtainable;
import org.jboss.webbeans.CurrentManager;
import org.jboss.webbeans.ManagerImpl;
import org.jboss.webbeans.bean.AbstractBean;
import org.jboss.webbeans.bean.AbstractClassBean;
import org.jboss.webbeans.bean.BeanFactory;
import org.jboss.webbeans.bean.EventBean;
import org.jboss.webbeans.bean.InstanceBean;
import org.jboss.webbeans.bean.ProducerFieldBean;
import org.jboss.webbeans.bean.ProducerMethodBean;
import org.jboss.webbeans.bindings.InitializedBinding;
import org.jboss.webbeans.bootstrap.spi.WebBeanDiscovery;
import org.jboss.webbeans.contexts.DependentContext;
import org.jboss.webbeans.ejb.DefaultEnterpriseBeanLookup;
import org.jboss.webbeans.event.ObserverImpl;
import org.jboss.webbeans.introspector.AnnotatedField;
import org.jboss.webbeans.introspector.AnnotatedItem;
import org.jboss.webbeans.introspector.AnnotatedMethod;
import org.jboss.webbeans.introspector.AnnotatedParameter;
import org.jboss.webbeans.log.LogProvider;
import org.jboss.webbeans.log.Logging;
import org.jboss.webbeans.transaction.Transaction;
import org.jboss.webbeans.util.JNDI;
import org.jboss.webbeans.util.Reflections;
/**
* Bootstrapping functionality that is run at application startup and detects
* and register beans
*
* @author Pete Muir
*/
public class WebBeansBootstrap
{
// The property name of the discovery class
public static String WEB_BEAN_DISCOVERY_PROPERTY_NAME = "org.jboss.webbeans.bootstrap.webBeanDiscovery";
// The log provider
private static LogProvider log = Logging.getLogProvider(WebBeansBootstrap.class);
// The Web Beans manager
protected ManagerImpl manager;
/**
* Constructor
*
* Starts up with the singleton Manager
*/
public WebBeansBootstrap(ManagerImpl manager)
{
this.manager = manager;
registerManager();
manager.addContext(DependentContext.INSTANCE);
}
protected void registerManager()
{
JNDI.bind(ManagerImpl.JNDI_KEY, manager);
CurrentManager.setRootManager(manager);
}
public WebBeansBootstrap()
{
this(new ManagerImpl());
}
/**
* Register any beans defined by the provided classes with the manager
*
* @param classes The classes to register
*/
protected void registerBeans(Class<?>... classes)
{
registerBeans(new HashSet<Class<?>>(Arrays.asList(classes)));
}
/**
* Register the bean with the manager, including any standard (built in) beans
*
* @param classes The classes to register as Web Beans
*/
protected void registerBeans(Iterable<Class<?>> classes)
{
Set<AbstractBean<?, ?>> beans = createBeans(classes);
beans.addAll(createStandardBeans());
manager.setBeans(beans);
}
/**
* Creates the standard beans used internally by the RI
*
* @return A set containing the created beans
*/
protected Set<AbstractBean<?, ?>> createStandardBeans()
{
Set<AbstractBean<?, ?>> beans = new HashSet<AbstractBean<?, ?>>();
createBean(BeanFactory.createSimpleBean(Transaction.class, manager), beans);
createBean(BeanFactory.createSimpleBean(ManagerImpl.class, manager), beans);
createBean(BeanFactory.createSimpleBean(DefaultEnterpriseBeanLookup.class, manager), beans);
return beans;
}
/**
* Creates Web Beans from a set of classes
*
* Iterates over the classes and creates a Web Bean of the corresponding
* type. Also register the beans injection points with the resolver. If the
* bean has producer methods, producer beans are created for these and those
* injection points are also registered.
*
* @param classes The classes to adapt
* @return A set of adapted Web Beans
*/
protected Set<AbstractBean<?, ?>> createBeans(Iterable<Class<?>> classes)
{
Set<AbstractBean<?, ?>> beans = new HashSet<AbstractBean<?, ?>>();
for (Class<?> clazz : classes)
{
if (manager.getEjbDescriptorCache().containsKey(clazz))
{
createBean(createEnterpriseBean(clazz, manager), beans);
}
else if (isTypeSimpleWebBean(clazz))
{
createBean(createSimpleBean(clazz, manager), beans);
}
}
return beans;
}
/**
* Creates a Web Bean from a bean abstraction and adds it to the set of created beans
*
* Also creates the implicit field- and method-level beans, if present
*
* @param bean The bean representation
* @param beans The set of created beans
*/
@SuppressWarnings("unchecked")
protected void createBean(AbstractClassBean<?> bean, Set<AbstractBean<?, ?>> beans)
{
beans.add(bean);
manager.getResolver().addInjectionPoints(bean.getInjectionPoints());
for (AnnotatedMethod<Object> producerMethod : bean.getProducerMethods())
{
ProducerMethodBean<?> producerMethodBean = createProducerMethodBean(producerMethod, bean, manager);
beans.add(producerMethodBean);
manager.getResolver().addInjectionPoints(producerMethodBean.getInjectionPoints());
registerEvents(producerMethodBean.getInjectionPoints(), beans);
log.info("Web Bean: " + producerMethodBean);
}
for (AnnotatedField<Object> producerField : bean.getProducerFields())
{
ProducerFieldBean<?> producerFieldBean = createProducerFieldBean(producerField, bean, manager);
beans.add(producerFieldBean);
log.info("Web Bean: " + producerFieldBean);
}
for (AnnotatedMethod<Object> initializerMethod : bean.getInitializerMethods())
{
for (AnnotatedParameter<Object> parameter : initializerMethod.getAnnotatedParameters(Observable.class))
{
registerEvent(parameter, beans);
}
}
for (AnnotatedItem injectionPoint : bean.getInjectionPoints())
{
if ( injectionPoint.isAnnotationPresent(Observable.class) )
{
registerEvent(injectionPoint, beans);
}
if ( injectionPoint.isAnnotationPresent(Obtainable.class) )
{
InstanceBean<Object, Field> instanceBean = createInstanceBean(injectionPoint, manager);
beans.add(instanceBean);
log.info("Web Bean: " + instanceBean);
}
}
for (AnnotatedMethod<Object> observerMethod : bean.getObserverMethods())
{
ObserverImpl<?> observer = createObserver(observerMethod, bean, manager);
if (observerMethod.getAnnotatedParameters(Observes.class).size() == 1)
{
registerObserver(observer, observerMethod.getAnnotatedParameters(Observes.class).get(0).getType(), observerMethod.getAnnotatedParameters(Observes.class).get(0).getBindingTypesAsArray());
}
else
{
throw new DefinitionException("Observer method can only have one parameter annotated @Observes " + observer);
}
}
log.info("Web Bean: " + bean);
}
/**
* Starts the boot process.
*
* Discovers the beans and registers them with the manager. Also resolves the
* injection points.
*
* @param webBeanDiscovery The discovery implementation
*/
public synchronized void boot(WebBeanDiscovery webBeanDiscovery)
{
log.info("Starting Web Beans RI " + getVersion());
if (webBeanDiscovery == null)
{
throw new IllegalStateException("No WebBeanDiscovery provider found, you need to implement the org.jboss.webbeans.bootstrap.spi.WebBeanDiscovery interface, and tell the RI to use it by specifying -D" + WebBeansBootstrap.WEB_BEAN_DISCOVERY_PROPERTY_NAME + "=<classname>");
}
// Must populate EJB cache first, as we need it to detect whether a bean is an EJB!
manager.getEjbDescriptorCache().addAll(webBeanDiscovery.discoverEjbs());
registerBeans(webBeanDiscovery.discoverWebBeanClasses());
log.info("Validing Web Bean injection points");
manager.getResolver().resolveInjectionPoints();
manager.fireEvent(manager, new InitializedBinding());
log.info("Web Beans RI initialized");
}
/**
* Gets version information
*
* @return The implementation version from the Bootstrap class package.
*/
public static String getVersion()
{
Package pkg = WebBeansBootstrap.class.getPackage();
return pkg != null ? pkg.getImplementationVersion() : null;
}
/**
* Gets the available discovery implementations
*
* Parses the web-beans-ri.properties file and for each row describing a
* discover class, instantiate that class and add it to the set
*
* @return A set of discovery implementations
* @see org.jboss.webbeans.bootstrap.DeploymentProperties
*/
@SuppressWarnings("unchecked")
public static Set<Class<? extends WebBeanDiscovery>> getWebBeanDiscoveryClasses()
{
Set<Class<? extends WebBeanDiscovery>> webBeanDiscoveryClasses = new HashSet<Class<? extends WebBeanDiscovery>>();
for (String className : new DeploymentProperties(Thread.currentThread().getContextClassLoader()).getPropertyValues(WEB_BEAN_DISCOVERY_PROPERTY_NAME))
{
try
{
webBeanDiscoveryClasses.add((Class<WebBeanDiscovery>) Class.forName(className));
}
catch (ClassNotFoundException e)
{
log.debug("Unable to load WebBeanDiscovery provider " + className, e);
}
catch (NoClassDefFoundError e)
{
log.warn("Unable to load WebBeanDiscovery provider " + className + " due classDependencyProblem", e);
}
}
return webBeanDiscoveryClasses;
}
/**
* Registers an observer with the manager
*
* @param observer The observer
* @param eventType The event type to observe
* @param bindings The binding types to observe on
*/
@SuppressWarnings("unchecked")
private <T> void registerObserver(Observer<T> observer, Class<?> eventType, Annotation[] bindings)
{
manager.addObserver(observer, (Class<T>) eventType, bindings);
}
/**
* Iterates through the injection points and creates and registers any Event
* observables specified with the @Observable annotation
*
* @param injectionPoints A set of injection points to inspect
* @param beans A set of beans to add the Event beans to
*/
@SuppressWarnings("unchecked")
private void registerEvents(Set<AnnotatedItem<?,?>> injectionPoints, Set<AbstractBean<?, ?>> beans)
{
for (AnnotatedItem injectionPoint : injectionPoints)
{
registerEvent(injectionPoint, beans);
}
}
@SuppressWarnings("unchecked")
private void registerEvent(AnnotatedItem injectionPoint, Set<AbstractBean<?, ?>> beans)
{
if ( injectionPoint.isAnnotationPresent(Observable.class) )
{
EventBean<Object, Method> eventBean = createEventBean(injectionPoint, manager);
beans.add(eventBean);
log.info("Web Bean: " + eventBean);
}
}
/**
* Indicates if the type is a simple Web Bean
*
* @param type The type to inspect
* @return True if simple Web Bean, false otherwise
*/
protected static boolean isTypeSimpleWebBean(Class<?> type)
{
return !type.isAnnotation() && !Reflections.isAbstract(type) && !SERVLET_CLASS.isAssignableFrom(type) && !FILTER_CLASS.isAssignableFrom(type) && !SERVLET_CONTEXT_LISTENER_CLASS.isAssignableFrom(type) && !HTTP_SESSION_LISTENER_CLASS.isAssignableFrom(type) && !SERVLET_REQUEST_LISTENER_CLASS.isAssignableFrom(type) && !ENTERPRISE_BEAN_CLASS.isAssignableFrom(type) && !UICOMPONENT_CLASS.isAssignableFrom(type);
}
}
| test for correct constructor before creating the SimpleBean!
git-svn-id: 811cd8a17a8c3c0c263af499002feedd54a892d0@640 1c488680-804c-0410-94cd-c6b725194a0e
| webbeans-ri/src/main/java/org/jboss/webbeans/bootstrap/WebBeansBootstrap.java | test for correct constructor before creating the SimpleBean! | <ide><path>ebbeans-ri/src/main/java/org/jboss/webbeans/bootstrap/WebBeansBootstrap.java
<ide> import static org.jboss.webbeans.servlet.Servlet.SERVLET_REQUEST_LISTENER_CLASS;
<ide>
<ide> import java.lang.annotation.Annotation;
<add>import java.lang.reflect.Constructor;
<ide> import java.lang.reflect.Field;
<ide> import java.lang.reflect.Method;
<ide> import java.util.Arrays;
<ide> import java.util.Set;
<ide>
<ide> import javax.webbeans.DefinitionException;
<add>import javax.webbeans.Initializer;
<ide> import javax.webbeans.Observable;
<ide> import javax.webbeans.Observer;
<ide> import javax.webbeans.Observes;
<ide> */
<ide> protected static boolean isTypeSimpleWebBean(Class<?> type)
<ide> {
<del> return !type.isAnnotation() && !Reflections.isAbstract(type) && !SERVLET_CLASS.isAssignableFrom(type) && !FILTER_CLASS.isAssignableFrom(type) && !SERVLET_CONTEXT_LISTENER_CLASS.isAssignableFrom(type) && !HTTP_SESSION_LISTENER_CLASS.isAssignableFrom(type) && !SERVLET_REQUEST_LISTENER_CLASS.isAssignableFrom(type) && !ENTERPRISE_BEAN_CLASS.isAssignableFrom(type) && !UICOMPONENT_CLASS.isAssignableFrom(type);
<add> //TODO: check 3.2.1 for more rules!!!!!!
<add> return !type.isAnnotation() &&
<add> !Reflections.isAbstract(type) &&
<add> !SERVLET_CLASS.isAssignableFrom(type) &&
<add> !FILTER_CLASS.isAssignableFrom(type) &&
<add> !SERVLET_CONTEXT_LISTENER_CLASS.isAssignableFrom(type) &&
<add> !HTTP_SESSION_LISTENER_CLASS.isAssignableFrom(type) &&
<add> !SERVLET_REQUEST_LISTENER_CLASS.isAssignableFrom(type) &&
<add> !ENTERPRISE_BEAN_CLASS.isAssignableFrom(type) &&
<add> !UICOMPONENT_CLASS.isAssignableFrom(type) &&
<add> hasSimpleWebBeanConstructor(type);
<add> }
<add>
<add> private static boolean hasSimpleWebBeanConstructor(Class<?> type) {
<add> try {
<add> type.getDeclaredConstructor();
<add> return true;
<add> }
<add> catch (NoSuchMethodException nsme)
<add> {
<add> for (Constructor<?> c: type.getDeclaredConstructors())
<add> {
<add> if (c.isAnnotationPresent(Initializer.class)) return true;
<add> }
<add> return false;
<add> }
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 263de8eb3329f77c930d3983a581515f948ce351 | 0 | pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus | /**
* Copyright 2007-2012 University Of Southern California
*
* 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.
*/
package edu.isi.pegasus.planner.dax;
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Set;
import java.util.LinkedHashSet;
import java.io.Writer;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.common.logging.LogManagerFactory;
import edu.isi.pegasus.common.util.Version;
import edu.isi.pegasus.common.util.XMLWriter;
import edu.isi.pegasus.planner.dax.Invoke.WHEN;
import edu.isi.pegasus.planner.namespace.Metadata;
/**
* <pre>
* <b>This class provides the Java API to create DAX files.</b>
*
* The DAX XML SCHEMA is available at <a href="http://pegasus.isi.edu/schema/dax-3.6.xsd">http://pegasus.isi.edu/schema/dax-3.6.xsd</a>
* and documentation available at <a href="http://pegasus.isi.edu/wms/docs/schemas/dax-3.6/dax-3.6.html">http://pegasus.isi.edu/wms/docs/schemas/dax-3.6/dax-3.6.html</a>
*
* The DAX consists of 6 parts the first 4 are optional and the last is optional.
* </pre> <ol> <li><b>file:</b>Used as "In DAX" Replica Catalog
* (Optional)</li><br> <li><b>executable:</b> Used as "In DAX" Transformation
* Catalog (Optional)</li><br> <li><b>transformation:</b> Used to describe
* compound executables. i.e. Executable depending on other executables
* (Optional)</li><br> <li><b>job|dax|dag:</b> Used to describe a single job or
* sub dax or sub dax. Atleast 1 required.</li><br> <li><b>child:</b> The
* dependency section to describe dependencies between job|dax|dag elements.
* (Optional)</li><br> </ol> <center><img
* src="http://pegasus.isi.edu/wms/docs/schemas/dax-3.6/dax-3.6_p1.png"/></center>
* <pre>
* To generate an example DIAMOND DAX run the ADAG Class as shown below
* <b>java ADAG filename</b>
* <b>NOTE: This is an illustrative example only. Please see examples directory for a working example</b>
*
* Here is sample java code that illustrates how to use the Java DAX API
* <pre>
* java.io.File cwdFile = new java.io.File (".");
String cwd = cwdFile.getCanonicalPath();
String pegasusHome = "/usr";
String site = "TestCluster";
ADAG dax = new ADAG("diamond");
dax.addNotification(Invoke.WHEN.start,"/pegasus/libexec/notification/email -t [email protected]");
dax.addNotification(Invoke.WHEN.at_end,"/pegasus/libexec/notification/email -t [email protected]");
dax.addMetadata( "name", "diamond");
dax.addMetadata( "createdBy", "Karan Vahi");
File fa = new File("f.a");
fa.addPhysicalFile("file://" + cwd + "/f.a", "local");
fa.addMetaData( "size", "1024" );
dax.addFile(fa);
File fb1 = new File("f.b1");
File fb2 = new File("f.b2");
File fc1 = new File("f.c1");
File fc2 = new File("f.c2");
File fd = new File("f.d");
fd.setRegister(true);
Executable preprocess = new Executable("pegasus", "preprocess", "4.0");
preprocess.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
preprocess.setInstalled(true);
preprocess.addMetaData( "size", "2048" );
preprocess.addPhysicalFile("file://" + pegasus_location + "/bin/keg", site_handle);
Executable findrange = new Executable("pegasus", "findrange", "4.0");
findrange.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
findrange.setInstalled(true);
findrange.addPhysicalFile("file://" + pegasus_location + "/bin/keg", site_handle);
Executable analyze = new Executable("pegasus", "analyze", "4.0");
analyze.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
analyze.setInstalled(true);
analyze.addPhysicalFile("file://" + pegasus_location + "/bin/keg", site_handle);
dax.addExecutable(preprocess).addExecutable(findrange).addExecutable(analyze);
// Add a preprocess job
Job j1 = new Job("j1", "pegasus", "preprocess", "4.0");
j1.addArgument("-a preprocess -T 60 -i ").addArgument(fa);
j1.addArgument("-o ").addArgument(fb1);
j1.addArgument(" ").addArgument(fb2);
j1.addMetadata( "time", "60" );
j1.uses(fa, File.LINK.INPUT);
j1.uses(fb1, File.LINK.OUTPUT);
j1.uses(fb2, File.LINK.OUTPUT);
j1.addNotification(Invoke.WHEN.start,"/pegasus/libexec/notification/email -t [email protected]");
j1.addNotification(Invoke.WHEN.at_end,"/pegasus/libexec/notification/email -t [email protected]");
dax.addJob(j1);
// Add left Findrange job
Job j2 = new Job("j2", "pegasus", "findrange", "4.0");
j2.addArgument("-a findrange -T 60 -i ").addArgument(fb1);
j2.addArgument("-o ").addArgument(fc1);
j2.addMetadata( "time", "60" );
j2.uses(fb1, File.LINK.INPUT);
j2.uses(fc1, File.LINK.OUTPUT);
j2.addNotification(Invoke.WHEN.start,"/pegasus/libexec/notification/email -t [email protected]");
j2.addNotification(Invoke.WHEN.at_end,"/pegasus/libexec/notification/email -t [email protected]");
dax.addJob(j2);
// Add right Findrange job
Job j3 = new Job("j3", "pegasus", "findrange", "4.0");
j3.addArgument("-a findrange -T 60 -i ").addArgument(fb2);
j3.addArgument("-o ").addArgument(fc2);
j3.addMetadata( "time", "60" );
j3.uses(fb2, File.LINK.INPUT);
j3.uses(fc2, File.LINK.OUTPUT);
j3.addNotification(Invoke.WHEN.start,"/pegasus/libexec/notification/email -t [email protected]");
j3.addNotification(Invoke.WHEN.at_end,"/pegasus/libexec/notification/email -t [email protected]");
dax.addJob(j3);
// Add analyze job
Job j4 = new Job("j4", "pegasus", "analyze", "4.0");
j4.addArgument("-a analyze -T 60 -i ").addArgument(fc1);
j4.addArgument(" ").addArgument(fc2);
j4.addArgument("-o ").addArgument(fd);
j4.addMetadata( "time", "60" );
j4.uses(fc1, File.LINK.INPUT);
j4.uses(fc2, File.LINK.INPUT);
j4.uses(fd, File.LINK.OUTPUT);
j4.addNotification(Invoke.WHEN.start,"/pegasus/libexec/notification/email -t [email protected]");
j4.addNotification(Invoke.WHEN.at_end,"/pegasus/libexec/notification/email -t [email protected]");
dax.addJob(j4);
dax.addDependency("j1", "j2");
dax.addDependency("j1", "j3");
dax.addDependency("j2", "j4");
dax.addDependency("j3", "j4");
dax.writeToSTDOUT();
* </pre>
*
* @author Gaurang Mehta gmehta at isi dot edu
* @author Karan Vahi
* @version $Revision$
*/
public class ADAG {
/**
* The "official" namespace URI of the site catalog schema.
*/
public static final String SCHEMA_NAMESPACE =
"http://pegasus.isi.edu/schema/DAX";
/**
* XSI SCHEMA NAMESPACE
*/
public static final String SCHEMA_NAMESPACE_XSI =
"http://www.w3.org/2001/XMLSchema-instance";
/**
* The "not-so-official" location URL of the DAX schema definition.
*/
public static final String SCHEMA_LOCATION =
"http://pegasus.isi.edu/schema/dax-3.6.xsd";
/**
* The version to report.
*/
public static final String SCHEMA_VERSION = "3.6";
/**
* The type of DAX API generated
*/
private static final String DAX_API_TYPE = "java";
/**
* The Name / Label of the DAX
*/
private String mName;
/**
* The Index of the dax object. I out of N
*/
private int mIndex;
/**
* The Count of the number of dax objects : N
*/
private int mCount;
/**
* The List of Job,DAX and DAG objects
*
* @see DAG
* @see DAX
* @see Job
* @see AbstractJob
*/
private Map<String, AbstractJob> mJobs;
private List<Job> mLJobs;
private List<DAG> mLDAGs;
private List<DAX> mLDAXs;
/**
* The List of Transformation objects
*
* @see Transformation
*/
private Set<Transformation> mTransformations;
/**
* The list of Executable objects
*
* @see Executable
*/
private Set<Executable> mExecutables;
/**
* The list of edu.isi.pegasus.planner.dax.File objects
*
* @see File
*/
private List<File> mFiles;
/**
* Map of Dependencies between Job,DAX,DAG objects. Map key is a string that
* holds the child element reference, the value is a List of Parent objects
*
* @see Parent
*/
private Map<String, Set<Edge>> mDependencies;
/**
* List of Notification objects
*/
private List<Invoke> mInvokes;
/**
* The metadata attributes associated with the whole workflow.
*/
private Set<MetaData> mMetaDataAttributes;
/**
* Handle the XML writer
*/
private XMLWriter mWriter;
private LogManager mLogger;
/**
* The Simple constructor for the DAX object
*
* @param name DAX LABEL
*/
public ADAG(String name) {
this(name, 0, 1);
}
/**
* DAX Constructor
*
* @param name DAX Label
* @param index Index of DAX out of N DAX's
* @param count Number of DAXS in a group
*/
public ADAG(String name, int index, int count) {
//initialize everything
mName = name;
mIndex = index;
mCount = count;
mJobs = new LinkedHashMap<String, AbstractJob>();
mLJobs = new LinkedList<Job>();
mLDAGs = new LinkedList<DAG>();
mLDAXs = new LinkedList<DAX>();
mTransformations = new LinkedHashSet<Transformation>();
mExecutables = new LinkedHashSet<Executable>();
mMetaDataAttributes = new LinkedHashSet<MetaData>();
mMetaDataAttributes.add( new MetaData(Metadata.DAX_API_KEY, DAX_API_TYPE));
mFiles = new LinkedList<File>();
mInvokes = new LinkedList<Invoke>();
mDependencies = new LinkedHashMap<String, Set<Edge>>();
mLogger = LogManagerFactory.loadSingletonInstance();
mLogger.logEventStart("event.dax.generate", "pegasus.version", Version.
instance().toString());
}
/**
* Return the name/label of the dax
*
* @return
*/
public String getName() {
return mName;
}
/* Return the index of the dax
* @return int
*/
public int getIndex() {
return mIndex;
}
/**
* Returns the total count of the dax collection. (legacy)
*
* @return int
*/
public int getCount() {
return mCount;
}
/**
* Add a Notification for this Workflow
*
* @param when
* @param what
* @return ADAG
*/
public ADAG addInvoke(Invoke.WHEN when, String what) {
Invoke i = new Invoke(when, what);
mInvokes.add(i);
return this;
}
/**
* Add a Notification for this Workflow
*
* @param when
* @param what
* @return ADAG
*/
public ADAG addNotification(Invoke.WHEN when, String what) {
return addInvoke(when, what);
}
/**
* Add a Notification for this Workflow
*
* @param invoke
* @return ADAG
*/
public ADAG addInvoke(Invoke invoke) {
mInvokes.add(invoke.clone());
return this;
}
/**
* Add a Notification for this Workflow
*
* @param invoke
* @return ADAG
*/
public ADAG addNotification(Invoke invoke) {
return addInvoke(invoke);
}
/**
* Add a List of Notifications for this Workflow
*
* @param invokes
* @return ADAG
*/
public ADAG addInvokes(List<Invoke> invokes) {
for (Invoke invoke : invokes) {
this.addInvoke(invoke);
}
return this;
}
/**
* Add a List of Notifications for this Workflow
*
* @param invokes
* @return ADAG
*/
public ADAG addNotifications(List<Invoke> invokes) {
return addInvokes(invokes);
}
/**
* Returns a list of Invoke objects associated with the workflow
*
* @return
*/
public List<Invoke> getInvoke() {
return mInvokes;
}
/**
* Returns a list of Invoke objects associated with the workflow. Same as
* getInvoke()
*
* @return
*/
public List<Invoke> getNotification() {
return getInvoke();
}
/**
* Adds metadata to the workflow
*
* @param key key name for metadata
* @param value value
* @return
*/
public ADAG addMetaData( String key, String value ){
this.mMetaDataAttributes.add( new MetaData( key, value ) );
return this;
}
/**
* Returns the metadata associated for a key if exists, else null
*
* @param key
*
* @return
*/
public String getMetaData( String key ){
return this.mMetaDataAttributes.contains( key )?
((MetaData)mMetaDataAttributes).getValue():
null;
}
/**
* Add a RC File object to the top of the DAX.
*
* @param file File object to be added to the RC section
* @return ADAG
* @see File
*/
public ADAG addFile(File file) {
mFiles.add(file);
return this;
}
/**
* Add Files to the RC Section on top of the DAX
*
* @param files List<File> List of file objects to be added to the RC
* Section
* @return ADAG
* @see File
*
*/
public ADAG addFiles(List<File> files) {
mFiles.addAll(files);
return this;
}
/**
* Returns a list of File objects defined as the inDax Replica Catalog
*
* @return
*/
public List<File> getFiles() {
return mFiles;
}
/**
* Add Executable to the DAX
*
* @param executable Executable to be added
* @return ADAG
* @see Executable
*/
public ADAG addExecutable(Executable executable) {
if (executable != null) {
if (!mExecutables.contains(executable)) {
mExecutables.add(executable);
} else {
throw new RuntimeException("Error: Executable " + executable.
toString() + " already exists in the DAX.\n");
}
} else {
throw new RuntimeException("Error: The executable passed is null\n");
}
return this;
}
/**
* Add Multiple Executable objects to the DAX
*
* @param executables List of Executable objects to be added
* @return ADAG
* @see Executable
*/
public ADAG addExecutables(List<Executable> executables) {
if (executables != null && !executables.isEmpty()) {
for (Executable executable : executables) {
addExecutable(executable);
}
} else {
throw new RuntimeException(
"Error: The executables list to be added is either null or empty\n");
}
return this;
}
/**
* Returns a set of Executable Objects stored as part of the inDAX
* Transformation Catalog;
*
* @return
*/
public Set<Executable> getExecutables() {
return mExecutables;
}
/**
* Checks if a given executable exists in the DAX based Transformation
* Catalog
*
* @param executable
* @return boolean
*/
public boolean containsExecutable(Executable executable) {
return mExecutables.contains(executable);
}
/**
* Add Transformation to the DAX
*
* @param transformation Transformation object to be added
* @return ADAG
* @see Transformation
*/
public ADAG addTransformation(Transformation transformation) {
if (transformation != null) {
if (!mTransformations.contains(transformation)) {
mTransformations.add(transformation);
} else {
throw new RuntimeException("Error: Transformation " + transformation.
toString() + " already exists in the DAX.\n");
}
} else {
throw new RuntimeException("Transformation provided is null\n");
}
return this;
}
/**
* Add Multiple Transformation to the DAX
*
* @param transformations List of Transformation objects
* @return ADAG
* @see Transformation
*/
public ADAG addTransformations(List<Transformation> transformations) {
if (transformations != null && !transformations.isEmpty()) {
for (Transformation transformation : transformations) {
addTransformation(transformation);
}
} else {
throw new RuntimeException(
"List of transformations provided is null");
}
return this;
}
/**
* Checks if a given Transformation exists in the DAX based Transformation
* Catalog
*
* @param transformation Transformation
* @return boolean
*/
public boolean containsTransformation(Transformation transformation) {
return mTransformations.contains(transformation);
}
/**
* Returns a set of Transformation Objects (complex executables) stored in
* the DAX based Transformation Catalog
*
* @return
*/
public Set<Transformation> getTransformations() {
return mTransformations;
}
/**
* Add AbstractJob to the DAX
*
* @param ajob AbstractJob
* @return ADAG
* @see Job
* @see DAG
* @see DAX
* @see AbstractJob
*/
private ADAG addAbstractJob(AbstractJob ajob) {
if (!mJobs.containsKey(ajob.mId)) {
mJobs.put(ajob.mId, ajob);
if (ajob.isDAG()) {
mLDAGs.add((DAG) ajob);
} else if (ajob.isDAX()) {
mLDAXs.add((DAX) ajob);
} else if (ajob.isJob()) {
mLJobs.add((Job) ajob);
}
} else {
throw new RuntimeException(
"Job of type" + ajob.getClass().getSimpleName() + " with jobid " + ajob.mId + " already exists in the DAX");
}
return this;
}
/**
* Add AbstractJobs to the DAX
*
* @param ajobs AbstractJob
* @return ADAG
* @see Job
* @see DAG
* @see DAX
* @see AbstractJob
*/
private ADAG addAbstractJobs(List<AbstractJob> ajobs) {
for (AbstractJob ajob : ajobs) {
addAbstractJob(ajob);
}
return this;
}
/**
* Returns an abstract Job with id ajobid if present otherwise null.
*
* @param ajobid
* @return
*/
private AbstractJob getAbstractJob(String ajobid) {
if (ajobid != null) {
AbstractJob j = mJobs.get(ajobid);
if (j != null) {
return j;
} else {
mLogger.log("No Job/DAX/DAG found with id " + ajobid,
LogManager.ERROR_MESSAGE_LEVEL);
}
}
return null;
}
/**
* Check if an abstractjob exists in the DAX
*
* @param ajob
* @return
*/
private boolean containsAbstractJob(AbstractJob ajob) {
return containsAbstractJobId(ajob.mId);
}
/**
* Check if a jobid exists in the DAX
*
* @param ajobid
* @return
*/
private boolean containsAbstractJobId(String ajobid) {
return mJobs.containsKey(ajobid);
}
/**
* Add Job to the DAX
*
* @param job
* @return ADAG
* @see Job
* @see AbstractJob
*/
public ADAG addJob(Job job) {
return addAbstractJob(job);
}
/**
* Add multiple Jobs to the DAX
*
* @param jobs
* @return ADAG
* @see Job
* @see AbstractJob
*/
public ADAG addJobs(List<Job> jobs) {
for (Job job : jobs) {
addJob(job);
}
return this;
}
/**
* Check if a job exists in the DAX
*
* @param job
* @return
*/
public boolean containsJob(Job job) {
return containsAbstractJob(job);
}
/**
* Check if a jobid exists in the DAX
*
* @param jobid
* @return
*/
public boolean containsJobId(String jobid) {
return containsAbstractJobId(jobid);
}
/**
* Returns a Job object with id jobid if present otherwise null.
*
* @param jobid
* @return
*/
public Job getJob(String jobid) {
AbstractJob j = getAbstractJob(jobid);
if (j != null) {
if (j.isJob()) {
return (Job) j;
} else {
mLogger.log("Returned object is not of type Job, but " + j.
getClass().getSimpleName(),
LogManager.ERROR_MESSAGE_LEVEL);
}
}
return null;
}
/**
* Get a list of all the DAG jobs.
*
* @return
*/
public List<Job> getJobs() {
return mLJobs;
}
/**
* Get a list of all the DAX jobs.
*
* @return
*/
public List<DAX> getDAXs() {
return mLDAXs;
}
/**
* Returns a DAX object with id daxid if present otherwise null.
*
* @param daxid
* @return
*/
public DAX getDAX(String daxid) {
AbstractJob j = getAbstractJob(daxid);
if (j != null) {
if (j.isDAX()) {
return (DAX) j;
} else {
mLogger.log("Return object is not of type DAX, but " + j.
getClass().getSimpleName(),
LogManager.ERROR_MESSAGE_LEVEL);
}
}
return null;
}
/**
* Get a list of all the DAG jobs.
*
* @return
*/
public List<DAG> getDAGs() {
return mLDAGs;
}
/**
* Returns a DAG object with id dagid if present otherwise null.
*
* @param dagid
* @return
*/
public DAG getDAG(String dagid) {
AbstractJob j = getAbstractJob(dagid);
if (j != null) {
if (j.isDAG()) {
return (DAG) j;
} else {
mLogger.log("Return object is not of type DAG, but " + j.
getClass().getSimpleName(),
LogManager.ERROR_MESSAGE_LEVEL);
}
}
return null;
}
/**
* Add a DAG job to the DAX
*
* @param dag the DAG to be added
* @return ADAG
* @see DAG
* @see AbstractJob
*/
public ADAG addDAG(DAG dag) {
return addAbstractJob(dag);
}
/**
* Add multiple DAG jobs to the DAX
*
* @param dags List of DAG jobs to be added
* @return ADAG
* @see DAG
* @see AbstractJob
*/
public ADAG addDAGs(List<DAG> dags) {
for (DAG dag : dags) {
addDAG(dag);
}
return this;
}
/**
* Check if a DAG job exists in the DAX
*
* @param dag
* @return
*/
public boolean containsDAG(DAG dag) {
return containsAbstractJob(dag);
}
/**
* Check if a DAG job id exists in the DAX
*
* @param dagid
* @return
*/
public boolean containsDAGId(String dagid) {
return containsAbstractJobId(dagid);
}
/**
* Add a DAX job to the DAX
*
* @param dax DAX to be added
* @return ADAG
* @see DAX
* @see AbstractJob
*/
public ADAG addDAX(DAX dax) {
return addAbstractJob(dax);
}
/**
* Add multiple DAX jobs to the DAX
*
* @param daxs LIST of DAX jobs to be added
* @return ADAG
* @see DAX
* @see AbstractJob
*/
public ADAG addDAXs(List<DAX> daxs) {
for (DAX dax : daxs) {
addDAX(dax);
}
return this;
}
/**
* Check if a DAX job exists in the DAX
*
* @param dax
* @return
*/
public boolean containsDAX(DAX dax) {
return containsAbstractJob(dax);
}
/**
* Check if a DAX job id exists in the DAX
*
* @param daxid
* @return
*/
public boolean containsDAXId(String daxid) {
return containsAbstractJobId(daxid);
}
/**
* Add a parent child dependency between two jobs,dax,dag
*
* @param parent String job,dax,dag id
* @param child String job,dax,dag,id
* @return ADAG
*
*/
public ADAG addDependency(String parent, String child) {
addDependency(parent, child, null);
return this;
}
/**
* Add a parent child dependency between two jobs,dax,dag
*
* @param parent Job|DAX|DAG object
* @param child Job|DAX|DAG object
* @return
*/
public ADAG addDependency(AbstractJob parent, AbstractJob child) {
addDependency(parent.getId(), child.getId(), null);
return this;
}
/**
* Add a parent child dependency with a dependency label
*
* @param parent String job,dax,dag id
* @param child String job,dax,dag id
* @param label String dependency label
* @return ADAG
*/
public ADAG addDependency(String parent, String child, String label) {
if (containsAbstractJobId(parent) && containsAbstractJobId(child)) {
Set<Edge> edges = mDependencies.get(child);
if (edges == null) {
edges = new LinkedHashSet<Edge>();
}
Edge e = new Edge(parent,child, label);
edges.add(e);
mDependencies.put(child, edges);
} else {
throw new RuntimeException(
"Either Job with id " + parent + " or " + child + "is not added to the DAX.\n"
+ "Please add the jobs first to the dax and then add the dependencies between them\n");
}
return this;
}
/**
* Returns a list of Edge objects for a child job/dax/dag id. Returns an
* empty set if the child does not have any parents Returns null if the
* child is not a valid job/dax/dag id
*
* @param child
* @return
*/
public Set<Edge> getEdges(String child) {
if (child != null && mJobs.containsKey(child)) {
return mDependencies.containsKey(child) ? mDependencies.get(child)
: new LinkedHashSet<Edge>();
}
return null;
}
/**
* Returns a Set of all the Edge objects for the DAX. Returns empty if no dependencies.
*
* @param child
* @return
*/
public Set<Edge> getEdges() {
Set<Edge> edges = new LinkedHashSet<Edge>();
for(Set<Edge>s : mDependencies.values()){
edges.addAll(s);
}
return edges;
}
/**
* Add a parent child dependency with a dependency label
*
* @param parent Job|DAX|DAG object
* @param child Job|DAX|DAG object
* @param label String label for annotation
* @return ADAG
*/
public ADAG addDependency(AbstractJob parent, AbstractJob child,
String label) {
addDependency(parent.getId(), child.getId(), label);
return this;
}
/**
* Generate a DAX File out of this object;
*
* @param daxfile The file to write the DAX to
*/
public void writeToFile(String daxfile) {
try {
mWriter = new XMLWriter(new FileWriter(daxfile));
toXML(mWriter);
mWriter.close();
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
}
/**
* Generate a DAX representation on STDOUT.
*/
public void writeToSTDOUT() {
mWriter = new XMLWriter(new BufferedWriter(new OutputStreamWriter(
System.out)));
toXML(mWriter);
mWriter.close();
}
/**
* Generate a DAX representation and pipe it into the Writer
*
* @param writer A Writer object
* @param close Whether writer should be closed on return.
*/
public void writeToWriter(Writer writer, boolean close) {
mWriter = new XMLWriter(writer);
toXML(mWriter);
if (close) {
mWriter.close();
}
}
/**
* Generates a DAX representation.
*
* @param writer @
*/
public void toXML(XMLWriter writer) {
int indent = 0;
writer.startElement("adag");
writer.writeAttribute("xmlns", SCHEMA_NAMESPACE);
writer.writeAttribute("xmlns:xsi", SCHEMA_NAMESPACE_XSI);
writer.writeAttribute("xsi:schemaLocation",
SCHEMA_NAMESPACE + " " + SCHEMA_LOCATION);
writer.writeAttribute("version", SCHEMA_VERSION);
writer.writeAttribute("name", mName);
writer.writeAttribute("index", Integer.toString(mIndex));
writer.writeAttribute("count", Integer.toString(mCount));
//add metadata attributes
writer.writeXMLComment( "Section 1: Metadata attributes for the workflow (can be empty) ", true );
for( MetaData md : this.mMetaDataAttributes ){
md.toXML(writer, indent + 1 );
}
//print notification invokes
writer.
writeXMLComment(
"Section 2: Invokes - Adds notifications for a workflow (can be empty)",
true);
for (Invoke i : mInvokes) {
i.toXML(writer, indent + 1);
}
//print file
writer.writeXMLComment(
"Section 3: Files - Acts as a Replica Catalog (can be empty)",
true);
for (File f : mFiles) {
f.toXML(writer, indent + 1);
}
//print executable
writer.
writeXMLComment(
"Section 4: Executables - Acts as a Transformaton Catalog (can be empty)",
true);
for (Executable e : mExecutables) {
e.toXML(writer, indent + 1);
}
//print transformation
writer.
writeXMLComment(
"Section 5: Transformations - Aggregates executables and Files (can be empty)",
true);
for (Transformation t : mTransformations) {
t.toXML(writer, indent + 1);
}
//print jobs, daxes and dags
writer.
writeXMLComment(
"Section 6: Job's, DAX's or Dag's - Defines a JOB or DAX or DAG (Atleast 1 required)",
true);
for (AbstractJob j : mJobs.values()) {
j.toXML(writer, indent + 1);
}
//print dependencies
writer.
writeXMLComment(
"Section 7: Dependencies - Parent Child relationships (can be empty)",
true);
for (String child : mDependencies.keySet()) {
writer.startElement("child", indent + 1).
writeAttribute("ref", child);
for (Edge e : mDependencies.get(child)) {
e.toXMLParent(writer, indent + 2);
}
writer.endElement(indent + 1);
}
//end adag
writer.endElement();
}
/**
* Create an example DIAMOND DAX
*
* @param args
*/
public static void main(String[] args) {
String dax = "diamond.dax";
if (args.length > 0) {
dax = args[0];
}
Diamond().writeToFile( dax );
}
private static ADAG Diamond() {
ADAG dax = new ADAG("test");
File fa = new File("f.a");
fa.addMetaData( "foo", "bar");
fa.addMetaData( "num", "1");
fa.addProfile("env", "FOO", "/usr/bar");
fa.addProfile("globus", "walltime", "40");
fa.addPhysicalFile("file:///scratch/f.a", "local");
dax.addFile(fa);
File fb1 = new File("f.b1");
fb1.addMetaData( "foo", "bar");
fb1.addMetaData( "num", "2");
fb1.addProfile("env", "GOO", "/usr/foo");
fb1.addProfile("globus", "walltime", "40");
dax.addFile(fb1);
File fb2 = new File("f.b2");
fb2.addMetaData( "foo", "bar");
fb2.addMetaData( "num", "3");
fb2.addProfile("env", "BAR", "/usr/goo");
fb2.addProfile("globus", "walltime", "40");
dax.addFile(fb2);
File fc1 = new File("f.c1");
fc1.addProfile("env", "TEST", "/usr/bin/true");
fc1.addProfile("globus", "walltime", "40");
dax.addFile(fc1);
File fc2 = new File("f.c2");
fc2.addMetaData( "foo", "bar");
fc2.addMetaData( "num", "5");
dax.addFile(fc2);
File fd = new File("f.d");
dax.addFile(fd);
Executable preprocess = new Executable("pegasus", "preproces", "1.0");
preprocess.setArchitecture(Executable.ARCH.X86).setOS(
Executable.OS.LINUX);
preprocess.setInstalled(false);
preprocess.addPhysicalFile(
new PFN("file:///opt/pegasus/default/bin/keg"));
preprocess.addProfile(Profile.NAMESPACE.globus, "walltime", "120");
preprocess.addMetaData( "project", "pegasus");
Executable findrange = new Executable("pegasus", "findrange", "1.0");
findrange.setArchitecture(Executable.ARCH.X86).
setOS(Executable.OS.LINUX);
findrange.unsetInstalled();
findrange.
addPhysicalFile(new PFN("http://pegasus.isi.edu/code/bin/keg"));
findrange.addProfile(Profile.NAMESPACE.globus, "walltime", "120");
findrange.addMetaData( "project", "pegasus");
Executable analyze = new Executable("pegasus", "analyze", "1.0");
analyze.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
analyze.unsetInstalled();
analyze.addPhysicalFile(new PFN(
"gsiftp://localhost/opt/pegasus/default/bin/keg"));
analyze.addProfile(Profile.NAMESPACE.globus, "walltime", "120");
analyze.addMetaData( "project", "pegasus");
dax.addExecutable(preprocess).addExecutable(findrange).addExecutable(
analyze);
Transformation diamond = new Transformation("pegasus", "diamond", "1.0");
diamond.uses(preprocess).uses(findrange).uses(analyze);
diamond.uses(new File("config", File.LINK.INPUT));
dax.addTransformation(diamond);
Job j1 = new Job("j1", "pegasus", "preprocess", "1.0", "j1");
j1.addArgument("-a preprocess -T 60 -i ").addArgument(fa);
j1.addArgument("-o ").addArgument(fb1).addArgument(fb2);
j1.uses(fa, File.LINK.INPUT);
j1.uses(fb1, File.LINK.OUTPUT);
j1.uses("f.b2", File.LINK.OUTPUT);
j1.addProfile(Profile.NAMESPACE.dagman, "pre", "20");
j1.
addInvoke(WHEN.start,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
j1.
addInvoke(WHEN.at_end,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
dax.addJob(j1);
DAG j2 = new DAG("j2", "findrange.dag", "j2");
j2.uses(new File("f.b1"), File.LINK.INPUT);
j2.uses("f.c1", File.LINK.OUTPUT, File.TRANSFER.FALSE, false);
j2.addProfile(Profile.NAMESPACE.dagman, "pre", "20");
j2.addProfile("condor", "universe", "vanilla");
j2.
addInvoke(WHEN.start,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
j2.
addInvoke(WHEN.at_end,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
dax.addDAG(j2);
DAX j3 = new DAX("j3", "findrange.dax", "j3");
j3.addArgument("--site ").addArgument("local");
j3.uses(new File("f.b2"), File.LINK.INPUT,"");
j3.uses(new File("f.c2"), File.LINK.OUTPUT, File.TRANSFER.FALSE, false,false, false,"30");
j3.addInvoke(Invoke.WHEN.start, "/bin/notify -m START [email protected]");
j3.addInvoke(Invoke.WHEN.at_end, "/bin/notify -m END [email protected]");
j3.
addInvoke(WHEN.start,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
j3.
addInvoke(WHEN.at_end,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
j3.addProfile("ENV", "HAHA", "YADAYADAYADA");
dax.addDAX(j3);
Job j4 = new Job("j4", "pegasus", "analyze", "");
File[] infiles = {fc1, fc2};
j4.addArgument("-a", "analyze").addArgument("-T").addArgument("60").
addArgument("-i", infiles, " ", ",");
j4.addArgument("-o", fd);
j4.uses(fc1, File.LINK.INPUT);
j4.uses(fc2, File.LINK.INPUT);
j4.uses(fd, File.LINK.OUTPUT);
j4.
addInvoke(WHEN.start,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
j4.
addInvoke(WHEN.at_end,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
dax.addJob(j4);
dax.addDependency("j1", "j2", "1-2");
dax.addDependency("j1", "j3", "1-3");
dax.addDependency("j2", "j4");
dax.addDependency("j3", "j4");
return dax;
}
}
| src/edu/isi/pegasus/planner/dax/ADAG.java | /**
* Copyright 2007-2012 University Of Southern California
*
* 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.
*/
package edu.isi.pegasus.planner.dax;
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Set;
import java.util.LinkedHashSet;
import java.io.Writer;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.common.logging.LogManagerFactory;
import edu.isi.pegasus.common.util.Version;
import edu.isi.pegasus.common.util.XMLWriter;
import edu.isi.pegasus.planner.dax.Invoke.WHEN;
/**
* <pre>
* <b>This class provides the Java API to create DAX files.</b>
*
* The DAX XML SCHEMA is available at <a href="http://pegasus.isi.edu/schema/dax-3.6.xsd">http://pegasus.isi.edu/schema/dax-3.6.xsd</a>
* and documentation available at <a href="http://pegasus.isi.edu/wms/docs/schemas/dax-3.6/dax-3.6.html">http://pegasus.isi.edu/wms/docs/schemas/dax-3.6/dax-3.6.html</a>
*
* The DAX consists of 6 parts the first 4 are optional and the last is optional.
* </pre> <ol> <li><b>file:</b>Used as "In DAX" Replica Catalog
* (Optional)</li><br> <li><b>executable:</b> Used as "In DAX" Transformation
* Catalog (Optional)</li><br> <li><b>transformation:</b> Used to describe
* compound executables. i.e. Executable depending on other executables
* (Optional)</li><br> <li><b>job|dax|dag:</b> Used to describe a single job or
* sub dax or sub dax. Atleast 1 required.</li><br> <li><b>child:</b> The
* dependency section to describe dependencies between job|dax|dag elements.
* (Optional)</li><br> </ol> <center><img
* src="http://pegasus.isi.edu/wms/docs/schemas/dax-3.6/dax-3.6_p1.png"/></center>
* <pre>
* To generate an example DIAMOND DAX run the ADAG Class as shown below
* <b>java ADAG filename</b>
* <b>NOTE: This is an illustrative example only. Please see examples directory for a working example</b>
*
* Here is sample java code that illustrates how to use the Java DAX API
* <pre>
* java.io.File cwdFile = new java.io.File (".");
String cwd = cwdFile.getCanonicalPath();
String pegasusHome = "/usr";
String site = "TestCluster";
ADAG dax = new ADAG("diamond");
dax.addNotification(Invoke.WHEN.start,"/pegasus/libexec/notification/email -t [email protected]");
dax.addNotification(Invoke.WHEN.at_end,"/pegasus/libexec/notification/email -t [email protected]");
dax.addMetadata( "name", "diamond");
dax.addMetadata( "createdBy", "Karan Vahi");
File fa = new File("f.a");
fa.addPhysicalFile("file://" + cwd + "/f.a", "local");
fa.addMetaData( "size", "1024" );
dax.addFile(fa);
File fb1 = new File("f.b1");
File fb2 = new File("f.b2");
File fc1 = new File("f.c1");
File fc2 = new File("f.c2");
File fd = new File("f.d");
fd.setRegister(true);
Executable preprocess = new Executable("pegasus", "preprocess", "4.0");
preprocess.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
preprocess.setInstalled(true);
preprocess.addMetaData( "size", "2048" );
preprocess.addPhysicalFile("file://" + pegasus_location + "/bin/keg", site_handle);
Executable findrange = new Executable("pegasus", "findrange", "4.0");
findrange.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
findrange.setInstalled(true);
findrange.addPhysicalFile("file://" + pegasus_location + "/bin/keg", site_handle);
Executable analyze = new Executable("pegasus", "analyze", "4.0");
analyze.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
analyze.setInstalled(true);
analyze.addPhysicalFile("file://" + pegasus_location + "/bin/keg", site_handle);
dax.addExecutable(preprocess).addExecutable(findrange).addExecutable(analyze);
// Add a preprocess job
Job j1 = new Job("j1", "pegasus", "preprocess", "4.0");
j1.addArgument("-a preprocess -T 60 -i ").addArgument(fa);
j1.addArgument("-o ").addArgument(fb1);
j1.addArgument(" ").addArgument(fb2);
j1.addMetadata( "time", "60" );
j1.uses(fa, File.LINK.INPUT);
j1.uses(fb1, File.LINK.OUTPUT);
j1.uses(fb2, File.LINK.OUTPUT);
j1.addNotification(Invoke.WHEN.start,"/pegasus/libexec/notification/email -t [email protected]");
j1.addNotification(Invoke.WHEN.at_end,"/pegasus/libexec/notification/email -t [email protected]");
dax.addJob(j1);
// Add left Findrange job
Job j2 = new Job("j2", "pegasus", "findrange", "4.0");
j2.addArgument("-a findrange -T 60 -i ").addArgument(fb1);
j2.addArgument("-o ").addArgument(fc1);
j2.addMetadata( "time", "60" );
j2.uses(fb1, File.LINK.INPUT);
j2.uses(fc1, File.LINK.OUTPUT);
j2.addNotification(Invoke.WHEN.start,"/pegasus/libexec/notification/email -t [email protected]");
j2.addNotification(Invoke.WHEN.at_end,"/pegasus/libexec/notification/email -t [email protected]");
dax.addJob(j2);
// Add right Findrange job
Job j3 = new Job("j3", "pegasus", "findrange", "4.0");
j3.addArgument("-a findrange -T 60 -i ").addArgument(fb2);
j3.addArgument("-o ").addArgument(fc2);
j3.addMetadata( "time", "60" );
j3.uses(fb2, File.LINK.INPUT);
j3.uses(fc2, File.LINK.OUTPUT);
j3.addNotification(Invoke.WHEN.start,"/pegasus/libexec/notification/email -t [email protected]");
j3.addNotification(Invoke.WHEN.at_end,"/pegasus/libexec/notification/email -t [email protected]");
dax.addJob(j3);
// Add analyze job
Job j4 = new Job("j4", "pegasus", "analyze", "4.0");
j4.addArgument("-a analyze -T 60 -i ").addArgument(fc1);
j4.addArgument(" ").addArgument(fc2);
j4.addArgument("-o ").addArgument(fd);
j4.addMetadata( "time", "60" );
j4.uses(fc1, File.LINK.INPUT);
j4.uses(fc2, File.LINK.INPUT);
j4.uses(fd, File.LINK.OUTPUT);
j4.addNotification(Invoke.WHEN.start,"/pegasus/libexec/notification/email -t [email protected]");
j4.addNotification(Invoke.WHEN.at_end,"/pegasus/libexec/notification/email -t [email protected]");
dax.addJob(j4);
dax.addDependency("j1", "j2");
dax.addDependency("j1", "j3");
dax.addDependency("j2", "j4");
dax.addDependency("j3", "j4");
dax.writeToSTDOUT();
* </pre>
*
* @author Gaurang Mehta gmehta at isi dot edu
* @author Karan Vahi
* @version $Revision$
*/
public class ADAG {
/**
* The "official" namespace URI of the site catalog schema.
*/
public static final String SCHEMA_NAMESPACE =
"http://pegasus.isi.edu/schema/DAX";
/**
* XSI SCHEMA NAMESPACE
*/
public static final String SCHEMA_NAMESPACE_XSI =
"http://www.w3.org/2001/XMLSchema-instance";
/**
* The "not-so-official" location URL of the DAX schema definition.
*/
public static final String SCHEMA_LOCATION =
"http://pegasus.isi.edu/schema/dax-3.6.xsd";
/**
* The version to report.
*/
public static final String SCHEMA_VERSION = "3.6";
/**
* The Name / Label of the DAX
*/
private String mName;
/**
* The Index of the dax object. I out of N
*/
private int mIndex;
/**
* The Count of the number of dax objects : N
*/
private int mCount;
/**
* The List of Job,DAX and DAG objects
*
* @see DAG
* @see DAX
* @see Job
* @see AbstractJob
*/
private Map<String, AbstractJob> mJobs;
private List<Job> mLJobs;
private List<DAG> mLDAGs;
private List<DAX> mLDAXs;
/**
* The List of Transformation objects
*
* @see Transformation
*/
private Set<Transformation> mTransformations;
/**
* The list of Executable objects
*
* @see Executable
*/
private Set<Executable> mExecutables;
/**
* The list of edu.isi.pegasus.planner.dax.File objects
*
* @see File
*/
private List<File> mFiles;
/**
* Map of Dependencies between Job,DAX,DAG objects. Map key is a string that
* holds the child element reference, the value is a List of Parent objects
*
* @see Parent
*/
private Map<String, Set<Edge>> mDependencies;
/**
* List of Notification objects
*/
private List<Invoke> mInvokes;
/**
* The metadata attributes associated with the whole workflow.
*/
private Set<MetaData> mMetaDataAttributes;
/**
* Handle the XML writer
*/
private XMLWriter mWriter;
private LogManager mLogger;
/**
* The Simple constructor for the DAX object
*
* @param name DAX LABEL
*/
public ADAG(String name) {
this(name, 0, 1);
}
/**
* DAX Constructor
*
* @param name DAX Label
* @param index Index of DAX out of N DAX's
* @param count Number of DAXS in a group
*/
public ADAG(String name, int index, int count) {
//initialize everything
mName = name;
mIndex = index;
mCount = count;
mJobs = new LinkedHashMap<String, AbstractJob>();
mLJobs = new LinkedList<Job>();
mLDAGs = new LinkedList<DAG>();
mLDAXs = new LinkedList<DAX>();
mTransformations = new LinkedHashSet<Transformation>();
mExecutables = new LinkedHashSet<Executable>();
mMetaDataAttributes = new LinkedHashSet<MetaData>();
mFiles = new LinkedList<File>();
mInvokes = new LinkedList<Invoke>();
mDependencies = new LinkedHashMap<String, Set<Edge>>();
mLogger = LogManagerFactory.loadSingletonInstance();
mLogger.logEventStart("event.dax.generate", "pegasus.version", Version.
instance().toString());
}
/**
* Return the name/label of the dax
*
* @return
*/
public String getName() {
return mName;
}
/* Return the index of the dax
* @return int
*/
public int getIndex() {
return mIndex;
}
/**
* Returns the total count of the dax collection. (legacy)
*
* @return int
*/
public int getCount() {
return mCount;
}
/**
* Add a Notification for this Workflow
*
* @param when
* @param what
* @return ADAG
*/
public ADAG addInvoke(Invoke.WHEN when, String what) {
Invoke i = new Invoke(when, what);
mInvokes.add(i);
return this;
}
/**
* Add a Notification for this Workflow
*
* @param when
* @param what
* @return ADAG
*/
public ADAG addNotification(Invoke.WHEN when, String what) {
return addInvoke(when, what);
}
/**
* Add a Notification for this Workflow
*
* @param invoke
* @return ADAG
*/
public ADAG addInvoke(Invoke invoke) {
mInvokes.add(invoke.clone());
return this;
}
/**
* Add a Notification for this Workflow
*
* @param invoke
* @return ADAG
*/
public ADAG addNotification(Invoke invoke) {
return addInvoke(invoke);
}
/**
* Add a List of Notifications for this Workflow
*
* @param invokes
* @return ADAG
*/
public ADAG addInvokes(List<Invoke> invokes) {
for (Invoke invoke : invokes) {
this.addInvoke(invoke);
}
return this;
}
/**
* Add a List of Notifications for this Workflow
*
* @param invokes
* @return ADAG
*/
public ADAG addNotifications(List<Invoke> invokes) {
return addInvokes(invokes);
}
/**
* Returns a list of Invoke objects associated with the workflow
*
* @return
*/
public List<Invoke> getInvoke() {
return mInvokes;
}
/**
* Returns a list of Invoke objects associated with the workflow. Same as
* getInvoke()
*
* @return
*/
public List<Invoke> getNotification() {
return getInvoke();
}
/**
* Adds metadata to the workflow
*
* @param key key name for metadata
* @param value value
* @return
*/
public ADAG addMetaData( String key, String value ){
this.mMetaDataAttributes.add( new MetaData( key, value ) );
return this;
}
/**
* Returns the metadata associated for a key if exists, else null
*
* @param key
*
* @return
*/
public String getMetaData( String key ){
return this.mMetaDataAttributes.contains( key )?
((MetaData)mMetaDataAttributes).getValue():
null;
}
/**
* Add a RC File object to the top of the DAX.
*
* @param file File object to be added to the RC section
* @return ADAG
* @see File
*/
public ADAG addFile(File file) {
mFiles.add(file);
return this;
}
/**
* Add Files to the RC Section on top of the DAX
*
* @param files List<File> List of file objects to be added to the RC
* Section
* @return ADAG
* @see File
*
*/
public ADAG addFiles(List<File> files) {
mFiles.addAll(files);
return this;
}
/**
* Returns a list of File objects defined as the inDax Replica Catalog
*
* @return
*/
public List<File> getFiles() {
return mFiles;
}
/**
* Add Executable to the DAX
*
* @param executable Executable to be added
* @return ADAG
* @see Executable
*/
public ADAG addExecutable(Executable executable) {
if (executable != null) {
if (!mExecutables.contains(executable)) {
mExecutables.add(executable);
} else {
throw new RuntimeException("Error: Executable " + executable.
toString() + " already exists in the DAX.\n");
}
} else {
throw new RuntimeException("Error: The executable passed is null\n");
}
return this;
}
/**
* Add Multiple Executable objects to the DAX
*
* @param executables List of Executable objects to be added
* @return ADAG
* @see Executable
*/
public ADAG addExecutables(List<Executable> executables) {
if (executables != null && !executables.isEmpty()) {
for (Executable executable : executables) {
addExecutable(executable);
}
} else {
throw new RuntimeException(
"Error: The executables list to be added is either null or empty\n");
}
return this;
}
/**
* Returns a set of Executable Objects stored as part of the inDAX
* Transformation Catalog;
*
* @return
*/
public Set<Executable> getExecutables() {
return mExecutables;
}
/**
* Checks if a given executable exists in the DAX based Transformation
* Catalog
*
* @param executable
* @return boolean
*/
public boolean containsExecutable(Executable executable) {
return mExecutables.contains(executable);
}
/**
* Add Transformation to the DAX
*
* @param transformation Transformation object to be added
* @return ADAG
* @see Transformation
*/
public ADAG addTransformation(Transformation transformation) {
if (transformation != null) {
if (!mTransformations.contains(transformation)) {
mTransformations.add(transformation);
} else {
throw new RuntimeException("Error: Transformation " + transformation.
toString() + " already exists in the DAX.\n");
}
} else {
throw new RuntimeException("Transformation provided is null\n");
}
return this;
}
/**
* Add Multiple Transformation to the DAX
*
* @param transformations List of Transformation objects
* @return ADAG
* @see Transformation
*/
public ADAG addTransformations(List<Transformation> transformations) {
if (transformations != null && !transformations.isEmpty()) {
for (Transformation transformation : transformations) {
addTransformation(transformation);
}
} else {
throw new RuntimeException(
"List of transformations provided is null");
}
return this;
}
/**
* Checks if a given Transformation exists in the DAX based Transformation
* Catalog
*
* @param transformation Transformation
* @return boolean
*/
public boolean containsTransformation(Transformation transformation) {
return mTransformations.contains(transformation);
}
/**
* Returns a set of Transformation Objects (complex executables) stored in
* the DAX based Transformation Catalog
*
* @return
*/
public Set<Transformation> getTransformations() {
return mTransformations;
}
/**
* Add AbstractJob to the DAX
*
* @param ajob AbstractJob
* @return ADAG
* @see Job
* @see DAG
* @see DAX
* @see AbstractJob
*/
private ADAG addAbstractJob(AbstractJob ajob) {
if (!mJobs.containsKey(ajob.mId)) {
mJobs.put(ajob.mId, ajob);
if (ajob.isDAG()) {
mLDAGs.add((DAG) ajob);
} else if (ajob.isDAX()) {
mLDAXs.add((DAX) ajob);
} else if (ajob.isJob()) {
mLJobs.add((Job) ajob);
}
} else {
throw new RuntimeException(
"Job of type" + ajob.getClass().getSimpleName() + " with jobid " + ajob.mId + " already exists in the DAX");
}
return this;
}
/**
* Add AbstractJobs to the DAX
*
* @param ajobs AbstractJob
* @return ADAG
* @see Job
* @see DAG
* @see DAX
* @see AbstractJob
*/
private ADAG addAbstractJobs(List<AbstractJob> ajobs) {
for (AbstractJob ajob : ajobs) {
addAbstractJob(ajob);
}
return this;
}
/**
* Returns an abstract Job with id ajobid if present otherwise null.
*
* @param ajobid
* @return
*/
private AbstractJob getAbstractJob(String ajobid) {
if (ajobid != null) {
AbstractJob j = mJobs.get(ajobid);
if (j != null) {
return j;
} else {
mLogger.log("No Job/DAX/DAG found with id " + ajobid,
LogManager.ERROR_MESSAGE_LEVEL);
}
}
return null;
}
/**
* Check if an abstractjob exists in the DAX
*
* @param ajob
* @return
*/
private boolean containsAbstractJob(AbstractJob ajob) {
return containsAbstractJobId(ajob.mId);
}
/**
* Check if a jobid exists in the DAX
*
* @param ajobid
* @return
*/
private boolean containsAbstractJobId(String ajobid) {
return mJobs.containsKey(ajobid);
}
/**
* Add Job to the DAX
*
* @param job
* @return ADAG
* @see Job
* @see AbstractJob
*/
public ADAG addJob(Job job) {
return addAbstractJob(job);
}
/**
* Add multiple Jobs to the DAX
*
* @param jobs
* @return ADAG
* @see Job
* @see AbstractJob
*/
public ADAG addJobs(List<Job> jobs) {
for (Job job : jobs) {
addJob(job);
}
return this;
}
/**
* Check if a job exists in the DAX
*
* @param job
* @return
*/
public boolean containsJob(Job job) {
return containsAbstractJob(job);
}
/**
* Check if a jobid exists in the DAX
*
* @param jobid
* @return
*/
public boolean containsJobId(String jobid) {
return containsAbstractJobId(jobid);
}
/**
* Returns a Job object with id jobid if present otherwise null.
*
* @param jobid
* @return
*/
public Job getJob(String jobid) {
AbstractJob j = getAbstractJob(jobid);
if (j != null) {
if (j.isJob()) {
return (Job) j;
} else {
mLogger.log("Returned object is not of type Job, but " + j.
getClass().getSimpleName(),
LogManager.ERROR_MESSAGE_LEVEL);
}
}
return null;
}
/**
* Get a list of all the DAG jobs.
*
* @return
*/
public List<Job> getJobs() {
return mLJobs;
}
/**
* Get a list of all the DAX jobs.
*
* @return
*/
public List<DAX> getDAXs() {
return mLDAXs;
}
/**
* Returns a DAX object with id daxid if present otherwise null.
*
* @param daxid
* @return
*/
public DAX getDAX(String daxid) {
AbstractJob j = getAbstractJob(daxid);
if (j != null) {
if (j.isDAX()) {
return (DAX) j;
} else {
mLogger.log("Return object is not of type DAX, but " + j.
getClass().getSimpleName(),
LogManager.ERROR_MESSAGE_LEVEL);
}
}
return null;
}
/**
* Get a list of all the DAG jobs.
*
* @return
*/
public List<DAG> getDAGs() {
return mLDAGs;
}
/**
* Returns a DAG object with id dagid if present otherwise null.
*
* @param dagid
* @return
*/
public DAG getDAG(String dagid) {
AbstractJob j = getAbstractJob(dagid);
if (j != null) {
if (j.isDAG()) {
return (DAG) j;
} else {
mLogger.log("Return object is not of type DAG, but " + j.
getClass().getSimpleName(),
LogManager.ERROR_MESSAGE_LEVEL);
}
}
return null;
}
/**
* Add a DAG job to the DAX
*
* @param dag the DAG to be added
* @return ADAG
* @see DAG
* @see AbstractJob
*/
public ADAG addDAG(DAG dag) {
return addAbstractJob(dag);
}
/**
* Add multiple DAG jobs to the DAX
*
* @param dags List of DAG jobs to be added
* @return ADAG
* @see DAG
* @see AbstractJob
*/
public ADAG addDAGs(List<DAG> dags) {
for (DAG dag : dags) {
addDAG(dag);
}
return this;
}
/**
* Check if a DAG job exists in the DAX
*
* @param dag
* @return
*/
public boolean containsDAG(DAG dag) {
return containsAbstractJob(dag);
}
/**
* Check if a DAG job id exists in the DAX
*
* @param dagid
* @return
*/
public boolean containsDAGId(String dagid) {
return containsAbstractJobId(dagid);
}
/**
* Add a DAX job to the DAX
*
* @param dax DAX to be added
* @return ADAG
* @see DAX
* @see AbstractJob
*/
public ADAG addDAX(DAX dax) {
return addAbstractJob(dax);
}
/**
* Add multiple DAX jobs to the DAX
*
* @param daxs LIST of DAX jobs to be added
* @return ADAG
* @see DAX
* @see AbstractJob
*/
public ADAG addDAXs(List<DAX> daxs) {
for (DAX dax : daxs) {
addDAX(dax);
}
return this;
}
/**
* Check if a DAX job exists in the DAX
*
* @param dax
* @return
*/
public boolean containsDAX(DAX dax) {
return containsAbstractJob(dax);
}
/**
* Check if a DAX job id exists in the DAX
*
* @param daxid
* @return
*/
public boolean containsDAXId(String daxid) {
return containsAbstractJobId(daxid);
}
/**
* Add a parent child dependency between two jobs,dax,dag
*
* @param parent String job,dax,dag id
* @param child String job,dax,dag,id
* @return ADAG
*
*/
public ADAG addDependency(String parent, String child) {
addDependency(parent, child, null);
return this;
}
/**
* Add a parent child dependency between two jobs,dax,dag
*
* @param parent Job|DAX|DAG object
* @param child Job|DAX|DAG object
* @return
*/
public ADAG addDependency(AbstractJob parent, AbstractJob child) {
addDependency(parent.getId(), child.getId(), null);
return this;
}
/**
* Add a parent child dependency with a dependency label
*
* @param parent String job,dax,dag id
* @param child String job,dax,dag id
* @param label String dependency label
* @return ADAG
*/
public ADAG addDependency(String parent, String child, String label) {
if (containsAbstractJobId(parent) && containsAbstractJobId(child)) {
Set<Edge> edges = mDependencies.get(child);
if (edges == null) {
edges = new LinkedHashSet<Edge>();
}
Edge e = new Edge(parent,child, label);
edges.add(e);
mDependencies.put(child, edges);
} else {
throw new RuntimeException(
"Either Job with id " + parent + " or " + child + "is not added to the DAX.\n"
+ "Please add the jobs first to the dax and then add the dependencies between them\n");
}
return this;
}
/**
* Returns a list of Edge objects for a child job/dax/dag id. Returns an
* empty set if the child does not have any parents Returns null if the
* child is not a valid job/dax/dag id
*
* @param child
* @return
*/
public Set<Edge> getEdges(String child) {
if (child != null && mJobs.containsKey(child)) {
return mDependencies.containsKey(child) ? mDependencies.get(child)
: new LinkedHashSet<Edge>();
}
return null;
}
/**
* Returns a Set of all the Edge objects for the DAX. Returns empty if no dependencies.
*
* @param child
* @return
*/
public Set<Edge> getEdges() {
Set<Edge> edges = new LinkedHashSet<Edge>();
for(Set<Edge>s : mDependencies.values()){
edges.addAll(s);
}
return edges;
}
/**
* Add a parent child dependency with a dependency label
*
* @param parent Job|DAX|DAG object
* @param child Job|DAX|DAG object
* @param label String label for annotation
* @return ADAG
*/
public ADAG addDependency(AbstractJob parent, AbstractJob child,
String label) {
addDependency(parent.getId(), child.getId(), label);
return this;
}
/**
* Generate a DAX File out of this object;
*
* @param daxfile The file to write the DAX to
*/
public void writeToFile(String daxfile) {
try {
mWriter = new XMLWriter(new FileWriter(daxfile));
toXML(mWriter);
mWriter.close();
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
}
/**
* Generate a DAX representation on STDOUT.
*/
public void writeToSTDOUT() {
mWriter = new XMLWriter(new BufferedWriter(new OutputStreamWriter(
System.out)));
toXML(mWriter);
mWriter.close();
}
/**
* Generate a DAX representation and pipe it into the Writer
*
* @param writer A Writer object
* @param close Whether writer should be closed on return.
*/
public void writeToWriter(Writer writer, boolean close) {
mWriter = new XMLWriter(writer);
toXML(mWriter);
if (close) {
mWriter.close();
}
}
/**
* Generates a DAX representation.
*
* @param writer @
*/
public void toXML(XMLWriter writer) {
int indent = 0;
writer.startElement("adag");
writer.writeAttribute("xmlns", SCHEMA_NAMESPACE);
writer.writeAttribute("xmlns:xsi", SCHEMA_NAMESPACE_XSI);
writer.writeAttribute("xsi:schemaLocation",
SCHEMA_NAMESPACE + " " + SCHEMA_LOCATION);
writer.writeAttribute("version", SCHEMA_VERSION);
writer.writeAttribute("name", mName);
writer.writeAttribute("index", Integer.toString(mIndex));
writer.writeAttribute("count", Integer.toString(mCount));
//add metadata attributes
writer.writeXMLComment( "Section 1: Metadata attributes for the workflow (can be empty) ", true );
for( MetaData md : this.mMetaDataAttributes ){
md.toXML(writer, indent + 1 );
}
//print notification invokes
writer.
writeXMLComment(
"Section 2: Invokes - Adds notifications for a workflow (can be empty)",
true);
for (Invoke i : mInvokes) {
i.toXML(writer, indent + 1);
}
//print file
writer.writeXMLComment(
"Section 3: Files - Acts as a Replica Catalog (can be empty)",
true);
for (File f : mFiles) {
f.toXML(writer, indent + 1);
}
//print executable
writer.
writeXMLComment(
"Section 4: Executables - Acts as a Transformaton Catalog (can be empty)",
true);
for (Executable e : mExecutables) {
e.toXML(writer, indent + 1);
}
//print transformation
writer.
writeXMLComment(
"Section 5: Transformations - Aggregates executables and Files (can be empty)",
true);
for (Transformation t : mTransformations) {
t.toXML(writer, indent + 1);
}
//print jobs, daxes and dags
writer.
writeXMLComment(
"Section 6: Job's, DAX's or Dag's - Defines a JOB or DAX or DAG (Atleast 1 required)",
true);
for (AbstractJob j : mJobs.values()) {
j.toXML(writer, indent + 1);
}
//print dependencies
writer.
writeXMLComment(
"Section 7: Dependencies - Parent Child relationships (can be empty)",
true);
for (String child : mDependencies.keySet()) {
writer.startElement("child", indent + 1).
writeAttribute("ref", child);
for (Edge e : mDependencies.get(child)) {
e.toXMLParent(writer, indent + 2);
}
writer.endElement(indent + 1);
}
//end adag
writer.endElement();
}
/**
* Create an example DIAMOND DAX
*
* @param args
*/
public static void main(String[] args) {
String dax = "diamond.dax";
if (args.length > 0) {
dax = args[0];
}
Diamond().writeToFile( dax );
}
private static ADAG Diamond() {
ADAG dax = new ADAG("test");
File fa = new File("f.a");
fa.addMetaData( "foo", "bar");
fa.addMetaData( "num", "1");
fa.addProfile("env", "FOO", "/usr/bar");
fa.addProfile("globus", "walltime", "40");
fa.addPhysicalFile("file:///scratch/f.a", "local");
dax.addFile(fa);
File fb1 = new File("f.b1");
fb1.addMetaData( "foo", "bar");
fb1.addMetaData( "num", "2");
fb1.addProfile("env", "GOO", "/usr/foo");
fb1.addProfile("globus", "walltime", "40");
dax.addFile(fb1);
File fb2 = new File("f.b2");
fb2.addMetaData( "foo", "bar");
fb2.addMetaData( "num", "3");
fb2.addProfile("env", "BAR", "/usr/goo");
fb2.addProfile("globus", "walltime", "40");
dax.addFile(fb2);
File fc1 = new File("f.c1");
fc1.addProfile("env", "TEST", "/usr/bin/true");
fc1.addProfile("globus", "walltime", "40");
dax.addFile(fc1);
File fc2 = new File("f.c2");
fc2.addMetaData( "foo", "bar");
fc2.addMetaData( "num", "5");
dax.addFile(fc2);
File fd = new File("f.d");
dax.addFile(fd);
Executable preprocess = new Executable("pegasus", "preproces", "1.0");
preprocess.setArchitecture(Executable.ARCH.X86).setOS(
Executable.OS.LINUX);
preprocess.setInstalled(false);
preprocess.addPhysicalFile(
new PFN("file:///opt/pegasus/default/bin/keg"));
preprocess.addProfile(Profile.NAMESPACE.globus, "walltime", "120");
preprocess.addMetaData( "project", "pegasus");
Executable findrange = new Executable("pegasus", "findrange", "1.0");
findrange.setArchitecture(Executable.ARCH.X86).
setOS(Executable.OS.LINUX);
findrange.unsetInstalled();
findrange.
addPhysicalFile(new PFN("http://pegasus.isi.edu/code/bin/keg"));
findrange.addProfile(Profile.NAMESPACE.globus, "walltime", "120");
findrange.addMetaData( "project", "pegasus");
Executable analyze = new Executable("pegasus", "analyze", "1.0");
analyze.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
analyze.unsetInstalled();
analyze.addPhysicalFile(new PFN(
"gsiftp://localhost/opt/pegasus/default/bin/keg"));
analyze.addProfile(Profile.NAMESPACE.globus, "walltime", "120");
analyze.addMetaData( "project", "pegasus");
dax.addExecutable(preprocess).addExecutable(findrange).addExecutable(
analyze);
Transformation diamond = new Transformation("pegasus", "diamond", "1.0");
diamond.uses(preprocess).uses(findrange).uses(analyze);
diamond.uses(new File("config", File.LINK.INPUT));
dax.addTransformation(diamond);
Job j1 = new Job("j1", "pegasus", "preprocess", "1.0", "j1");
j1.addArgument("-a preprocess -T 60 -i ").addArgument(fa);
j1.addArgument("-o ").addArgument(fb1).addArgument(fb2);
j1.uses(fa, File.LINK.INPUT);
j1.uses(fb1, File.LINK.OUTPUT);
j1.uses("f.b2", File.LINK.OUTPUT);
j1.addProfile(Profile.NAMESPACE.dagman, "pre", "20");
j1.
addInvoke(WHEN.start,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
j1.
addInvoke(WHEN.at_end,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
dax.addJob(j1);
DAG j2 = new DAG("j2", "findrange.dag", "j2");
j2.uses(new File("f.b1"), File.LINK.INPUT);
j2.uses("f.c1", File.LINK.OUTPUT, File.TRANSFER.FALSE, false);
j2.addProfile(Profile.NAMESPACE.dagman, "pre", "20");
j2.addProfile("condor", "universe", "vanilla");
j2.
addInvoke(WHEN.start,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
j2.
addInvoke(WHEN.at_end,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
dax.addDAG(j2);
DAX j3 = new DAX("j3", "findrange.dax", "j3");
j3.addArgument("--site ").addArgument("local");
j3.uses(new File("f.b2"), File.LINK.INPUT,"");
j3.uses(new File("f.c2"), File.LINK.OUTPUT, File.TRANSFER.FALSE, false,false, false,"30");
j3.addInvoke(Invoke.WHEN.start, "/bin/notify -m START [email protected]");
j3.addInvoke(Invoke.WHEN.at_end, "/bin/notify -m END [email protected]");
j3.
addInvoke(WHEN.start,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
j3.
addInvoke(WHEN.at_end,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
j3.addProfile("ENV", "HAHA", "YADAYADAYADA");
dax.addDAX(j3);
Job j4 = new Job("j4", "pegasus", "analyze", "");
File[] infiles = {fc1, fc2};
j4.addArgument("-a", "analyze").addArgument("-T").addArgument("60").
addArgument("-i", infiles, " ", ",");
j4.addArgument("-o", fd);
j4.uses(fc1, File.LINK.INPUT);
j4.uses(fc2, File.LINK.INPUT);
j4.uses(fd, File.LINK.OUTPUT);
j4.
addInvoke(WHEN.start,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
j4.
addInvoke(WHEN.at_end,
"/usr/local/pegasus/libexec/notification/email -t [email protected] -f [email protected]");
dax.addJob(j4);
dax.addDependency("j1", "j2", "1-2");
dax.addDependency("j1", "j3", "1-3");
dax.addDependency("j2", "j4");
dax.addDependency("j3", "j4");
return dax;
}
}
| PM-1311 get the dax generator api to always generate workflow metadata
with key dax.api and value java
| src/edu/isi/pegasus/planner/dax/ADAG.java | PM-1311 get the dax generator api to always generate workflow metadata with key dax.api and value java | <ide><path>rc/edu/isi/pegasus/planner/dax/ADAG.java
<ide> import edu.isi.pegasus.common.util.Version;
<ide> import edu.isi.pegasus.common.util.XMLWriter;
<ide> import edu.isi.pegasus.planner.dax.Invoke.WHEN;
<add>import edu.isi.pegasus.planner.namespace.Metadata;
<ide>
<ide> /**
<ide> * <pre>
<ide> * The version to report.
<ide> */
<ide> public static final String SCHEMA_VERSION = "3.6";
<add>
<add> /**
<add> * The type of DAX API generated
<add> */
<add> private static final String DAX_API_TYPE = "java";
<add>
<ide> /**
<ide> * The Name / Label of the DAX
<ide> */
<ide> mTransformations = new LinkedHashSet<Transformation>();
<ide> mExecutables = new LinkedHashSet<Executable>();
<ide> mMetaDataAttributes = new LinkedHashSet<MetaData>();
<add> mMetaDataAttributes.add( new MetaData(Metadata.DAX_API_KEY, DAX_API_TYPE));
<ide> mFiles = new LinkedList<File>();
<ide> mInvokes = new LinkedList<Invoke>();
<ide> mDependencies = new LinkedHashMap<String, Set<Edge>>(); |
|
Java | mit | 2a706d0e43936ba761234e832e218a42e8c9fd26 | 0 | Nincodedo/Ninbot | package com.nincraft.ninbot.components.event;
import com.nincraft.ninbot.components.config.ConfigDao;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import net.dv8tion.jda.core.JDA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Timer;
@Log4j2
@Component
public class EventScheduler {
private EventDao eventDao;
@Value("${debugEnabled:false}")
private boolean isDebugEnabled;
private ConfigDao configDao;
@Autowired
public EventScheduler(EventDao eventDao, ConfigDao configDao) {
this.eventDao = eventDao;
this.configDao = configDao;
}
public void scheduleAll(JDA jda) {
log.trace("scheduling events");
val events = eventDao.getAllEvents();
for (val event : events) {
scheduleEvent(event, jda);
}
}
void addEvent(Event event, JDA jda) {
eventDao.addEvent(event);
scheduleEvent(event, jda);
}
private void scheduleEvent(Event event, JDA jda) {
Timer timer = new Timer();
Instant eventStartTime = event.getStartTime().toInstant();
int minutesBeforeStart = 30;
Instant eventEarlyReminder = event.getStartTime().toInstant().minus(minutesBeforeStart, ChronoUnit.MINUTES);
Instant eventEndTime;
if (event.getEndTime() != null) {
eventEndTime = event.getStartTime().toInstant();
} else {
eventEndTime = eventStartTime.plus(1, ChronoUnit.DAYS);
}
if (eventEndTime.isBefore(Instant.now()) ||
(event.getEndTime() == null && eventStartTime.plus(1, ChronoUnit.DAYS).isBefore(Instant.now()))) {
log.debug("Removing event {}, the end time is passed", event.getName());
new EventRemove(event, eventDao).run();
} else {
log.debug("Scheduling {} for {}", event.getName(), event.getStartTime());
scheduleEvent(event, timer, eventStartTime, 0, jda);
scheduleEvent(event, timer, eventEarlyReminder, minutesBeforeStart, jda);
timer.schedule(new EventRemove(event, eventDao), Date.from(eventEndTime));
}
}
private void scheduleEvent(Event event, Timer timer, Instant eventTime, int minutesBeforeStart, JDA jda) {
if (!eventTime.isBefore(Instant.now())) {
timer.schedule(new EventAnnounce(event, minutesBeforeStart, isDebugEnabled, configDao, jda), Date.from(eventTime));
}
}
}
| src/main/java/com/nincraft/ninbot/components/event/EventScheduler.java | package com.nincraft.ninbot.components.event;
import com.nincraft.ninbot.components.config.ConfigDao;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import net.dv8tion.jda.core.JDA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Timer;
@Log4j2
@Component
public class EventScheduler {
private EventDao eventDao;
@Value("${debugEnabled:false}")
private boolean isDebugEnabled;
private ConfigDao configDao;
@Autowired
public EventScheduler(EventDao eventDao, ConfigDao configDao) {
this.eventDao = eventDao;
this.configDao = configDao;
}
public void scheduleAll(JDA jda) {
log.trace("scheduling events");
val events = eventDao.getAllEvents();
for (val event : events) {
scheduleEvent(event, jda);
}
}
void addEvent(Event event, JDA jda) {
eventDao.addEvent(event);
scheduleEvent(event, jda);
}
private void scheduleEvent(Event event, JDA jda) {
Timer timer = new Timer();
Instant eventStartTime = event.getStartTime().toInstant();
int minutesBeforeStart = 30;
Instant eventEarlyReminder = event.getStartTime().toInstant().minus(minutesBeforeStart, ChronoUnit.MINUTES);
Instant eventEndTime;
if (event.getEndTime() != null) {
eventEndTime = event.getStartTime().toInstant();
} else {
eventEndTime = eventStartTime.plus(1, ChronoUnit.DAYS);
}
if (eventEndTime.isBefore(Instant.now())) {
log.debug("Removing event {}, the end time is passed", event.getName());
new EventRemove(event, eventDao).run();
} else {
log.debug("Scheduling {} for {}", event.getName(), event.getStartTime());
scheduleEvent(event, timer, eventStartTime, 0, jda);
scheduleEvent(event, timer, eventEarlyReminder, minutesBeforeStart, jda);
timer.schedule(new EventRemove(event, eventDao), Date.from(eventEndTime));
}
}
private void scheduleEvent(Event event, Timer timer, Instant eventTime, int minutesBeforeStart, JDA jda) {
if (!eventTime.isBefore(Instant.now())) {
timer.schedule(new EventAnnounce(event, minutesBeforeStart, isDebugEnabled, configDao, jda), Date.from(eventTime));
}
}
}
| Fixes #27
| src/main/java/com/nincraft/ninbot/components/event/EventScheduler.java | Fixes #27 | <ide><path>rc/main/java/com/nincraft/ninbot/components/event/EventScheduler.java
<ide> } else {
<ide> eventEndTime = eventStartTime.plus(1, ChronoUnit.DAYS);
<ide> }
<del> if (eventEndTime.isBefore(Instant.now())) {
<add> if (eventEndTime.isBefore(Instant.now()) ||
<add> (event.getEndTime() == null && eventStartTime.plus(1, ChronoUnit.DAYS).isBefore(Instant.now()))) {
<ide> log.debug("Removing event {}, the end time is passed", event.getName());
<ide> new EventRemove(event, eventDao).run();
<ide> } else { |
|
JavaScript | mit | c85c92364b1a501bbd2b85f7cef9acb96a357988 | 0 | mil/lunch | 'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var yaml = require('js-yaml');
var read_dir = require('fs-readdir-recursive');
function config_loader(config_dir) {
return _.merge.apply({},
_.map(read_dir(config_dir), function(file) {
return yaml.safeLoad(
fs.readFileSync(
path.join(config_dir, file), 'utf-8'
)
);
})
);
}
module.exports = config_loader;
| modules/config_loader.js | 'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var yaml = require('js-yaml');
var read_dir = require('fs-readdir-recursive');
function config_loader(config_dir) {
return _.merge.apply({},
_.map(read_dir(config_dir), function(file) {
return yaml.safeLoad(
fs.readFileSync(
path.join(config_dir, file), 'utf-8'
)
);
})
);
}
module.exports = config_loader;
| whitespace
| modules/config_loader.js | whitespace | <ide><path>odules/config_loader.js
<ide> );
<ide> }
<ide>
<del>
<ide> module.exports = config_loader; |
|
JavaScript | unlicense | 2a1387d3667f9021f63397ffdf864b3257ea0dc0 | 0 | xpl/ololog | const mocha = require ('mocha')
, ansi = require ('ansicolor')
, ololog = require ('ololog')
, StackTracey = require ('stacktracey')
, log = ololog.configure ({ locate: false })
, { isBlank } = require ('printable-characters')
/* ------------------------------------------------------------------------ */
const printError = e => {
log.newline ()
if (e instanceof SyntaxError) {
console.log (e) // revert to default console.log because it shows source line where a SyntaxError was occured (something we can't do with Ololog now...)
} else if (('actual' in e) && ('expected' in e)) { // Assertion
log.bright.red.error ('[AssertionError] ' + e.message)
log.newline ()
log.red.error.indent (1) ('actual: ', e.actual)
log.newline ()
log.green.error.indent (1) ('expected:', e.expected)
log.newline ()
log.bright.red.error.indent (1) (new StackTracey (e).pretty)
} else {
log.bright.red.error (e)
}
}
process.on ('uncaughtException', printError)
process.on ('unhandledRejection', printError)
/* ------------------------------------------------------------------------ */
const sleep = ms => new Promise (resolve => setTimeout (resolve, ms))
/* ------------------------------------------------------------------------ */
module.exports = function (runner) {
mocha.reporters.Base.call (this, runner)
const originalImpl = Object.assign ({}, ololog.impl)
const cursorUp = '\u001b[1A'
StackTracey.resetCache () // when running mocha under --watch, this is needed to re-load the changed sources
runner.on ('suite', ({ title }) => {
if (title) {
log.bright (title + ':', '\n')
}
})
runner.on ('suite end', ({ title, tests }) => {
if (tests.length) {
console.log ('')
}
})
runner.on ('test', test => {
test.logBuffer = ''
let prevLocation
ololog.impl.render = text => {
const lines = text.split ('\n')
const multiline = lines.length > 1
const location = new StackTracey ().clean.at (2)
const locationChanged = prevLocation && !StackTracey.locationsEqual (location, prevLocation)
prevLocation = location
test.logBuffer += ((locationChanged || multiline) ? '\n' : '') + text + '\n'
}
;(async () => {
const clock = ['◐', '◓', '◑', '◒']
console.log ('')
for (let i = 0, n = clock.length; !test.state; i++) {
console.log (ansi.darkGray (cursorUp + clock[i % n] + ' ' + test.title + ' ' + '.'.repeat (i/2 % 5).padEnd (5)))
await sleep (100)
}
}) ()
})
runner.on ('test end', ({ state = undefined, title, logBuffer, only, verbose = false, parent, ...other }) => {
ololog.impl.render = originalImpl.render
if (state) {
log.darkGray (cursorUp + { 'passed': '��', 'failed': '��' }[state] + ' ', title, ' ')
const onlyEnabled = parent._onlyTests.length
while (!verbose && parent) {
verbose = parent.verbose
parent = parent.parent
}
let show = (onlyEnabled || verbose || (state === 'failed')) && logBuffer
if (show) {
const sanitized = logBuffer
.split ('\n')
.map (line => isBlank (line) ? '' : line)
.join ('\n')
log (' ', '\n' + sanitized.replace (/\n\n\n+/g, '\n\n').trim () + '\n')
}
}
})
runner.on ('fail', (test, err) => { printError (err) })
}
| reporter.js | const mocha = require ('mocha')
, ansi = require ('ansicolor')
, ololog = require ('ololog')
, StackTracey = require ('stacktracey')
, log = ololog.configure ({ locate: false })
, { isBlank } = require ('printable-characters')
/* ------------------------------------------------------------------------ */
process.on ('uncaughtException', e => { log.bright.red.error (e) })
process.on ('unhandledRejection', e => { log.bright.red.error (e) })
/* ------------------------------------------------------------------------ */
const sleep = ms => new Promise (resolve => setTimeout (resolve, ms))
/* ------------------------------------------------------------------------ */
module.exports = function (runner) {
mocha.reporters.Base.call (this, runner)
const originalImpl = Object.assign ({}, ololog.impl)
const cursorUp = '\u001b[1A'
StackTracey.resetCache () // when running mocha under --watch, this is needed to re-load the changed sources
runner.on ('suite', ({ title }) => {
if (title) {
log.bright (title + ':', '\n')
}
})
runner.on ('suite end', ({ title, tests }) => {
if (tests.length) {
console.log ('')
}
})
runner.on ('test', test => {
test.logBuffer = ''
let prevLocation
ololog.impl.render = text => {
const lines = text.split ('\n')
const multiline = lines.length > 1
const location = new StackTracey ().clean.at (2)
const locationChanged = prevLocation && !StackTracey.locationsEqual (location, prevLocation)
prevLocation = location
test.logBuffer += ((locationChanged || multiline) ? '\n' : '') + text + '\n'
}
;(async () => {
const clock = ['◐', '◓', '◑', '◒']
console.log ('')
for (let i = 0, n = clock.length; !test.state; i++) {
console.log (ansi.darkGray (cursorUp + clock[i % n] + ' ' + test.title + ' ' + '.'.repeat (i/2 % 5).padEnd (5)))
await sleep (100)
}
}) ()
})
runner.on ('test end', ({ state = undefined, title, logBuffer, only, verbose = false, parent, ...other }) => {
ololog.impl.render = originalImpl.render
if (state) {
log.darkGray (cursorUp + { 'passed': '��', 'failed': '��' }[state] + ' ', title, ' ')
const onlyEnabled = parent._onlyTests.length
while (!verbose && parent) {
verbose = parent.verbose
parent = parent.parent
}
let show = (onlyEnabled || verbose || (state === 'failed')) && logBuffer
if (show) {
const sanitized = logBuffer
.split ('\n')
.map (line => isBlank (line) ? '' : line)
.join ('\n')
log (' ', '\n' + sanitized.replace (/\n\n\n+/g, '\n\n').trim () + '\n')
}
}
})
runner.on ('fail', (test, err) => {
if (('actual' in err) && ('expected' in err)) {
log.bright.red.error ('[AssertionError] ' + err.message)
log.newline ()
log.red.error.indent (1) ('actual: ', err.actual)
log.newline ()
log.green.error.indent (1) ('expected:', err.expected)
log.newline ()
log.bright.red.error.indent (1) (new StackTracey (err).pretty)
} else {
log.bright.red.error ('\n', err)
}
})
}
| better error reporting in Mocha (now shows SyntaxErrors correctly) | reporter.js | better error reporting in Mocha (now shows SyntaxErrors correctly) | <ide><path>eporter.js
<ide>
<ide> /* ------------------------------------------------------------------------ */
<ide>
<del>process.on ('uncaughtException', e => { log.bright.red.error (e) })
<del>process.on ('unhandledRejection', e => { log.bright.red.error (e) })
<add>const printError = e => {
<add>
<add> log.newline ()
<add>
<add> if (e instanceof SyntaxError) {
<add>
<add> console.log (e) // revert to default console.log because it shows source line where a SyntaxError was occured (something we can't do with Ololog now...)
<add>
<add> } else if (('actual' in e) && ('expected' in e)) { // Assertion
<add>
<add> log.bright.red.error ('[AssertionError] ' + e.message)
<add> log.newline ()
<add> log.red.error.indent (1) ('actual: ', e.actual)
<add> log.newline ()
<add> log.green.error.indent (1) ('expected:', e.expected)
<add>
<add> log.newline ()
<add> log.bright.red.error.indent (1) (new StackTracey (e).pretty)
<add>
<add> } else {
<add> log.bright.red.error (e)
<add> }
<add>}
<add>
<add>process.on ('uncaughtException', printError)
<add>process.on ('unhandledRejection', printError)
<ide>
<ide> /* ------------------------------------------------------------------------ */
<ide>
<ide> }
<ide> })
<ide>
<del> runner.on ('fail', (test, err) => {
<del>
<del> if (('actual' in err) && ('expected' in err)) {
<del>
<del> log.bright.red.error ('[AssertionError] ' + err.message)
<del> log.newline ()
<del> log.red.error.indent (1) ('actual: ', err.actual)
<del> log.newline ()
<del> log.green.error.indent (1) ('expected:', err.expected)
<del>
<del> log.newline ()
<del> log.bright.red.error.indent (1) (new StackTracey (err).pretty)
<del>
<del> } else {
<del> log.bright.red.error ('\n', err)
<del> }
<del> })
<add> runner.on ('fail', (test, err) => { printError (err) })
<ide> } |
|
Java | apache-2.0 | 49a83c242c5976e54025ccbfd9df84420671d7a5 | 0 | baratine/lucene-plugin,baratine/lucene-plugin,baratine/lucene-plugin,baratine/lucene-plugin | package com.caucho.lucene;
import com.caucho.env.system.RootDirectorySystem;
import com.caucho.util.LruCache;
import io.baratine.core.ServiceManager;
import io.baratine.files.BfsFileSync;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.ConcurrentMergeScheduler;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.SimpleMergedSegmentWarmer;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TieredMergePolicy;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.SearcherFactory;
import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.MMapDirectory;
import org.apache.lucene.store.NRTCachingDirectory;
import org.apache.lucene.util.InfoStream;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.xml.sax.SAXException;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
//@Startup
//@ApplicationScoped
public class LuceneIndexBean extends SearcherFactory
{
private static final String externalKey = "__extKey__";
private static final String collectionKey = "__collectionKey__";
private static final String primaryKey = "__primary_key__";
private static final Set<String> fieldSet
= Collections.singleton(externalKey);
private final static LuceneIndexBean bean = new LuceneIndexBean();
private static Logger log = Logger.getLogger(LuceneIndexBean.class.getName());
private final static long softCommitMaxDocs = 16;
private final static long softCommitMaxAge = TimeUnit.SECONDS.toMillis(1);
private Directory _directory;
private IndexWriter _writer;
private AutoDetectParser _parser;
private String _indexDirectory;
@Inject
ServiceManager _manager;
private StandardAnalyzer _analyzer;
private double _maxMergeSizeMb = 4;
private double _maxCacheMb = 48;
private int _maxMergeAtOnce = 10;
private double _segmentsPerTier = 10;
private SearcherManager _searcherManager;
private AtomicBoolean _isInitialized = new AtomicBoolean(false);
private LruCache<String,Query> _queryCache = new LruCache<>(1024);
private AtomicLong _updateSequence = new AtomicLong();
private AtomicLong _searcherSequence = new AtomicLong();
private AtomicLong _notFoundCounter = new AtomicLong();
private long _lastUpdateSequence;
private long _softCommitMaxDocs = softCommitMaxDocs;
private long _softCommitMaxAge = softCommitMaxAge;
public LuceneIndexBean()
{
_parser = new AutoDetectParser();
}
public final static LuceneIndexBean getInstance()
{
return bean;
}
private ServiceManager getManager()
{
if (_manager == null)
_manager = ServiceManager.getCurrent();
return _manager;
}
@PostConstruct
public void init() throws IOException
{
if (!_isInitialized.compareAndSet(false, true))
return;
String baratineData
= RootDirectorySystem.getCurrentDataDirectory().getFullPath();
_indexDirectory = baratineData + File.separatorChar + "lucene";
initIndexWriter();
_searcherManager = new SearcherManager(getIndexWriter(), true, this);
log.finer("creating new " + this);
}
@Override
public IndexSearcher newSearcher(IndexReader reader,
IndexReader previousReader)
throws IOException
{
long v = _searcherSequence.incrementAndGet();
BaratineIndexSearcher searcher = new BaratineIndexSearcher(reader, v);
return searcher;
}
public AtomicLong getSearcherSequence()
{
return _searcherSequence;
}
private Term createPkTerm(String collection, String externalId)
{
return new Term(primaryKey, collection + ':' + externalId);
}
private StringField createPkField(String collection, String externalId)
{
return new StringField(primaryKey,
collection + ':' + externalId,
Field.Store.YES);
}
public boolean indexFile(String collection,
final String path)
{
if (log.isLoggable(Level.FINER))
log.finer(String.format("indexFile('%s')", path));
collection = escape(collection);
BfsFileSync file = getManager().lookup(path).as(BfsFileSync.class);
Field extId = new StringField(externalKey, path, Field.Store.YES);
StringField pkField = createPkField(collection, path);
Term pkTerm = createPkTerm(collection, path);
try (InputStream in = file.openRead()) {
indexStream(collection, in, extId, pkField, pkTerm);
return true;
} catch (IOException e) {
String message = String.format("failed to index file %1$s due to %2$s",
file.toString(),
e.toString());
log.log(Level.FINER, message, e);
throw LuceneException.create(e);
}
}
private boolean indexStream(String collection,
InputStream in,
Field extId,
Field pkField,
Term pkTerm)
{
try {
IndexWriter writer = getIndexWriter();
Document document = new Document();
document.add(extId);
document.add(pkField);
document.add(new StringField(collectionKey, collection, Field.Store.YES));
Metadata metadata = new Metadata();
LuceneContentHandler handler = new LuceneContentHandler(document);
_parser.parse(in, handler, metadata);
for (String name : metadata.names()) {
for (String value : metadata.getValues(name)) {
document.add(new TextField(name, value, Field.Store.NO));
}
}
//log.warning(String.format("indexing ('%1$s') ", pkTerm));
writer.updateDocument(pkTerm, document);
if (log.isLoggable(Level.FINER))
log.finer(String.format("indexing ('%1$s')->('%2$s') complete",
pkTerm, extId.stringValue()));
updateSequence();
return true;
} catch (IOException | SAXException e) {
log.log(Level.WARNING,
String.format("indexing ('%s') failed", extId.stringValue()), e);
throw LuceneException.create(e);
} catch (TikaException e) {
log.log(Level.WARNING,
String.format("indexing ('%s') failed", extId.stringValue()), e);
LuceneException le = LuceneException.create(e);
throw le;
}
}
public boolean indexText(String collection,
String id,
String text)
{
if (log.isLoggable(Level.FINER))
log.finer(String.format("indexText('%s')", id));
collection = escape(collection);
Field extId = new StringField(externalKey, id, Field.Store.YES);
Field pkField = createPkField(collection, id);
Term pkTerm = createPkTerm(collection, id);
ByteArrayInputStream stream
= new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
boolean result = indexStream(collection, stream, extId, pkField, pkTerm);
return result;
}
public boolean indexMap(String collection,
String id,
Map<String,Object> map) throws LuceneException
{
if (map.isEmpty()) {
log.fine(String.format("indexMap('%s') empty map", id));
return true;
}
collection = escape(collection);
if (log.isLoggable(Level.FINER))
log.finer(String.format("indexMap('%1$s') %2$s", id, map));
Field extId = new StringField(externalKey, id, Field.Store.YES);
Field pkField = createPkField(collection, id);
Term pkTerm = createPkTerm(collection, id);
try {
IndexWriter writer = getIndexWriter();
Document document = new Document();
document.add(extId);
document.add(pkField);
document.add(new StringField(collectionKey, collection, Field.Store.YES));
for (Map.Entry<String,Object> entry : map.entrySet()) {
document.add(makeIndexableField(entry.getKey(), entry.getValue()));
}
writer.updateDocument(pkTerm, document);
if (log.isLoggable(Level.FINER))
log.finer(String.format("indexing ('%s') complete", extId));
updateSequence();
return true;
} catch (IOException e) {
log.log(Level.WARNING, String.format("indexing ('%s') failed", extId), e);
throw LuceneException.create(e);
}
}
public LuceneEntry[] search(BaratineIndexSearcher searcher,
QueryParser queryParser,
String collection,
String query,
int limit)
{
if (log.isLoggable(Level.FINER))
log.finer(
String.format("search('%1$s', %2$s, %3$d)",
collection,
query,
limit));
try {
final String cacheKey = query + "::" + collection;
LuceneEntry[] results = searcher.get(cacheKey);
if (results != null)
return results;
Query q = _queryCache.get(cacheKey);
if (q == null) {
Query userQuery = queryParser.parse(query);
BooleanQuery bq = new BooleanQuery();
bq.add(userQuery, BooleanClause.Occur.MUST);
collection = escape(collection);
bq.add(new TermQuery(new Term(collectionKey, collection)),
BooleanClause.Occur.MUST);
q = bq;
_queryCache.put(cacheKey, q);
}
TopDocs docs = searcher.search(q, limit);
ScoreDoc[] scoreDocs = docs.scoreDocs;
results = new LuceneEntry[scoreDocs.length];
for (int i = 0; i < scoreDocs.length; i++) {
ScoreDoc doc = scoreDocs[i];
String key = searcher.externalId(doc.doc);
if (key == null) {
Document d = searcher.doc(doc.doc, fieldSet);
key = d.get(externalKey);
searcher.cacheExternalId(doc.doc, key);
}
LuceneEntry entry = new LuceneEntry(doc.doc,
doc.score,
key);
results[i] = entry;
}
if (results.length > 0) {
searcher.put(cacheKey, results);
}
else {
long notFound = _notFoundCounter.incrementAndGet();
if (notFound % 100 == 0) { //XXX: debug
//log.warning(String.format("search not found %1$d", notFound));
}
}
if (log.isLoggable(Level.FINER))
log.finer(
String.format("search('%1$s', %2$d with results %3$s)",
query,
limit,
Arrays.asList(results)));
if (log.isLoggable(Level.FINEST))
log.finest(
String.format("search('%1$s', %2$d with results %3$s, %4$s)",
query,
limit,
Arrays.asList(results),
searcher + "@" + System.identityHashCode(searcher))
+ ": ");
return results;
} catch (AlreadyClosedException e) {
log.log(Level.WARNING, String.format("%1$s searcher %2$s", e, searcher));
throw LuceneException.create(e);
} catch (Throwable t) {
log.log(Level.WARNING, t.getMessage(), t);
throw LuceneException.create(t);
} finally {
}
}
public boolean delete(String collection, final String id)
{
try {
if (log.isLoggable(Level.FINER))
log.finer(String.format("delete('%s')", id));
collection = escape(collection);
IndexWriter writer = getIndexWriter();
Term pk = createPkTerm(collection, id);
writer.deleteDocuments(pk);
if (log.isLoggable(Level.FINER))
log.finer(String.format("delete('%1$s'->'%2$s') complete",
pk, id));
updateSequence();
return true;
} catch (IOException e) {
log.log(Level.WARNING, e.getMessage(), e);
throw LuceneException.create(e);
}
}
public void commit() throws IOException
{
if (_writer != null && _writer.hasUncommittedChanges()) {
long delta = _lastUpdateSequence;
_lastUpdateSequence = _updateSequence.get();
delta = _lastUpdateSequence - delta;
if (log.isLoggable(Level.FINER))
log.log(Level.FINER,
String.format(
"commit delta: [%1$d], updateSequence [%2$s], searcherSequence [%3$s]",
delta,
_updateSequence,
_searcherSequence));
_writer.commit();
}
}
public boolean clear(QueryParser queryParser, String collection)
{
try {
if (log.isLoggable(Level.FINER))
log.finer(String.format("clear('%s')", collection));
collection = escape(collection);
IndexWriter writer = getIndexWriter();
Query query = queryParser.parse(collectionKey + ':' + collection);
writer.deleteDocuments(query);
if (log.isLoggable(Level.FINER))
log.finer(String.format("clear('%1$s') complete", query));
updateSequence();
return true;
} catch (IOException e) {
log.log(Level.WARNING, e.getMessage(), e);
throw LuceneException.create(e);
} catch (ParseException e) {
log.log(Level.WARNING, e.getMessage(), e);
throw LuceneException.create(e);
}
}
@Override
public String toString()
{
return this.getClass().getSimpleName() + '[' + _manager + ']';
}
private String escape(String collection)
{
StringBuilder builder = new StringBuilder();
char[] buffer = collection.toCharArray();
for (char c : buffer) {
switch (c) {
case '+':
case '-':
case '!':
case '(':
case ')':
case '{':
case '}':
case '[':
case ']':
case '^':
case '"':
case '~':
case '*':
case '?':
case ':':
case '\\': {
//XXX: escaping doesn't really work for some reason
break;
}
default: {
builder.append(c);
}
}
}
return builder.toString();
}
void release(BaratineIndexSearcher searcher) throws IOException
{
_searcherManager.release(searcher);
}
private void updateSequence()
{
_updateSequence.incrementAndGet();
}
AtomicBoolean _isUpdating = new AtomicBoolean();
public AtomicLong getUpdateSequence()
{
return _updateSequence;
}
public long getUpdatesCount()
{
return _updateSequence.get() - _lastUpdateSequence;
}
public BaratineIndexSearcher acquireSearcher() throws IOException
{
if (_searcherSequence.get() % 100 == 0)
log.log(Level.INFO, "acquireSearcher: " + _searcherSequence.get());
return (BaratineIndexSearcher) _searcherManager.acquire();
}
public void updateSearcher()
{
try {
_searcherManager.maybeRefresh();
} catch (Throwable e) {
log.log(Level.WARNING, e.getMessage(), e);
}
}
public long getSoftCommitMaxDocs()
{
return _softCommitMaxDocs;
}
public void setSoftCommitMaxDocs(long softCommitMaxDocs)
{
_softCommitMaxDocs = softCommitMaxDocs;
}
public long getSoftCommitMaxAge()
{
return _softCommitMaxAge;
}
public void setSoftCommitMaxAge(long softCommitMaxAge)
{
_softCommitMaxAge = softCommitMaxAge;
}
private IndexWriter getIndexWriter() throws IOException
{
return _writer;
}
private void initIndexWriter() throws IOException
{
Analyzer analyzer = new StandardAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
iwc.setMergedSegmentWarmer(
new SimpleMergedSegmentWarmer(new LoggingInfoStream(Level.FINER)));
iwc.setReaderPooling(true);
// iwc.setMergeScheduler(new SerialMergeScheduler());
ConcurrentMergeScheduler mergeScheduler = new ConcurrentMergeScheduler();
iwc.setMergeScheduler(mergeScheduler);
TieredMergePolicy mergePolicy = new TieredMergePolicy();
mergePolicy.setMaxMergeAtOnce(_maxMergeAtOnce);
mergePolicy.setSegmentsPerTier(_segmentsPerTier);
iwc.setMergePolicy(mergePolicy);
iwc.setInfoStream(new LoggingInfoStream(Level.FINER));
_writer = new IndexWriter(getDirectory(), iwc);
}
private Directory getDirectory() throws IOException
{
if (_directory == null)
_directory = createDirectory();
return _directory;
}
private Directory createDirectory() throws IOException
{
log.log(Level.FINER, "create new BfsDirectory");
//Directory directory = new BfsDirectory();
//Directory directory = new RAMDirectory();
Directory directory = MMapDirectory.open(getPath());
directory = new NRTCachingDirectory(directory,
_maxMergeSizeMb,
_maxCacheMb);
return directory;
}
private Path getPath() throws IOException
{
Path path = FileSystems.getDefault().getPath(_indexDirectory, "index");
return Files.createDirectories(path);
}
QueryParser createQueryParser()
{
if (_analyzer == null)
_analyzer = new StandardAnalyzer();
QueryParser queryParser = new QueryParser("text", _analyzer);
return queryParser;
}
private IndexableField makeIndexableField(String name, Object obj)
{
IndexableField field = null;
if (name == null) {
}
else if (obj == null) {
}
else {
field = new TextField(name, String.valueOf(obj), Field.Store.NO);
}
return field;
}
}
class LoggingInfoStream extends InfoStream
{
private final static Logger log
= Logger.getLogger(LoggingInfoStream.class.getName());
private final Level level;
public LoggingInfoStream(Level level)
{
this.level = level;
}
@Override
public void message(String component, String message)
{
log.log(level, component + ": " + message);
}
@Override
public boolean isEnabled(String component)
{
return log.isLoggable(level);
}
@Override
public void close() throws IOException
{
}
}
class BaratineIndexSearcher extends IndexSearcher
{
private final static Logger log
= Logger.getLogger(BaratineIndexSearcher.class.getName());
private LruCache<Integer,String> _keysCache
= new LruCache<>(8 * 1024);
private LruCache<String,LuceneEntry[]> _resultsCache = new LruCache<>(512);
private final long _version;
public BaratineIndexSearcher(IndexReader reader, long version)
{
super(reader);
setQueryCache(null);
_version = version;
}
public long getVersion()
{
return _version;
}
public String externalId(Integer key)
{
return _keysCache.get(key);
}
public void cacheExternalId(Integer key, String value)
{
_keysCache.put(key, value);
}
@Override
public String toString()
{
IndexReader reader = getIndexReader();
return "XIndexSearcher ["
+ reader.getClass().getSimpleName()
+ '@'
+ System.identityHashCode(reader)
+
']';
}
public LuceneEntry[] get(String cacheKey)
{
return _resultsCache.get(cacheKey);
}
public void put(String cacheKey, LuceneEntry[] results)
{
_resultsCache.put(cacheKey, results);
}
}
| service/src/main/java/com/caucho/lucene/LuceneIndexBean.java | package com.caucho.lucene;
import com.caucho.env.system.RootDirectorySystem;
import com.caucho.util.LruCache;
import io.baratine.core.ServiceManager;
import io.baratine.files.BfsFileSync;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.ConcurrentMergeScheduler;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.SimpleMergedSegmentWarmer;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TieredMergePolicy;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.SearcherFactory;
import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.MMapDirectory;
import org.apache.lucene.store.NRTCachingDirectory;
import org.apache.lucene.util.InfoStream;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.xml.sax.SAXException;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
//@Startup
//@ApplicationScoped
public class LuceneIndexBean extends SearcherFactory
{
private static final String externalKey = "__extKey__";
private static final String collectionKey = "__collectionKey__";
private static final String primaryKey = "__primary_key__";
private static final Set<String> fieldSet
= Collections.singleton(externalKey);
private final static LuceneIndexBean bean = new LuceneIndexBean();
private static Logger log = Logger.getLogger(LuceneIndexBean.class.getName());
private final static long softCommitMaxDocs = 16;
private final static long softCommitMaxAge = TimeUnit.SECONDS.toMillis(1);
private Directory _directory;
private IndexWriter _writer;
private AutoDetectParser _parser;
private String _indexDirectory;
@Inject
ServiceManager _manager;
private StandardAnalyzer _analyzer;
private double _maxMergeSizeMb = 4;
private double _maxCacheMb = 48;
private int _maxMergeAtOnce = 10;
private double _segmentsPerTier = 10;
private SearcherManager _searcherManager;
private AtomicBoolean _isInitialized = new AtomicBoolean(false);
private LruCache<String,Query> _queryCache = new LruCache<>(1024);
private LruCache<String,LuceneEntry[]> _resultsCache = new LruCache<>(512);
private AtomicLong _updateSequence = new AtomicLong();
private AtomicLong _searcherSequence = new AtomicLong();
private AtomicLong _notFoundCounter = new AtomicLong();
private long _lastUpdateSequence;
private long _softCommitMaxDocs = softCommitMaxDocs;
private long _softCommitMaxAge = softCommitMaxAge;
public LuceneIndexBean()
{
_parser = new AutoDetectParser();
}
public final static LuceneIndexBean getInstance()
{
return bean;
}
private ServiceManager getManager()
{
if (_manager == null)
_manager = ServiceManager.getCurrent();
return _manager;
}
@PostConstruct
public void init() throws IOException
{
if (!_isInitialized.compareAndSet(false, true))
return;
String baratineData
= RootDirectorySystem.getCurrentDataDirectory().getFullPath();
_indexDirectory = baratineData + File.separatorChar + "lucene";
initIndexWriter();
_searcherManager = new SearcherManager(getIndexWriter(), true, this);
log.finer("creating new " + this);
}
@Override
public IndexSearcher newSearcher(IndexReader reader,
IndexReader previousReader)
throws IOException
{
long v = _searcherSequence.incrementAndGet();
BaratineIndexSearcher searcher = new BaratineIndexSearcher(reader, v);
return searcher;
}
public AtomicLong getSearcherSequence()
{
return _searcherSequence;
}
private Term createPkTerm(String collection, String externalId)
{
return new Term(primaryKey, collection + ':' + externalId);
}
private StringField createPkField(String collection, String externalId)
{
return new StringField(primaryKey,
collection + ':' + externalId,
Field.Store.YES);
}
public boolean indexFile(String collection,
final String path)
{
if (log.isLoggable(Level.FINER))
log.finer(String.format("indexFile('%s')", path));
collection = escape(collection);
BfsFileSync file = getManager().lookup(path).as(BfsFileSync.class);
Field extId = new StringField(externalKey, path, Field.Store.YES);
StringField pkField = createPkField(collection, path);
Term pkTerm = createPkTerm(collection, path);
try (InputStream in = file.openRead()) {
indexStream(collection, in, extId, pkField, pkTerm);
return true;
} catch (IOException e) {
String message = String.format("failed to index file %1$s due to %2$s",
file.toString(),
e.toString());
log.log(Level.FINER, message, e);
throw LuceneException.create(e);
}
}
private boolean indexStream(String collection,
InputStream in,
Field extId,
Field pkField,
Term pkTerm)
{
try {
IndexWriter writer = getIndexWriter();
Document document = new Document();
document.add(extId);
document.add(pkField);
document.add(new StringField(collectionKey, collection, Field.Store.YES));
Metadata metadata = new Metadata();
LuceneContentHandler handler = new LuceneContentHandler(document);
_parser.parse(in, handler, metadata);
for (String name : metadata.names()) {
for (String value : metadata.getValues(name)) {
document.add(new TextField(name, value, Field.Store.NO));
}
}
//log.warning(String.format("indexing ('%1$s') ", pkTerm));
writer.updateDocument(pkTerm, document);
if (log.isLoggable(Level.FINER))
log.finer(String.format("indexing ('%1$s')->('%2$s') complete",
pkTerm, extId.stringValue()));
updateSequence();
return true;
} catch (IOException | SAXException e) {
log.log(Level.WARNING,
String.format("indexing ('%s') failed", extId.stringValue()), e);
throw LuceneException.create(e);
} catch (TikaException e) {
log.log(Level.WARNING,
String.format("indexing ('%s') failed", extId.stringValue()), e);
LuceneException le = LuceneException.create(e);
throw le;
}
}
public boolean indexText(String collection,
String id,
String text)
{
if (log.isLoggable(Level.FINER))
log.finer(String.format("indexText('%s')", id));
collection = escape(collection);
Field extId = new StringField(externalKey, id, Field.Store.YES);
Field pkField = createPkField(collection, id);
Term pkTerm = createPkTerm(collection, id);
ByteArrayInputStream stream
= new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
boolean result = indexStream(collection, stream, extId, pkField, pkTerm);
return result;
}
public boolean indexMap(String collection,
String id,
Map<String,Object> map) throws LuceneException
{
if (map.isEmpty()) {
log.fine(String.format("indexMap('%s') empty map", id));
return true;
}
collection = escape(collection);
if (log.isLoggable(Level.FINER))
log.finer(String.format("indexMap('%1$s') %2$s", id, map));
Field extId = new StringField(externalKey, id, Field.Store.YES);
Field pkField = createPkField(collection, id);
Term pkTerm = createPkTerm(collection, id);
try {
IndexWriter writer = getIndexWriter();
Document document = new Document();
document.add(extId);
document.add(pkField);
document.add(new StringField(collectionKey, collection, Field.Store.YES));
for (Map.Entry<String,Object> entry : map.entrySet()) {
document.add(makeIndexableField(entry.getKey(), entry.getValue()));
}
writer.updateDocument(pkTerm, document);
if (log.isLoggable(Level.FINER))
log.finer(String.format("indexing ('%s') complete", extId));
updateSequence();
return true;
} catch (IOException e) {
log.log(Level.WARNING, String.format("indexing ('%s') failed", extId), e);
throw LuceneException.create(e);
}
}
public LuceneEntry[] search(BaratineIndexSearcher searcher,
QueryParser queryParser,
String collection,
String query,
int limit)
{
if (log.isLoggable(Level.FINER))
log.finer(
String.format("search('%1$s', %2$s, %3$d)",
collection,
query,
limit));
try {
final String cacheKey = query + "::" + collection;
LuceneEntry[] results = _resultsCache.get(cacheKey);
if (results != null)
return results;
Query q = _queryCache.get(cacheKey);
if (q == null) {
Query userQuery = queryParser.parse(query);
BooleanQuery bq = new BooleanQuery();
bq.add(userQuery, BooleanClause.Occur.MUST);
collection = escape(collection);
bq.add(new TermQuery(new Term(collectionKey, collection)),
BooleanClause.Occur.MUST);
q = bq;
_queryCache.put(cacheKey, q);
}
TopDocs docs = searcher.search(q, limit);
ScoreDoc[] scoreDocs = docs.scoreDocs;
results = new LuceneEntry[scoreDocs.length];
for (int i = 0; i < scoreDocs.length; i++) {
ScoreDoc doc = scoreDocs[i];
String key = searcher.externalId(doc.doc);
if (key == null) {
Document d = searcher.doc(doc.doc, fieldSet);
key = d.get(externalKey);
searcher.cacheExternalId(doc.doc, key);
}
LuceneEntry entry = new LuceneEntry(doc.doc,
doc.score,
key);
results[i] = entry;
}
if (results.length > 0) {
_resultsCache.put(cacheKey, results);
}
else {
long notFound = _notFoundCounter.incrementAndGet();
if (notFound % 100 == 0) { //XXX: debug
//log.warning(String.format("search not found %1$d", notFound));
}
}
if (log.isLoggable(Level.FINER))
log.finer(
String.format("search('%1$s', %2$d with results %3$s)",
query,
limit,
Arrays.asList(results)));
if (log.isLoggable(Level.FINEST))
log.finest(
String.format("search('%1$s', %2$d with results %3$s, %4$s)",
query,
limit,
Arrays.asList(results),
searcher + "@" + System.identityHashCode(searcher))
+ ": ");
return results;
} catch (AlreadyClosedException e) {
log.log(Level.WARNING, String.format("%1$s searcher %2$s", e, searcher));
throw LuceneException.create(e);
} catch (Throwable t) {
log.log(Level.WARNING, t.getMessage(), t);
throw LuceneException.create(t);
} finally {
}
}
public boolean delete(String collection, final String id)
{
try {
if (log.isLoggable(Level.FINER))
log.finer(String.format("delete('%s')", id));
collection = escape(collection);
IndexWriter writer = getIndexWriter();
Term pk = createPkTerm(collection, id);
writer.deleteDocuments(pk);
if (log.isLoggable(Level.FINER))
log.finer(String.format("delete('%1$s'->'%2$s') complete",
pk, id));
updateSequence();
return true;
} catch (IOException e) {
log.log(Level.WARNING, e.getMessage(), e);
throw LuceneException.create(e);
}
}
public void commit() throws IOException
{
if (_writer != null && _writer.hasUncommittedChanges()) {
long delta = _lastUpdateSequence;
_lastUpdateSequence = _updateSequence.get();
delta = _lastUpdateSequence - delta;
if (log.isLoggable(Level.FINER))
log.log(Level.FINER,
String.format(
"commit delta: [%1$d], updateSequence [%2$s], searcherSequence [%3$s]",
delta,
_updateSequence,
_searcherSequence));
_writer.commit();
_resultsCache.clear();
}
}
public boolean clear(QueryParser queryParser, String collection)
{
try {
if (log.isLoggable(Level.FINER))
log.finer(String.format("clear('%s')", collection));
collection = escape(collection);
IndexWriter writer = getIndexWriter();
Query query = queryParser.parse(collectionKey + ':' + collection);
writer.deleteDocuments(query);
if (log.isLoggable(Level.FINER))
log.finer(String.format("clear('%1$s') complete", query));
updateSequence();
return true;
} catch (IOException e) {
log.log(Level.WARNING, e.getMessage(), e);
throw LuceneException.create(e);
} catch (ParseException e) {
log.log(Level.WARNING, e.getMessage(), e);
throw LuceneException.create(e);
}
}
@Override
public String toString()
{
return this.getClass().getSimpleName() + '[' + _manager + ']';
}
private String escape(String collection)
{
StringBuilder builder = new StringBuilder();
char[] buffer = collection.toCharArray();
for (char c : buffer) {
switch (c) {
case '+':
case '-':
case '!':
case '(':
case ')':
case '{':
case '}':
case '[':
case ']':
case '^':
case '"':
case '~':
case '*':
case '?':
case ':':
case '\\': {
//XXX: escaping doesn't really work for some reason
break;
}
default: {
builder.append(c);
}
}
}
return builder.toString();
}
void release(BaratineIndexSearcher searcher) throws IOException
{
_searcherManager.release(searcher);
}
private void updateSequence()
{
_updateSequence.incrementAndGet();
}
AtomicBoolean _isUpdating = new AtomicBoolean();
public AtomicLong getUpdateSequence()
{
return _updateSequence;
}
public long getUpdatesCount()
{
return _updateSequence.get() - _lastUpdateSequence;
}
public BaratineIndexSearcher acquireSearcher() throws IOException
{
if (_searcherSequence.get() % 100 == 0)
log.log(Level.INFO, "acquireSearcher: " + _searcherSequence.get());
return (BaratineIndexSearcher) _searcherManager.acquire();
}
public void updateSearcher()
{
try {
_searcherManager.maybeRefresh();
} catch (Throwable e) {
log.log(Level.WARNING, e.getMessage(), e);
}
}
public long getSoftCommitMaxDocs()
{
return _softCommitMaxDocs;
}
public void setSoftCommitMaxDocs(long softCommitMaxDocs)
{
_softCommitMaxDocs = softCommitMaxDocs;
}
public long getSoftCommitMaxAge()
{
return _softCommitMaxAge;
}
public void setSoftCommitMaxAge(long softCommitMaxAge)
{
_softCommitMaxAge = softCommitMaxAge;
}
private IndexWriter getIndexWriter() throws IOException
{
return _writer;
}
private void initIndexWriter() throws IOException
{
Analyzer analyzer = new StandardAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
iwc.setMergedSegmentWarmer(
new SimpleMergedSegmentWarmer(new LoggingInfoStream(Level.FINER)));
iwc.setReaderPooling(true);
// iwc.setMergeScheduler(new SerialMergeScheduler());
ConcurrentMergeScheduler mergeScheduler = new ConcurrentMergeScheduler();
iwc.setMergeScheduler(mergeScheduler);
TieredMergePolicy mergePolicy = new TieredMergePolicy();
mergePolicy.setMaxMergeAtOnce(_maxMergeAtOnce);
mergePolicy.setSegmentsPerTier(_segmentsPerTier);
iwc.setMergePolicy(mergePolicy);
iwc.setInfoStream(new LoggingInfoStream(Level.FINER));
_writer = new IndexWriter(getDirectory(), iwc);
}
private Directory getDirectory() throws IOException
{
if (_directory == null)
_directory = createDirectory();
return _directory;
}
private Directory createDirectory() throws IOException
{
log.log(Level.FINER, "create new BfsDirectory");
//Directory directory = new BfsDirectory();
//Directory directory = new RAMDirectory();
Directory directory = MMapDirectory.open(getPath());
directory = new NRTCachingDirectory(directory,
_maxMergeSizeMb,
_maxCacheMb);
return directory;
}
private Path getPath() throws IOException
{
Path path = FileSystems.getDefault().getPath(_indexDirectory, "index");
return Files.createDirectories(path);
}
QueryParser createQueryParser()
{
if (_analyzer == null)
_analyzer = new StandardAnalyzer();
QueryParser queryParser = new QueryParser("text", _analyzer);
return queryParser;
}
private IndexableField makeIndexableField(String name, Object obj)
{
IndexableField field = null;
if (name == null) {
}
else if (obj == null) {
}
else {
field = new TextField(name, String.valueOf(obj), Field.Store.NO);
}
return field;
}
}
class LoggingInfoStream extends InfoStream
{
private final static Logger log
= Logger.getLogger(LoggingInfoStream.class.getName());
private final Level level;
public LoggingInfoStream(Level level)
{
this.level = level;
}
@Override
public void message(String component, String message)
{
log.log(level, component + ": " + message);
}
@Override
public boolean isEnabled(String component)
{
return log.isLoggable(level);
}
@Override
public void close() throws IOException
{
}
}
class BaratineIndexSearcher extends IndexSearcher
{
private final static Logger log
= Logger.getLogger(BaratineIndexSearcher.class.getName());
private LruCache<Integer,String> _keysCache
= new LruCache<>(8 * 1024);
private final long _version;
public BaratineIndexSearcher(IndexReader reader, long version)
{
super(reader);
setQueryCache(null);
_version = version;
}
public long getVersion()
{
return _version;
}
public String externalId(Integer key)
{
return _keysCache.get(key);
}
public void cacheExternalId(Integer key, String value)
{
_keysCache.put(key, value);
}
@Override
public String toString()
{
IndexReader reader = getIndexReader();
return "XIndexSearcher ["
+ reader.getClass().getSimpleName()
+ '@'
+ System.identityHashCode(reader)
+
']';
}
}
| caching updates
| service/src/main/java/com/caucho/lucene/LuceneIndexBean.java | caching updates | <ide><path>ervice/src/main/java/com/caucho/lucene/LuceneIndexBean.java
<ide>
<ide> private LruCache<String,Query> _queryCache = new LruCache<>(1024);
<ide>
<del> private LruCache<String,LuceneEntry[]> _resultsCache = new LruCache<>(512);
<del>
<ide> private AtomicLong _updateSequence = new AtomicLong();
<ide> private AtomicLong _searcherSequence = new AtomicLong();
<ide>
<ide> try {
<ide> final String cacheKey = query + "::" + collection;
<ide>
<del> LuceneEntry[] results = _resultsCache.get(cacheKey);
<add> LuceneEntry[] results = searcher.get(cacheKey);
<ide>
<ide> if (results != null)
<ide> return results;
<ide> }
<ide>
<ide> if (results.length > 0) {
<del> _resultsCache.put(cacheKey, results);
<add> searcher.put(cacheKey, results);
<ide> }
<ide> else {
<ide> long notFound = _notFoundCounter.incrementAndGet();
<ide> _searcherSequence));
<ide>
<ide> _writer.commit();
<del>
<del> _resultsCache.clear();
<ide> }
<ide> }
<ide>
<ide> private LruCache<Integer,String> _keysCache
<ide> = new LruCache<>(8 * 1024);
<ide>
<add> private LruCache<String,LuceneEntry[]> _resultsCache = new LruCache<>(512);
<add>
<ide> private final long _version;
<ide>
<ide> public BaratineIndexSearcher(IndexReader reader, long version)
<ide> +
<ide> ']';
<ide> }
<add>
<add> public LuceneEntry[] get(String cacheKey)
<add> {
<add> return _resultsCache.get(cacheKey);
<add> }
<add>
<add> public void put(String cacheKey, LuceneEntry[] results)
<add> {
<add> _resultsCache.put(cacheKey, results);
<add> }
<ide> } |
|
JavaScript | mpl-2.0 | 39c9df0cd23f3b1dd0fb6aa23fe8e9d52f7cca9e | 0 | asamuzaK/sidebarTabs,asamuzaK/sidebarTabs | /* sidebar.js */
"use strict";
{
/* api */
const {
bookmarks, contextualIdentities, i18n, management, sessions, storage, tabs,
windows,
} = browser;
/* constants */
const ACTIVE = "active";
const AUDIBLE = "audible";
const AUDIO_MUTE = "muteAudio";
const AUDIO_MUTE_UNMUTE = "unmuteAudio";
const CLASS_MENU = "menu";
const CLASS_TAB = "tab";
const CLASS_TAB_AUDIO = "tab-audio";
const CLASS_TAB_AUDIO_ICON = "tab-audio-icon";
const CLASS_TAB_CLOSE = "tab-close";
const CLASS_TAB_CLOSE_ICON = "tab-close-icon";
const CLASS_TAB_COLLAPSED = "tab-collapsed";
const CLASS_TAB_CONTAINER = "tab-container";
const CLASS_TAB_CONTAINER_TMPL = "tab-container-template";
const CLASS_TAB_CONTENT = "tab-content";
const CLASS_TAB_CONTEXT = "tab-context";
const CLASS_TAB_GROUP = "tab-group";
const CLASS_TAB_ICON = "tab-icon";
const CLASS_TAB_TITLE = "tab-title";
const CLASS_TAB_TMPL = "tab-template";
const CLASS_TAB_TOGGLE_ICON = "tab-toggle-icon";
const CLASS_THEME_DARK = "dark-theme";
const CLASS_THEME_LIGHT = "light-theme";
const CONNECTING = "connecting";
const MENU = "sidebar-tabs-menu";
const MENU_SIDEBAR_INIT = "sidebar-tabs-menu-sidebar-init";
const MENU_TAB = "sidebar-tabs-menu-tab";
const MENU_TABS_BOOKMARK_ALL = "sidebar-tabs-menu-tabs-bookmark-all";
const MENU_TABS_RELOAD_ALL = "sidebar-tabs-menu-tabs-reload-all";
const MENU_TAB_AUDIO = "sidebar-tabs-menu-tab-audio";
const MENU_TAB_CLOSE = "sidebar-tabs-menu-tab-close";
const MENU_TAB_CLOSE_UNDO = "sidebar-tabs-menu-tab-close-undo";
const MENU_TAB_GROUP = "sidebar-tabs-menu-tab-group";
const MENU_TAB_GROUP_COLLAPSE = "sidebar-tabs-menu-tab-group-collapse";
const MENU_TAB_GROUP_RELOAD = "sidebar-tabs-menu-tab-group-reload";
const MENU_TAB_GROUP_UNGROUP = "sidebar-tabs-menu-tab-group-ungroup";
const MENU_TAB_NEW_WIN_MOVE = "sidebar-tabs-menu-tab-new-win-move";
const MENU_TAB_PIN = "sidebar-tabs-menu-tab-pin";
const MENU_TAB_RELOAD = "sidebar-tabs-menu-tab-reload";
const MENU_TAB_TABS_CLOSE_END = "sidebar-tabs-menu-tab-close-end";
const MENU_TAB_TABS_CLOSE_OTHER = "sidebar-tabs-menu-tab-close-other";
const MENU_THEME_DARK = "sidebar-tabs-menu-sidebar-theme-dark";
const MENU_THEME_DEFAULT = "sidebar-tabs-menu-sidebar-theme-default";
const MENU_THEME_LIGHT = "sidebar-tabs-menu-sidebar-theme-light";
const MENU_THEME_SELECT = "sidebar-tabs-menu-sidebar-theme-select";
const MIME_TYPE = "text/plain";
const MOUSE_BUTTON_RIGHT = 2;
const NEW_TAB = "newtab";
const NEW_WIN_MOVE = "moveToNewWindow";
const PINNED = "pinned";
const SIDEBAR_INIT = "initSidebar";
const TAB = "tab";
const TABS_BOOKMARK_ALL = "bookmarkAllTabs";
const TABS_CLOSE_END = "closeTabsToTheEnd";
const TABS_CLOSE_OTHER = "closeOtherTabs";
const TABS_RELOAD_ALL = "reloadAllTabs";
const TAB_CLOSE = "closeTab";
const TAB_CLOSE_UNDO = "undoCloseTab";
const TAB_GROUP = "groupTabs";
const TAB_GROUP_COLLAPSE = "collapseTabs";
const TAB_GROUP_EXPAND = "expandTabs";
const TAB_GROUP_RELOAD = "reloadGroupTabs";
const TAB_GROUP_UNGROUP = "ungroupTabs";
const TAB_PIN = "pinTab";
const TAB_PIN_UNPIN = "unpinTab";
const TAB_RELOAD = "reloadTab";
const THEME = "theme";
const THEME_DARK = "darkTheme";
const THEME_DARK_ID = "[email protected]@personas.mozilla.org";
const THEME_DEFAULT = "defaultTheme";
const THEME_LIGHT = "lightTheme";
const THEME_LIGHT_ID =
"[email protected]@personas.mozilla.org";
const THEME_SELECT = "selectTheme";
const TYPE_FROM = 8;
const TYPE_TO = -1;
const URL_AUDIO_MUTED = "../shared/tab-audio-muted.svg";
const URL_AUDIO_PLAYING = "../shared/tab-audio-playing.svg";
const URL_CONNECTING_SPINNER = "../img/spinner.svg#connecting";
const URL_DEFAULT_FAVICON = "../shared/defaultFavicon.svg";
const URL_LOADING_SPINNER = "../img/spinner.svg";
const TAB_QUERY = `.${CLASS_TAB}:not(.${CLASS_MENU}):not(.${NEW_TAB})`;
/**
* log error
* @param {!Object} e - Error
* @returns {boolean} - false
*/
const logError = e => {
console.error(e);
return false;
};
/**
* log warn
* @param {*} msg - message
* @returns {boolean} - false
*/
const logWarn = msg => {
console.warn(msg);
return false;
};
/**
* get type
* @param {*} o - object to check
* @returns {string} - type of object
*/
const getType = o =>
Object.prototype.toString.call(o).slice(TYPE_FROM, TYPE_TO);
/**
* is string
* @param {*} o - object to check
* @returns {boolean} - result
*/
const isString = o => typeof o === "string" || o instanceof String;
/**
* is object, and not an empty object
* @param {*} o - object to check;
* @returns {boolean} - result
*/
const isObjectNotEmpty = o => {
const items = /Object/i.test(getType(o)) && Object.keys(o);
return !!(items && items.length);
};
/**
* compare url string
* @param {string} url1 - URL
* @param {string} url2 - URL
* @param {boolean} query - compare query string too or not
* @param {boolean} frag - compare fragment identifier string too or not
* @returns {boolean} - result
*/
const isUrlEqual = (url1, url2, query = false, frag = false) => {
url1 = new URL(url1);
url2 = new URL(url2);
return url1.origin === url2.origin && url1.pathname === url2.pathname &&
(!query || url1.search === url2.search) &&
(!frag || url1.hash === url2.hash);
};
/* sidebar */
const sidebar = {
incognito: false,
windowId: null,
context: null,
lastClosedTab: null,
};
/**
* set sidebar
* @returns {void}
*/
const setSidebar = async () => {
const win = await windows.getCurrent({
populate: true,
windowTypes: ["normal"],
});
if (win) {
const {focused, id, incognito} = win;
if (focused) {
sidebar.incognito = incognito;
sidebar.windowId = id;
}
}
};
/**
* store data
* @param {Object} data - data to store
* @returns {?AsyncFunction} - storage.local.set()
*/
const storeData = async data => {
let func;
if (isObjectNotEmpty(data)) {
func = storage.local.set(data);
}
return func || null;
};
/**
* get theme
* @returns {Array} - theme class list
*/
const getTheme = async () => {
const {theme: storedTheme} = await storage.local.get(THEME);
let theme = [];
if (Array.isArray(storedTheme) && storedTheme.length) {
theme = storedTheme;
} else if (management) {
const items = await management.getAll().then(arr => arr.filter(info =>
info.type && info.type === "theme" && info.enabled && info
));
if (Array.isArray(items) && items.length) {
for (const item of items) {
const {id} = item;
switch (id) {
case THEME_DARK_ID:
theme.push(THEME_DARK);
break;
case THEME_LIGHT_ID:
theme.push(THEME_LIGHT);
break;
default:
}
}
}
!theme.length && theme.push(THEME_DEFAULT);
}
return theme;
};
/**
* set theme
* @param {Array} theme - array of theme
* @returns {void}
*/
const setTheme = async theme => {
if (!Array.isArray(theme)) {
throw new TypeError(`Expected Array but got ${getType(theme)}.`);
}
const elm = document.querySelector("body");
const {classList} = elm;
for (const item of theme) {
switch (item) {
case THEME_DARK:
classList.remove(CLASS_THEME_LIGHT);
classList.add(CLASS_THEME_DARK);
break;
case THEME_DEFAULT:
classList.remove(CLASS_THEME_DARK);
classList.remove(CLASS_THEME_LIGHT);
break;
case THEME_LIGHT:
classList.remove(CLASS_THEME_DARK);
classList.add(CLASS_THEME_LIGHT);
break;
default:
}
}
await storeData({
[THEME]: theme,
});
};
/**
* init sidebar
* @param {boolean} bool - bypass cache
* @returns {void}
*/
const initSidebar = async (bool = false) => {
await storage.local.clear();
window.location.reload(bool);
};
/* handle real tabs */
/**
* create tab
* @param {Object} opt - options
* @returns {AsyncFunction} - tabs.create()
*/
const createTab = async (opt = {}) => {
opt = isObjectNotEmpty(opt) && opt || null;
return tabs.create(opt);
};
/**
* update tab
* @param {number} tabId - tab ID
* @param {Object} opt - options
* @returns {AsyncFunction} - tabs.update()
*/
const updateTab = async (tabId, opt = {}) => {
if (!Number.isInteger(tabId)) {
throw new TypeError(`Expected Number but got ${getType(tabId)}.`);
}
opt = isObjectNotEmpty(opt) && opt || null;
return tabs.update(tabId, opt);
};
/**
* move tab
* @param {number} tabId - tab ID
* @param {Object} opt - options
* @returns {AsyncFunction} - tabs.move();
*/
const moveTab = async (tabId, opt = {}) => {
if (!Number.isInteger(tabId)) {
throw new TypeError(`Expected Number but got ${getType(tabId)}.`);
}
opt = isObjectNotEmpty(opt) && opt || null;
return tabs.move(tabId, opt);
};
/**
* reload tab
* @param {number} tabId - tab ID
* @param {Object} opt - options
* @returns {AsyncFunction} - tabs.reload()
*/
const reloadTab = async (tabId, opt = {}) => {
if (!Number.isInteger(tabId)) {
throw new TypeError(`Expected Number but got ${getType(tabId)}.`);
}
opt = isObjectNotEmpty(opt) && opt || null;
return tabs.reload(tabId, opt);
};
/**
* remove tab
* @param {number|Array} arg - tab ID or array of tab ID
* @returns {AsyncFunction} - tabs.remove()
*/
const removeTab = async arg => {
if (Number.isInteger(arg)) {
arg = [arg];
}
if (!Array.isArray(arg)) {
throw new TypeError(`Expected Array but got ${getType(arg)}.`);
}
return tabs.remove(arg);
};
/**
* bookmark tab
* @param {Object} opt - options
* @returns {AsyncFunction} - bookmarks.create()
*/
const bookmarkTab = async (opt = {}) => {
opt = isObjectNotEmpty(opt) && opt || null;
return bookmarks.create(opt);
};
/**
* create new window
* @param {Object} opt - options
* @returns {AsyncFunction} - windows.create();
*/
const createNewWindow = async (opt = {}) => {
opt = isObjectNotEmpty(opt) && opt || null;
return windows.create(opt);
};
/**
* get last closed tab
* @returns {Object} - tabs.Tab
*/
const getLastClosedTab = async () => {
const session = await sessions.getRecentlyClosed();
let tab;
if (Array.isArray(session) && session.length) {
const {windowId} = sidebar;
for (const item of session) {
const {tab: itemTab} = item;
if (itemTab) {
const {windowId: itemWindowId} = itemTab;
if (itemWindowId === windowId) {
tab = itemTab;
sidebar.lastClosedTab = tab;
break;
}
}
}
}
return tab || null;
};
/**
* restore tab
* @param {string} sessionId - session ID
* @returns {AsyncFunction} - sessions.restore()
*/
const restoreClosedTab = async sessionId => {
if (!isString(sessionId)) {
throw new TypeError(`Expected String but got ${getType(sessionId)}.`);
}
return sessions.restore(sessionId);
};
/* sidebar tabs */
/**
* get template
* @param {string} id - template ID
* @returns {Object} - document fragment
*/
const getTemplate = id => {
const tmpl = document.getElementById(id);
const {content: {firstElementChild}} = tmpl;
return document.importNode(firstElementChild, true);
};
/**
* create new tab
* @returns {AsyncFunction} - createTab()
*/
const createNewTab = async () => createTab({windowId: sidebar.windowId});
/**
* add new tab click listener
* @returns {void}
*/
const addNewTabClickListener = async () => {
const newTab = document.getElementById(NEW_TAB);
newTab.addEventListener("click", evt => createNewTab(evt).catch(logError));
};
/**
* get sidebar tab container from parent node
* @param {Object} node - node
* @returns {Object} - sidebar tab container
*/
const getSidebarTabContainer = node => {
const root = document.documentElement;
let tab;
while (node && node.parentNode && node.parentNode !== root) {
const {classList, parentNode} = node;
if (classList.contains(CLASS_TAB_CONTAINER)) {
tab = node;
break;
}
node = parentNode;
}
return tab || null;
};
/**
* get sidebar tab from parent node
* @param {Object} node - node
* @returns {Object} - sidebar tab
*/
const getSidebarTab = node => {
const root = document.documentElement;
let tab;
while (node && node.parentNode && node.parentNode !== root) {
const {dataset, parentNode} = node;
if (dataset.tabId) {
tab = node;
break;
}
node = parentNode;
}
return tab || null;
};
/**
* get sidebar tab ID
* @param {Object} node - node
* @returns {?number} - tab ID
*/
const getSidebarTabId = node => {
const root = document.documentElement;
let tabId;
while (node && node.parentNode && node.parentNode !== root) {
const {dataset, parentNode} = node;
if (dataset.tabId) {
tabId = dataset.tabId * 1;
break;
}
node = parentNode;
}
return tabId || null;
};
/**
* get sidebar tab index
* @param {Object} tab - tab
* @returns {?number} - index
*/
const getSidebarTabIndex = tab => {
let index;
if (tab && tab.nodeType === Node.ELEMENT_NODE) {
const items = document.querySelectorAll(TAB_QUERY);
const l = items.length;
let i = 0;
while (i < l && !index) {
if (items[i] === tab) {
index = i;
break;
}
i++;
}
}
return Number.isInteger(index) ?
index :
null;
};
/**
* activate tab
* @param {!Object} evt - event
* @returns {?AsyncFunction} - tabs.update()
*/
const activateTab = async evt => {
const {target} = evt;
const tabId = await getSidebarTabId(target);
let func;
if (Number.isInteger(tabId)) {
const active = true;
func = updateTab(tabId, {active});
}
return func || null;
};
/**
* add sidebar tab click listener
* @param {Object} elm - element
* @returns {void}
*/
const addTabClickListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("click", evt => activateTab(evt).catch(logError));
}
};
/**
* create tab data
* @returns {Array} - tab data
*/
const createTabData = async () => {
const items = document.querySelectorAll(TAB_QUERY);
const tab = [];
for (const item of items) {
const tabsTab = item.dataset && item.dataset.tab &&
JSON.parse(item.dataset.tab);
const {url} = tabsTab;
tab.push(url);
}
return tab;
};
/**
* create tab group data
* @returns {Array} - tab group data
*/
const createTabGroupData = async () => {
const items = document.querySelectorAll(
`.${CLASS_TAB_CONTAINER}.${CLASS_TAB_GROUP}:not(.${PINNED})`
);
const group = [];
for (const item of items) {
const {children} = item;
const arr = [];
for (const child of children) {
const index = getSidebarTabIndex(child);
Number.isInteger(index) && arr.push(index);
}
arr.length && group.push(arr);
}
return group;
};
/**
* store tab data
* @returns {AsyncFunction} - storeData()
*/
const storeTabData = async () => {
const tab = await createTabData() || [];
const group = await createTabGroupData() || [];
return storeData({
[TAB]: {
tab, group,
},
});
};
/* sidebar tab content */
/**
* tab icon fallback
* @param {!Object} evt - event
* @returns {boolean} - false
*/
const tabIconFallback = evt => {
const {target} = evt;
target.hasOwnProperty("src") && (target.src = URL_DEFAULT_FAVICON);
return false;
};
/**
* add tab icon error listener
* @param {Object} elm - img element
* @returns {void}
*/
const addTabIconErrorListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("error", tabIconFallback);
}
};
/**
* set favicon
* @param {Object} elm - img element
* @param {string} favIconUrl - favicon url
* @returns {void}
*/
const setFavicon = async (elm, favIconUrl) => {
if (elm && elm.nodeType === Node.ELEMENT_NODE && elm.localName === "img" &&
isString(favIconUrl)) {
elm.src = await fetch(favIconUrl).then(res => {
let url;
if (res.ok) {
url = favIconUrl;
} else {
url = URL_DEFAULT_FAVICON;
}
return url;
}).catch(e => {
console.error(e);
return URL_DEFAULT_FAVICON;
});
}
};
/**
* set tab icon
* @param {Object} elm - img element
* @param {Object} info - tab info
* @returns {?AsyncFunction} - setFavicon()
*/
const setTabIcon = (elm, info) => {
let func;
if (elm && elm.nodeType === Node.ELEMENT_NODE && elm.localName === "img") {
const {status, title, favIconUrl} = info;
const connectText = i18n.getMessage(CONNECTING);
if (status === "loading") {
if (title === connectText) {
elm.src = URL_CONNECTING_SPINNER;
} else {
elm.src = URL_LOADING_SPINNER;
}
} else if (status === "complete") {
if (favIconUrl) {
func = setFavicon(elm, favIconUrl);
} else {
elm.src = URL_DEFAULT_FAVICON;
}
} else {
elm.src = URL_DEFAULT_FAVICON;
}
}
return func || null;
};
/* sidebar tab audio */
/**
* toggle audio state
* @param {!Object} evt - event
* @returns {?AsyncFunction} - tabs.update()
*/
const toggleAudio = async evt => {
const {target} = evt;
const tabId = await getSidebarTabId(target);
let func;
if (Number.isInteger(tabId)) {
const tab = document.querySelector(`[data-tab-id="${tabId}"]`);
if (tab) {
const tabsTab = JSON.parse(tab.dataset.tab);
const {mutedInfo: {muted}} = tabsTab;
func = updateTab(tabId, {muted: !muted});
}
}
return func || null;
};
/**
* add tab audio click event listener
* @param {Object} elm - element
* @returns {void}
*/
const addTabAudioClickListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("click", evt => toggleAudio(evt).catch(logError));
}
};
/**
* set tab audio
* @param {Object} elm - element
* @param {Object} info - audio info
* @returns {void}
*/
const setTabAudio = async (elm, info) => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
const {audible, muted} = info;
if (muted) {
elm.title = i18n.getMessage(`${AUDIO_MUTE_UNMUTE}_tooltip`);
} else if (audible) {
elm.title = i18n.getMessage(`${AUDIO_MUTE}_tooltip`);
} else {
elm.title = "";
}
}
};
/**
* set tab audio icon
* @param {Object} elm - element
* @param {Object} info - audio info
* @returns {void}
*/
const setTabAudioIcon = async (elm, info) => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
const {audible, muted} = info;
if (muted) {
elm.alt = i18n.getMessage(`${AUDIO_MUTE_UNMUTE}`);
elm.src = URL_AUDIO_MUTED;
} else if (audible) {
elm.alt = i18n.getMessage(`${AUDIO_MUTE}`);
elm.src = URL_AUDIO_PLAYING;
} else {
elm.alt = "";
elm.src = "";
}
}
};
/* close button */
/**
* close tab
* @param {!Object} evt - event
* @returns {?AsyncFunction} - removeTab()
*/
const closeTab = async evt => {
const {target} = evt;
const tabId = await getSidebarTabId(target);
let func;
if (Number.isInteger(tabId)) {
func = removeTab(tabId);
}
return func || null;
};
/**
* add tab close click listener
* @param {Object} elm - element
* @returns {void}
*/
const addTabCloseClickListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("click", evt => closeTab(evt).catch(logError));
}
};
/* tab group */
/**
* toggle tab collapsed
* @param {!Object} evt - event
* @returns {?AsyncFunction} - activateTab()
*/
const toggleTabCollapsed = async evt => {
const {target} = evt;
const container = await getSidebarTabContainer(target);
let func;
if (container) {
const {firstElementChild: tab} = container;
const {firstElementChild: tabContext} = tab;
const {firstElementChild: toggleIcon} = tabContext;
if (container.classList.contains(CLASS_TAB_GROUP) &&
tab && tab.style.display !== "none") {
container.classList.toggle(CLASS_TAB_COLLAPSED);
if (container.classList.contains(CLASS_TAB_COLLAPSED)) {
tabContext.title = i18n.getMessage(`${TAB_GROUP_EXPAND}_tooltip`);
toggleIcon.alt = i18n.getMessage(`${TAB_GROUP_EXPAND}`);
} else {
tabContext.title = i18n.getMessage(`${TAB_GROUP_COLLAPSE}_tooltip`);
toggleIcon.alt = i18n.getMessage(`${TAB_GROUP_COLLAPSE}`);
}
func = activateTab({target: tab});
}
}
return func || null;
};
/**
* add tab context click listener
* @param {Object} elm - element
* @returns {void}
*/
const addTabContextClickListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("click", evt => toggleTabCollapsed(evt));
}
};
/**
* ungroup tabs
* @param {Object} node - tab group container
* @returns {void}
*/
const ungroupTabs = async (node = {}) => {
const {id, classList, nodeType, parentNode} = node;
if (nodeType === Node.ELEMENT_NODE && id !== PINNED &&
classList.contains(CLASS_TAB_GROUP)) {
const items = node.querySelectorAll(TAB_QUERY);
for (const item of items) {
const container = getTemplate(CLASS_TAB_CONTAINER_TMPL);
container.appendChild(item);
parentNode.insertBefore(container, node);
}
}
};
/* DnD */
/**
* handle drop
* @param {!Object} evt - event
* @returns {?AsyncFunction} - storeTabData()
*/
const handleDrop = evt => {
const {dataTransfer, ctrlKey, target} = evt;
const id = dataTransfer.getData(MIME_TYPE);
let func;
if (isString(id)) {
const tab = document.querySelector(`[data-tab-id="${id}"]`);
if (tab) {
const root = document.documentElement;
let node = target;
let dropTarget;
while (node && node.parentNode && node.parentNode !== root) {
const {dataset} = node;
if (dataset) {
const {tabId} = dataset;
if (tabId) {
dropTarget = node;
break;
}
}
node = node.parentNode;
}
if (dropTarget && dropTarget !== tab) {
const {parentNode: dropParent} = dropTarget;
const {
childElementCount: dropParentChild,
nextElementSibling: dropParentNextElement,
} = dropParent;
const {parentNode: tabParent} = tab;
if (dropParentNextElement === tabParent && dropParentChild === 1 &&
ctrlKey) {
dropParent.appendChild(tab);
dropParent.classList.add(CLASS_TAB_GROUP);
switch (tabParent.childElementCount) {
case 0:
tabParent.parentNode.removeChild(tabParent);
break;
case 1:
tabParent.classList.remove(CLASS_TAB_GROUP);
break;
default:
}
} else {
const dropIndex = getSidebarTabIndex(dropTarget);
const tabIndex = getSidebarTabIndex(tab);
const index = tabIndex >= dropIndex && dropIndex + 1 || dropIndex;
tab.dataset.group = !!ctrlKey;
moveTab(id * 1, {
index,
windowId: sidebar.windowId,
});
}
func = storeTabData().catch(logError);
}
}
}
evt.stopPropagation();
evt.preventDefault();
return func || null;
};
/**
* handle dragover
* @param {!Object} evt - event
* @returns {void}
*/
const handleDragOver = evt => {
const {dataTransfer: {types}} = evt;
if (Array.isArray(types) && types.includes(MIME_TYPE)) {
evt.preventDefault();
}
};
/**
* handle dragenter
* @param {!Object} evt - event
* @returns {void}
*/
const handleDragEnter = evt => {
const {target, dataTransfer} = evt;
if (target.nodeType === Node.ELEMENT_NODE) {
const {types} = dataTransfer;
if (Array.isArray(types) && types.includes(MIME_TYPE)) {
dataTransfer.dropEffect = "move";
}
}
};
/**
* add DnD drop event listener
* @param {Object} elm - draggable element
* @returns {void}
*/
const addDropEventListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("dragenter", handleDragEnter);
elm.addEventListener("dragover", handleDragOver);
elm.addEventListener("drop", handleDrop);
}
};
/**
* handle dragstart
* @param {!Object} evt - event
* @returns {void}
*/
const handleDragStart = evt => {
const {target: {dataset: {tabId}}} = evt;
if (tabId) {
evt.dataTransfer.effectAllowed = "move";
evt.dataTransfer.setData(MIME_TYPE, tabId);
}
};
/**
* add DnD drag event listener
* @param {Object} elm - draggable element
* @returns {void}
*/
const addDragEventListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("dragstart", handleDragStart);
}
};
/* sidebar tab containers */
/**
* restore sidebar tab containers
* @returns {Promise.<Array>} - result of each handler
*/
const restoreTabContainers = async () => {
const func = [];
const items = document.querySelectorAll(
`.${CLASS_TAB_CONTAINER}:not(#${NEW_TAB})`
);
for (const item of items) {
const {childElementCount, classList, id, parentNode} = item;
switch (childElementCount) {
case 0:
id !== PINNED && parentNode.removeChild(item);
break;
case 1:
classList.remove(CLASS_TAB_GROUP);
break;
default:
classList.add(CLASS_TAB_GROUP);
}
id !== PINNED && func.push(addDropEventListener(item));
}
func.push(storeTabData());
return Promise.all(func);
};
/* context menus */
/**
* handle context menu click
* @param {!Object} evt - event
* @returns {Promise.<Array>} - results of each handler
*/
const handleClickedContextMenu = async evt => {
const {target: {id}} = evt;
const tab = sidebar.context && sidebar.context.classList &&
sidebar.context.classList.contains(TAB) && sidebar.context;
const tabId = tab && tab.dataset && tab.dataset.tabId &&
tab.dataset.tabId * 1;
const tabsTab = tab && tab.dataset && tab.dataset.tab &&
JSON.parse(tab.dataset.tab);
const func = [];
switch (id) {
case MENU_SIDEBAR_INIT:
func.push(initSidebar(true));
break;
case MENU_TABS_BOOKMARK_ALL: {
const items = document.querySelectorAll(
`${TAB_QUERY}:not(.${PINNED})`
);
if (items && items.length > 1) {
for (const item of items) {
const itemTab = item.dataset && item.dataset.tab &&
JSON.parse(item.dataset.tab);
const {title, url} = itemTab;
func.push(bookmarkTab({title, url}));
}
}
break;
}
case MENU_TABS_RELOAD_ALL: {
const items = document.querySelectorAll(TAB_QUERY);
if (items && items.length) {
for (const item of items) {
const itemId = item && item.dataset && item.dataset.tabId * 1;
Number.isInteger(itemId) && func.push(reloadTab(itemId));
}
}
break;
}
case MENU_TAB_AUDIO: {
if (Number.isInteger(tabId) && tabsTab) {
const {mutedInfo: {muted}} = tabsTab;
func.push(updateTab(tabId, {muted: !muted}));
}
break;
}
case MENU_TAB_CLOSE:
Number.isInteger(tabId) && func.push(removeTab(tabId));
break;
case MENU_TAB_CLOSE_UNDO: {
const {lastClosedTab} = sidebar;
if (lastClosedTab) {
const {sessionId} = lastClosedTab;
isString(sessionId) && func.push(restoreClosedTab(sessionId));
}
break;
}
case MENU_TAB_GROUP_COLLAPSE:
tab && tab.parentNode.classList.contains(CLASS_TAB_GROUP) &&
func.push(toggleTabCollapsed({target: tab}));
break;
case MENU_TAB_GROUP_RELOAD: {
if (tab) {
const {parentNode} = tab;
if (parentNode.classList.contains(CLASS_TAB_GROUP)) {
const items = parentNode.querySelectorAll(TAB_QUERY);
if (items && items.length) {
for (const item of items) {
const itemId = item && item.dataset && item.dataset.tabId * 1;
Number.isInteger(itemId) && func.push(reloadTab(itemId));
}
}
}
}
break;
}
case MENU_TAB_GROUP_UNGROUP: {
if (tab && tabsTab) {
const {parentNode} = tab;
!tabsTab.pinned && parentNode.classList.contains(CLASS_TAB_GROUP) &&
func.push(ungroupTabs(parentNode).then(restoreTabContainers));
}
break;
}
case MENU_TAB_NEW_WIN_MOVE:
Number.isInteger(tabId) && func.push(createNewWindow({
tabId,
type: "normal",
}));
break;
case MENU_TAB_PIN: {
if (tabsTab) {
const {pinned} = tabsTab;
func.push(updateTab(tabId, {pinned: !pinned}));
}
break;
}
case MENU_TAB_RELOAD:
Number.isInteger(tabId) && func.push(reloadTab(tabId));
break;
case MENU_TAB_TABS_CLOSE_END: {
if (Number.isInteger(tabId)) {
const index = tabsTab && tabsTab.index && tabsTab.index * 1;
const items = document.querySelectorAll(
`${TAB_QUERY}:not([data-tab-id="${tabId}"])`
);
const arr = [];
if (items && items.length && Number.isInteger(index)) {
for (const item of items) {
const {dataset} = item;
const itemId = dataset && dataset.tabId && dataset.tabId * 1;
const itemTab = dataset && dataset.tab && JSON.parse(dataset.tab);
const itemIndex = itemTab && itemTab.index && itemTab.index * 1;
Number.isInteger(itemId) && Number.isInteger(itemIndex) &&
itemIndex > index && arr.push(itemId);
}
}
arr.length && func.push(removeTab(arr));
}
break;
}
case MENU_TAB_TABS_CLOSE_OTHER: {
const items = Number.isInteger(tabId) && document.querySelectorAll(
`${TAB_QUERY}:not([data-tab-id="${tabId}"])`
);
const arr = [];
if (items && items.length) {
for (const item of items) {
const {dataset} = item;
const itemId = dataset && dataset.tabId && dataset.tabId * 1;
Number.isInteger(itemId) && arr.push(itemId);
}
}
arr.length && func.push(removeTab(arr));
break;
}
case MENU_THEME_DARK:
func.push(setTheme([THEME_DARK]));
break;
case MENU_THEME_DEFAULT:
func.push(setTheme([THEME_DEFAULT]));
break;
case MENU_THEME_LIGHT:
func.push(setTheme([THEME_LIGHT]));
break;
default: {
const msg = `No handler found for ${id}.`;
func.push(logWarn(msg));
}
}
return Promise.all(func);
};
/* context menu items */
const menuItems = {
sidebarTabs: {
id: MENU,
title: i18n.getMessage("extensionShortName"),
contexts: ["page"],
type: "normal",
enabled: false,
subItems: {
/* tab */
[TAB]: {
id: MENU_TAB,
title: i18n.getMessage(`${TAB}_label`),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
subItems: {
[TAB_RELOAD]: {
id: MENU_TAB_RELOAD,
title: i18n.getMessage(TAB_RELOAD),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
[AUDIO_MUTE]: {
id: MENU_TAB_AUDIO,
title: i18n.getMessage(AUDIO_MUTE),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
toggleTitle: i18n.getMessage(AUDIO_MUTE_UNMUTE),
},
[TAB_PIN]: {
id: MENU_TAB_PIN,
title: i18n.getMessage(TAB_PIN),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
toggleTitle: i18n.getMessage(TAB_PIN_UNPIN),
},
[NEW_WIN_MOVE]: {
id: MENU_TAB_NEW_WIN_MOVE,
title: i18n.getMessage(NEW_WIN_MOVE),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
[TABS_CLOSE_END]: {
id: MENU_TAB_TABS_CLOSE_END,
title: i18n.getMessage(TABS_CLOSE_END),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
[TABS_CLOSE_OTHER]: {
id: MENU_TAB_TABS_CLOSE_OTHER,
title: i18n.getMessage(TABS_CLOSE_OTHER),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
[TAB_CLOSE]: {
id: MENU_TAB_CLOSE,
title: i18n.getMessage(TAB_CLOSE),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
},
},
/* tab group */
[TAB_GROUP]: {
id: MENU_TAB_GROUP,
title: i18n.getMessage(`${TAB_GROUP}_label`),
contexts: [CLASS_TAB_GROUP],
type: "normal",
enabled: false,
subItems: {
[TAB_GROUP_RELOAD]: {
id: MENU_TAB_GROUP_RELOAD,
title: i18n.getMessage(TAB_GROUP_RELOAD),
contexts: [CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
[TAB_GROUP_COLLAPSE]: {
id: MENU_TAB_GROUP_COLLAPSE,
title: i18n.getMessage(TAB_GROUP_COLLAPSE),
contexts: [CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
toggleTitle: i18n.getMessage(TAB_GROUP_EXPAND),
},
[TAB_GROUP_UNGROUP]: {
id: MENU_TAB_GROUP_UNGROUP,
title: i18n.getMessage(TAB_GROUP_UNGROUP),
contexts: [CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
},
},
/* all tabs */
[TABS_RELOAD_ALL]: {
id: MENU_TABS_RELOAD_ALL,
title: i18n.getMessage(TABS_RELOAD_ALL),
contexts: ["page"],
type: "normal",
enabled: true,
onclick: true,
},
[TABS_BOOKMARK_ALL]: {
id: MENU_TABS_BOOKMARK_ALL,
title: i18n.getMessage(TABS_BOOKMARK_ALL),
contexts: ["page"],
type: "normal",
enabled: false,
onclick: true,
},
[TAB_CLOSE_UNDO]: {
id: MENU_TAB_CLOSE_UNDO,
title: i18n.getMessage(TAB_CLOSE_UNDO),
contexts: ["page"],
type: "normal",
enabled: false,
onclick: true,
},
/* sidebar */
[THEME_SELECT]: {
id: MENU_THEME_SELECT,
title: i18n.getMessage(THEME_SELECT),
contexts: ["page"],
type: "normal",
enabled: true,
subItems: {
[THEME_DEFAULT]: {
id: MENU_THEME_DEFAULT,
title: i18n.getMessage(THEME_DEFAULT),
contexts: ["page"],
type: "normal",
enabled: true,
onclick: true,
},
[THEME_LIGHT]: {
id: MENU_THEME_LIGHT,
title: i18n.getMessage(THEME_LIGHT),
contexts: ["page"],
type: "normal",
enabled: true,
onclick: true,
},
[THEME_DARK]: {
id: MENU_THEME_DARK,
title: i18n.getMessage(THEME_DARK),
contexts: ["page"],
type: "normal",
enabled: true,
onclick: true,
},
},
},
[SIDEBAR_INIT]: {
id: MENU_SIDEBAR_INIT,
title: i18n.getMessage(SIDEBAR_INIT),
contexts: ["page"],
type: "normal",
enabled: true,
onclick: true,
},
},
},
};
/**
* add menuitem click listener
* @param {Object} elm - element
* @returns {void}
*/
const addContextMenuClickListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("click", evt =>
handleClickedContextMenu(evt).catch(logError)
);
}
};
/**
* create context menu item
* @param {string} id - menu item ID
* @param {Object} data - context data
* @returns {Promise.<Array>} - results of each handler
*/
const createMenuItem = async (id, data = {}) => {
const {enabled, onclick, title, type} = data;
const func = [];
if (isString(id) && type === "normal") {
const elm = document.getElementById(id);
if (elm) {
elm.label = title;
if (elm.localName === "menuitem") {
elm.disabled = !enabled && true || false;
onclick && func.push(addContextMenuClickListener(elm));
}
}
}
return Promise.all(func);
};
/**
* create context menu items
* @param {Object} menu - menu
* @returns {Promise.<Array>} - results of each handler
*/
const createContextMenu = async (menu = menuItems) => {
const func = [];
const items = Object.keys(menu);
for (const item of items) {
const {enabled, id, onclick, subItems, title, type} = menu[item];
const itemData = {enabled, onclick, title, type};
func.push(createMenuItem(id, itemData));
if (subItems) {
func.push(createContextMenu(subItems));
}
}
return Promise.all(func);
};
/**
* update context menu
* @param {string} id - menu item ID
* @param {Object} data - update items data
* @returns {void}
*/
const updateContextMenu = async (id, data = {}) => {
if (isString(id)) {
const elm = document.getElementById(id);
if (elm) {
const {enabled, title} = data;
title && (elm.label = title);
if (elm.localName === "menuitem") {
elm.disabled = !enabled && true || false;
}
}
}
};
/**
* toggle context menu class
* @param {string} name - class name
* @param {boolean} bool - add class
* @returns {void}
*/
const toggleContextMenuClass = async (name, bool = false) => {
if (isString(name)) {
const elm = document.getElementById(MENU);
if (elm) {
const {classList} = elm;
if (bool) {
classList.add(name);
} else {
classList.remove(name);
}
}
}
};
/**
* set context
* @param {!Object} evt - event
* @returns {Promise.<Array>} - results of each handler
*/
const setContext = async evt => {
const {button, key, shiftKey, target} = evt;
const func = [];
if (shiftKey && key === "F10" || key === "ContextMenu" ||
button === MOUSE_BUTTON_RIGHT) {
const tab = await getSidebarTab(target);
const tabMenu = menuItems.sidebarTabs.subItems[TAB];
const tabKeys = [
TAB_RELOAD, AUDIO_MUTE, TAB_PIN, NEW_WIN_MOVE, TAB_CLOSE,
TABS_CLOSE_END, TABS_CLOSE_OTHER,
];
const tabGroupMenu = menuItems.sidebarTabs.subItems[TAB_GROUP];
const tabGroupKeys = [
TAB_GROUP_RELOAD,
TAB_GROUP_COLLAPSE,
TAB_GROUP_UNGROUP,
];
const allTabsKeys = [TABS_BOOKMARK_ALL, TAB_CLOSE_UNDO];
if (tab) {
const {parentNode} = tab;
const {classList: parentClass} = parentNode;
const tabId = tab.dataset && tab.dataset.tabId;
const tabsTab = tab.dataset && JSON.parse(tab.dataset.tab);
sidebar.context = tab;
func.push(
updateContextMenu(tabMenu.id, {
enabled: true,
title: tabMenu.title,
}),
toggleContextMenuClass(CLASS_TAB, true),
);
for (const itemKey of tabKeys) {
const item = tabMenu.subItems[itemKey];
const {id, title, toggleTitle} = item;
const data = {};
switch (itemKey) {
case AUDIO_MUTE: {
const obj = tab.querySelector(`.${CLASS_TAB_AUDIO_ICON}`);
data.enabled = true;
if (obj && obj.alt) {
data.title = obj.alt;
} else {
data.title = title;
}
break;
}
case TABS_CLOSE_END: {
if (tabsTab.pinned) {
data.enabled = false;
} else {
const index = getSidebarTabIndex(tab);
const obj = document.querySelectorAll(TAB_QUERY);
if (obj && obj.length - 1 > index) {
data.enabled = true;
} else {
data.enabled = false;
}
}
data.title = title;
break;
}
case TABS_CLOSE_OTHER: {
if (tabsTab.pinned) {
data.enabled = false;
} else {
const obj = tabId && document.querySelectorAll(
`${TAB_QUERY}:not([data-tab-id="${tabId}"])`
);
if (obj && obj.length) {
data.enabled = true;
} else {
data.enabled = false;
}
}
data.title = title;
break;
}
case TAB_PIN:
data.enabled = true;
if (parentClass.contains(PINNED)) {
data.title = toggleTitle;
} else {
data.title = title;
}
break;
default:
data.enabled = true;
data.title = title;
}
func.push(updateContextMenu(id, data));
}
if (parentClass.contains(CLASS_TAB_GROUP)) {
func.push(
updateContextMenu(tabGroupMenu.id, {
enabled: true,
title: tabGroupMenu.title,
}),
toggleContextMenuClass(CLASS_TAB_GROUP, true),
);
} else {
func.push(
updateContextMenu(tabGroupMenu.id, {
enabled: false,
title: tabGroupMenu.title,
}),
toggleContextMenuClass(CLASS_TAB_GROUP, false),
);
}
for (const itemKey of tabGroupKeys) {
const item = tabGroupMenu.subItems[itemKey];
const {id, title} = item;
const data = {};
switch (itemKey) {
case TAB_GROUP_COLLAPSE: {
const obj = tab.querySelector(`.${CLASS_TAB_TOGGLE_ICON}`);
if (parentClass.contains(CLASS_TAB_GROUP) && obj && obj.alt) {
data.enabled = true;
data.title = obj.alt;
} else {
data.enabled = false;
data.title = title;
}
break;
}
case TAB_GROUP_UNGROUP:
if (!tabsTab.pinned && parentClass.contains(CLASS_TAB_GROUP)) {
data.enabled = true;
} else {
data.enabled = false;
}
data.title = title;
break;
default:
if (parentClass.contains(CLASS_TAB_GROUP)) {
data.enabled = true;
} else {
data.enabled = false;
}
data.title = title;
}
func.push(updateContextMenu(id, data));
}
} else {
sidebar.context = target;
func.push(
updateContextMenu(tabMenu.id, {
enabled: false,
title: tabMenu.title,
}),
toggleContextMenuClass(CLASS_TAB, false),
toggleContextMenuClass(CLASS_TAB_GROUP, false),
);
for (const itemKey of tabKeys) {
const item = tabMenu.subItems[itemKey];
const {id, title} = item;
const enabled = false;
func.push(updateContextMenu(id, {enabled, title}));
}
func.push(updateContextMenu(tabGroupMenu.id, {
enabled: false,
title: tabGroupMenu.title,
}));
for (const itemKey of tabGroupKeys) {
const item = tabGroupMenu.subItems[itemKey];
const {id, title} = item;
const enabled = false;
func.push(updateContextMenu(id, {enabled, title}));
}
}
for (const itemKey of allTabsKeys) {
const item = menuItems.sidebarTabs.subItems[itemKey];
const {id, title} = item;
const data = {};
switch (itemKey) {
case TABS_BOOKMARK_ALL: {
const items = document.querySelectorAll(
`${TAB_QUERY}:not(.${PINNED})`
);
if (items && items.length > 1) {
data.enabled = true;
} else {
data.enabled = false;
}
break;
}
case TAB_CLOSE_UNDO: {
const {lastClosedTab} = sidebar;
if (lastClosedTab) {
data.enabled = true;
} else {
data.enabled = false;
}
break;
}
default:
data.enabled = true;
}
data.title = title;
func.push(updateContextMenu(id, data));
}
}
return Promise.all(func);
};
/* tabs event handlers */
/**
* handle activated tab
* @param {!Object} info - activated info
* @returns {void}
*/
const handleActivatedTab = async info => {
const {tabId, windowId} = info;
if (windowId === sidebar.windowId && tabId !== tabs.TAB_ID_NONE) {
const newActiveTab = document.querySelector(`[data-tab-id="${tabId}"]`);
const oldActiveTab = document.querySelector(`.${CLASS_TAB}.${ACTIVE}`);
if (newActiveTab && oldActiveTab && newActiveTab !== oldActiveTab) {
const {
classList: newClassList, parentNode: {classList: newParentClassList},
} = newActiveTab;
const {
classList: oldClassList, parentNode: {classList: oldParentClassList},
} = oldActiveTab;
oldClassList.remove(ACTIVE);
oldParentClassList.remove(ACTIVE);
newParentClassList.add(ACTIVE);
newClassList.add(ACTIVE);
}
}
};
/**
* handle created tab
* @param {Object} tabsTab - tabs.Tab
* @returns {Promise.<Array>} - results of each handler
*/
const handleCreatedTab = async tabsTab => {
const {
active, audible, cookieStoreId, favIconUrl, id, index, mutedInfo, pinned,
status, title, windowId,
} = tabsTab;
const {muted} = mutedInfo;
const func = [];
if (windowId === sidebar.windowId && id !== tabs.TAB_ID_NONE) {
const tab = await getTemplate(CLASS_TAB_TMPL);
const tabItems = [
`.${TAB}`, `.${CLASS_TAB_CONTEXT}`, `.${CLASS_TAB_TOGGLE_ICON}`,
`.${CLASS_TAB_CONTENT}`, `.${CLASS_TAB_ICON}`, `.${CLASS_TAB_TITLE}`,
`.${CLASS_TAB_AUDIO}`, `.${CLASS_TAB_AUDIO_ICON}`,
`.${CLASS_TAB_CLOSE}`, `.${CLASS_TAB_CLOSE_ICON}`,
];
const items = tab.querySelectorAll(tabItems.join(","));
const list = document.querySelectorAll(TAB_QUERY);
const listIdx = list && list[index];
const listIdxPrev = list && index > 0 && list[index - 1];
let container;
for (const item of items) {
const {classList} = item;
if (classList.contains(CLASS_TAB_CONTEXT)) {
item.title = i18n.getMessage(`${TAB_GROUP_COLLAPSE}_tooltip`);
func.push(addTabContextClickListener(item));
} else if (classList.contains(CLASS_TAB_TOGGLE_ICON)) {
item.alt = i18n.getMessage(`${TAB_GROUP_COLLAPSE}`);
} else if (classList.contains(CLASS_TAB_CONTENT)) {
item.title = title;
} else if (classList.contains(CLASS_TAB_ICON)) {
item.alt = title;
func.push(
setTabIcon(item, {status, title, favIconUrl}),
addTabIconErrorListener(item),
);
} else if (classList.contains(CLASS_TAB_TITLE)) {
item.textContent = title;
} else if (classList.contains(CLASS_TAB_AUDIO)) {
if (audible || muted) {
classList.add(AUDIBLE);
} else {
classList.remove(AUDIBLE);
}
func.push(
setTabAudio(item, {audible, muted}),
addTabAudioClickListener(item),
);
} else if (classList.contains(CLASS_TAB_AUDIO_ICON)) {
func.push(setTabAudioIcon(item, {audible, muted}));
} else if (classList.contains(CLASS_TAB_CLOSE)) {
item.title = i18n.getMessage(`${TAB_CLOSE}_tooltip`);
func.push(addTabCloseClickListener(item));
} else if (classList.contains(CLASS_TAB_CLOSE_ICON)) {
item.alt = i18n.getMessage(`${TAB_CLOSE}`);
}
func.push(addTabClickListener(item));
}
tab.dataset.tabId = id;
tab.dataset.tab = JSON.stringify(tabsTab);
active && tab.classList.add(ACTIVE);
if (cookieStoreId) {
const ident = await contextualIdentities.get(cookieStoreId);
if (ident) {
const {color} = ident;
tab.style.borderColor = color;
}
}
if (pinned) {
container = document.getElementById(PINNED);
tab.classList.add(PINNED);
tab.removeAttribute("draggable");
if (container.children[index]) {
container.insertBefore(tab, container.children[index]);
} else {
container.appendChild(tab);
}
container.childElementCount > 1 &&
container.classList.add(CLASS_TAB_GROUP);
} else if (list.length !== index && listIdx && listIdx.parentNode &&
listIdx.parentNode.classList.contains(CLASS_TAB_GROUP) &&
listIdxPrev && listIdxPrev.parentNode &&
listIdxPrev.parentNode.classList.contains(CLASS_TAB_GROUP) &&
listIdx.parentNode === listIdxPrev.parentNode) {
container = listIdx.parentNode;
container.insertBefore(tab, listIdx);
} else {
let target;
if (list.length !== index && listIdx && listIdx.parentNode) {
target = listIdx.parentNode;
} else {
target = document.getElementById(NEW_TAB);
}
await addDragEventListener(tab);
container = await getTemplate(CLASS_TAB_CONTAINER_TMPL);
container.appendChild(tab);
target.parentNode.insertBefore(container, target);
}
}
return Promise.all(func);
};
/**
* handle attached tab
* @param {number} tabId - tab ID
* @param {Object} info - attached tab info
* @returns {?AsyncFunction} - tabs.Tab
*/
const handleAttachedTab = async (tabId, info) => {
const {newPosition, newWindowId} = info;
let func;
if (newWindowId === sidebar.windowId && tabId !== tabs.TAB_ID_NONE) {
const tabsTab = await tabs.get(tabId);
if (tabsTab) {
tabsTab.index = newPosition;
func = handleCreatedTab(tabsTab);
}
}
return func || null;
};
/**
* handle updated tab
* Note: Occurs frequently, so it should not be async.
* @param {number} tabId - tab ID
* @param {Object} info - updated tab info
* @param {Object} tabsTab - tabs.Tab
* @returns {Promise.<Array>} - results of each handler
*/
const handleUpdatedTab = (tabId, info, tabsTab) => {
const {windowId} = tabsTab;
const func = [];
if (windowId === sidebar.windowId && tabId !== tabs.TAB_ID_NONE) {
const tab = document.querySelector(`[data-tab-id="${tabId}"]`);
if (tab) {
const {favIconUrl, status, title} = tabsTab;
const tabContent = tab.querySelector(`.${CLASS_TAB_CONTENT}`);
const tabTitle = tab.querySelector(`.${CLASS_TAB_TITLE}`);
const tabIcon = tab.querySelector(`.${CLASS_TAB_ICON}`);
tabContent && (tabContent.title = title);
tabTitle && (tabTitle.textContent = title);
// Note: Don't push to Promise array
tabIcon && setTabIcon(tabIcon, {favIconUrl, status, title});
if (info.hasOwnProperty("audible") ||
info.hasOwnProperty("mutedInfo")) {
const tabAudio = tab.querySelector(`.${CLASS_TAB_AUDIO}`);
const tabAudioIcon = tab.querySelector(`.${CLASS_TAB_AUDIO_ICON}`);
const {muted} = tabsTab.mutedInfo;
const {audible} = tabsTab;
const opt = {audible, muted};
if (tabAudio) {
if (audible || muted) {
tabAudio.classList.add(AUDIBLE);
} else {
tabAudio.classList.remove(audible);
}
func.push(setTabAudio(tabAudio, opt));
}
tabAudioIcon && func.push(setTabAudioIcon(tabAudioIcon, opt));
}
if (info.hasOwnProperty("pinned")) {
const pinnedContainer = document.getElementById(PINNED);
if (info.pinned) {
const container = pinnedContainer;
tab.classList.add(PINNED);
tab.removeAttribute("draggable");
container.appendChild(tab);
func.push(restoreTabContainers());
} else {
const {
nextElementSibling: pinnedNextElement,
parentNode: pinnedParentNode,
} = pinnedContainer;
const container = getTemplate(CLASS_TAB_CONTAINER_TMPL);
tab.classList.remove(PINNED);
tab.setAttribute("draggable", "true");
func.push(addDragEventListener(tab));
container.appendChild(tab);
pinnedParentNode.insertBefore(container, pinnedNextElement);
func.push(restoreTabContainers());
}
}
tab.dataset.tab = JSON.stringify(tabsTab);
}
}
return Promise.all(func).catch(logError);
};
/**
* handle moved tab
* @param {!number} tabId - tab ID
* @param {!Object} info - moved info
* @returns {void}
*/
const handleMovedTab = async (tabId, info) => {
const {fromIndex, toIndex, windowId} = info;
if (windowId === sidebar.windowId && tabId !== tabs.TAB_ID_NONE) {
const tab = document.querySelector(`[data-tab-id="${tabId}"]`);
const items = document.querySelectorAll(TAB_QUERY);
if (toIndex === 0) {
const tabsTab = await tabs.get(tabId);
const {pinned} = tabsTab;
if (pinned) {
const container = document.getElementById(PINNED);
const {firstElementChild} = container;
container.insertBefore(tab, firstElementChild);
} else {
const container = await getTemplate(CLASS_TAB_CONTAINER_TMPL);
const [target] = items;
container.appendChild(tab);
target.parentNode.insertBefore(container, target);
}
} else {
const target = items[fromIndex >= toIndex && toIndex - 1 || toIndex];
const {nextElementSibling, parentNode} = target;
const unPinned =
toIndex > fromIndex &&
items[fromIndex].parentNode.classList.contains(PINNED) &&
items[toIndex].parentNode.classList.contains(PINNED) &&
items[toIndex] === items[toIndex].parentNode.lastElementChild;
let {dataset: {group}} = tab;
group = group === "true" && true || false;
if (!group && parentNode.childElementCount === 1 || unPinned) {
const {
nextElementSibling: parentNextElementSibling,
parentNode: parentParentNode,
} = parentNode;
const frag = await getTemplate(CLASS_TAB_CONTAINER_TMPL);
if (frag) {
frag.appendChild(tab);
if (parentNextElementSibling) {
parentParentNode.insertBefore(frag, parentNextElementSibling);
} else {
const newtab = document.getElementById(NEW_TAB);
parentParentNode.insertBefore(frag, newtab);
}
}
} else if (nextElementSibling) {
parentNode.insertBefore(tab, nextElementSibling);
} else {
parentNode.appendChild(tab);
}
}
tab.dataset.group = null;
}
};
/**
* handle detached tab
* @param {number} tabId - tab ID
* @param {Object} info - detached tab info
* @returns {void}
*/
const handleDetachedTab = async (tabId, info) => {
const {oldWindowId} = info;
if (oldWindowId === sidebar.windowId && tabId !== tabs.TAB_ID_NONE) {
const tab = document.querySelector(`[data-tab-id="${tabId}"]`);
tab && tab.parentNode.removeChild(tab);
}
};
/**
* handle removed tab
* @param {number} tabId - tab ID
* @param {Object} info - removed tab info
* @returns {void}
*/
const handleRemovedTab = async (tabId, info) => {
const {isWindowClosing, windowId} = info;
if (windowId === sidebar.windowId && !isWindowClosing &&
tabId !== tabs.TAB_ID_NONE) {
const tab = document.querySelector(`[data-tab-id="${tabId}"]`);
tab && tab.parentNode.removeChild(tab);
}
};
/* listeners */
tabs.onActivated.addListener(info =>
handleActivatedTab(info).catch(logError)
);
tabs.onAttached.addListener((tabId, info) =>
handleAttachedTab(tabId, info).then(restoreTabContainers).catch(logError)
);
tabs.onCreated.addListener(tabsTab =>
handleCreatedTab(tabsTab).then(restoreTabContainers).catch(logError)
);
tabs.onDetached.addListener((tabId, info) =>
handleDetachedTab(tabId, info).then(restoreTabContainers).catch(logError)
);
tabs.onMoved.addListener((tabId, info) =>
handleMovedTab(tabId, info).then(restoreTabContainers).catch(logError)
);
tabs.onRemoved.addListener((tabId, info) =>
handleRemovedTab(tabId, info).then(restoreTabContainers)
.then(getLastClosedTab).catch(logError)
);
// Note: Occurs frequently, so handler should not be async.
tabs.onUpdated.addListener(handleUpdatedTab);
/* start up */
/**
* set stored tab group data
* @returns {void}
*/
const restoreTabGroup = async () => {
const {tab: storedTab} = await storage.local.get(TAB);
if (storedTab) {
const {tab, group: groups} = storedTab;
const items = document.querySelectorAll(TAB_QUERY);
if (items.length === tab.length) {
const l = items.length;
let i = 0;
let bool;
while (i < l) {
const item = items[i];
const tabsTab = item.dataset && item.dataset.tab &&
JSON.parse(item.dataset.tab);
const {url} = tabsTab;
bool = isUrlEqual(url, tab[i]);
if (!bool) {
break;
}
i++;
}
if (bool) {
for (const group of groups) {
const [target, ...indexes] = group;
const container = items[target].parentNode;
container.classList.add(CLASS_TAB_GROUP);
for (const index of indexes) {
container.appendChild(items[index]);
}
}
}
}
}
};
/**
* emulate tabs to sidebar
* @returns {Promise.<Array>} - results of each handler
*/
const emulateTabs = async () => {
const items = await tabs.query({windowId: windows.WINDOW_ID_CURRENT});
const func = [];
for (const item of items) {
func.push(handleCreatedTab(item));
}
return Promise.all(func);
};
document.addEventListener("DOMContentLoaded", () => Promise.all([
addNewTabClickListener(),
createContextMenu(),
getTheme().then(setTheme),
setSidebar(),
]).then(emulateTabs).then(restoreTabGroup).then(restoreTabContainers)
.catch(logError));
window.addEventListener("keydown", evt => setContext(evt).catch(logError),
true);
window.addEventListener("mousedown", evt => setContext(evt).catch(logError),
true);
}
| src/js/sidebar.js | /* sidebar.js */
"use strict";
{
/* api */
const {
bookmarks, contextualIdentities, i18n, management, sessions, storage, tabs,
windows,
} = browser;
/* constants */
const ACTIVE = "active";
const AUDIBLE = "audible";
const AUDIO_MUTE = "muteAudio";
const AUDIO_MUTE_UNMUTE = "unmuteAudio";
const CLASS_MENU = "menu";
const CLASS_TAB = "tab";
const CLASS_TAB_AUDIO = "tab-audio";
const CLASS_TAB_AUDIO_ICON = "tab-audio-icon";
const CLASS_TAB_CLOSE = "tab-close";
const CLASS_TAB_CLOSE_ICON = "tab-close-icon";
const CLASS_TAB_COLLAPSED = "tab-collapsed";
const CLASS_TAB_CONTAINER = "tab-container";
const CLASS_TAB_CONTAINER_TMPL = "tab-container-template";
const CLASS_TAB_CONTENT = "tab-content";
const CLASS_TAB_CONTEXT = "tab-context";
const CLASS_TAB_GROUP = "tab-group";
const CLASS_TAB_ICON = "tab-icon";
const CLASS_TAB_TITLE = "tab-title";
const CLASS_TAB_TMPL = "tab-template";
const CLASS_TAB_TOGGLE_ICON = "tab-toggle-icon";
const CLASS_THEME_DARK = "dark-theme";
const CLASS_THEME_LIGHT = "light-theme";
const CONNECTING = "connecting";
const MENU = "sidebar-tabs-menu";
const MENU_SIDEBAR_INIT = "sidebar-tabs-menu-sidebar-init";
const MENU_TAB = "sidebar-tabs-menu-tab";
const MENU_TABS_BOOKMARK_ALL = "sidebar-tabs-menu-tabs-bookmark-all";
const MENU_TABS_RELOAD_ALL = "sidebar-tabs-menu-tabs-reload-all";
const MENU_TAB_AUDIO = "sidebar-tabs-menu-tab-audio";
const MENU_TAB_CLOSE = "sidebar-tabs-menu-tab-close";
const MENU_TAB_CLOSE_UNDO = "sidebar-tabs-menu-tab-close-undo";
const MENU_TAB_GROUP = "sidebar-tabs-menu-tab-group";
const MENU_TAB_GROUP_COLLAPSE = "sidebar-tabs-menu-tab-group-collapse";
const MENU_TAB_GROUP_RELOAD = "sidebar-tabs-menu-tab-group-reload";
const MENU_TAB_GROUP_UNGROUP = "sidebar-tabs-menu-tab-group-ungroup";
const MENU_TAB_NEW_WIN_MOVE = "sidebar-tabs-menu-tab-new-win-move";
const MENU_TAB_PIN = "sidebar-tabs-menu-tab-pin";
const MENU_TAB_RELOAD = "sidebar-tabs-menu-tab-reload";
const MENU_TAB_TABS_CLOSE_END = "sidebar-tabs-menu-tab-close-end";
const MENU_TAB_TABS_CLOSE_OTHER = "sidebar-tabs-menu-tab-close-other";
const MENU_THEME_DARK = "sidebar-tabs-menu-sidebar-theme-dark";
const MENU_THEME_DEFAULT = "sidebar-tabs-menu-sidebar-theme-default";
const MENU_THEME_LIGHT = "sidebar-tabs-menu-sidebar-theme-light";
const MENU_THEME_SELECT = "sidebar-tabs-menu-sidebar-theme-select";
const MIME_TYPE = "text/plain";
const MOUSE_BUTTON_RIGHT = 2;
const NEW_TAB = "newtab";
const NEW_WIN_MOVE = "moveToNewWindow";
const PINNED = "pinned";
const SIDEBAR_INIT = "initSidebar";
const TAB = "tab";
const TABS_BOOKMARK_ALL = "bookmarkAllTabs";
const TABS_CLOSE_END = "closeTabsToTheEnd";
const TABS_CLOSE_OTHER = "closeOtherTabs";
const TABS_RELOAD_ALL = "reloadAllTabs";
const TAB_CLOSE = "closeTab";
const TAB_CLOSE_UNDO = "undoCloseTab";
const TAB_GROUP = "groupTabs";
const TAB_GROUP_COLLAPSE = "collapseTabs";
const TAB_GROUP_EXPAND = "expandTabs";
const TAB_GROUP_RELOAD = "reloadGroupTabs";
const TAB_GROUP_UNGROUP = "ungroupTabs";
const TAB_PIN = "pinTab";
const TAB_PIN_UNPIN = "unpinTab";
const TAB_RELOAD = "reloadTab";
const THEME = "theme";
const THEME_DARK = "darkTheme";
const THEME_DARK_ID = "[email protected]@personas.mozilla.org";
const THEME_DEFAULT = "defaultTheme";
const THEME_LIGHT = "lightTheme";
const THEME_LIGHT_ID =
"[email protected]@personas.mozilla.org";
const THEME_SELECT = "selectTheme";
const TYPE_FROM = 8;
const TYPE_TO = -1;
const URL_AUDIO_MUTED = "../shared/tab-audio-muted.svg";
const URL_AUDIO_PLAYING = "../shared/tab-audio-playing.svg";
const URL_CONNECTING_SPINNER = "../img/spinner.svg#connecting";
const URL_DEFAULT_FAVICON = "../shared/defaultFavicon.svg";
const URL_LOADING_SPINNER = "../img/spinner.svg";
const TAB_QUERY = `.${CLASS_TAB}:not(.${CLASS_MENU}):not(.${NEW_TAB})`;
/**
* log error
* @param {!Object} e - Error
* @returns {boolean} - false
*/
const logError = e => {
console.error(e);
return false;
};
/**
* log warn
* @param {*} msg - message
* @returns {boolean} - false
*/
const logWarn = msg => {
console.warn(msg);
return false;
};
/**
* get type
* @param {*} o - object to check
* @returns {string} - type of object
*/
const getType = o =>
Object.prototype.toString.call(o).slice(TYPE_FROM, TYPE_TO);
/**
* is string
* @param {*} o - object to check
* @returns {boolean} - result
*/
const isString = o => typeof o === "string" || o instanceof String;
/**
* is object, and not an empty object
* @param {*} o - object to check;
* @returns {boolean} - result
*/
const isObjectNotEmpty = o => {
const items = /Object/i.test(getType(o)) && Object.keys(o);
return !!(items && items.length);
};
/**
* compare url string
* @param {string} url1 - URL
* @param {string} url2 - URL
* @param {boolean} query - compare query string too or not
* @param {boolean} frag - compare fragment identifier string too or not
* @returns {boolean} - result
*/
const isUrlEqual = (url1, url2, query = false, frag = false) => {
url1 = new URL(url1);
url2 = new URL(url2);
return url1.origin === url2.origin && url1.pathname === url2.pathname &&
(!query || url1.search === url2.search) &&
(!frag || url1.hash === url2.hash);
};
/* sidebar */
const sidebar = {
incognito: false,
windowId: null,
context: null,
lastClosedTab: null,
};
/**
* set sidebar
* @returns {void}
*/
const setSidebar = async () => {
const win = await windows.getCurrent({
populate: true,
windowTypes: ["normal"],
});
if (win) {
const {focused, id, incognito} = win;
if (focused) {
sidebar.incognito = incognito;
sidebar.windowId = id;
}
}
};
/**
* store data
* @param {Object} data - data to store
* @returns {?AsyncFunction} - storage.local.set()
*/
const storeData = async data => {
let func;
if (isObjectNotEmpty(data)) {
func = storage.local.set(data);
}
return func || null;
};
/**
* get theme
* @returns {Array} - theme class list
*/
const getTheme = async () => {
const {theme: storedTheme} = await storage.local.get(THEME);
let theme = [];
if (Array.isArray(storedTheme) && storedTheme.length) {
theme = storedTheme;
} else if (management) {
const items = await management.getAll().then(arr => arr.filter(info =>
info.type && info.type === "theme" && info.enabled && info
));
if (Array.isArray(items) && items.length) {
for (const item of items) {
const {id} = item;
switch (id) {
case THEME_DARK_ID:
theme.push(THEME_DARK);
break;
case THEME_LIGHT_ID:
theme.push(THEME_LIGHT);
break;
default:
}
}
}
!theme.length && theme.push(THEME_DEFAULT);
}
return theme;
};
/**
* set theme
* @param {Array} theme - array of theme
* @returns {void}
*/
const setTheme = async theme => {
if (!Array.isArray(theme)) {
throw new TypeError(`Expected Array but got ${getType(theme)}.`);
}
const elm = document.querySelector("body");
const {classList} = elm;
for (const item of theme) {
switch (item) {
case THEME_DARK:
classList.remove(CLASS_THEME_LIGHT);
classList.add(CLASS_THEME_DARK);
break;
case THEME_DEFAULT:
classList.remove(CLASS_THEME_DARK);
classList.remove(CLASS_THEME_LIGHT);
break;
case THEME_LIGHT:
classList.remove(CLASS_THEME_DARK);
classList.add(CLASS_THEME_LIGHT);
break;
default:
}
}
await storeData({
[THEME]: theme,
});
};
/**
* init sidebar
* @param {boolean} bool - bypass cache
* @returns {void}
*/
const initSidebar = async (bool = false) => {
await storage.local.clear();
window.location.reload(bool);
};
/* handle real tabs */
/**
* create tab
* @param {Object} opt - options
* @returns {AsyncFunction} - tabs.create()
*/
const createTab = async (opt = {}) => {
opt = isObjectNotEmpty(opt) && opt || null;
return tabs.create(opt);
};
/**
* update tab
* @param {number} tabId - tab ID
* @param {Object} opt - options
* @returns {AsyncFunction} - tabs.update()
*/
const updateTab = async (tabId, opt = {}) => {
if (!Number.isInteger(tabId)) {
throw new TypeError(`Expected Number but got ${getType(tabId)}.`);
}
opt = isObjectNotEmpty(opt) && opt || null;
return tabs.update(tabId, opt);
};
/**
* move tab
* @param {number} tabId - tab ID
* @param {Object} opt - options
* @returns {AsyncFunction} - tabs.move();
*/
const moveTab = async (tabId, opt = {}) => {
if (!Number.isInteger(tabId)) {
throw new TypeError(`Expected Number but got ${getType(tabId)}.`);
}
opt = isObjectNotEmpty(opt) && opt || null;
return tabs.move(tabId, opt);
};
/**
* reload tab
* @param {number} tabId - tab ID
* @param {Object} opt - options
* @returns {AsyncFunction} - tabs.reload()
*/
const reloadTab = async (tabId, opt = {}) => {
if (!Number.isInteger(tabId)) {
throw new TypeError(`Expected Number but got ${getType(tabId)}.`);
}
opt = isObjectNotEmpty(opt) && opt || null;
return tabs.reload(tabId, opt);
};
/**
* remove tab
* @param {number|Array} arg - tab ID or array of tab ID
* @returns {AsyncFunction} - tabs.remove()
*/
const removeTab = async arg => {
if (Number.isInteger(arg)) {
arg = [arg];
}
if (!Array.isArray(arg)) {
throw new TypeError(`Expected Array but got ${getType(arg)}.`);
}
return tabs.remove(arg);
};
/**
* bookmark tab
* @param {Object} opt - options
* @returns {AsyncFunction} - bookmarks.create()
*/
const bookmarkTab = async (opt = {}) => {
opt = isObjectNotEmpty(opt) && opt || null;
return bookmarks.create(opt);
};
/**
* create new window
* @param {Object} opt - options
* @returns {AsyncFunction} - windows.create();
*/
const createNewWindow = async (opt = {}) => {
opt = isObjectNotEmpty(opt) && opt || null;
return windows.create(opt);
};
/**
* get last closed tab
* @returns {Object} - tabs.Tab
*/
const getLastClosedTab = async () => {
const session = await sessions.getRecentlyClosed();
let tab;
if (Array.isArray(session) && session.length) {
const {windowId} = sidebar;
for (const item of session) {
const {tab: itemTab} = item;
if (itemTab) {
const {windowId: itemWindowId} = itemTab;
if (itemWindowId === windowId) {
tab = itemTab;
sidebar.lastClosedTab = tab;
break;
}
}
}
}
return tab || null;
};
/**
* restore tab
* @param {string} sessionId - session ID
* @returns {AsyncFunction} - sessions.restore()
*/
const restoreClosedTab = async sessionId => {
if (!isString(sessionId)) {
throw new TypeError(`Expected String but got ${getType(sessionId)}.`);
}
return sessions.restore(sessionId);
};
/* sidebar tabs */
/**
* get template
* @param {string} id - template ID
* @returns {Object} - document fragment
*/
const getTemplate = id => {
const tmpl = document.getElementById(id);
const {content: {firstElementChild}} = tmpl;
return document.importNode(firstElementChild, true);
};
/**
* create new tab
* @returns {AsyncFunction} - createTab()
*/
const createNewTab = async () => createTab({windowId: sidebar.windowId});
/**
* add new tab click listener
* @returns {void}
*/
const addNewTabClickListener = async () => {
const newTab = document.getElementById(NEW_TAB);
newTab.addEventListener("click", evt => createNewTab(evt).catch(logError));
};
/**
* get sidebar tab container from parent node
* @param {Object} node - node
* @returns {Object} - sidebar tab container
*/
const getSidebarTabContainer = node => {
const root = document.documentElement;
let tab;
while (node && node.parentNode && node.parentNode !== root) {
const {classList, parentNode} = node;
if (classList.contains(CLASS_TAB_CONTAINER)) {
tab = node;
break;
}
node = parentNode;
}
return tab || null;
};
/**
* get sidebar tab from parent node
* @param {Object} node - node
* @returns {Object} - sidebar tab
*/
const getSidebarTab = node => {
const root = document.documentElement;
let tab;
while (node && node.parentNode && node.parentNode !== root) {
const {dataset, parentNode} = node;
if (dataset.tabId) {
tab = node;
break;
}
node = parentNode;
}
return tab || null;
};
/**
* get sidebar tab ID
* @param {Object} node - node
* @returns {?number} - tab ID
*/
const getSidebarTabId = node => {
const root = document.documentElement;
let tabId;
while (node && node.parentNode && node.parentNode !== root) {
const {dataset, parentNode} = node;
if (dataset.tabId) {
tabId = dataset.tabId * 1;
break;
}
node = parentNode;
}
return tabId || null;
};
/**
* get sidebar tab index
* @param {Object} tab - tab
* @returns {?number} - index
*/
const getSidebarTabIndex = tab => {
let index;
if (tab && tab.nodeType === Node.ELEMENT_NODE) {
const items = document.querySelectorAll(TAB_QUERY);
const l = items.length;
let i = 0;
while (i < l && !index) {
if (items[i] === tab) {
index = i;
break;
}
i++;
}
}
return Number.isInteger(index) ?
index :
null;
};
/**
* activate tab
* @param {!Object} evt - event
* @returns {?AsyncFunction} - tabs.update()
*/
const activateTab = async evt => {
const {target} = evt;
const tabId = await getSidebarTabId(target);
let func;
if (Number.isInteger(tabId)) {
const active = true;
func = updateTab(tabId, {active});
}
return func || null;
};
/**
* add sidebar tab click listener
* @param {Object} elm - element
* @returns {void}
*/
const addTabClickListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("click", evt => activateTab(evt).catch(logError));
}
};
/**
* create tab data
* @returns {Array} - tab data
*/
const createTabData = async () => {
const items = document.querySelectorAll(TAB_QUERY);
const tab = [];
for (const item of items) {
const tabsTab = item.dataset && item.dataset.tab &&
JSON.parse(item.dataset.tab);
const {url} = tabsTab;
tab.push(url);
}
return tab;
};
/**
* create tab group data
* @returns {Array} - tab group data
*/
const createTabGroupData = async () => {
const items = document.querySelectorAll(
`.${CLASS_TAB_CONTAINER}.${CLASS_TAB_GROUP}:not(.${PINNED})`
);
const group = [];
for (const item of items) {
const {children} = item;
const arr = [];
for (const child of children) {
const index = getSidebarTabIndex(child);
Number.isInteger(index) && arr.push(index);
}
arr.length && group.push(arr);
}
return group;
};
/**
* store tab data
* @returns {AsyncFunction} - storeData()
*/
const storeTabData = async () => {
const tab = await createTabData() || [];
const group = await createTabGroupData() || [];
return storeData({
[TAB]: {
tab, group,
},
});
};
/* sidebar tab content */
/**
* tab icon fallback
* @param {!Object} evt - event
* @returns {boolean} - false
*/
const tabIconFallback = evt => {
const {target} = evt;
target.hasOwnProperty("src") && (target.src = URL_DEFAULT_FAVICON);
return false;
};
/**
* add tab icon error listener
* @param {Object} elm - img element
* @returns {void}
*/
const addTabIconErrorListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("error", tabIconFallback);
}
};
/**
* set favicon
* @param {Object} elm - img element
* @param {string} favIconUrl - favicon url
* @returns {void}
*/
const setFavicon = async (elm, favIconUrl) => {
if (elm && elm.nodeType === Node.ELEMENT_NODE && elm.localName === "img" &&
isString(favIconUrl)) {
elm.src = await fetch(favIconUrl).then(res => {
let url;
if (res.ok) {
url = favIconUrl;
} else {
url = URL_DEFAULT_FAVICON;
}
return url;
}).catch(e => {
console.error(e);
return URL_DEFAULT_FAVICON;
});
}
};
/**
* set tab icon
* @param {Object} elm - img element
* @param {Object} info - tab info
* @returns {?AsyncFunction} - setFavicon()
*/
const setTabIcon = (elm, info) => {
let func;
if (elm && elm.nodeType === Node.ELEMENT_NODE && elm.localName === "img") {
const {status, title, favIconUrl} = info;
const connectText = i18n.getMessage(CONNECTING);
if (status === "loading") {
if (title === connectText) {
elm.src = URL_CONNECTING_SPINNER;
} else {
elm.src = URL_LOADING_SPINNER;
}
} else if (status === "complete") {
if (favIconUrl) {
func = setFavicon(elm, favIconUrl);
} else {
elm.src = URL_DEFAULT_FAVICON;
}
} else {
elm.src = URL_DEFAULT_FAVICON;
}
}
return func || null;
};
/* sidebar tab audio */
/**
* toggle audio state
* @param {!Object} evt - event
* @returns {?AsyncFunction} - tabs.update()
*/
const toggleAudio = async evt => {
const {target} = evt;
const tabId = await getSidebarTabId(target);
let func;
if (Number.isInteger(tabId)) {
const tab = document.querySelector(`[data-tab-id="${tabId}"]`);
if (tab) {
const tabsTab = JSON.parse(tab.dataset.tab);
const {mutedInfo: {muted}} = tabsTab;
func = updateTab(tabId, {muted: !muted});
}
}
return func || null;
};
/**
* add tab audio click event listener
* @param {Object} elm - element
* @returns {void}
*/
const addTabAudioClickListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("click", evt => toggleAudio(evt).catch(logError));
}
};
/**
* set tab audio
* @param {Object} elm - element
* @param {Object} info - audio info
* @returns {void}
*/
const setTabAudio = async (elm, info) => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
const {audible, muted} = info;
if (muted) {
elm.title = i18n.getMessage(`${AUDIO_MUTE_UNMUTE}_tooltip`);
} else if (audible) {
elm.title = i18n.getMessage(`${AUDIO_MUTE}_tooltip`);
} else {
elm.title = "";
}
}
};
/**
* set tab audio icon
* @param {Object} elm - element
* @param {Object} info - audio info
* @returns {void}
*/
const setTabAudioIcon = async (elm, info) => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
const {audible, muted} = info;
if (muted) {
elm.alt = i18n.getMessage(`${AUDIO_MUTE_UNMUTE}`);
elm.src = URL_AUDIO_MUTED;
} else if (audible) {
elm.alt = i18n.getMessage(`${AUDIO_MUTE}`);
elm.src = URL_AUDIO_PLAYING;
} else {
elm.alt = "";
elm.src = "";
}
}
};
/* close button */
/**
* close tab
* @param {!Object} evt - event
* @returns {?AsyncFunction} - removeTab()
*/
const closeTab = async evt => {
const {target} = evt;
const tabId = await getSidebarTabId(target);
let func;
if (Number.isInteger(tabId)) {
func = removeTab(tabId);
}
return func || null;
};
/**
* add tab close click listener
* @param {Object} elm - element
* @returns {void}
*/
const addTabCloseClickListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("click", evt => closeTab(evt).catch(logError));
}
};
/* tab group */
/**
* toggle tab collapsed
* @param {!Object} evt - event
* @returns {?AsyncFunction} - activateTab()
*/
const toggleTabCollapsed = async evt => {
const {target} = evt;
const container = await getSidebarTabContainer(target);
let func;
if (container) {
const {firstElementChild: tab} = container;
const {firstElementChild: tabContext} = tab;
const {firstElementChild: toggleIcon} = tabContext;
if (container.classList.contains(CLASS_TAB_GROUP) &&
tab && tab.style.display !== "none") {
container.classList.toggle(CLASS_TAB_COLLAPSED);
if (container.classList.contains(CLASS_TAB_COLLAPSED)) {
tabContext.title = i18n.getMessage(`${TAB_GROUP_EXPAND}_tooltip`);
toggleIcon.alt = i18n.getMessage(`${TAB_GROUP_EXPAND}`);
} else {
tabContext.title = i18n.getMessage(`${TAB_GROUP_COLLAPSE}_tooltip`);
toggleIcon.alt = i18n.getMessage(`${TAB_GROUP_COLLAPSE}`);
}
func = activateTab({target: tab});
}
}
return func || null;
};
/**
* add tab context click listener
* @param {Object} elm - element
* @returns {void}
*/
const addTabContextClickListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("click", evt => toggleTabCollapsed(evt));
}
};
/**
* ungroup tabs
* @param {Object} node - tab group container
* @returns {void}
*/
const ungroupTabs = async (node = {}) => {
const {id, classList, nodeType, parentNode} = node;
if (nodeType === Node.ELEMENT_NODE && id !== PINNED &&
classList.contains(CLASS_TAB_GROUP)) {
const items = node.querySelectorAll(TAB_QUERY);
for (const item of items) {
const container = getTemplate(CLASS_TAB_CONTAINER_TMPL);
container.appendChild(item);
parentNode.insertBefore(container, node);
}
}
};
/* DnD */
/**
* handle drop
* @param {!Object} evt - event
* @returns {?AsyncFunction} - storeTabData()
*/
const handleDrop = evt => {
const {dataTransfer, ctrlKey, target} = evt;
const id = dataTransfer.getData(MIME_TYPE);
let func;
if (isString(id)) {
const tab = document.querySelector(`[data-tab-id="${id}"]`);
if (tab) {
const root = document.documentElement;
let node = target;
let dropTarget;
while (node && node.parentNode && node.parentNode !== root) {
const {dataset} = node;
if (dataset) {
const {tabId} = dataset;
if (tabId) {
dropTarget = node;
break;
}
}
node = node.parentNode;
}
if (dropTarget && dropTarget !== tab) {
const {parentNode: dropParent} = dropTarget;
const {
childElementCount: dropParentChild,
nextElementSibling: dropParentNextElement,
} = dropParent;
const {parentNode: tabParent} = tab;
if (dropParentNextElement === tabParent && dropParentChild === 1 &&
ctrlKey) {
dropParent.appendChild(tab);
dropParent.classList.add(CLASS_TAB_GROUP);
switch (tabParent.childElementCount) {
case 0:
tabParent.parentNode.removeChild(tabParent);
break;
case 1:
tabParent.classList.remove(CLASS_TAB_GROUP);
break;
default:
}
} else {
const dropIndex = getSidebarTabIndex(dropTarget);
const tabIndex = getSidebarTabIndex(tab);
const index = tabIndex >= dropIndex && dropIndex + 1 || dropIndex;
tab.dataset.group = !!ctrlKey;
moveTab(id * 1, {
index,
windowId: sidebar.windowId,
});
}
func = storeTabData().catch(logError);
}
}
}
evt.stopPropagation();
evt.preventDefault();
return func || null;
};
/**
* handle dragover
* @param {!Object} evt - event
* @returns {void}
*/
const handleDragOver = evt => {
const {dataTransfer: {types}} = evt;
if (Array.isArray(types) && types.includes(MIME_TYPE)) {
evt.preventDefault();
}
};
/**
* handle dragenter
* @param {!Object} evt - event
* @returns {void}
*/
const handleDragEnter = evt => {
const {target, dataTransfer} = evt;
if (target.nodeType === Node.ELEMENT_NODE) {
const {types} = dataTransfer;
if (Array.isArray(types) && types.includes(MIME_TYPE)) {
dataTransfer.dropEffect = "move";
}
}
};
/**
* add DnD drop event listener
* @param {Object} elm - draggable element
* @returns {void}
*/
const addDropEventListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("dragenter", handleDragEnter);
elm.addEventListener("dragover", handleDragOver);
elm.addEventListener("drop", handleDrop);
}
};
/**
* handle dragstart
* @param {!Object} evt - event
* @returns {void}
*/
const handleDragStart = evt => {
const {target: {dataset: {tabId}}} = evt;
if (tabId) {
evt.dataTransfer.effectAllowed = "move";
evt.dataTransfer.setData(MIME_TYPE, tabId);
}
};
/**
* add DnD drag event listener
* @param {Object} elm - draggable element
* @returns {void}
*/
const addDragEventListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("dragstart", handleDragStart);
}
};
/* sidebar tab containers */
/**
* restore sidebar tab containers
* @returns {Promise.<Array>} - result of each handler
*/
const restoreTabContainers = async () => {
const func = [];
const items = document.querySelectorAll(
`.${CLASS_TAB_CONTAINER}:not(#${NEW_TAB})`
);
for (const item of items) {
const {childElementCount, classList, id, parentNode} = item;
switch (childElementCount) {
case 0:
id !== PINNED && parentNode.removeChild(item);
break;
case 1:
classList.remove(CLASS_TAB_GROUP);
break;
default:
classList.add(CLASS_TAB_GROUP);
}
id !== PINNED && func.push(addDropEventListener(item));
}
func.push(storeTabData());
return Promise.all(func);
};
/* context menus */
/**
* handle context menu click
* @param {!Object} evt - event
* @returns {Promise.<Array>} - results of each handler
*/
const handleClickedContextMenu = async evt => {
const {target: {id}} = evt;
const tab = sidebar.context && sidebar.context.classList &&
sidebar.context.classList.contains(TAB) && sidebar.context;
const tabId = tab && tab.dataset && tab.dataset.tabId &&
tab.dataset.tabId * 1;
const tabsTab = tab && tab.dataset && tab.dataset.tab &&
JSON.parse(tab.dataset.tab);
const func = [];
switch (id) {
case MENU_SIDEBAR_INIT:
func.push(initSidebar(true));
break;
case MENU_TABS_BOOKMARK_ALL: {
const items = document.querySelectorAll(
`${TAB_QUERY}:not(.${PINNED})`
);
if (items && items.length > 1) {
for (const item of items) {
const itemTab = item.dataset && item.dataset.tab &&
JSON.parse(item.dataset.tab);
const {title, url} = itemTab;
func.push(bookmarkTab({title, url}));
}
}
break;
}
case MENU_TABS_RELOAD_ALL: {
const items = document.querySelectorAll(TAB_QUERY);
if (items && items.length) {
for (const item of items) {
const itemId = item && item.dataset && item.dataset.tabId * 1;
Number.isInteger(itemId) && func.push(reloadTab(itemId));
}
}
break;
}
case MENU_TAB_AUDIO: {
if (Number.isInteger(tabId) && tabsTab) {
const {mutedInfo: {muted}} = tabsTab;
func.push(updateTab(tabId, {muted: !muted}));
}
break;
}
case MENU_TAB_CLOSE:
Number.isInteger(tabId) && func.push(removeTab(tabId));
break;
case MENU_TAB_CLOSE_UNDO: {
const {lastClosedTab} = sidebar;
if (lastClosedTab) {
const {sessionId} = lastClosedTab;
isString(sessionId) && func.push(restoreClosedTab(sessionId));
}
break;
}
case MENU_TAB_GROUP_COLLAPSE:
tab && tab.parentNode.classList.contains(CLASS_TAB_GROUP) &&
func.push(toggleTabCollapsed({target: tab}));
break;
case MENU_TAB_GROUP_RELOAD: {
if (tab) {
const {parentNode} = tab;
if (parentNode.classList.contains(CLASS_TAB_GROUP)) {
const items = parentNode.querySelectorAll(TAB_QUERY);
if (items && items.length) {
for (const item of items) {
const itemId = item && item.dataset && item.dataset.tabId * 1;
Number.isInteger(itemId) && func.push(reloadTab(itemId));
}
}
}
}
break;
}
case MENU_TAB_GROUP_UNGROUP: {
if (tab && tabsTab) {
const {parentNode} = tab;
!tabsTab.pinned && parentNode.classList.contains(CLASS_TAB_GROUP) &&
func.push(ungroupTabs(parentNode).then(restoreTabContainers));
}
break;
}
case MENU_TAB_NEW_WIN_MOVE:
Number.isInteger(tabId) && func.push(createNewWindow({
tabId,
type: "normal",
}));
break;
case MENU_TAB_PIN: {
if (tabsTab) {
const {pinned} = tabsTab;
func.push(updateTab(tabId, {pinned: !pinned}));
}
break;
}
case MENU_TAB_RELOAD:
Number.isInteger(tabId) && func.push(reloadTab(tabId));
break;
case MENU_TAB_TABS_CLOSE_END: {
if (Number.isInteger(tabId)) {
const index = tabsTab && tabsTab.index && tabsTab.index * 1;
const items = document.querySelectorAll(
`${TAB_QUERY}:not([data-tab-id="${tabId}"])`
);
const arr = [];
if (items && items.length && Number.isInteger(index)) {
for (const item of items) {
const {dataset} = item;
const itemId = dataset && dataset.tabId && dataset.tabId * 1;
const itemTab = dataset && dataset.tab && JSON.parse(dataset.tab);
const itemIndex = itemTab && itemTab.index && itemTab.index * 1;
Number.isInteger(itemId) && Number.isInteger(itemIndex) &&
itemIndex > index && arr.push(itemId);
}
}
arr.length && func.push(removeTab(arr));
}
break;
}
case MENU_TAB_TABS_CLOSE_OTHER: {
const items = Number.isInteger(tabId) && document.querySelectorAll(
`${TAB_QUERY}:not([data-tab-id="${tabId}"])`
);
const arr = [];
if (items && items.length) {
for (const item of items) {
const {dataset} = item;
const itemId = dataset && dataset.tabId && dataset.tabId * 1;
Number.isInteger(itemId) && arr.push(itemId);
}
}
arr.length && func.push(removeTab(arr));
break;
}
case MENU_THEME_DARK:
func.push(setTheme([THEME_DARK]));
break;
case MENU_THEME_DEFAULT:
func.push(setTheme([THEME_DEFAULT]));
break;
case MENU_THEME_LIGHT:
func.push(setTheme([THEME_LIGHT]));
break;
default: {
const msg = `No handler found for ${id}.`;
func.push(logWarn(msg));
}
}
return Promise.all(func);
};
/* context menu items */
const menuItems = {
sidebarTabs: {
id: MENU,
title: i18n.getMessage("extensionShortName"),
contexts: ["page"],
type: "normal",
enabled: false,
subItems: {
/* tab */
[TAB]: {
id: MENU_TAB,
title: i18n.getMessage(`${TAB}_label`),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
subItems: {
[TAB_RELOAD]: {
id: MENU_TAB_RELOAD,
title: i18n.getMessage(TAB_RELOAD),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
[AUDIO_MUTE]: {
id: MENU_TAB_AUDIO,
title: i18n.getMessage(AUDIO_MUTE),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
toggleTitle: i18n.getMessage(AUDIO_MUTE_UNMUTE),
},
[TAB_PIN]: {
id: MENU_TAB_PIN,
title: i18n.getMessage(TAB_PIN),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
toggleTitle: i18n.getMessage(TAB_PIN_UNPIN),
},
[NEW_WIN_MOVE]: {
id: MENU_TAB_NEW_WIN_MOVE,
title: i18n.getMessage(NEW_WIN_MOVE),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
[TABS_CLOSE_END]: {
id: MENU_TAB_TABS_CLOSE_END,
title: i18n.getMessage(TABS_CLOSE_END),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
[TABS_CLOSE_OTHER]: {
id: MENU_TAB_TABS_CLOSE_OTHER,
title: i18n.getMessage(TABS_CLOSE_OTHER),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
[TAB_CLOSE]: {
id: MENU_TAB_CLOSE,
title: i18n.getMessage(TAB_CLOSE),
contexts: [CLASS_TAB, CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
},
},
/* tab group */
[TAB_GROUP]: {
id: MENU_TAB_GROUP,
title: i18n.getMessage(`${TAB_GROUP}_label`),
contexts: [CLASS_TAB_GROUP],
type: "normal",
enabled: false,
subItems: {
[TAB_GROUP_RELOAD]: {
id: MENU_TAB_GROUP_RELOAD,
title: i18n.getMessage(TAB_GROUP_RELOAD),
contexts: [CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
[TAB_GROUP_COLLAPSE]: {
id: MENU_TAB_GROUP_COLLAPSE,
title: i18n.getMessage(TAB_GROUP_COLLAPSE),
contexts: [CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
toggleTitle: i18n.getMessage(TAB_GROUP_EXPAND),
},
[TAB_GROUP_UNGROUP]: {
id: MENU_TAB_GROUP_UNGROUP,
title: i18n.getMessage(TAB_GROUP_UNGROUP),
contexts: [CLASS_TAB_GROUP],
type: "normal",
enabled: false,
onclick: true,
},
},
},
/* all tabs */
[TABS_RELOAD_ALL]: {
id: MENU_TABS_RELOAD_ALL,
title: i18n.getMessage(TABS_RELOAD_ALL),
contexts: ["page"],
type: "normal",
enabled: true,
onclick: true,
},
[TABS_BOOKMARK_ALL]: {
id: MENU_TABS_BOOKMARK_ALL,
title: i18n.getMessage(TABS_BOOKMARK_ALL),
contexts: ["page"],
type: "normal",
enabled: false,
onclick: true,
},
[TAB_CLOSE_UNDO]: {
id: MENU_TAB_CLOSE_UNDO,
title: i18n.getMessage(TAB_CLOSE_UNDO),
contexts: ["page"],
type: "normal",
enabled: false,
onclick: true,
},
/* sidebar */
[THEME_SELECT]: {
id: MENU_THEME_SELECT,
title: i18n.getMessage(THEME_SELECT),
contexts: ["page"],
type: "normal",
enabled: true,
subItems: {
[THEME_DEFAULT]: {
id: MENU_THEME_DEFAULT,
title: i18n.getMessage(THEME_DEFAULT),
contexts: ["page"],
type: "normal",
enabled: true,
onclick: true,
},
[THEME_LIGHT]: {
id: MENU_THEME_LIGHT,
title: i18n.getMessage(THEME_LIGHT),
contexts: ["page"],
type: "normal",
enabled: true,
onclick: true,
},
[THEME_DARK]: {
id: MENU_THEME_DARK,
title: i18n.getMessage(THEME_DARK),
contexts: ["page"],
type: "normal",
enabled: true,
onclick: true,
},
},
},
[SIDEBAR_INIT]: {
id: MENU_SIDEBAR_INIT,
title: i18n.getMessage(SIDEBAR_INIT),
contexts: ["page"],
type: "normal",
enabled: true,
onclick: true,
},
},
},
};
/**
* add menuitem click listener
* @param {Object} elm - element
* @returns {void}
*/
const addContextMenuClickListener = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
elm.addEventListener("click", evt =>
handleClickedContextMenu(evt).catch(logError)
);
}
};
/**
* create context menu item
* @param {string} id - menu item ID
* @param {Object} data - context data
* @returns {Promise.<Array>} - results of each handler
*/
const createMenuItem = async (id, data = {}) => {
const {enabled, onclick, title, type} = data;
const func = [];
if (isString(id) && type === "normal") {
const elm = document.getElementById(id);
if (elm) {
elm.label = title;
if (elm.localName === "menuitem") {
elm.disabled = !enabled && true || false;
onclick && func.push(addContextMenuClickListener(elm));
}
}
}
return Promise.all(func);
};
/**
* create context menu items
* @param {Object} menu - menu
* @returns {Promise.<Array>} - results of each handler
*/
const createContextMenu = async (menu = menuItems) => {
const func = [];
const items = Object.keys(menu);
for (const item of items) {
const {enabled, id, onclick, subItems, title, type} = menu[item];
const itemData = {enabled, onclick, title, type};
func.push(createMenuItem(id, itemData));
if (subItems) {
func.push(createContextMenu(subItems));
}
}
return Promise.all(func);
};
/**
* update context menu
* @param {string} id - menu item ID
* @param {Object} data - update items data
* @returns {void}
*/
const updateContextMenu = async (id, data = {}) => {
if (isString(id)) {
const elm = document.getElementById(id);
if (elm) {
const {enabled, title} = data;
title && (elm.label = title);
if (elm.localName === "menuitem") {
elm.disabled = !enabled && true || false;
}
}
}
};
/**
* toggle context menu class
* @param {string} name - class name
* @param {boolean} bool - add class
* @returns {void}
*/
const toggleContextMenuClass = async (name, bool = false) => {
if (isString(name)) {
const elm = document.getElementById(MENU);
if (elm) {
const {classList} = elm;
if (bool) {
classList.add(name);
} else {
classList.remove(name);
}
}
}
};
/**
* set context
* @param {!Object} evt - event
* @returns {Promise.<Array>} - results of each handler
*/
const setContext = async evt => {
const {button, key, shiftKey, target} = evt;
const func = [];
if (shiftKey && key === "F10" || key === "ContextMenu" ||
button === MOUSE_BUTTON_RIGHT) {
const tab = await getSidebarTab(target);
const tabMenu = menuItems.sidebarTabs.subItems[TAB];
const tabKeys = [
TAB_RELOAD, AUDIO_MUTE, TAB_PIN, NEW_WIN_MOVE, TAB_CLOSE,
TABS_CLOSE_END, TABS_CLOSE_OTHER,
];
const tabGroupMenu = menuItems.sidebarTabs.subItems[TAB_GROUP];
const tabGroupKeys = [
TAB_GROUP_RELOAD,
TAB_GROUP_COLLAPSE,
TAB_GROUP_UNGROUP,
];
const allTabsKeys = [TABS_BOOKMARK_ALL, TAB_CLOSE_UNDO];
if (tab) {
const {parentNode} = tab;
const {classList: parentClass} = parentNode;
const tabId = tab.dataset && tab.dataset.tabId;
const tabsTab = tab.dataset && JSON.parse(tab.dataset.tab);
sidebar.context = tab;
func.push(
updateContextMenu(tabMenu.id, {
enabled: true,
title: tabMenu.title,
}),
toggleContextMenuClass(CLASS_TAB, true),
);
for (const itemKey of tabKeys) {
const item = tabMenu.subItems[itemKey];
const {id, title, toggleTitle} = item;
const data = {};
switch (itemKey) {
case AUDIO_MUTE: {
const obj = tab.querySelector(`.${CLASS_TAB_AUDIO_ICON}`);
data.enabled = true;
if (obj && obj.alt) {
data.title = obj.alt;
} else {
data.title = title;
}
break;
}
case TABS_CLOSE_END: {
if (tabsTab.pinned) {
data.enabled = false;
} else {
const index = getSidebarTabIndex(tab);
const obj = document.querySelectorAll(TAB_QUERY);
if (obj && obj.length - 1 > index) {
data.enabled = true;
} else {
data.enabled = false;
}
}
data.title = title;
break;
}
case TABS_CLOSE_OTHER: {
if (tabsTab.pinned) {
data.enabled = false;
} else {
const obj = tabId && document.querySelectorAll(
`${TAB_QUERY}:not([data-tab-id="${tabId}"])`
);
if (obj && obj.length) {
data.enabled = true;
} else {
data.enabled = false;
}
}
data.title = title;
break;
}
case TAB_PIN:
data.enabled = true;
if (parentClass.contains(PINNED)) {
data.title = toggleTitle;
} else {
data.title = title;
}
break;
default:
data.enabled = true;
data.title = title;
}
func.push(updateContextMenu(id, data));
}
if (parentClass.contains(CLASS_TAB_GROUP)) {
func.push(
updateContextMenu(tabGroupMenu.id, {
enabled: true,
title: tabGroupMenu.title,
}),
toggleContextMenuClass(CLASS_TAB_GROUP, true),
);
} else {
func.push(
updateContextMenu(tabGroupMenu.id, {
enabled: false,
title: tabGroupMenu.title,
}),
toggleContextMenuClass(CLASS_TAB_GROUP, false),
);
}
for (const itemKey of tabGroupKeys) {
const item = tabGroupMenu.subItems[itemKey];
const {id, title} = item;
const data = {};
switch (itemKey) {
case TAB_GROUP_COLLAPSE: {
const obj = tab.querySelector(`.${CLASS_TAB_TOGGLE_ICON}`);
if (parentClass.contains(CLASS_TAB_GROUP) && obj && obj.alt) {
data.enabled = true;
data.title = obj.alt;
} else {
data.enabled = false;
data.title = title;
}
break;
}
case TAB_GROUP_UNGROUP:
if (!tabsTab.pinned && parentClass.contains(CLASS_TAB_GROUP)) {
data.enabled = true;
} else {
data.enabled = false;
}
data.title = title;
break;
default:
if (parentClass.contains(CLASS_TAB_GROUP)) {
data.enabled = true;
} else {
data.enabled = false;
}
data.title = title;
}
func.push(updateContextMenu(id, data));
}
} else {
sidebar.context = target;
func.push(
updateContextMenu(tabMenu.id, {
enabled: false,
title: tabMenu.title,
}),
toggleContextMenuClass(CLASS_TAB, false),
toggleContextMenuClass(CLASS_TAB_GROUP, false),
);
for (const itemKey of tabKeys) {
const item = tabMenu.subItems[itemKey];
const {id, title} = item;
const enabled = false;
func.push(updateContextMenu(id, {enabled, title}));
}
func.push(updateContextMenu(tabGroupMenu.id, {
enabled: false,
title: tabGroupMenu.title,
}));
for (const itemKey of tabGroupKeys) {
const item = tabGroupMenu.subItems[itemKey];
const {id, title} = item;
const enabled = false;
func.push(updateContextMenu(id, {enabled, title}));
}
}
for (const itemKey of allTabsKeys) {
const item = menuItems.sidebarTabs.subItems[itemKey];
const {id, title} = item;
const data = {};
switch (itemKey) {
case TABS_BOOKMARK_ALL: {
const items = document.querySelectorAll(
`${TAB_QUERY}:not(.${PINNED})`
);
if (items && items.length > 1) {
data.enabled = true;
} else {
data.enabled = false;
}
break;
}
case TAB_CLOSE_UNDO: {
const {lastClosedTab} = sidebar;
if (lastClosedTab) {
data.enabled = true;
} else {
data.enabled = false;
}
break;
}
default:
data.enabled = true;
}
data.title = title;
func.push(updateContextMenu(id, data));
}
}
return Promise.all(func);
};
/* tabs event handlers */
/**
* handle activated tab
* @param {!Object} info - activated info
* @returns {void}
*/
const handleActivatedTab = async info => {
const {tabId, windowId} = info;
if (windowId === sidebar.windowId && tabId !== tabs.TAB_ID_NONE) {
const newActiveTab = document.querySelector(`[data-tab-id="${tabId}"]`);
const oldActiveTab = document.querySelector(`.${CLASS_TAB}.${ACTIVE}`);
if (newActiveTab && oldActiveTab && newActiveTab !== oldActiveTab) {
const {
classList: newClassList, parentNode: {classList: newParentClassList},
} = newActiveTab;
const {
classList: oldClassList, parentNode: {classList: oldParentClassList},
} = oldActiveTab;
oldClassList.remove(ACTIVE);
oldParentClassList.remove(ACTIVE);
newParentClassList.add(ACTIVE);
newClassList.add(ACTIVE);
}
}
};
/**
* handle created tab
* @param {Object} tabsTab - tabs.Tab
* @returns {Promise.<Array>} - results of each handler
*/
const handleCreatedTab = async tabsTab => {
const {
active, audible, cookieStoreId, favIconUrl, id, index, mutedInfo, pinned,
status, title, windowId,
} = tabsTab;
const {muted} = mutedInfo;
const func = [];
if (windowId === sidebar.windowId && id !== tabs.TAB_ID_NONE) {
const tab = await getTemplate(CLASS_TAB_TMPL);
const tabItems = [
`.${TAB}`, `.${CLASS_TAB_CONTEXT}`, `.${CLASS_TAB_TOGGLE_ICON}`,
`.${CLASS_TAB_CONTENT}`, `.${CLASS_TAB_ICON}`, `.${CLASS_TAB_TITLE}`,
`.${CLASS_TAB_AUDIO}`, `.${CLASS_TAB_AUDIO_ICON}`,
`.${CLASS_TAB_CLOSE}`, `.${CLASS_TAB_CLOSE_ICON}`,
];
const items = tab.querySelectorAll(tabItems.join(","));
const list = document.querySelectorAll(TAB_QUERY);
const listIdx = list && list[index];
const listIdxPrev = list && index > 0 && list[index - 1];
let container;
for (const item of items) {
const {classList} = item;
if (classList.contains(CLASS_TAB_CONTEXT)) {
item.title = i18n.getMessage(`${TAB_GROUP_COLLAPSE}_tooltip`);
func.push(addTabContextClickListener(item));
} else if (classList.contains(CLASS_TAB_TOGGLE_ICON)) {
item.alt = i18n.getMessage(`${TAB_GROUP_COLLAPSE}`);
} else if (classList.contains(CLASS_TAB_CONTENT)) {
item.title = title;
} else if (classList.contains(CLASS_TAB_ICON)) {
item.alt = title;
func.push(
setTabIcon(item, {status, title, favIconUrl}),
addTabIconErrorListener(item),
);
} else if (classList.contains(CLASS_TAB_TITLE)) {
item.textContent = title;
} else if (classList.contains(CLASS_TAB_AUDIO)) {
if (audible || muted) {
classList.add(AUDIBLE);
} else {
classList.remove(AUDIBLE);
}
func.push(
setTabAudio(item, {audible, muted}),
addTabAudioClickListener(item),
);
} else if (classList.contains(CLASS_TAB_AUDIO_ICON)) {
func.push(setTabAudioIcon(item, {audible, muted}));
} else if (classList.contains(CLASS_TAB_CLOSE)) {
item.title = i18n.getMessage(`${TAB_CLOSE}_tooltip`);
func.push(addTabCloseClickListener(item));
} else if (classList.contains(CLASS_TAB_CLOSE_ICON)) {
item.alt = i18n.getMessage(`${TAB_CLOSE}`);
}
func.push(addTabClickListener(item));
}
tab.dataset.tabId = id;
tab.dataset.tab = JSON.stringify(tabsTab);
active && tab.classList.add(ACTIVE);
if (cookieStoreId) {
const ident = await contextualIdentities.get(cookieStoreId);
if (ident) {
const {color} = ident;
tab.style.borderColor = color;
}
}
if (pinned) {
container = document.getElementById(PINNED);
tab.classList.add(PINNED);
tab.removeAttribute("draggable");
if (container.children[index]) {
container.insertBefore(tab, container.children[index]);
} else {
container.appendChild(tab);
}
container.childElementCount > 1 &&
container.classList.add(CLASS_TAB_GROUP);
} else if (list.length !== index && listIdx && listIdx.parentNode &&
listIdx.parentNode.classList.contains(CLASS_TAB_GROUP) &&
listIdxPrev && listIdxPrev.parentNode &&
listIdxPrev.parentNode.classList.contains(CLASS_TAB_GROUP) &&
listIdx.parentNode === listIdxPrev.parentNode) {
container = listIdx.parentNode;
container.insertBefore(tab, listIdx);
} else {
let target;
if (list.length !== index && listIdx && listIdx.parentNode) {
target = listIdx.parentNode;
} else {
target = document.getElementById(NEW_TAB);
}
await addDragEventListener(tab);
container = await getTemplate(CLASS_TAB_CONTAINER_TMPL);
container.appendChild(tab);
target.parentNode.insertBefore(container, target);
}
}
return Promise.all(func);
};
/**
* handle attached tab
* @param {number} tabId - tab ID
* @param {Object} info - attached tab info
* @returns {?AsyncFunction} - tabs.Tab
*/
const handleAttachedTab = async (tabId, info) => {
const {newPosition, newWindowId} = info;
let func;
if (newWindowId === sidebar.windowId && tabId !== tabs.TAB_ID_NONE) {
const tabsTab = await tabs.get(tabId);
if (tabsTab) {
tabsTab.index = newPosition;
func = handleCreatedTab(tabsTab);
}
}
return func || null;
};
/**
* handle updated tab
* Note: Occurs frequently, so it should not be async.
* @param {number} tabId - tab ID
* @param {Object} info - updated tab info
* @param {Object} tabsTab - tabs.Tab
* @returns {Promise.<Array>} - results of each handler
*/
const handleUpdatedTab = (tabId, info, tabsTab) => {
const {windowId} = tabsTab;
const func = [];
if (windowId === sidebar.windowId && tabId !== tabs.TAB_ID_NONE) {
const tab = document.querySelector(`[data-tab-id="${tabId}"]`);
if (tab) {
if (info.hasOwnProperty("favIconUrl") ||
info.hasOwnProperty("status") ||
info.hasOwnProperty("title") ||
info.hasOwnProperty("url")) {
const tabContent = tab.querySelector(`.${CLASS_TAB_CONTENT}`);
const tabIcon = tab.querySelector(`.${CLASS_TAB_ICON}`);
const tabTitle = tab.querySelector(`.${CLASS_TAB_TITLE}`);
const {favIconUrl, status, title} = tabsTab;
tabContent && (tabContent.title = title);
tabTitle && (tabTitle.textContent = title);
// Note: Don't push to Promise array
tabIcon && setTabIcon(tabIcon, {favIconUrl, status, title});
}
if (info.hasOwnProperty("audible") ||
info.hasOwnProperty("mutedInfo")) {
const tabAudio = tab.querySelector(`.${CLASS_TAB_AUDIO}`);
const tabAudioIcon = tab.querySelector(`.${CLASS_TAB_AUDIO_ICON}`);
const {muted} = tabsTab.mutedInfo;
const {audible} = tabsTab;
const opt = {audible, muted};
if (tabAudio) {
if (audible || muted) {
tabAudio.classList.add(AUDIBLE);
} else {
tabAudio.classList.remove(audible);
}
func.push(setTabAudio(tabAudio, opt));
}
tabAudioIcon && func.push(setTabAudioIcon(tabAudioIcon, opt));
}
if (info.hasOwnProperty("pinned")) {
const pinnedContainer = document.getElementById(PINNED);
if (info.pinned) {
const container = pinnedContainer;
tab.classList.add(PINNED);
tab.removeAttribute("draggable");
container.appendChild(tab);
func.push(restoreTabContainers());
} else {
const {
nextElementSibling: pinnedNextElement,
parentNode: pinnedParentNode,
} = pinnedContainer;
const container = getTemplate(CLASS_TAB_CONTAINER_TMPL);
tab.classList.remove(PINNED);
tab.setAttribute("draggable", "true");
func.push(addDragEventListener(tab));
container.appendChild(tab);
pinnedParentNode.insertBefore(container, pinnedNextElement);
func.push(restoreTabContainers());
}
}
tab.dataset.tab = JSON.stringify(tabsTab);
}
}
return Promise.all(func).catch(logError);
};
/**
* handle moved tab
* @param {!number} tabId - tab ID
* @param {!Object} info - moved info
* @returns {void}
*/
const handleMovedTab = async (tabId, info) => {
const {fromIndex, toIndex, windowId} = info;
if (windowId === sidebar.windowId && tabId !== tabs.TAB_ID_NONE) {
const tab = document.querySelector(`[data-tab-id="${tabId}"]`);
const items = document.querySelectorAll(TAB_QUERY);
if (toIndex === 0) {
const tabsTab = await tabs.get(tabId);
const {pinned} = tabsTab;
if (pinned) {
const container = document.getElementById(PINNED);
const {firstElementChild} = container;
container.insertBefore(tab, firstElementChild);
} else {
const container = await getTemplate(CLASS_TAB_CONTAINER_TMPL);
const [target] = items;
container.appendChild(tab);
target.parentNode.insertBefore(container, target);
}
} else {
const target = items[fromIndex >= toIndex && toIndex - 1 || toIndex];
const {nextElementSibling, parentNode} = target;
const unPinned =
toIndex > fromIndex &&
items[fromIndex].parentNode.classList.contains(PINNED) &&
items[toIndex].parentNode.classList.contains(PINNED) &&
items[toIndex] === items[toIndex].parentNode.lastElementChild;
let {dataset: {group}} = tab;
group = group === "true" && true || false;
if (!group && parentNode.childElementCount === 1 || unPinned) {
const {
nextElementSibling: parentNextElementSibling,
parentNode: parentParentNode,
} = parentNode;
const frag = await getTemplate(CLASS_TAB_CONTAINER_TMPL);
if (frag) {
frag.appendChild(tab);
if (parentNextElementSibling) {
parentParentNode.insertBefore(frag, parentNextElementSibling);
} else {
const newtab = document.getElementById(NEW_TAB);
parentParentNode.insertBefore(frag, newtab);
}
}
} else if (nextElementSibling) {
parentNode.insertBefore(tab, nextElementSibling);
} else {
parentNode.appendChild(tab);
}
}
tab.dataset.group = null;
}
};
/**
* handle detached tab
* @param {number} tabId - tab ID
* @param {Object} info - detached tab info
* @returns {void}
*/
const handleDetachedTab = async (tabId, info) => {
const {oldWindowId} = info;
if (oldWindowId === sidebar.windowId && tabId !== tabs.TAB_ID_NONE) {
const tab = document.querySelector(`[data-tab-id="${tabId}"]`);
tab && tab.parentNode.removeChild(tab);
}
};
/**
* handle removed tab
* @param {number} tabId - tab ID
* @param {Object} info - removed tab info
* @returns {void}
*/
const handleRemovedTab = async (tabId, info) => {
const {isWindowClosing, windowId} = info;
if (windowId === sidebar.windowId && !isWindowClosing &&
tabId !== tabs.TAB_ID_NONE) {
const tab = document.querySelector(`[data-tab-id="${tabId}"]`);
tab && tab.parentNode.removeChild(tab);
}
};
/* listeners */
tabs.onActivated.addListener(info =>
handleActivatedTab(info).catch(logError)
);
tabs.onAttached.addListener((tabId, info) =>
handleAttachedTab(tabId, info).then(restoreTabContainers).catch(logError)
);
tabs.onCreated.addListener(tabsTab =>
handleCreatedTab(tabsTab).then(restoreTabContainers).catch(logError)
);
tabs.onDetached.addListener((tabId, info) =>
handleDetachedTab(tabId, info).then(restoreTabContainers).catch(logError)
);
tabs.onMoved.addListener((tabId, info) =>
handleMovedTab(tabId, info).then(restoreTabContainers).catch(logError)
);
tabs.onRemoved.addListener((tabId, info) =>
handleRemovedTab(tabId, info).then(restoreTabContainers)
.then(getLastClosedTab).catch(logError)
);
// Note: Occurs frequently, so handler should not be async.
tabs.onUpdated.addListener(handleUpdatedTab);
/* start up */
/**
* set stored tab group data
* @returns {void}
*/
const restoreTabGroup = async () => {
const {tab: storedTab} = await storage.local.get(TAB);
if (storedTab) {
const {tab, group: groups} = storedTab;
const items = document.querySelectorAll(TAB_QUERY);
if (items.length === tab.length) {
const l = items.length;
let i = 0;
let bool;
while (i < l) {
const item = items[i];
const tabsTab = item.dataset && item.dataset.tab &&
JSON.parse(item.dataset.tab);
const {url} = tabsTab;
bool = isUrlEqual(url, tab[i]);
if (!bool) {
break;
}
i++;
}
if (bool) {
for (const group of groups) {
const [target, ...indexes] = group;
const container = items[target].parentNode;
container.classList.add(CLASS_TAB_GROUP);
for (const index of indexes) {
container.appendChild(items[index]);
}
}
}
}
}
};
/**
* emulate tabs to sidebar
* @returns {Promise.<Array>} - results of each handler
*/
const emulateTabs = async () => {
const items = await tabs.query({windowId: windows.WINDOW_ID_CURRENT});
const func = [];
for (const item of items) {
func.push(handleCreatedTab(item));
}
return Promise.all(func);
};
document.addEventListener("DOMContentLoaded", () => Promise.all([
addNewTabClickListener(),
createContextMenu(),
getTheme().then(setTheme),
setSidebar(),
]).then(emulateTabs).then(restoreTabGroup).then(restoreTabContainers)
.catch(logError));
window.addEventListener("keydown", evt => setContext(evt).catch(logError),
true);
window.addEventListener("mousedown", evt => setContext(evt).catch(logError),
true);
}
| Always update favicon and title
| src/js/sidebar.js | Always update favicon and title | <ide><path>rc/js/sidebar.js
<ide> if (windowId === sidebar.windowId && tabId !== tabs.TAB_ID_NONE) {
<ide> const tab = document.querySelector(`[data-tab-id="${tabId}"]`);
<ide> if (tab) {
<del> if (info.hasOwnProperty("favIconUrl") ||
<del> info.hasOwnProperty("status") ||
<del> info.hasOwnProperty("title") ||
<del> info.hasOwnProperty("url")) {
<del> const tabContent = tab.querySelector(`.${CLASS_TAB_CONTENT}`);
<del> const tabIcon = tab.querySelector(`.${CLASS_TAB_ICON}`);
<del> const tabTitle = tab.querySelector(`.${CLASS_TAB_TITLE}`);
<del> const {favIconUrl, status, title} = tabsTab;
<del> tabContent && (tabContent.title = title);
<del> tabTitle && (tabTitle.textContent = title);
<del> // Note: Don't push to Promise array
<del> tabIcon && setTabIcon(tabIcon, {favIconUrl, status, title});
<del> }
<add> const {favIconUrl, status, title} = tabsTab;
<add> const tabContent = tab.querySelector(`.${CLASS_TAB_CONTENT}`);
<add> const tabTitle = tab.querySelector(`.${CLASS_TAB_TITLE}`);
<add> const tabIcon = tab.querySelector(`.${CLASS_TAB_ICON}`);
<add> tabContent && (tabContent.title = title);
<add> tabTitle && (tabTitle.textContent = title);
<add> // Note: Don't push to Promise array
<add> tabIcon && setTabIcon(tabIcon, {favIconUrl, status, title});
<ide> if (info.hasOwnProperty("audible") ||
<ide> info.hasOwnProperty("mutedInfo")) {
<ide> const tabAudio = tab.querySelector(`.${CLASS_TAB_AUDIO}`); |
|
Java | apache-2.0 | 2f3ce2c7df1eaac2f9d964733b1e6e57ec57ee1c | 0 | commoncrawl/nutch,commoncrawl/nutch,commoncrawl/nutch,commoncrawl/nutch | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.commoncrawl.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import org.junit.Test;
public class TestWarcRecordWriter {
public final static String statusLine1 = "HTTP/1.1 200 OK";
public final static String testHeaders1[] = { //
"Content-Type", "text/html", //
"Accept-Ranges", "bytes", //
"Content-Encoding", "gzip", //
"Vary", "Accept-Encoding", "Server",
"Apache/2.0.63 (Unix) PHP/4.4.7 mod_ssl/2.0.63 OpenSSL/0.9.7e mod_fastcgi/2.4.2 DAV/2 SVN/1.4.2",
"Last-Modified", "Thu, 15 Jan 2009 00:02:29 GMT", "ETag",
"\"1262d9e-3ffa-2c19af40\"", //
"Date", "Mon, 26 Jan 2009 10:00:40 GMT", //
"Connection", "close", //
"Content-Length", "16378" };
public final static String testHeaderString1;
static {
StringBuilder headers = new StringBuilder();
headers.append(statusLine1).append(WarcRecordWriter.CRLF);
for (int i = 0; i < testHeaders1.length; i += 2) {
headers.append(testHeaders1[i]).append(WarcRecordWriter.COLONSP);
headers.append(testHeaders1[i+1]).append(WarcRecordWriter.CRLF);
}
headers.append(WarcRecordWriter.CRLF);
testHeaderString1 = headers.toString();
}
@Test
public void testFormatHttpHeaders() {
assertEquals("Formatting HTTP header failed", testHeaderString1,
WarcRecordWriter.formatHttpHeaders(statusLine1,
Arrays.asList(testHeaders1)));
}
@Test
public void testFixHttpHeaders() {
StringBuilder headers = new StringBuilder();
headers.append(statusLine1).append(WarcRecordWriter.CRLF);
for (int i = 0; i < testHeaders1.length; i += 2) {
headers.append(testHeaders1[i]).append(WarcRecordWriter.COLONSP);
headers.append(testHeaders1[i+1]).append(WarcRecordWriter.CRLF);
}
String fixed = WarcRecordWriter.fixHttpHeaders(WarcRecordWriter.formatHttpHeaders(statusLine1,
Arrays.asList(testHeaders1)), 50000);
assertFalse("Content-Encoding should be removed",
fixed.contains("\r\nContent-Encoding:"));
// assertFalse("Transfer-Encoding should be removed",
// fixed.contains("\r\nTransfer-Encoding:"));
assertTrue("Content-Length to be fixed",
fixed.contains("\r\nContent-Length: 50000\r\n"));
}
}
| src/test/org/commoncrawl/util/TestWarcRecordWriter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.commoncrawl.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import org.junit.Test;
public class TestWarcRecordWriter {
public final static String statusLine1 = "HTTP/1.1 200 OK";
public final static String testHeaders1[] = { //
"Content-Type", "text/html", //
"Accept-Ranges", "bytes", //
"Content-Encoding", "gzip", //
"Vary", "Accept-Encoding", "Server",
"Apache/2.0.63 (Unix) PHP/4.4.7 mod_ssl/2.0.63 OpenSSL/0.9.7e mod_fastcgi/2.4.2 DAV/2 SVN/1.4.2",
"Last-Modified", "Thu, 15 Jan 2009 00:02:29 GMT", "ETag",
"\"1262d9e-3ffa-2c19af40\"", //
"Date", "Mon, 26 Jan 2009 10:00:40 GMT", //
"Connection", "close", //
"Content-Length", "16378" };
public final static String testHeaderString1;
static {
StringBuilder headers = new StringBuilder();
headers.append(statusLine1).append(WarcRecordWriter.CRLF);
for (int i = 0; i < testHeaders1.length; i += 2) {
headers.append(testHeaders1[i]).append(WarcRecordWriter.COLONSP);
headers.append(testHeaders1[i+1]).append(WarcRecordWriter.CRLF);
}
testHeaderString1 = headers.toString();
}
@Test
public void testFormatHttpHeaders() {
assertEquals("Formatting HTTP header failed", testHeaderString1,
WarcRecordWriter.formatHttpHeaders(statusLine1,
Arrays.asList(testHeaders1)));
}
@Test
public void testFixHttpHeaders() {
StringBuilder headers = new StringBuilder();
headers.append(statusLine1).append(WarcRecordWriter.CRLF);
for (int i = 0; i < testHeaders1.length; i += 2) {
headers.append(testHeaders1[i]).append(WarcRecordWriter.COLONSP);
headers.append(testHeaders1[i+1]).append(WarcRecordWriter.CRLF);
}
String fixed = WarcRecordWriter.fixHttpHeaders(WarcRecordWriter.formatHttpHeaders(statusLine1,
Arrays.asList(testHeaders1)), 50000);
assertFalse("Content-Encoding should be removed",
fixed.contains("\r\nContent-Encoding:"));
// assertFalse("Transfer-Encoding should be removed",
// fixed.contains("\r\nTransfer-Encoding:"));
assertTrue("Content-Length to be fixed",
fixed.contains("\r\nContent-Length: 50000\r\n"));
}
}
| WARC writer incorrectly adds extra line in response records
between HTTP headers and payload content (#5)
- HTTP headers are now supposed to always contain a trailing empty line
- fix unit to reflect this
| src/test/org/commoncrawl/util/TestWarcRecordWriter.java | WARC writer incorrectly adds extra line in response records between HTTP headers and payload content (#5) - HTTP headers are now supposed to always contain a trailing empty line - fix unit to reflect this | <ide><path>rc/test/org/commoncrawl/util/TestWarcRecordWriter.java
<ide> headers.append(testHeaders1[i]).append(WarcRecordWriter.COLONSP);
<ide> headers.append(testHeaders1[i+1]).append(WarcRecordWriter.CRLF);
<ide> }
<add> headers.append(WarcRecordWriter.CRLF);
<ide> testHeaderString1 = headers.toString();
<ide> }
<ide> |
|
Java | apache-2.0 | 644d7c0902005484a481543520296aee0fb93adf | 0 | RackerWilliams/xercesj,RackerWilliams/xercesj,RackerWilliams/xercesj | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.xerces.dom;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.xerces.impl.dv.ValidatedInfo;
import org.apache.xerces.impl.xs.ElementPSVImpl;
import org.apache.xerces.impl.xs.util.StringListImpl;
import org.apache.xerces.xs.ElementPSVI;
import org.apache.xerces.xs.ItemPSVI;
import org.apache.xerces.xs.ShortList;
import org.apache.xerces.xs.StringList;
import org.apache.xerces.xs.XSAttributeUse;
import org.apache.xerces.xs.XSComplexTypeDefinition;
import org.apache.xerces.xs.XSElementDeclaration;
import org.apache.xerces.xs.XSModel;
import org.apache.xerces.xs.XSNotationDeclaration;
import org.apache.xerces.xs.XSSimpleTypeDefinition;
import org.apache.xerces.xs.XSTypeDefinition;
import org.apache.xerces.xs.XSValue;
/**
* Element namespace implementation; stores PSVI element items.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
*
* @version $Id$
*/
public class PSVIElementNSImpl extends ElementNSImpl implements ElementPSVI {
/** Serialization version. */
static final long serialVersionUID = 6815489624636016068L;
/**
* Construct an element node.
*/
public PSVIElementNSImpl(CoreDocumentImpl ownerDocument, String namespaceURI,
String qualifiedName, String localName) {
super(ownerDocument, namespaceURI, qualifiedName, localName);
}
/**
* Construct an element node.
*/
public PSVIElementNSImpl(CoreDocumentImpl ownerDocument, String namespaceURI,
String qualifiedName) {
super(ownerDocument, namespaceURI, qualifiedName);
}
/** element declaration */
protected XSElementDeclaration fDeclaration = null;
/** type of element, could be xsi:type */
protected XSTypeDefinition fTypeDecl = null;
/** true if clause 3.2 of Element Locally Valid (Element) (3.3.4)
* is satisfied, otherwise false
*/
protected boolean fNil = false;
/** false if the element value was provided by the schema; true otherwise.
*/
protected boolean fSpecified = true;
/** Schema value */
protected ValidatedInfo fValue = new ValidatedInfo();
/** http://www.w3.org/TR/xmlschema-1/#e-notation*/
protected XSNotationDeclaration fNotation = null;
/** validation attempted: none, partial, full */
protected short fValidationAttempted = ElementPSVI.VALIDATION_NONE;
/** validity: valid, invalid, unknown */
protected short fValidity = ElementPSVI.VALIDITY_NOTKNOWN;
/** error codes */
protected StringList fErrorCodes = null;
/** error messages */
protected StringList fErrorMessages = null;
/** validation context: could be QName or XPath expression*/
protected String fValidationContext = null;
/** the schema information property */
protected XSModel fSchemaInformation = null;
/** inherited attributes */
protected XSAttributeUse[] fInheritedAttributes = null;
//
// ElementPSVI methods
//
/* (non-Javadoc)
* @see org.apache.xerces.xs.ItemPSVI#constant()
*/
public ItemPSVI constant() {
return new ElementPSVImpl(true, this);
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.ItemPSVI#isConstant()
*/
public boolean isConstant() {
return false;
}
/**
* [schema default]
*
* @return The canonical lexical representation of the declaration's {value constraint} value.
* @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_default>XML Schema Part 1: Structures [schema default]</a>
*/
public String getSchemaDefault() {
return fDeclaration == null ? null : fDeclaration.getConstraintValue();
}
/**
* [schema normalized value]
*
*
* @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_normalized_value>XML Schema Part 1: Structures [schema normalized value]</a>
* @return the normalized value of this item after validation
*/
public String getSchemaNormalizedValue() {
return fValue.getNormalizedValue();
}
/**
* [schema specified]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_specified">XML Schema Part 1: Structures [schema specified]</a>
* @return false value was specified in schema, true value comes from the infoset
*/
public boolean getIsSchemaSpecified() {
return fSpecified;
}
/**
* Determines the extent to which the document has been validated
*
* @return return the [validation attempted] property. The possible values are
* NO_VALIDATION, PARTIAL_VALIDATION and FULL_VALIDATION
*/
public short getValidationAttempted() {
return fValidationAttempted;
}
/**
* Determine the validity of the node with respect
* to the validation being attempted
*
* @return return the [validity] property. Possible values are:
* UNKNOWN_VALIDITY, INVALID_VALIDITY, VALID_VALIDITY
*/
public short getValidity() {
return fValidity;
}
/**
* A list of error codes generated from validation attempts.
* Need to find all the possible subclause reports that need reporting
*
* @return Array of error codes
*/
public StringList getErrorCodes() {
if (fErrorCodes != null) {
return fErrorCodes;
}
return StringListImpl.EMPTY_LIST;
}
/**
* A list of error messages generated from the validation attempt or
* an empty <code>StringList</code> if no errors occurred during the
* validation attempt. The indices of error messages in this list are
* aligned with those in the <code>[schema error code]</code> list.
*/
public StringList getErrorMessages() {
if (fErrorMessages != null) {
return fErrorMessages;
}
return StringListImpl.EMPTY_LIST;
}
// This is the only information we can provide in a pipeline.
public String getValidationContext() {
return fValidationContext;
}
/**
* [nil]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#e-nil>XML Schema Part 1: Structures [nil]</a>
* @return true if clause 3.2 of Element Locally Valid (Element) (3.3.4) above is satisfied, otherwise false
*/
public boolean getNil() {
return fNil;
}
/**
* [notation]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#e-notation>XML Schema Part 1: Structures [notation]</a>
* @return The notation declaration.
*/
public XSNotationDeclaration getNotation() {
return fNotation;
}
/**
* An item isomorphic to the type definition used to validate this element.
*
* @return a type declaration
*/
public XSTypeDefinition getTypeDefinition() {
return fTypeDecl;
}
/**
* If and only if that type definition is a simple type definition
* with {variety} union, or a complex type definition whose {content type}
* is a simple thype definition with {variety} union, then an item isomorphic
* to that member of the union's {member type definitions} which actually
* validated the element item's normalized value.
*
* @return a simple type declaration
*/
public XSSimpleTypeDefinition getMemberTypeDefinition() {
return fValue.getMemberTypeDefinition();
}
/**
* An item isomorphic to the element declaration used to validate
* this element.
*
* @return an element declaration
*/
public XSElementDeclaration getElementDeclaration() {
return fDeclaration;
}
/**
* [schema information]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_information">XML Schema Part 1: Structures [schema information]</a>
* @return The schema information property if it's the validation root,
* null otherwise.
*/
public XSModel getSchemaInformation() {
return fSchemaInformation;
}
/**
* Inherited attributes.
*
* @return an array of inherited attribute, XSAttributeUse components. null if no inherited attributes were found.
*/
public XSAttributeUse[] getInheritedAttributes() {
return fInheritedAttributes;
}
/**
* Copy PSVI properties from another psvi item.
*
* @param elem the source of element PSVI items
*/
public void setPSVI(ElementPSVI elem) {
this.fDeclaration = elem.getElementDeclaration();
this.fNotation = elem.getNotation();
this.fValidationContext = elem.getValidationContext();
this.fTypeDecl = elem.getTypeDefinition();
this.fSchemaInformation = elem.getSchemaInformation();
this.fValidity = elem.getValidity();
this.fValidationAttempted = elem.getValidationAttempted();
this.fErrorCodes = elem.getErrorCodes();
this.fErrorMessages = elem.getErrorMessages();
if (fTypeDecl instanceof XSSimpleTypeDefinition ||
fTypeDecl instanceof XSComplexTypeDefinition &&
((XSComplexTypeDefinition)fTypeDecl).getContentType() == XSComplexTypeDefinition.CONTENTTYPE_SIMPLE) {
this.fValue.copyFrom(elem.getSchemaValue());
}
else {
this.fValue.reset();
}
this.fSpecified = elem.getIsSchemaSpecified();
this.fNil = elem.getNil();
this.fInheritedAttributes = elem.getInheritedAttributes();
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.ItemPSVI#getActualNormalizedValue()
*/
public Object getActualNormalizedValue() {
return fValue.getActualValue();
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.ItemPSVI#getActualNormalizedValueType()
*/
public short getActualNormalizedValueType() {
return fValue.getActualValueType();
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.ItemPSVI#getItemValueTypes()
*/
public ShortList getItemValueTypes() {
return fValue.getListValueTypes();
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.ItemPSVI#getSchemaValue()
*/
public XSValue getSchemaValue() {
return fValue;
}
// REVISIT: Forbid serialization of PSVI DOM until
// we support object serialization of grammars -- mrglavas
private void writeObject(ObjectOutputStream out)
throws IOException {
throw new NotSerializableException(getClass().getName());
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
throw new NotSerializableException(getClass().getName());
}
}
| src/org/apache/xerces/dom/PSVIElementNSImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.xerces.dom;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.xerces.impl.dv.ValidatedInfo;
import org.apache.xerces.impl.xs.ElementPSVImpl;
import org.apache.xerces.impl.xs.util.StringListImpl;
import org.apache.xerces.xs.ElementPSVI;
import org.apache.xerces.xs.ItemPSVI;
import org.apache.xerces.xs.ShortList;
import org.apache.xerces.xs.StringList;
import org.apache.xerces.xs.XSAttributeUse;
import org.apache.xerces.xs.XSComplexTypeDefinition;
import org.apache.xerces.xs.XSElementDeclaration;
import org.apache.xerces.xs.XSModel;
import org.apache.xerces.xs.XSNotationDeclaration;
import org.apache.xerces.xs.XSSimpleTypeDefinition;
import org.apache.xerces.xs.XSTypeDefinition;
import org.apache.xerces.xs.XSValue;
/**
* Element namespace implementation; stores PSVI element items.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
*
* @version $Id$
*/
public class PSVIElementNSImpl extends ElementNSImpl implements ElementPSVI {
/** Serialization version. */
static final long serialVersionUID = 6815489624636016068L;
/**
* Construct an element node.
*/
public PSVIElementNSImpl(CoreDocumentImpl ownerDocument, String namespaceURI,
String qualifiedName, String localName) {
super(ownerDocument, namespaceURI, qualifiedName, localName);
}
/**
* Construct an element node.
*/
public PSVIElementNSImpl(CoreDocumentImpl ownerDocument, String namespaceURI,
String qualifiedName) {
super(ownerDocument, namespaceURI, qualifiedName);
}
/** element declaration */
protected XSElementDeclaration fDeclaration = null;
/** type of element, could be xsi:type */
protected XSTypeDefinition fTypeDecl = null;
/** true if clause 3.2 of Element Locally Valid (Element) (3.3.4)
* is satisfied, otherwise false
*/
protected boolean fNil = false;
/** false if the element value was provided by the schema; true otherwise.
*/
protected boolean fSpecified = true;
/** Schema value */
protected ValidatedInfo fValue = new ValidatedInfo();
/** http://www.w3.org/TR/xmlschema-1/#e-notation*/
protected XSNotationDeclaration fNotation = null;
/** validation attempted: none, partial, full */
protected short fValidationAttempted = ElementPSVI.VALIDATION_NONE;
/** validity: valid, invalid, unknown */
protected short fValidity = ElementPSVI.VALIDITY_NOTKNOWN;
/** error codes */
protected StringList fErrorCodes = null;
/** error messages */
protected StringList fErrorMessages = null;
/** validation context: could be QName or XPath expression*/
protected String fValidationContext = null;
/** the schema information property */
protected XSModel fSchemaInformation = null;
/** inherited attributes **/
protected XSAttributeUse[] fInheritedAttributes = null;
//
// ElementPSVI methods
//
/* (non-Javadoc)
* @see org.apache.xerces.xs.ItemPSVI#constant()
*/
public ItemPSVI constant() {
return new ElementPSVImpl(true, this);
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.ItemPSVI#isConstant()
*/
public boolean isConstant() {
return false;
}
/**
* [schema default]
*
* @return The canonical lexical representation of the declaration's {value constraint} value.
* @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_default>XML Schema Part 1: Structures [schema default]</a>
*/
public String getSchemaDefault() {
return fDeclaration == null ? null : fDeclaration.getConstraintValue();
}
/**
* [schema normalized value]
*
*
* @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_normalized_value>XML Schema Part 1: Structures [schema normalized value]</a>
* @return the normalized value of this item after validation
*/
public String getSchemaNormalizedValue() {
return fValue.getNormalizedValue();
}
/**
* [schema specified]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_specified">XML Schema Part 1: Structures [schema specified]</a>
* @return false value was specified in schema, true value comes from the infoset
*/
public boolean getIsSchemaSpecified() {
return fSpecified;
}
/**
* Determines the extent to which the document has been validated
*
* @return return the [validation attempted] property. The possible values are
* NO_VALIDATION, PARTIAL_VALIDATION and FULL_VALIDATION
*/
public short getValidationAttempted() {
return fValidationAttempted;
}
/**
* Determine the validity of the node with respect
* to the validation being attempted
*
* @return return the [validity] property. Possible values are:
* UNKNOWN_VALIDITY, INVALID_VALIDITY, VALID_VALIDITY
*/
public short getValidity() {
return fValidity;
}
/**
* A list of error codes generated from validation attempts.
* Need to find all the possible subclause reports that need reporting
*
* @return Array of error codes
*/
public StringList getErrorCodes() {
if (fErrorCodes != null) {
return fErrorCodes;
}
return StringListImpl.EMPTY_LIST;
}
/**
* A list of error messages generated from the validation attempt or
* an empty <code>StringList</code> if no errors occurred during the
* validation attempt. The indices of error messages in this list are
* aligned with those in the <code>[schema error code]</code> list.
*/
public StringList getErrorMessages() {
if (fErrorMessages != null) {
return fErrorMessages;
}
return StringListImpl.EMPTY_LIST;
}
// This is the only information we can provide in a pipeline.
public String getValidationContext() {
return fValidationContext;
}
/**
* [nil]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#e-nil>XML Schema Part 1: Structures [nil]</a>
* @return true if clause 3.2 of Element Locally Valid (Element) (3.3.4) above is satisfied, otherwise false
*/
public boolean getNil() {
return fNil;
}
/**
* [notation]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#e-notation>XML Schema Part 1: Structures [notation]</a>
* @return The notation declaration.
*/
public XSNotationDeclaration getNotation() {
return fNotation;
}
/**
* An item isomorphic to the type definition used to validate this element.
*
* @return a type declaration
*/
public XSTypeDefinition getTypeDefinition() {
return fTypeDecl;
}
/**
* If and only if that type definition is a simple type definition
* with {variety} union, or a complex type definition whose {content type}
* is a simple thype definition with {variety} union, then an item isomorphic
* to that member of the union's {member type definitions} which actually
* validated the element item's normalized value.
*
* @return a simple type declaration
*/
public XSSimpleTypeDefinition getMemberTypeDefinition() {
return fValue.getMemberTypeDefinition();
}
/**
* An item isomorphic to the element declaration used to validate
* this element.
*
* @return an element declaration
*/
public XSElementDeclaration getElementDeclaration() {
return fDeclaration;
}
/**
* [schema information]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_information">XML Schema Part 1: Structures [schema information]</a>
* @return The schema information property if it's the validation root,
* null otherwise.
*/
public XSModel getSchemaInformation() {
return fSchemaInformation;
}
/**
* Inherited attributes.
*
* @return an array of inherited attribute, XSAttributeUse components. null if no inherited attributes were found.
*/
public XSAttributeUse[] getInheritedAttributes() {
return fInheritedAttributes;
}
/**
* Copy PSVI properties from another psvi item.
*
* @param elem the source of element PSVI items
*/
public void setPSVI(ElementPSVI elem) {
this.fDeclaration = elem.getElementDeclaration();
this.fNotation = elem.getNotation();
this.fValidationContext = elem.getValidationContext();
this.fTypeDecl = elem.getTypeDefinition();
this.fSchemaInformation = elem.getSchemaInformation();
this.fValidity = elem.getValidity();
this.fValidationAttempted = elem.getValidationAttempted();
this.fErrorCodes = elem.getErrorCodes();
this.fErrorMessages = elem.getErrorMessages();
if (fTypeDecl instanceof XSSimpleTypeDefinition ||
fTypeDecl instanceof XSComplexTypeDefinition &&
((XSComplexTypeDefinition)fTypeDecl).getContentType() == XSComplexTypeDefinition.CONTENTTYPE_SIMPLE) {
this.fValue.copyFrom(elem.getSchemaValue());
}
else {
this.fValue.reset();
}
this.fSpecified = elem.getIsSchemaSpecified();
this.fNil = elem.getNil();
this.fInheritedAttributes = elem.getInheritedAttributes();
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.ItemPSVI#getActualNormalizedValue()
*/
public Object getActualNormalizedValue() {
return fValue.getActualValue();
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.ItemPSVI#getActualNormalizedValueType()
*/
public short getActualNormalizedValueType() {
return fValue.getActualValueType();
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.ItemPSVI#getItemValueTypes()
*/
public ShortList getItemValueTypes() {
return fValue.getListValueTypes();
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.ItemPSVI#getSchemaValue()
*/
public XSValue getSchemaValue() {
return fValue;
}
// REVISIT: Forbid serialization of PSVI DOM until
// we support object serialization of grammars -- mrglavas
private void writeObject(ObjectOutputStream out)
throws IOException {
throw new NotSerializableException(getClass().getName());
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
throw new NotSerializableException(getClass().getName());
}
}
| cosmetic javadoc improvement
git-svn-id: 39602be06c88ea89c23a8a9fd3d1314146990de6@1086532 13f79535-47bb-0310-9956-ffa450edef68
| src/org/apache/xerces/dom/PSVIElementNSImpl.java | cosmetic javadoc improvement | <ide><path>rc/org/apache/xerces/dom/PSVIElementNSImpl.java
<ide> /** the schema information property */
<ide> protected XSModel fSchemaInformation = null;
<ide>
<del> /** inherited attributes **/
<add> /** inherited attributes */
<ide> protected XSAttributeUse[] fInheritedAttributes = null;
<ide>
<ide> //
<ide> */
<ide> public XSAttributeUse[] getInheritedAttributes() {
<ide> return fInheritedAttributes;
<del> }
<add> }
<ide>
<ide> /**
<ide> * Copy PSVI properties from another psvi item. |
|
Java | apache-2.0 | 50694242db15fe054720c30e515fe6f0a914956f | 0 | ACCTFORGH/foursquared,sathiamour/foursquared,shivasrinath/foursquared,codingz/foursquared,wenkeyang/foursquared.eclair,nextzy/foursquared.eclair,dreamapps786/foursquared.eclair,ksrpraneeth/foursquared,harajuko/foursquared.eclair,jotish/foursquared,hardikamal/foursquared,RahulRavindren/foursquared,pratikjk/foursquared.eclair,wenkeyang/foursquared,cairenjie1985/foursquared,savelees/foursquared.eclair,solubrew/foursquared,votinhaooo/foursquared.eclair,bancool/foursquared,forevervhuo/foursquared.eclair,kolawoletech/foursquared,martadewi/foursquared.eclair,zhoujianhanyu/foursquared,malathicode/foursquared.eclair,solubrew/foursquared.eclair,weizp/foursquared.eclair,hunanlike/foursquared,manisoni28/foursquared.eclair,nluetkemeyer/foursquared,haithemhamzaoui/foursquared.eclair,murat8505/foursquared,nehalok/foursquared.eclair,xytrams/foursquared.eclair,lenkyun/foursquared,artificiallight92/foursquared.eclair,manisoni28/foursquared,sakethkaparthi/foursquared,sbolisetty/foursquared,omondiy/foursquared.eclair,aasaandinesh/foursquared,abedmaatalla/foursquared.eclair,navesdad/foursquared,ming0627/foursquared,rguindon/raymondeguindon-foursquared,shrikantzarekar/foursquared.eclair,summerzhao/foursquared,sibendu/foursquared,aasaandinesh/foursquared,bubao/foursquared,ming0627/foursquared,akhilesh9205/foursquared,lenkyun/foursquared,aasaandinesh/foursquared.eclair,Bishwajet/foursquared.eclair,kvnh/foursquared.eclair,starspace/foursquared,mypapit/foursquared,foobarprime/foursquared,martinx/martinxus-foursquared,murat8505/foursquared,since2014/foursquared.eclair,rihtak/foursquared,akhilesh9205/foursquared.eclair,lxz2014/foursquared,ksrpraneeth/foursquared.eclair,yusuf-shalahuddin/foursquared,coersum01/foursquared,tamzi/foursquared,mikehowson/foursquared.eclair,rahulnagar8/foursquared,kitencx/foursquared,daya-shankar/foursquared,rahulnagar8/foursquared.eclair,sandeip-yadav/foursquared.eclair,Bishwajet/foursquared.eclair,sathiamour/foursquared.eclair,sbolisetty/foursquared,martinx/martinxus-foursquared,bancool/foursquared,ming0627/foursquared.eclair,yusuf-shalahuddin/foursquared,coersum01/foursquared.eclair,Zebronaft/foursquared,lxz2014/foursquared,abou78180/foursquared,codingz/foursquared,stonyyi/foursquared,coersum01/foursquared,ckarademir/foursquared.eclair,ksrpraneeth/foursquared.eclair,fatihcelik/foursquared,sovaa/foursquared,psvijayk/foursquared.eclair,edwinsnao/foursquared.eclair,kvnh/foursquared,sevenOneHero/foursquared.eclair,xzamirx/foursquared.eclair,gabtni/foursquared,MarginC/foursquared,hunanlike/foursquared.eclair,andrewjsauer/foursquared,sevenOneHero/foursquared.eclair,hejie/foursquared.eclair,itzmesayooj/foursquared,ACCTFORGH/foursquared,starspace/foursquared,bubao/foursquared,RahulRavindren/foursquared,fuzhou0099/foursquared.eclair,xytrams/foursquared,4DvAnCeBoY/foursquared.eclair,abou78180/foursquared,thtak/foursquared.eclair,since2014/foursquared,ewugreensignal/foursquared,abdallahynajar/foursquared.eclair,davideuler/foursquared,harajuko/foursquared,suripaleru/foursquared.eclair,manisoni28/foursquared,gokultaka/foursquared,NarikSmouke228/foursquared,hejie/foursquared,waasilzamri/foursquared.eclair,vsvankhede/foursquared,wenkeyang/foursquared,itzmesayooj/foursquared,jotish/foursquared,martinx/martinxus-foursquared,yusuf-shalahuddin/foursquared.eclair,xytrams/foursquared,kiruthikak/foursquared,idmouh/foursquared,suman4674/foursquared.eclair,bancool/foursquared,isaiasmercadom/foursquared,jotish/foursquared,murat8505/foursquared.eclair,sovaa/foursquared,sibendu/foursquared.eclair,karanVkgp/foursquared.eclair,4DvAnCeBoY/foursquared,weizp/foursquared,pratikjk/foursquared,kolawoletech/foursquared,dhysf/foursquared.eclair,waasilzamri/foursquared,smallperson/foursquared.eclair,smakeit/foursquared,gabtni/foursquared.eclair,psvijayk/foursquared,smallperson/foursquared,thtak/foursquared.eclair,smakeit/foursquared.eclair,nasvil/foursquared,srikanthguduru/foursquared.eclair,jamesmartins/foursquared.eclair,RameshBhupathi/foursquared,osiloke/foursquared.eclair,loganj/foursquared,omondiy/foursquared,rahul18cool/foursquared,votinhaooo/foursquared,sbagadi/foursquared,MarginC/foursquared,vsvankhede/foursquared,varunprathap/foursquared.eclair,BinodAryal/foursquared.eclair,mypapit/foursquared,rihtak/foursquared.eclair,PriteshJain/foursquared.eclair,RahulRavindren/foursquared.eclair,davideuler/foursquared,vsvankhede/foursquared.eclair,sakethkaparthi/foursquared,sonyraj/foursquared.eclair,navesdad/foursquared.eclair,4DvAnCeBoY/foursquared,abou78180/foursquared.eclair,nextzy/foursquared,ckarademir/foursquared,ragesh91/foursquared,rahulnagar8/foursquared,nluetkemeyer/foursquared.eclair,savelees/foursquared,CoderJackyHuang/foursquared.eclair,nasvil/foursquared.eclair,xuyunhong/foursquared.eclair,karthikkumar12/foursquared,PriteshJain/foursquared,tamzi/foursquared.eclair,sovaa/foursquared.eclair,coersum01/foursquared.eclair,prashantkumar0509/foursquared,nextzy/foursquared.eclair,osiloke/foursquared,vsvankhede/foursquared,thtak/foursquared,srikanthguduru/foursquared,karthikkumar12/foursquared,varunprathap/foursquared,nehalok/foursquared,xuyunhong/foursquared,lxz2014/foursquared.eclair,appoll/foursquared,varunprathap/foursquared.eclair,weizp/foursquared,ckarademir/foursquared.eclair,davideuler/foursquared,suripaleru/foursquared,summerzhao/foursquared,lepinay/foursquared,artificiallight92/foursquared,sandeip-yadav/foursquared,ckarademir/foursquared,sbagadi/foursquared,tianyong2/foursquared.eclair,zhoujianhanyu/foursquared.eclair,wenkeyang/foursquared,jamesmartins/foursquared,karanVkgp/foursquared.eclair,tahainfocreator/foursquared,suripaleru/foursquared.eclair,tahainfocreator/foursquared,dhysf/foursquared.eclair,EphraimKigamba/foursquared,smakeit/foursquared,abdallahynajar/foursquared,tahainfocreator/foursquared,mansourifatimaezzahraa/foursquared.eclair,sonyraj/foursquared,shivasrinath/foursquared.eclair,vsvankhede/foursquared.eclair,manisoni28/foursquared.eclair,632840804/foursquared.eclair,tianyong2/foursquared,martadewi/foursquared,daya-shankar/foursquared,weizp/foursquared,prashantkumar0509/foursquared.eclair,haithemhamzaoui/foursquared,fatihcelik/foursquared.eclair,hardikamal/foursquared.eclair,dhysf/foursquared,davideuler/foursquared.eclair,sibendu/foursquared,Archenemy-xiatian/foursquared.eclair,tyzhaoqi/foursquared,tyzhaoqi/foursquared.eclair,suman4674/foursquared,rahul18cool/foursquared,edwinsnao/foursquared,mansourifatimaezzahraa/foursquared,zhmkof/foursquared.eclair,savelees/foursquared,gtostock/foursquared.eclair,fuzhou0099/foursquared.eclair,ayndev/foursquared,foobarprime/foursquared,hardikamal/foursquared,ewugreensignal/foursquared.eclair,kiruthikak/foursquared,donka-s27/foursquared,kiruthikak/foursquared,idmouh/foursquared,kvnh/foursquared.eclair,EphraimKigamba/foursquared,andrewjsauer/foursquared,Bishwajet/foursquared,waasilzamri/foursquared,prashantkumar0509/foursquared,foobarprime/foursquared.eclair,zhoujianhanyu/foursquared.eclair,shivasrinath/foursquared,tianyong2/foursquared,cairenjie1985/foursquared,AnthonyCAS/foursquared.eclair,sbolisetty/foursquared.eclair,sbagadi/foursquared,aasaandinesh/foursquared,navesdad/foursquared,ramaraokotu/foursquared,nluetkemeyer/foursquared.eclair,azai91/foursquared,mansourifatimaezzahraa/foursquared,EphraimKigamba/foursquared.eclair,mikehowson/foursquared,kiruthikak/foursquared.eclair,santoshmehta82/foursquared,donka-s27/foursquared,sevenOneHero/foursquared.eclair,lepinay/foursquared,tahainfocreator/foursquared.eclair,nehalok/foursquared,codingz/foursquared,izBasit/foursquared.eclair,sandeip-yadav/foursquared,shrikantzarekar/foursquared.eclair,mansourifatimaezzahraa/foursquared,fatihcelik/foursquared,martadewi/foursquared.eclair,sandeip-yadav/foursquared,osiloke/foursquared,ragesh91/foursquared,Mutai/foursquared,suman4674/foursquared,cairenjie1985/foursquared.eclair,izBasit/foursquared.eclair,omondiy/foursquared.eclair,EphraimKigamba/foursquared.eclair,RameshBhupathi/foursquared.eclair,lepinay/foursquared.eclair,RameshBhupathi/foursquared,manisoni28/foursquared,codingz/foursquared.eclair,osiloke/foursquared,smallperson/foursquared,nasvil/foursquared,smallperson/foursquared.eclair,Mutai/foursquared,shivasrinath/foursquared.eclair,abedmaatalla/foursquared.eclair,ming0627/foursquared.eclair,thtak/foursquared,xuyunhong/foursquared,harajuko/foursquared,srikanthguduru/foursquared,suman4674/foursquared.eclair,nara-l/foursquared,EphraimKigamba/foursquared,malathicode/foursquared,xytrams/foursquared,itrobertson/foursquared,azizjonm/foursquared,varunprathap/foursquared,sathiamour/foursquared,lxz2014/foursquared.eclair,wenkeyang/foursquared.eclair,shrikantzarekar/foursquared,coersum01/foursquared,azizjonm/foursquared,gokultaka/foursquared,akhilesh9205/foursquared.eclair,4DvAnCeBoY/foursquared,itzmesayooj/foursquared,BinodAryal/foursquared,suripaleru/foursquared,ewugreensignal/foursquared.eclair,mikehowson/foursquared.eclair,suman4674/foursquared,Zebronaft/foursquared,summerzhao/foursquared.eclair,karthikkumar12/foursquared.eclair,foobarprime/foursquared.eclair,starspace/foursquared.eclair,santoshmehta82/foursquared.eclair,Zebronaft/foursquared,santoshmehta82/foursquared.eclair,azizjonm/foursquared,karthikkumar12/foursquared,aasaandinesh/foursquared.eclair,pratikjk/foursquared,prashantkumar0509/foursquared.eclair,gtostock/foursquared,yusuf-shalahuddin/foursquared,ewugreensignal/foursquared,thenewnewbie/foursquared.eclair,hunanlike/foursquared.eclair,tyzhaoqi/foursquared.eclair,BinodAryal/foursquared,donka-s27/foursquared,lenkyun/foursquared,sbagadi/foursquared.eclair,thenewnewbie/foursquared,sonyraj/foursquared,solubrew/foursquared.eclair,rahul18cool/foursquared.eclair,sovaa/foursquared,hejie/foursquared,Mutai/foursquared,solubrew/foursquared,paulodiogo/foursquared.eclair,xuyunhong/foursquared,sibendu/foursquared,votinhaooo/foursquared,rihtak/foursquared.eclair,srikanthguduru/foursquared.eclair,kiruthikak/foursquared.eclair,dreamapps786/foursquared.eclair,NarikSmouke228/foursquared.eclair,rahulnagar8/foursquared.eclair,ksrpraneeth/foursquared,RahulRavindren/foursquared,savelees/foursquared,gokultaka/foursquared.eclair,ekospinach/foursquared,sonyraj/foursquared,abou78180/foursquared.eclair,kitencx/foursquared,forevervhuo/foursquared.eclair,mypapit/foursquared,lepinay/foursquared.eclair,ekospinach/foursquared.eclair,hunanlike/foursquared,nara-l/foursquared.eclair,ming0627/foursquared,karanVkgp/foursquared,sakethkaparthi/foursquared,kitencx/foursquared,edwinsnao/foursquared.eclair,ramaraokotu/foursquared,gokultaka/foursquared.eclair,cairenjie1985/foursquared.eclair,votinhaooo/foursquared.eclair,bubao/foursquared,rguindon/raymondeguindon-foursquared,ayndev/foursquared,malathicode/foursquared.eclair,mansourifatimaezzahraa/foursquared.eclair,Mutai/foursquared.eclair,donka-s27/foursquared.eclair,sibendu/foursquared.eclair,lxz2014/foursquared,pratikjk/foursquared.eclair,murat8505/foursquared.eclair,abedmaatalla/foursquared,weizp/foursquared.eclair,gokultaka/foursquared,jiveshwar/foursquared.eclair,akhilesh9205/foursquared,PriteshJain/foursquared.eclair,karanVkgp/foursquared,tamzi/foursquared,shrikantzarekar/foursquared,lepinay/foursquared,loganj/foursquared,omondiy/foursquared,4DvAnCeBoY/foursquared.eclair,rihtak/foursquared,ramaraokotu/foursquared.eclair,jamesmartins/foursquared,artificiallight92/foursquared.eclair,smakeit/foursquared.eclair,shivasrinath/foursquared,ragesh91/foursquared.eclair,rahulnagar8/foursquared,stonyyi/foursquared,Zebronaft/foursquared.eclair,ekospinach/foursquared,bubao/foursquared.eclair,solubrew/foursquared,tyzhaoqi/foursquared,xuyunhong/foursquared.eclair,jamesmartins/foursquared.eclair,ekospinach/foursquared,kolawoletech/foursquared.eclair,dreamapps786/foursquared,rahul18cool/foursquared.eclair,NarikSmouke228/foursquared.eclair,mikehowson/foursquared,BinodAryal/foursquared,sbolisetty/foursquared,itrobertson/foursquared,mayankz/foursquared,dreamapps786/foursquared,santoshmehta82/foursquared,sbagadi/foursquared.eclair,tianyong2/foursquared,jamesmartins/foursquared,kvnh/foursquared,NarikSmouke228/foursquared,xytrams/foursquared.eclair,davideuler/foursquared.eclair,ewugreensignal/foursquared,bubao/foursquared.eclair,haithemhamzaoui/foursquared.eclair,dhysf/foursquared,foobarprime/foursquared,thtak/foursquared,idmouh/foursquared.eclair,632840804/foursquared.eclair,abedmaatalla/foursquared,nara-l/foursquared,malathicode/foursquared,cairenjie1985/foursquared,hejie/foursquared.eclair,azai91/foursquared,sathiamour/foursquared.eclair,psvijayk/foursquared,edwinsnao/foursquared,isaiasmercadom/foursquared.eclair,donka-s27/foursquared.eclair,fatihcelik/foursquared.eclair,srikanthguduru/foursquared,appoll/foursquared,since2014/foursquared.eclair,izBasit/foursquared,Bishwajet/foursquared,murat8505/foursquared,ramaraokotu/foursquared.eclair,stonyyi/foursquared,nasvil/foursquared,waasilzamri/foursquared.eclair,abdallahynajar/foursquared,smallperson/foursquared,tyzhaoqi/foursquared,mikehowson/foursquared,abdallahynajar/foursquared,tianyong2/foursquared.eclair,since2014/foursquared,dhysf/foursquared,nehalok/foursquared,RameshBhupathi/foursquared,rguindon/raymondeguindon-foursquared,harajuko/foursquared.eclair,suripaleru/foursquared,Archenemy-xiatian/foursquared,stonyyi/foursquared.eclair,ckarademir/foursquared,Archenemy-xiatian/foursquared,ragesh91/foursquared,abdallahynajar/foursquared.eclair,azai91/foursquared.eclair,malathicode/foursquared,martadewi/foursquared,sathiamour/foursquared,starspace/foursquared.eclair,karthikkumar12/foursquared.eclair,votinhaooo/foursquared,ayndev/foursquared,itrobertson/foursquared,dreamapps786/foursquared,daya-shankar/foursquared,rihtak/foursquared,karanVkgp/foursquared,zhoujianhanyu/foursquared,kvnh/foursquared,Bishwajet/foursquared,izBasit/foursquared,rahul18cool/foursquared,mayankz/foursquared,navesdad/foursquared.eclair,prashantkumar0509/foursquared,varunprathap/foursquared,abou78180/foursquared,Mutai/foursquared.eclair,tamzi/foursquared,kolawoletech/foursquared,waasilzamri/foursquared,since2014/foursquared,ACCTFORGH/foursquared,hejie/foursquared,azai91/foursquared,Archenemy-xiatian/foursquared,isaiasmercadom/foursquared,hardikamal/foursquared,azai91/foursquared.eclair,savelees/foursquared.eclair,smakeit/foursquared,gtostock/foursquared.eclair,sovaa/foursquared.eclair,edwinsnao/foursquared,idmouh/foursquared.eclair,hardikamal/foursquared.eclair,fatihcelik/foursquared,BinodAryal/foursquared.eclair,sbolisetty/foursquared.eclair,gabtni/foursquared,tahainfocreator/foursquared.eclair,nluetkemeyer/foursquared,summerzhao/foursquared.eclair,paulodiogo/foursquared.eclair,NarikSmouke228/foursquared,thenewnewbie/foursquared,bancool/foursquared.eclair,thenewnewbie/foursquared.eclair,Zebronaft/foursquared.eclair,nasvil/foursquared.eclair,sandeip-yadav/foursquared.eclair,thenewnewbie/foursquared,RahulRavindren/foursquared.eclair,nara-l/foursquared.eclair,omondiy/foursquared,artificiallight92/foursquared,haithemhamzaoui/foursquared,nextzy/foursquared,itzmesayooj/foursquared.eclair,jiveshwar/foursquared.eclair,Archenemy-xiatian/foursquared.eclair,nluetkemeyer/foursquared,xzamirx/foursquared.eclair,santoshmehta82/foursquared,ACCTFORGH/foursquared.eclair,osiloke/foursquared.eclair,nextzy/foursquared,PriteshJain/foursquared,hunanlike/foursquared,gtostock/foursquared,gabtni/foursquared,isaiasmercadom/foursquared.eclair,kolawoletech/foursquared.eclair,isaiasmercadom/foursquared,psvijayk/foursquared.eclair,mayankz/foursquared,codingz/foursquared.eclair,andrewjsauer/foursquared,starspace/foursquared,daya-shankar/foursquared.eclair,ACCTFORGH/foursquared.eclair,MarginC/foursquared,izBasit/foursquared,bancool/foursquared.eclair,AnthonyCAS/foursquared.eclair,jotish/foursquared.eclair,daya-shankar/foursquared.eclair,yusuf-shalahuddin/foursquared.eclair,zhmkof/foursquared.eclair,tamzi/foursquared.eclair,idmouh/foursquared,gabtni/foursquared.eclair,ayndev/foursquared.eclair,jotish/foursquared.eclair,sonyraj/foursquared.eclair,ekospinach/foursquared.eclair,PriteshJain/foursquared,CoderJackyHuang/foursquared.eclair,navesdad/foursquared,artificiallight92/foursquared,psvijayk/foursquared,stonyyi/foursquared.eclair,ayndev/foursquared.eclair,gtostock/foursquared,zhoujianhanyu/foursquared,appoll/foursquared,ragesh91/foursquared.eclair,pratikjk/foursquared,itzmesayooj/foursquared.eclair,abedmaatalla/foursquared,harajuko/foursquared,nehalok/foursquared.eclair,ramaraokotu/foursquared,summerzhao/foursquared,shrikantzarekar/foursquared,akhilesh9205/foursquared,ksrpraneeth/foursquared,martadewi/foursquared,RameshBhupathi/foursquared.eclair,nara-l/foursquared,haithemhamzaoui/foursquared | /**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.maps.VenueItemizedOverlay;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.util.Observable;
import java.util.Observer;
/**
* @author Joe LaPenna ([email protected])
*/
public class SearchVenueMapActivity extends MapActivity {
public static final String TAG = "SearchVenueMapActivity";
public static final boolean DEBUG = Foursquared.DEBUG;
private Venue mTappedVenue;
private MapView mMapView;
private MapController mMapController;
private VenueItemizedOverlay mVenuesOverlay;
private MyLocationOverlay mMyLocationOverlay;
private Observer mSearchResultsObserver;
private Button mVenueButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_venue_map_activity);
mVenueButton = (Button)findViewById(R.id.venueButton);
mVenueButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startVenueActivity(mTappedVenue);
}
});
initMap();
mSearchResultsObserver = new Observer() {
@Override
public void update(Observable observable, Object data) {
if (DEBUG) Log.d(TAG, "Observed search results change.");
clearMap();
loadSearchResults(SearchVenueActivity.searchResultsObservable.getSearchResults());
updateMap();
}
};
}
@Override
public void onResume() {
super.onResume();
if (DEBUG) Log.d(TAG, "onResume()");
mMyLocationOverlay.enableMyLocation();
// mMyLocationOverlay.enableCompass(); // Disabled due to a sdk 1.5 emulator bug
clearMap();
loadSearchResults(SearchVenueActivity.searchResultsObservable.getSearchResults());
updateMap();
SearchVenueActivity.searchResultsObservable.addObserver(mSearchResultsObserver);
}
@Override
public void onPause() {
super.onPause();
if (DEBUG) Log.d(TAG, "onPause()");
mMyLocationOverlay.disableMyLocation();
mMyLocationOverlay.disableCompass();
SearchVenueActivity.searchResultsObservable.deleteObserver(mSearchResultsObserver);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
private void initMap() {
mMapView = (MapView)findViewById(R.id.mapView);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMapView.getOverlays().add(mMyLocationOverlay);
mMyLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
if (DEBUG) Log.d(TAG, "runOnFirstFix()");
mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation());
mMapView.getController().setZoom(16);
}
});
}
private void loadSearchResults(Group searchResults) {
if (searchResults == null) {
if (DEBUG) Log.d(TAG, "no search results. Not loading.");
return;
}
if (DEBUG) Log.d(TAG, "Loading search results");
final int groupCount = searchResults.size();
for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
Group group = (Group)searchResults.get(groupIndex);
if (DEBUG) Log.d(TAG, "Adding items in group: " + group.getType());
final int venueCount = group.size();
for (int venueIndex = 0; venueIndex < venueCount; venueIndex++) {
Venue venue = (Venue)group.get(venueIndex);
if (isVenueMappable(venue)) {
if (DEBUG) Log.d(TAG, "adding venue: " + venue.getVenuename());
mVenuesOverlay.addVenue(venue);
}
}
}
if (mVenuesOverlay.size() > 0) {
if (DEBUG) Log.d(TAG, "adding mVenuesOverlay to mMapView");
mVenuesOverlay.finish();
mMapView.getOverlays().add(mVenuesOverlay);
}
}
private void clearMap() {
mMapView.getOverlays().remove(mVenuesOverlay);
mVenuesOverlay = new VenueItemizedOverlayWithButton(this.getResources().getDrawable(
R.drawable.reddot), this.getResources().getDrawable(R.drawable.bluedot));
}
private boolean isVenueMappable(Venue venue) {
if ((venue.getGeolat() == null || venue.getGeolong() == null) //
|| venue.getGeolat().equals("0") || venue.getGeolong().equals("0")) {
return false;
}
return true;
}
private void updateMap() {
GeoPoint center = mMyLocationOverlay.getMyLocation();
if (mVenuesOverlay.size() > 0) {
if (DEBUG) Log.d(TAG, "updateMap via overlay span");
center = mVenuesOverlay.getCenter();
mMapController.animateTo(center);
mMapController.zoomToSpan(mVenuesOverlay.getLatSpanE6(), mVenuesOverlay.getLonSpanE6());
return;
}
if (center != null) {
if (DEBUG) Log.d(TAG, "updateMap via location overlay");
mMapController.animateTo(center);
mMapController.setZoom(16);
return;
}
if (DEBUG) Log.d(TAG, "Could not re-center no location or venue overlay.");
}
void startVenueActivity(Venue venue) {
if (DEBUG) Log.d(TAG, "firing venue activity for venue");
Intent intent = new Intent(SearchVenueMapActivity.this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra("venue", venue);
startActivity(intent);
}
private class VenueItemizedOverlayWithButton extends VenueItemizedOverlay {
public static final String TAG = "VenueItemizedOverlayWithToast";
public static final boolean DEBUG = Foursquared.DEBUG;
private Drawable mBeenThereMarker;
public VenueItemizedOverlayWithButton(Drawable defaultMarker, Drawable beenThereMarker) {
super(defaultMarker);
mBeenThereMarker = boundCenterBottom(beenThereMarker);
}
@Override
public OverlayItem createItem(int i) {
VenueOverlayItem item = (VenueOverlayItem)super.createItem(i);
if (item.getVenue().beenhereMe()) {
if (DEBUG) Log.d(TAG, "using the beenThereMarker for: " + item.getVenue());
item.setMarker(mBeenThereMarker);
}
return item;
}
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
if (DEBUG) Log.d(TAG, "onTap: " + p);
mVenueButton.setVisibility(View.GONE);
return super.onTap(p, mapView);
}
@Override
protected boolean onTap(int i) {
if (DEBUG) Log.d(TAG, "onTap: " + i);
VenueOverlayItem item = (VenueOverlayItem)getItem(i);
mTappedVenue = item.getVenue();
mVenueButton.setText(item.getVenue().getVenuename());
mVenueButton.setVisibility(View.VISIBLE);
return super.onTap(i);
}
}
}
| src/com/joelapenna/foursquared/SearchVenueMapActivity.java | /**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.maps.VenueItemizedOverlay;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.util.Observable;
import java.util.Observer;
/**
* @author Joe LaPenna ([email protected])
*/
public class SearchVenueMapActivity extends MapActivity {
public static final String TAG = "SearchVenueMapActivity";
public static final boolean DEBUG = Foursquared.DEBUG;
private Venue mVenue;
private MapView mMapView;
private MapController mMapController;
private VenueItemizedOverlay mVenuesOverlay;
private MyLocationOverlay mMyLocationOverlay;
private Observer mSearchResultsObserver;
private Button mVenueButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_venue_map_activity);
mVenueButton = (Button)findViewById(R.id.venueButton);
mVenueButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startVenueActivity(mVenue);
}
});
initMap();
mSearchResultsObserver = new Observer() {
@Override
public void update(Observable observable, Object data) {
if (DEBUG) Log.d(TAG, "Observed search results change.");
clearMap();
loadSearchResults(SearchVenueActivity.searchResultsObservable.getSearchResults());
updateMap();
}
};
}
@Override
public void onResume() {
super.onResume();
if (DEBUG) Log.d(TAG, "onResume()");
mMyLocationOverlay.enableMyLocation();
// mMyLocationOverlay.enableCompass(); // Disabled due to a sdk 1.5 emulator bug
clearMap();
loadSearchResults(SearchVenueActivity.searchResultsObservable.getSearchResults());
updateMap();
SearchVenueActivity.searchResultsObservable.addObserver(mSearchResultsObserver);
}
@Override
public void onPause() {
super.onPause();
if (DEBUG) Log.d(TAG, "onPause()");
mMyLocationOverlay.disableMyLocation();
mMyLocationOverlay.disableCompass();
SearchVenueActivity.searchResultsObservable.deleteObserver(mSearchResultsObserver);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
private void initMap() {
mMapView = (MapView)findViewById(R.id.mapView);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMapView.getOverlays().add(mMyLocationOverlay);
mMyLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
if (DEBUG) Log.d(TAG, "runOnFirstFix()");
mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation());
mMapView.getController().setZoom(16);
}
});
}
private void loadSearchResults(Group searchResults) {
if (searchResults == null) {
if (DEBUG) Log.d(TAG, "no search results. Not loading.");
return;
}
if (DEBUG) Log.d(TAG, "Loading search results");
final int groupCount = searchResults.size();
for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
Group group = (Group)searchResults.get(groupIndex);
if (DEBUG) Log.d(TAG, "Adding items in group: " + group.getType());
final int venueCount = group.size();
for (int venueIndex = 0; venueIndex < venueCount; venueIndex++) {
Venue venue = (Venue)group.get(venueIndex);
if (isVenueMappable(venue)) {
if (DEBUG) Log.d(TAG, "adding venue: " + venue.getVenuename());
mVenuesOverlay.addVenue(venue);
}
}
}
if (mVenuesOverlay.size() > 0) {
if (DEBUG) Log.d(TAG, "adding mVenuesOverlay to mMapView");
mVenuesOverlay.finish();
mMapView.getOverlays().add(mVenuesOverlay);
}
}
private void clearMap() {
mMapView.getOverlays().remove(mVenuesOverlay);
mVenuesOverlay = new VenueItemizedOverlayWithButton(this.getResources().getDrawable(
R.drawable.reddot), this.getResources().getDrawable(R.drawable.bluedot));
}
private boolean isVenueMappable(Venue venue) {
if ((venue.getGeolat() == null || venue.getGeolong() == null) //
|| venue.getGeolat().equals("0") || venue.getGeolong().equals("0")) {
return false;
}
return true;
}
private void updateMap() {
GeoPoint center = mMyLocationOverlay.getMyLocation();
if (mVenuesOverlay.size() > 0) {
if (DEBUG) Log.d(TAG, "updateMap via overlay span");
center = mVenuesOverlay.getCenter();
mMapController.animateTo(center);
mMapController.zoomToSpan(mVenuesOverlay.getLatSpanE6(), mVenuesOverlay.getLonSpanE6());
return;
}
if (center != null) {
if (DEBUG) Log.d(TAG, "updateMap via location overlay");
mMapController.animateTo(center);
mMapController.setZoom(16);
return;
}
if (DEBUG) Log.d(TAG, "Could not re-center no location or venue overlay.");
}
void startVenueActivity(Venue venue) {
if (DEBUG) Log.d(TAG, "firing venue activity for venue");
Intent intent = new Intent(SearchVenueMapActivity.this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra("venue", venue);
startActivity(intent);
}
private class VenueItemizedOverlayWithButton extends VenueItemizedOverlay {
public static final String TAG = "VenueItemizedOverlayWithToast";
public static final boolean DEBUG = Foursquared.DEBUG;
private Drawable mBeenThereMarker;
public VenueItemizedOverlayWithButton(Drawable defaultMarker, Drawable beenThereMarker) {
super(defaultMarker);
mBeenThereMarker = boundCenterBottom(beenThereMarker);
}
@Override
public OverlayItem createItem(int i) {
VenueOverlayItem item = (VenueOverlayItem)super.createItem(i);
if (item.getVenue().beenhereMe()) {
if (DEBUG) Log.d(TAG, "using the beenThereMarker for: " + item.getVenue());
item.setMarker(mBeenThereMarker);
}
return item;
}
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
if (DEBUG) Log.d(TAG, "onTap: " + p);
mVenueButton.setVisibility(View.GONE);
return super.onTap(p, mapView);
}
@Override
protected boolean onTap(int i) {
if (DEBUG) Log.d(TAG, "onTap: " + i);
VenueOverlayItem item = (VenueOverlayItem)getItem(i);
mVenue = item.getVenue();
mVenueButton.setText(item.getVenue().getVenuename());
mVenueButton.setVisibility(View.VISIBLE);
return super.onTap(i);
}
}
}
| rename mVenue in SearchVenueMapActivity to make it clear its purpose.
committer: Joe LaPenna <[email protected]>
| src/com/joelapenna/foursquared/SearchVenueMapActivity.java | rename mVenue in SearchVenueMapActivity to make it clear its purpose. | <ide><path>rc/com/joelapenna/foursquared/SearchVenueMapActivity.java
<ide> public static final String TAG = "SearchVenueMapActivity";
<ide> public static final boolean DEBUG = Foursquared.DEBUG;
<ide>
<del> private Venue mVenue;
<add> private Venue mTappedVenue;
<ide>
<ide> private MapView mMapView;
<ide> private MapController mMapController;
<ide> mVenueButton.setOnClickListener(new OnClickListener() {
<ide> @Override
<ide> public void onClick(View v) {
<del> startVenueActivity(mVenue);
<add> startVenueActivity(mTappedVenue);
<ide> }
<ide> });
<ide>
<ide> protected boolean onTap(int i) {
<ide> if (DEBUG) Log.d(TAG, "onTap: " + i);
<ide> VenueOverlayItem item = (VenueOverlayItem)getItem(i);
<del> mVenue = item.getVenue();
<add> mTappedVenue = item.getVenue();
<ide> mVenueButton.setText(item.getVenue().getVenuename());
<ide> mVenueButton.setVisibility(View.VISIBLE);
<ide> return super.onTap(i); |
|
Java | apache-2.0 | fbc32f581b90940f78a47e659393144db80da9d1 | 0 | bhatvv/jitsi,bhatvv/jitsi,bhatvv/jitsi,bhatvv/jitsi,bhatvv/jitsi | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.sip;
import gov.nist.javax.sip.header.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.service.protocol.ProtocolProviderFactory;
import javax.sip.address.*;
import javax.sip.header.*;
import javax.sip.message.*;
import java.util.*;
/**
* Checks the <tt>protocolProvider</tt>'s account properties for configured
* custom headers and add them to the outgoing requests.
* The header account properties are of form:
* ConfigHeader.N.Name=HeaderName
* ConfigHeader.N.Value=HeaderValue
* ConfigHeader.N.Method=SIP_MethodName (optional)
* Where N is the index of the header, multiple custom headers can be added.
* Name is the header name to use and Value is its value. The optional
* property is whether to use a specific request method to attach headers to
* or if missing we will attach it to all requests.
*
* @author Damian Minkov
*/
public class ConfigHeaders
{
/**
* The logger for this class
*/
public final static Logger logger = Logger.getLogger(ConfigHeaders.class);
/**
* The account property holding all the custom pre-configured headers.
*/
private final static String ACC_PROPERTY_CONFIG_HEADER = "ConfigHeader";
/**
* The config property suffix for custom header name.
*/
private final static String ACC_PROPERTY_CONFIG_HEADER_NAME
= "Name";
/**
* The config property suffix for custom header value.
*/
private final static String ACC_PROPERTY_CONFIG_HEADER_VALUE
= "Value";
/**
* The config property suffix for custom header method.
*/
private final static String ACC_PROPERTY_CONFIG_HEADER_METHOD
= "Method";
/**
* Attach any custom headers pre configured for the account. Added only
* to message Requests.
* The header account properties are of form:
* ConfigHeader.N.Name=HeaderName
* ConfigHeader.N.Value=HeaderValue
* ConfigHeader.N.Method=SIP_MethodName (optional)
* Where N is the index of the header, multiple custom headers can be added.
* Name is the header name to use and Value is its value. The optional
* property is whether to use a specific request method to attach headers to
* or if missing we will attach it to all requests.
*
* @param message the message that we'd like to attach custom headers to.
* @param protocolProvider the protocol provider to check for configured
* custom headers.
*/
static void attachConfigHeaders(
Message message,
ProtocolProviderServiceSipImpl protocolProvider)
{
if(message instanceof Response)
return;
Request request = (Request)message;
ToHeader toHeader =
(ToHeader) request.getHeader(ToHeader.NAME);
String domainName = toHeader.getAddress().getURI().toString();
if(domainName.contains(";")) {
domainName = domainName.substring(domainName.indexOf("@"), domainName.indexOf(";"));
} else {
domainName = domainName.substring(domainName.indexOf("@"));
}
Map<String, String> props =
protocolProvider.getAccountID().getAccountProperties();
props.put("DomainName", domainName);
Map<String,Map<String,String>> headers
= new HashMap<String, Map<String, String>>();
// parse the properties into the map where the index is the key
for(Map.Entry<String, String> entry : props.entrySet())
{
String pName = entry.getKey();
String prefStr = entry.getValue();
String name;
String ix;
if(!pName.startsWith(ACC_PROPERTY_CONFIG_HEADER) || prefStr == null)
continue;
prefStr = prefStr.trim();
if(pName.contains("."))
{
pName = pName.replaceAll(ACC_PROPERTY_CONFIG_HEADER + ".", "");
name = pName.substring(pName.lastIndexOf('.') + 1).trim();
if(!pName.contains("."))
continue;
ix = pName.substring(0, pName.lastIndexOf('.')).trim();
}
else
continue;
Map<String,String> headerValues = headers.get(ix);
if(headerValues == null)
{
headerValues = new HashMap<String, String>();
headers.put(ix, headerValues);
}
headerValues.put(name, prefStr);
}
// process the found custom headers
for(Map<String, String> headerValues : headers.values())
{
String method = headerValues.get(ACC_PROPERTY_CONFIG_HEADER_METHOD);
// if there is a method setting and is different from
// current request method skip this header
// if any of the required properties are missing skip (Name & Value)
if((method != null
&& !request.getMethod().equalsIgnoreCase(method))
|| !headerValues.containsKey(ACC_PROPERTY_CONFIG_HEADER_NAME)
|| !headerValues.containsKey(ACC_PROPERTY_CONFIG_HEADER_VALUE))
continue;
try
{
String headerValue = headerValues.get(ACC_PROPERTY_CONFIG_HEADER_VALUE);
String name = headerValues.get(ACC_PROPERTY_CONFIG_HEADER_NAME);
String value = processParams(headerValue,request,props);
if(name.equals("P-Asserted-Identity")) {
value = value.split(":")[0] + ":+" + value.split(":")[1];
}
Header h = request.getHeader(name);
logger.info("Header : " + name + " : " + value);
// makes possible overriding already created headers which
// are not custom one
// RouteHeader is used by ProxyRouter/DefaultRouter and we
// cannot use it as custom header if we want to add it
if((h != null && !(h instanceof CustomHeader))
|| name.equals(SIPHeaderNames.ROUTE))
{
request.setHeader(protocolProvider.getHeaderFactory()
.createHeader(name, value));
}
else
request.addHeader(new CustomHeaderList(name, value));
}
catch(Exception e)
{
logger.error("Cannot create custom header", e);
}
}
}
/**
* Checks for certain params existence in the value, and replace them
* with real values obtained from <tt>request</tt>.
* @param value the value of the header param
* @param request the request we are processing
* @return the value with replaced params
*/
private static String processParams(String value, Request request, Map<String, String> props)
{
if(value.indexOf("${from.address}") != -1)
{
FromHeader fromHeader
= (FromHeader)request.getHeader(FromHeader.NAME);
if(fromHeader != null)
{
value = value.replace(
"${from.address}",
fromHeader.getAddress().getURI().toString());
}
if (value.contains(props.get(ProtocolProviderFactory.DOMAIN)))
{
value = value.replace(ProtocolProviderFactory.DOMAIN, props.get("DomainName"));
logger.info("from.address new value : " + value);
}
}
if(value.indexOf("${from.userID}") != -1)
{
FromHeader fromHeader
= (FromHeader)request.getHeader(FromHeader.NAME);
if(fromHeader != null)
{
URI fromURI = fromHeader.getAddress().getURI();
String fromAddr = fromURI.toString();
// strips sip: or sips:
if(fromURI.isSipURI())
{
fromAddr
= fromAddr.replaceFirst(fromURI.getScheme() + ":", "");
}
// take the userID part
int index = fromAddr.indexOf('@');
if ( index > -1 )
fromAddr = fromAddr.substring(0, index);
value = value.replace("${from.userID}", fromAddr);
}
}
if(value.indexOf("${to.address}") != -1)
{
ToHeader toHeader =
(ToHeader)request.getHeader(ToHeader.NAME);
if(toHeader != null)
{
value = value.replace(
"${to.address}",
toHeader.getAddress().getURI().toString());
}
}
if(value.indexOf("${to.userID}") != -1)
{
ToHeader toHeader =
(ToHeader)request.getHeader(ToHeader.NAME);
if(toHeader != null)
{
URI toURI = toHeader.getAddress().getURI();
String toAddr = toURI.toString();
// strips sip: or sips:
if(toURI.isSipURI())
{
toAddr = toAddr.replaceFirst(toURI.getScheme() + ":", "");
}
// take the userID part
int index = toAddr.indexOf('@');
if ( index > -1 )
toAddr = toAddr.substring(0, index);
value = value.replace("${to.userID}", toAddr);
}
}
if (value.indexOf("${domain}") != -1)
{
value =
value.replace("${domain}",
props.get(ProtocolProviderFactory.DOMAIN));
}
// Needed of IMS
if(value.indexOf("+") != -1 && !Boolean.parseBoolean(props.get(ProtocolProviderFactory.PLUS_ENABLED))) {
logger.info("Replacing + character !!");
value = value.replace("+","");
}
return value;
}
}
| src/net/java/sip/communicator/impl/protocol/sip/ConfigHeaders.java | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.sip;
import gov.nist.javax.sip.header.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.service.protocol.ProtocolProviderFactory;
import javax.sip.address.*;
import javax.sip.header.*;
import javax.sip.message.*;
import java.util.*;
/**
* Checks the <tt>protocolProvider</tt>'s account properties for configured
* custom headers and add them to the outgoing requests.
* The header account properties are of form:
* ConfigHeader.N.Name=HeaderName
* ConfigHeader.N.Value=HeaderValue
* ConfigHeader.N.Method=SIP_MethodName (optional)
* Where N is the index of the header, multiple custom headers can be added.
* Name is the header name to use and Value is its value. The optional
* property is whether to use a specific request method to attach headers to
* or if missing we will attach it to all requests.
*
* @author Damian Minkov
*/
public class ConfigHeaders
{
/**
* The logger for this class
*/
public final static Logger logger = Logger.getLogger(ConfigHeaders.class);
/**
* The account property holding all the custom pre-configured headers.
*/
private final static String ACC_PROPERTY_CONFIG_HEADER = "ConfigHeader";
/**
* The config property suffix for custom header name.
*/
private final static String ACC_PROPERTY_CONFIG_HEADER_NAME
= "Name";
/**
* The config property suffix for custom header value.
*/
private final static String ACC_PROPERTY_CONFIG_HEADER_VALUE
= "Value";
/**
* The config property suffix for custom header method.
*/
private final static String ACC_PROPERTY_CONFIG_HEADER_METHOD
= "Method";
/**
* Attach any custom headers pre configured for the account. Added only
* to message Requests.
* The header account properties are of form:
* ConfigHeader.N.Name=HeaderName
* ConfigHeader.N.Value=HeaderValue
* ConfigHeader.N.Method=SIP_MethodName (optional)
* Where N is the index of the header, multiple custom headers can be added.
* Name is the header name to use and Value is its value. The optional
* property is whether to use a specific request method to attach headers to
* or if missing we will attach it to all requests.
*
* @param message the message that we'd like to attach custom headers to.
* @param protocolProvider the protocol provider to check for configured
* custom headers.
*/
static void attachConfigHeaders(
Message message,
ProtocolProviderServiceSipImpl protocolProvider)
{
if(message instanceof Response)
return;
Request request = (Request)message;
ToHeader toHeader =
(ToHeader) request.getHeader(ToHeader.NAME);
String domainName = toHeader.getAddress().getURI().toString();
if(domainName.contains(";")) {
domainName = domainName.substring(domainName.indexOf("@"), domainName.indexOf(";"));
} else {
domainName = domainName.substring(domainName.indexOf("@"));
}
Map<String, String> props =
protocolProvider.getAccountID().getAccountProperties();
props.put("DomainName", domainName);
Map<String,Map<String,String>> headers
= new HashMap<String, Map<String, String>>();
// parse the properties into the map where the index is the key
for(Map.Entry<String, String> entry : props.entrySet())
{
String pName = entry.getKey();
String prefStr = entry.getValue();
String name;
String ix;
if(!pName.startsWith(ACC_PROPERTY_CONFIG_HEADER) || prefStr == null)
continue;
prefStr = prefStr.trim();
if(pName.contains("."))
{
pName = pName.replaceAll(ACC_PROPERTY_CONFIG_HEADER + ".", "");
name = pName.substring(pName.lastIndexOf('.') + 1).trim();
if(!pName.contains("."))
continue;
ix = pName.substring(0, pName.lastIndexOf('.')).trim();
}
else
continue;
Map<String,String> headerValues = headers.get(ix);
if(headerValues == null)
{
headerValues = new HashMap<String, String>();
headers.put(ix, headerValues);
}
headerValues.put(name, prefStr);
}
// process the found custom headers
for(Map<String, String> headerValues : headers.values())
{
String method = headerValues.get(ACC_PROPERTY_CONFIG_HEADER_METHOD);
// if there is a method setting and is different from
// current request method skip this header
// if any of the required properties are missing skip (Name & Value)
if((method != null
&& !request.getMethod().equalsIgnoreCase(method))
|| !headerValues.containsKey(ACC_PROPERTY_CONFIG_HEADER_NAME)
|| !headerValues.containsKey(ACC_PROPERTY_CONFIG_HEADER_VALUE))
continue;
try
{
String headerValue = headerValues.get(ACC_PROPERTY_CONFIG_HEADER_VALUE);
String name = headerValues.get(ACC_PROPERTY_CONFIG_HEADER_NAME);
String value = processParams(headerValue,request,props);
if(name.equals("P-Asserted-Identity")) {
value = value.split(":")[0] + ":+" + value.split(":")[1];
}
Header h = request.getHeader(name);
logger.info("Header : " + name + " : " + value);
// makes possible overriding already created headers which
// are not custom one
// RouteHeader is used by ProxyRouter/DefaultRouter and we
// cannot use it as custom header if we want to add it
if((h != null && !(h instanceof CustomHeader))
|| name.equals(SIPHeaderNames.ROUTE))
{
request.setHeader(protocolProvider.getHeaderFactory()
.createHeader(name, value));
}
else
request.addHeader(new CustomHeaderList(name, value));
}
catch(Exception e)
{
logger.error("Cannot create custom header", e);
}
}
}
/**
* Checks for certain params existence in the value, and replace them
* with real values obtained from <tt>request</tt>.
* @param value the value of the header param
* @param request the request we are processing
* @return the value with replaced params
*/
private static String processParams(String value, Request request, Map<String, String> props)
{
if(value.indexOf("${from.address}") != -1)
{
FromHeader fromHeader
= (FromHeader)request.getHeader(FromHeader.NAME);
if(fromHeader != null)
{
value = value.replace(
"${from.address}",
fromHeader.getAddress().getURI().toString());
}
if (value.contains(props.get(ProtocolProviderFactory.DOMAIN)))
{
value = value.replace(value.substring(value.indexOf("@"),value.indexOf("@") + props.get(ProtocolProviderFactory.DOMAIN).length() + 1), props.get("DomainName"));
logger.info("from.address new value : " + value);
}
}
if(value.indexOf("${from.userID}") != -1)
{
FromHeader fromHeader
= (FromHeader)request.getHeader(FromHeader.NAME);
if(fromHeader != null)
{
URI fromURI = fromHeader.getAddress().getURI();
String fromAddr = fromURI.toString();
// strips sip: or sips:
if(fromURI.isSipURI())
{
fromAddr
= fromAddr.replaceFirst(fromURI.getScheme() + ":", "");
}
// take the userID part
int index = fromAddr.indexOf('@');
if ( index > -1 )
fromAddr = fromAddr.substring(0, index);
value = value.replace("${from.userID}", fromAddr);
}
}
if(value.indexOf("${to.address}") != -1)
{
ToHeader toHeader =
(ToHeader)request.getHeader(ToHeader.NAME);
if(toHeader != null)
{
value = value.replace(
"${to.address}",
toHeader.getAddress().getURI().toString());
}
}
if(value.indexOf("${to.userID}") != -1)
{
ToHeader toHeader =
(ToHeader)request.getHeader(ToHeader.NAME);
if(toHeader != null)
{
URI toURI = toHeader.getAddress().getURI();
String toAddr = toURI.toString();
// strips sip: or sips:
if(toURI.isSipURI())
{
toAddr = toAddr.replaceFirst(toURI.getScheme() + ":", "");
}
// take the userID part
int index = toAddr.indexOf('@');
if ( index > -1 )
toAddr = toAddr.substring(0, index);
value = value.replace("${to.userID}", toAddr);
}
}
if (value.indexOf("${domain}") != -1)
{
value =
value.replace("${domain}",
props.get(ProtocolProviderFactory.DOMAIN));
}
// Needed of IMS
if(value.indexOf("+") != -1 && !Boolean.parseBoolean(props.get(ProtocolProviderFactory.PLUS_ENABLED))) {
logger.info("Replacing + character !!");
value = value.replace("+","");
}
return value;
}
}
| fix for configurable domain change | src/net/java/sip/communicator/impl/protocol/sip/ConfigHeaders.java | fix for configurable domain change | <ide><path>rc/net/java/sip/communicator/impl/protocol/sip/ConfigHeaders.java
<ide>
<ide> if (value.contains(props.get(ProtocolProviderFactory.DOMAIN)))
<ide> {
<del> value = value.replace(value.substring(value.indexOf("@"),value.indexOf("@") + props.get(ProtocolProviderFactory.DOMAIN).length() + 1), props.get("DomainName"));
<add> value = value.replace(ProtocolProviderFactory.DOMAIN, props.get("DomainName"));
<ide> logger.info("from.address new value : " + value);
<ide> }
<ide> } |
|
Java | agpl-3.0 | 44f0956721d102bf0dee81fd786afbeb498f6a5b | 0 | ngaut/sql-layer,shunwang/sql-layer-1,qiuyesuifeng/sql-layer,qiuyesuifeng/sql-layer,shunwang/sql-layer-1,shunwang/sql-layer-1,ngaut/sql-layer,ngaut/sql-layer,jaytaylor/sql-layer,jaytaylor/sql-layer,relateiq/sql-layer,relateiq/sql-layer,qiuyesuifeng/sql-layer,relateiq/sql-layer,wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer,ngaut/sql-layer,jaytaylor/sql-layer,wfxiang08/sql-layer-1,wfxiang08/sql-layer-1,jaytaylor/sql-layer,wfxiang08/sql-layer-1,relateiq/sql-layer,shunwang/sql-layer-1 | /**
* Copyright (C) 2009-2013 FoundationDB, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.foundationdb.sql.script;
import com.foundationdb.ais.model.Parameter;
import com.foundationdb.qp.operator.QueryBindings;
import com.foundationdb.sql.server.ServerCallExplainer;
import com.foundationdb.sql.server.ServerJavaRoutine;
import com.foundationdb.sql.server.ServerJavaValues;
import com.foundationdb.sql.server.ServerQueryContext;
import com.foundationdb.sql.server.ServerRoutineInvocation;
import com.foundationdb.server.explain.Attributes;
import com.foundationdb.server.explain.CompoundExplainer;
import com.foundationdb.server.explain.ExplainContext;
import com.foundationdb.server.explain.Label;
import com.foundationdb.server.explain.PrimitiveExplainer;
import com.foundationdb.server.service.routines.ScriptEvaluator;
import com.foundationdb.server.service.routines.ScriptPool;
import javax.script.Bindings;
import java.sql.ResultSet;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.List;
import java.util.Map;
/** Implementation of the <code>SCRIPT_BINDINGS</code> calling convention.
* Inputs are passed as named (script engine scope) variables.
* Outputs can be received in the same way, or (since that is not
* possible in all languages) via the scripts return value, which can
* be a single value or a list or a dictionary.
*/
public class ScriptBindingsRoutine extends ServerJavaRoutine
{
private ScriptPool<ScriptEvaluator> pool;
private ScriptEvaluator evaluator;
private Bindings bindings;
private Object evalResult;
public ScriptBindingsRoutine(ServerQueryContext context,
QueryBindings queryBindings,
ServerRoutineInvocation invocation,
ScriptPool<ScriptEvaluator> pool) {
super(context, queryBindings, invocation);
this.pool = pool;
}
@Override
public void push() {
super.push();
evaluator = pool.get();
bindings = evaluator.getBindings();
}
@Override
public void setInParameter(Parameter parameter, ServerJavaValues values, int index) {
String var = parameter.getName();
if (var == null)
var = String.format("arg%d", index+1);
bindings.put(var, values.getObject(index));
}
@Override
public void invoke() {
evalResult = evaluator.eval(bindings);
}
@Override
public Object getOutParameter(Parameter parameter, int index) {
if (parameter.getDirection() == Parameter.Direction.RETURN) {
return evalResult;
}
String var = parameter.getName();
if (var == null)
var = String.format("arg%d", index+1);
if (bindings.containsKey(var)) {
// Rhino Bindings exposes internal objects directly.
return getRhino17Interface().unwrap(bindings.get(var));
}
// Not bound, try to find in result.
if (parameter.getRoutine().isProcedure()) {
// Unless FUNCTION, can usurp return value.
if (evalResult instanceof Map) {
Map mresult = (Map)evalResult;
if (mresult.containsKey(var))
return mresult.get(var);
Integer jndex = getParameterArrayPosition(parameter);
if (mresult.containsKey(jndex))
return mresult.get(jndex);
}
else if (evalResult instanceof List) {
List lresult = (List)evalResult;
int jndex = getParameterArrayPosition(parameter);
if (jndex < lresult.size())
return lresult.get(jndex);
}
else {
for (Parameter otherParam : parameter.getRoutine().getParameters()) {
if (otherParam == parameter) continue;
if (otherParam.getDirection() != Parameter.Direction.IN)
return null; // Too many outputs.
}
return evalResult;
}
}
return null;
}
protected static int getParameterArrayPosition(Parameter parameter) {
int index = 0;
for (Parameter otherParam : parameter.getRoutine().getParameters()) {
if (otherParam == parameter) break;
if (otherParam.getDirection() != Parameter.Direction.IN)
index++;
}
return index;
}
@Override
public Queue<ResultSet> getDynamicResultSets() {
Queue<ResultSet> result = new ArrayDeque<>();
if (evalResult instanceof ResultSet) {
result.add((ResultSet)evalResult);
}
else if (evalResult instanceof List) {
for (Object obj : (List)evalResult) {
if (obj instanceof ResultSet) {
result.add((ResultSet)obj);
}
}
}
return result;
}
@Override
public void pop(boolean success) {
pool.put(evaluator, success);
evaluator = null;
super.pop(success);
}
/** In Rhino (1.7), internal Java object wrappers can leak out.
* TODO: Needed until completely migrated to Nashorn (Java 8).
*/
static class Rhino17Interface {
private final Class nativeJavaObject;
private final java.lang.reflect.Method unwrap;
public Rhino17Interface() {
Class clazz = null;
java.lang.reflect.Method meth = null;
try {
clazz = Class.forName("sun.org.mozilla.javascript.NativeJavaObject");
}
catch (Exception ex) {
}
if (clazz == null) {
try {
clazz = Class.forName("sun.org.mozilla.javascript.internal.NativeJavaObject");
}
catch (Exception ex) {
}
}
if (clazz != null) {
try {
meth = clazz.getMethod("unwrap");
}
catch (Exception ex) {
clazz = null;
}
}
this.nativeJavaObject = clazz;
this.unwrap = meth;
}
public Object unwrap(Object obj) {
try {
if ((nativeJavaObject != null) &&
nativeJavaObject.isInstance(obj)) {
obj = unwrap.invoke(obj);
}
}
catch (Exception ex) {
}
return obj;
}
}
private static Rhino17Interface rhino17Interface = null;
private static Rhino17Interface getRhino17Interface() {
if (rhino17Interface == null) {
synchronized (ScriptBindingsRoutine.class) {
if (rhino17Interface == null) {
rhino17Interface = new Rhino17Interface();
}
}
}
return rhino17Interface;
}
@Override
public CompoundExplainer getExplainer(ExplainContext context) {
Attributes atts = new Attributes();
ScriptEvaluator evaluator = pool.get();
atts.put(Label.PROCEDURE_IMPLEMENTATION,
PrimitiveExplainer.getInstance(evaluator.getEngineName()));
if (evaluator.isCompiled())
atts.put(Label.PROCEDURE_IMPLEMENTATION,
PrimitiveExplainer.getInstance("compiled"));
if (evaluator.isShared())
atts.put(Label.PROCEDURE_IMPLEMENTATION,
PrimitiveExplainer.getInstance("shared"));
pool.put(evaluator, true);
return new ServerCallExplainer(getInvocation(), atts, context);
}
}
| src/main/java/com/foundationdb/sql/script/ScriptBindingsRoutine.java | /**
* Copyright (C) 2009-2013 FoundationDB, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.foundationdb.sql.script;
import com.foundationdb.ais.model.Parameter;
import com.foundationdb.qp.operator.QueryBindings;
import com.foundationdb.server.error.ExternalRoutineInvocationException;
import com.foundationdb.sql.server.ServerCallExplainer;
import com.foundationdb.sql.server.ServerJavaRoutine;
import com.foundationdb.sql.server.ServerJavaValues;
import com.foundationdb.sql.server.ServerQueryContext;
import com.foundationdb.sql.server.ServerRoutineInvocation;
import com.foundationdb.server.explain.Attributes;
import com.foundationdb.server.explain.CompoundExplainer;
import com.foundationdb.server.explain.ExplainContext;
import com.foundationdb.server.explain.Explainable;
import com.foundationdb.server.explain.Label;
import com.foundationdb.server.explain.PrimitiveExplainer;
import com.foundationdb.server.service.routines.ScriptEvaluator;
import com.foundationdb.server.service.routines.ScriptPool;
import javax.script.Bindings;
import java.sql.ResultSet;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.List;
import java.util.Map;
/** Implementation of the <code>SCRIPT_BINDINGS</code> calling convention.
* Inputs are passed as named (script engine scope) variables.
* Outputs can be received in the same way, or (since that is not
* possible in all languages) via the scripts return value, which can
* be a single value or a list or a dictionary.
*/
public class ScriptBindingsRoutine extends ServerJavaRoutine
{
private ScriptPool<ScriptEvaluator> pool;
private ScriptEvaluator evaluator;
private Bindings bindings;
private Object evalResult;
public ScriptBindingsRoutine(ServerQueryContext context,
QueryBindings queryBindings,
ServerRoutineInvocation invocation,
ScriptPool<ScriptEvaluator> pool) {
super(context, queryBindings, invocation);
this.pool = pool;
}
@Override
public void push() {
super.push();
evaluator = pool.get();
bindings = evaluator.getBindings();
}
@Override
public void setInParameter(Parameter parameter, ServerJavaValues values, int index) {
String var = parameter.getName();
if (var == null)
var = String.format("arg%d", index+1);
bindings.put(var, values.getObject(index));
}
@Override
public void invoke() {
evalResult = evaluator.eval(bindings);
}
@Override
public Object getOutParameter(Parameter parameter, int index) {
if (parameter.getDirection() == Parameter.Direction.RETURN) {
return evalResult;
}
String var = parameter.getName();
if (var == null)
var = String.format("arg%d", index+1);
if (bindings.containsKey(var))
return bindings.get(var);
// Not bound, try to find in result.
if (parameter.getRoutine().isProcedure()) {
// Unless FUNCTION, can usurp return value.
if (evalResult instanceof Map) {
Map mresult = (Map)evalResult;
if (mresult.containsKey(var))
return mresult.get(var);
Integer jndex = getParameterArrayPosition(parameter);
if (mresult.containsKey(jndex))
return mresult.get(jndex);
}
else if (evalResult instanceof List) {
List lresult = (List)evalResult;
int jndex = getParameterArrayPosition(parameter);
if (jndex < lresult.size())
return lresult.get(jndex);
}
else if (getRhino16Interface().isScriptable(evalResult)) {
return getRhino16Interface().getOutParameter(parameter, var, evalResult);
}
else {
for (Parameter otherParam : parameter.getRoutine().getParameters()) {
if (otherParam == parameter) continue;
if (otherParam.getDirection() != Parameter.Direction.IN)
return null; // Too many outputs.
}
return evalResult;
}
}
return null;
}
protected static int getParameterArrayPosition(Parameter parameter) {
int index = 0;
for (Parameter otherParam : parameter.getRoutine().getParameters()) {
if (otherParam == parameter) break;
if (otherParam.getDirection() != Parameter.Direction.IN)
index++;
}
return index;
}
@Override
public Queue<ResultSet> getDynamicResultSets() {
Queue<ResultSet> result = new ArrayDeque<>();
if (evalResult instanceof ResultSet) {
result.add((ResultSet)evalResult);
}
else if (evalResult instanceof List) {
for (Object obj : (List)evalResult) {
if (obj instanceof ResultSet) {
result.add((ResultSet)obj);
}
}
}
else if (getRhino16Interface().isScriptable(evalResult)) {
getRhino16Interface().getDynamicResultSets(result, evalResult);
}
return result;
}
@Override
public void pop(boolean success) {
pool.put(evaluator, success);
evaluator = null;
super.pop(success);
}
/** In Rhino 1.7R3, which comes with JDK 7, Array and Object are List and Map, respectively.
* In Rhino 1.6R2, which comes with JDK 6, they are not.
* TODO: Remove when migrated to JDK 7 exclusively.
*/
static class Rhino16Interface {
private final Class scriptable, nativeJavaObject;
private final java.lang.reflect.Method getInt, getString, unwrap;
private final Object NOT_FOUND;
public Rhino16Interface() {
Class c1, c2;
java.lang.reflect.Method m1, m2, m3;
Object unique;
try {
c1 = Class.forName("sun.org.mozilla.javascript.internal.Scriptable");
c2 = Class.forName("sun.org.mozilla.javascript.internal.NativeJavaObject");
unique = c1.getField("NOT_FOUND").get(null);
m1 = c1.getMethod("get", Integer.TYPE, c1);
m2 = c1.getMethod("get", String.class, c1);
m3 = c2.getMethod("unwrap");
}
catch (Exception ex) {
c1 = c2 = null;
unique = null;
m1 = m2 = m3 = null;
}
this.scriptable = c1;
this.nativeJavaObject = c2;
this.getInt = m1;
this.getString = m2;
this.unwrap = m3;
this.NOT_FOUND = unique;
}
public boolean isScriptable(Object obj) {
if (scriptable != null) {
try {
return scriptable.isInstance(obj);
}
catch (Exception ex) {
}
}
return false;
}
public Object getOutParameter(Parameter parameter, String var,
Object evalResult) {
try {
Object byName = getString.invoke(evalResult, var, null);
if (byName != NOT_FOUND) return byName;
int index = getParameterArrayPosition(parameter);
Object byPosition = getInt.invoke(evalResult, index, null);
if (byPosition != NOT_FOUND) return byPosition;
}
catch (Exception ex) {
}
return null;
}
public static final int MAX_LENGTH = 100; // Just in case.
public void getDynamicResultSets(Queue<ResultSet> result, Object evalResult) {
try {
for (int i = 0; i < MAX_LENGTH; i++) {
Object elem = getInt.invoke(evalResult, i, null);
if (elem == NOT_FOUND) break;
if (nativeJavaObject.isInstance(elem))
elem = unwrap.invoke(elem);
if (elem instanceof ResultSet)
result.add((ResultSet)elem);
}
}
catch (Exception ex) {
}
}
}
private static Rhino16Interface rhino16Interface = null;
private static Rhino16Interface getRhino16Interface() {
if (rhino16Interface == null) {
synchronized (ScriptBindingsRoutine.class) {
if (rhino16Interface == null) {
rhino16Interface = new Rhino16Interface();
}
}
}
return rhino16Interface;
}
@Override
public CompoundExplainer getExplainer(ExplainContext context) {
Attributes atts = new Attributes();
ScriptEvaluator evaluator = pool.get();
atts.put(Label.PROCEDURE_IMPLEMENTATION,
PrimitiveExplainer.getInstance(evaluator.getEngineName()));
if (evaluator.isCompiled())
atts.put(Label.PROCEDURE_IMPLEMENTATION,
PrimitiveExplainer.getInstance("compiled"));
if (evaluator.isShared())
atts.put(Label.PROCEDURE_IMPLEMENTATION,
PrimitiveExplainer.getInstance("shared"));
pool.put(evaluator, true);
return new ServerCallExplainer(getInvocation(), atts, context);
}
}
| Adjust for the Rhino 1.7 problem.
| src/main/java/com/foundationdb/sql/script/ScriptBindingsRoutine.java | Adjust for the Rhino 1.7 problem. | <ide><path>rc/main/java/com/foundationdb/sql/script/ScriptBindingsRoutine.java
<ide>
<ide> import com.foundationdb.ais.model.Parameter;
<ide> import com.foundationdb.qp.operator.QueryBindings;
<del>import com.foundationdb.server.error.ExternalRoutineInvocationException;
<ide> import com.foundationdb.sql.server.ServerCallExplainer;
<ide> import com.foundationdb.sql.server.ServerJavaRoutine;
<ide> import com.foundationdb.sql.server.ServerJavaValues;
<ide> import com.foundationdb.server.explain.Attributes;
<ide> import com.foundationdb.server.explain.CompoundExplainer;
<ide> import com.foundationdb.server.explain.ExplainContext;
<del>import com.foundationdb.server.explain.Explainable;
<ide> import com.foundationdb.server.explain.Label;
<ide> import com.foundationdb.server.explain.PrimitiveExplainer;
<ide> import com.foundationdb.server.service.routines.ScriptEvaluator;
<ide> String var = parameter.getName();
<ide> if (var == null)
<ide> var = String.format("arg%d", index+1);
<del> if (bindings.containsKey(var))
<del> return bindings.get(var);
<add> if (bindings.containsKey(var)) {
<add> // Rhino Bindings exposes internal objects directly.
<add> return getRhino17Interface().unwrap(bindings.get(var));
<add> }
<ide> // Not bound, try to find in result.
<ide> if (parameter.getRoutine().isProcedure()) {
<ide> // Unless FUNCTION, can usurp return value.
<ide> if (jndex < lresult.size())
<ide> return lresult.get(jndex);
<ide> }
<del> else if (getRhino16Interface().isScriptable(evalResult)) {
<del> return getRhino16Interface().getOutParameter(parameter, var, evalResult);
<del> }
<ide> else {
<ide> for (Parameter otherParam : parameter.getRoutine().getParameters()) {
<ide> if (otherParam == parameter) continue;
<ide> }
<ide> }
<ide> }
<del> else if (getRhino16Interface().isScriptable(evalResult)) {
<del> getRhino16Interface().getDynamicResultSets(result, evalResult);
<del> }
<ide> return result;
<ide> }
<ide>
<ide> super.pop(success);
<ide> }
<ide>
<del> /** In Rhino 1.7R3, which comes with JDK 7, Array and Object are List and Map, respectively.
<del> * In Rhino 1.6R2, which comes with JDK 6, they are not.
<del> * TODO: Remove when migrated to JDK 7 exclusively.
<add> /** In Rhino (1.7), internal Java object wrappers can leak out.
<add> * TODO: Needed until completely migrated to Nashorn (Java 8).
<ide> */
<del> static class Rhino16Interface {
<del> private final Class scriptable, nativeJavaObject;
<del> private final java.lang.reflect.Method getInt, getString, unwrap;
<del> private final Object NOT_FOUND;
<del>
<del> public Rhino16Interface() {
<del> Class c1, c2;
<del> java.lang.reflect.Method m1, m2, m3;
<del> Object unique;
<add> static class Rhino17Interface {
<add> private final Class nativeJavaObject;
<add> private final java.lang.reflect.Method unwrap;
<add>
<add> public Rhino17Interface() {
<add> Class clazz = null;
<add> java.lang.reflect.Method meth = null;
<ide> try {
<del> c1 = Class.forName("sun.org.mozilla.javascript.internal.Scriptable");
<del> c2 = Class.forName("sun.org.mozilla.javascript.internal.NativeJavaObject");
<del> unique = c1.getField("NOT_FOUND").get(null);
<del> m1 = c1.getMethod("get", Integer.TYPE, c1);
<del> m2 = c1.getMethod("get", String.class, c1);
<del> m3 = c2.getMethod("unwrap");
<add> clazz = Class.forName("sun.org.mozilla.javascript.NativeJavaObject");
<ide> }
<ide> catch (Exception ex) {
<del> c1 = c2 = null;
<del> unique = null;
<del> m1 = m2 = m3 = null;
<del> }
<del> this.scriptable = c1;
<del> this.nativeJavaObject = c2;
<del> this.getInt = m1;
<del> this.getString = m2;
<del> this.unwrap = m3;
<del> this.NOT_FOUND = unique;
<del> }
<del>
<del> public boolean isScriptable(Object obj) {
<del> if (scriptable != null) {
<add> }
<add> if (clazz == null) {
<ide> try {
<del> return scriptable.isInstance(obj);
<add> clazz = Class.forName("sun.org.mozilla.javascript.internal.NativeJavaObject");
<ide> }
<ide> catch (Exception ex) {
<ide> }
<ide> }
<del> return false;
<del> }
<del>
<del> public Object getOutParameter(Parameter parameter, String var,
<del> Object evalResult) {
<add> if (clazz != null) {
<add> try {
<add> meth = clazz.getMethod("unwrap");
<add> }
<add> catch (Exception ex) {
<add> clazz = null;
<add> }
<add> }
<add> this.nativeJavaObject = clazz;
<add> this.unwrap = meth;
<add> }
<add>
<add> public Object unwrap(Object obj) {
<ide> try {
<del> Object byName = getString.invoke(evalResult, var, null);
<del> if (byName != NOT_FOUND) return byName;
<del> int index = getParameterArrayPosition(parameter);
<del> Object byPosition = getInt.invoke(evalResult, index, null);
<del> if (byPosition != NOT_FOUND) return byPosition;
<add> if ((nativeJavaObject != null) &&
<add> nativeJavaObject.isInstance(obj)) {
<add> obj = unwrap.invoke(obj);
<add> }
<ide> }
<ide> catch (Exception ex) {
<ide> }
<del> return null;
<del> }
<del>
<del> public static final int MAX_LENGTH = 100; // Just in case.
<del>
<del> public void getDynamicResultSets(Queue<ResultSet> result, Object evalResult) {
<del> try {
<del> for (int i = 0; i < MAX_LENGTH; i++) {
<del> Object elem = getInt.invoke(evalResult, i, null);
<del> if (elem == NOT_FOUND) break;
<del> if (nativeJavaObject.isInstance(elem))
<del> elem = unwrap.invoke(elem);
<del> if (elem instanceof ResultSet)
<del> result.add((ResultSet)elem);
<del> }
<del> }
<del> catch (Exception ex) {
<del> }
<del> }
<del> }
<del>
<del> private static Rhino16Interface rhino16Interface = null;
<del>
<del> private static Rhino16Interface getRhino16Interface() {
<del> if (rhino16Interface == null) {
<add> return obj;
<add> }
<add> }
<add>
<add> private static Rhino17Interface rhino17Interface = null;
<add>
<add> private static Rhino17Interface getRhino17Interface() {
<add> if (rhino17Interface == null) {
<ide> synchronized (ScriptBindingsRoutine.class) {
<del> if (rhino16Interface == null) {
<del> rhino16Interface = new Rhino16Interface();
<del> }
<del> }
<del> }
<del> return rhino16Interface;
<add> if (rhino17Interface == null) {
<add> rhino17Interface = new Rhino17Interface();
<add> }
<add> }
<add> }
<add> return rhino17Interface;
<ide> }
<ide>
<ide> @Override |
|
Java | epl-1.0 | aee462612da899da95bfd59029bf17438ab2d341 | 0 | SmithRWORNL/ice,wo-amlangwang/ice,nickstanish/ice,nickstanish/ice,eclipse/ice,SmithRWORNL/ice,nickstanish/ice,menghanli/ice,SmithRWORNL/ice,eclipse/ice,eclipse/ice,nickstanish/ice,wo-amlangwang/ice,wo-amlangwang/ice,gorindn/ice,SmithRWORNL/ice,nickstanish/ice,gorindn/ice,wo-amlangwang/ice,menghanli/ice,nickstanish/ice,gorindn/ice,nickstanish/ice,menghanli/ice,SmithRWORNL/ice,wo-amlangwang/ice,wo-amlangwang/ice,gorindn/ice,SmithRWORNL/ice,eclipse/ice,SmithRWORNL/ice,SmithRWORNL/ice,wo-amlangwang/ice,gorindn/ice,menghanli/ice,wo-amlangwang/ice,menghanli/ice,gorindn/ice,eclipse/ice,eclipse/ice,menghanli/ice,menghanli/ice,gorindn/ice | /*******************************************************************************
* Copyright (c) 2012, 2014 UT-Battelle, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Initial API and implementation and/or initial documentation -
* Jay Jay Billings, Kasper Gammeltoft
*******************************************************************************/
package org.eclipse.ice.datastructures.test;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.bind.JAXBException;
import org.eclipse.ice.datastructures.ICEObject.ICEJAXBHandler;
import org.eclipse.ice.datastructures.form.Material;
import org.eclipse.ice.datastructures.form.MaterialStack;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test class for {@link org.eclipse.ice.datastructures.form.MaterialStack}
* @author Jay Jay Billings, Kasper Gammeltoft
*
*/
public class MaterialStackTester {
/**
* Test method for {@link org.eclipse.ice.datastructures.form.MaterialStack#MaterialStack()}.
*/
@Test
public void testConstruction() {
Material matTest1 = new Material();
matTest1.setName("Nitrogen");
MaterialStack stack1 = new MaterialStack(matTest1, 3);
assertNotNull(matTest1);
MaterialStack stack2 = new MaterialStack();
stack2.setMaterial(matTest1);
stack2.setAmount(3);
assertTrue(stack1.equals(stack2));
}
/**
* Test method for {@link org.eclipse.ice.datastructures.form.MaterialStack#getMaterial()}.
*/
@Test
public void testGetMaterial() {
Material C02 = TestMaterialFactory.createCO2();
MaterialStack stack = new MaterialStack(C02, 3);
Material testMat = stack.getMaterial();
assertTrue(C02.equals(testMat));
}
/**
* Test method for {@link org.eclipse.ice.datastructures.form.MaterialStack#getAmount()}.
*/
@Test
public void testGetAmount() {
int amount = 3;
MaterialStack stack = new MaterialStack(TestMaterialFactory.createH2O(), amount);
int testAmount = stack.getAmount();
assertTrue(amount==testAmount);
}
/**
* Test method for {@link org.eclipse.ice.datastructures.form.MaterialStack#incrementAmount()}.
*/
@Test
public void testIncrementAmount() {
int startAmount = 2;
MaterialStack stack = new MaterialStack(TestMaterialFactory.createH2O(), startAmount);
stack.incrementAmount();
assertEquals(startAmount+1, stack.getAmount());
startAmount++;
int add = 5;
stack.addAmount(add);
assertEquals(startAmount+add, stack.getAmount());
}
/**
* Test method for {@link org.eclipse.ice.datastructures.form.MaterialStack#equals(org.eclipse.ice.datastructures.form.MaterialStack)}.
*/
@Test
public void testEqualsMaterialStack() {
// Put some carbon in a couple of stacks
Material carbon = new Material();
carbon.setName("C");
Material secondCarbon = new Material();
secondCarbon.setName("C");
MaterialStack stack = new MaterialStack(carbon, 1);
MaterialStack stack2 = new MaterialStack(secondCarbon, 1);
// Check them
assertTrue(stack.equals(stack2));
// Create two CO2 molecules
stack = new MaterialStack(TestMaterialFactory.createCO2(), 1);
stack2 = new MaterialStack(TestMaterialFactory.createCO2(), 1);
// Check them
assertTrue(stack.equals(stack2));
return;
}
/**
* This operation checks that the Material class can be loaded and written
* with JAXB.
*/
@Test
public void checkPersistence() {
// Local Declarations
ICEJAXBHandler xmlHandler = new ICEJAXBHandler();
ArrayList<Class> classList = new ArrayList<Class>();
classList.add(Material.class);
classList.add(MaterialStack.class);
// Use the ICE JAXB Manipulator instead of raw JAXB. Waste not want not.
ICEJAXBHandler jaxbHandler = new ICEJAXBHandler();
// Create a Material that will be written to XML
Material material = TestMaterialFactory.createCO2();
MaterialStack stack = new MaterialStack();
stack.setMaterial(material);
try {
// Write the material to a byte stream so that it can be converted
// easily and read back in.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
jaxbHandler.write(stack, classList, outputStream);
// Read it back from the stream into a second Material by converting
// the output stream into a byte array and then an input stream.
ByteArrayInputStream inputStream = new ByteArrayInputStream(
outputStream.toByteArray());
MaterialStack readMaterialStack = (MaterialStack) jaxbHandler.read(classList,
inputStream);
// They should be equal.
assertTrue(readMaterialStack.equals(stack));
} catch (NullPointerException | JAXBException | IOException e) {
// Complain
e.printStackTrace();
fail();
}
}
}
| tests/org.eclipse.ice.datastructures.test/src/org/eclipse/ice/datastructures/test/MaterialStackTester.java | /*******************************************************************************
* Copyright (c) 2012, 2014 UT-Battelle, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Initial API and implementation and/or initial documentation -
* Jay Jay Billings, Kasper Gammeltoft
*******************************************************************************/
package org.eclipse.ice.datastructures.test;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.bind.JAXBException;
import org.eclipse.ice.datastructures.ICEObject.ICEJAXBHandler;
import org.eclipse.ice.datastructures.form.Material;
import org.eclipse.ice.datastructures.form.MaterialStack;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test class for {@link org.eclipse.ice.datastructures.form.MaterialStack}
* @author Jay Jay Billings, Kasper Gammeltoft
*
*/
public class MaterialStackTester {
/**
* Test method for {@link org.eclipse.ice.datastructures.form.MaterialStack#MaterialStack()}.
*/
@Test
public void testConstruction() {
Material matTest1 = new Material();
matTest1.setName("Nitrogen");
MaterialStack stack1 = new MaterialStack(matTest1, 3);
assertNotNull(matTest1);
MaterialStack stack2 = new MaterialStack();
stack2.setMaterial(matTest1);
stack2.setAmount(3);
assertTrue(stack1.equals(stack2));
}
/**
* Test method for {@link org.eclipse.ice.datastructures.form.MaterialStack#getMaterial()}.
*/
@Test
public void testGetMaterial() {
Material C02 = TestMaterialFactory.createCO2();
MaterialStack stack = new MaterialStack(C02, 3);
Material testMat = stack.getMaterial();
assertTrue(C02.equals(testMat));
}
/**
* Test method for {@link org.eclipse.ice.datastructures.form.MaterialStack#getAmount()}.
*/
@Test
public void testGetAmount() {
int amount = 3;
MaterialStack stack = new MaterialStack(TestMaterialFactory.createH2O(), amount);
int testAmount = stack.getAmount();
assertTrue(amount==testAmount);
}
/**
* Test method for {@link org.eclipse.ice.datastructures.form.MaterialStack#incrementAmount()}.
*/
@Test
public void testIncrementAmount() {
int startAmount = 2;
MaterialStack stack = new MaterialStack(TestMaterialFactory.createH2O(), startAmount);
stack.incrementAmount();
assertEquals(startAmount+1, stack.getAmount());
startAmount++;
int add = 5;
stack.addAmount(add);
assertEquals(startAmount+add, stack.getAmount());
}
/**
* Test method for {@link org.eclipse.ice.datastructures.form.MaterialStack#equals(org.eclipse.ice.datastructures.form.MaterialStack)}.
*/
@Test
public void testEqualsMaterialStack() {
// Put some carbon in a couple of stacks
Material carbon = new Material();
carbon.setName("C");
Material secondCarbon = new Material();
secondCarbon.setName("C");
MaterialStack stack = new MaterialStack(carbon, 1);
MaterialStack stack2 = new MaterialStack(secondCarbon, 1);
// Check them
assertTrue(stack.equals(stack2));
// Create two CO2 molecules
stack = new MaterialStack(TestMaterialFactory.createCO2(), 1);
stack2 = new MaterialStack(TestMaterialFactory.createCO2(), 1);
// Check them
assertTrue(stack.equals(stack2));
return;
}
/**
* This operation checks that the Material class can be loaded and written
* with JAXB.
*/
@Test
public void checkPersistence() {
// Local Declarations
ICEJAXBHandler xmlHandler = new ICEJAXBHandler();
ArrayList<Class> classList = new ArrayList<Class>();
classList.add(Material.class);
classList.add(MaterialStack.class);
// Use the ICE JAXB Manipulator instead of raw JAXB. Waste not want not.
ICEJAXBHandler jaxbHandler = new ICEJAXBHandler();
// Create a Material that will be written to XML
Material material = new Material();//TestMaterialFactory.createCO2();
material.addComponent(new Material());
MaterialStack stack = new MaterialStack();
stack.setMaterial(material);
try {
// Write the material to a byte stream so that it can be converted
// easily and read back in.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
jaxbHandler.write(stack, classList, outputStream);
// Read it back from the stream into a second Material by converting
// the output stream into a byte array and then an input stream.
ByteArrayInputStream inputStream = new ByteArrayInputStream(
outputStream.toByteArray());
MaterialStack readMaterialStack = (MaterialStack) jaxbHandler.read(classList,
inputStream);
// They should be equal.
assertTrue(readMaterialStack.equals(stack));
} catch (NullPointerException | JAXBException | IOException e) {
// Complain
e.printStackTrace();
fail();
}
}
}
| Apparently the bug with XML parsing for the Material is not a problem
for Java 1.8 on my home machine. I reset the test to use CO2.
Signed-off-by: Jay Jay Billings <[email protected]> | tests/org.eclipse.ice.datastructures.test/src/org/eclipse/ice/datastructures/test/MaterialStackTester.java | Apparently the bug with XML parsing for the Material is not a problem for Java 1.8 on my home machine. I reset the test to use CO2. | <ide><path>ests/org.eclipse.ice.datastructures.test/src/org/eclipse/ice/datastructures/test/MaterialStackTester.java
<ide> ICEJAXBHandler jaxbHandler = new ICEJAXBHandler();
<ide>
<ide> // Create a Material that will be written to XML
<del> Material material = new Material();//TestMaterialFactory.createCO2();
<del> material.addComponent(new Material());
<add> Material material = TestMaterialFactory.createCO2();
<ide>
<ide> MaterialStack stack = new MaterialStack();
<ide> stack.setMaterial(material); |
|
JavaScript | mit | cbe1d5230b1a51bf119bd8a14df9165c41f149af | 0 | asnowwolf/lottery-ui,asnowwolf/lottery-ui | 'use strict';
angular.module('app').factory('daoLottery', function () {
function Award(award) {
_.extend(this, award);
}
function DaoLottery() {
this.name = '';
this.description = '';
this.awards = [{id: 1}];
}
DaoLottery.prototype.clear = function () {
this.name = '';
this.description = '';
this.awards = [{id: 1}];
};
DaoLottery.prototype.load = function () {
var data = localStorage.getItem('lottery');
_.extend(this, angular.fromJson(data));
};
DaoLottery.prototype.save = function () {
_.each(this.awards, function(award) {
award.id = +award.id
});
var data = angular.toJson(this);
localStorage.setItem('lottery', data);
};
DaoLottery.prototype.addAward = function (award) {
award = award || {};
if (!award.id) {
award.id = this.awards.length + 1;
} else {
award.id = +awardId;
}
this.awards.push(new Award(award));
};
DaoLottery.prototype.findAward = function (awardId) {
var award = _.where(this.awards, {id: awardId});
};
DaoLottery.prototype.removeAward = function (award) {
this.awards.splice(this.awards.indexOf(award), 1);
};
DaoLottery.prototype.importJson = function(text) {
var data = angular.fromJson(text);
_.extend(this, data);
};
DaoLottery.prototype.exportJson = function() {
var blob = new Blob([angular.toJson(this)], {type: "application/json;charset=utf-8"});
saveAs(blob, "lottery-" + moment().format('YYYYMMDD') + ".json");
};
return new DaoLottery();
});
| app/scripts/services/dao/DaoLottery.js | 'use strict';
angular.module('app').factory('daoLottery', function () {
function Award(award) {
_.extend(this, award);
}
function DaoLottery() {
this.name = '';
this.description = '';
this.awards = [{id: 1}];
}
DaoLottery.prototype.clear = function () {
this.name = '';
this.description = '';
this.awards = [{id: 1}];
};
DaoLottery.prototype.load = function () {
var data = localStorage.getItem('lottery');
_.extend(this, angular.fromJson(data));
};
DaoLottery.prototype.save = function () {
_.each(this.awards, function(award) {
award.id = +award.id
});
var data = angular.toJson(this);
localStorage.setItem('lottery', data);
};
DaoLottery.prototype.addAward = function (award) {
award = award || {};
if (!award.id) {
award.id = this.awards.length + 1;
} else {
award.id = +awardId;
}
this.awards.push(new Award(award));
};
DaoLottery.prototype.findAward = function (awardId) {
var award = _.where(this.awards, {id: awardId});
};
DaoLottery.prototype.removeAward = function (award) {
this.awards.splice(this.awards.indexOf(award));
};
DaoLottery.prototype.importJson = function(text) {
var data = angular.fromJson(text);
_.extend(this, data);
};
DaoLottery.prototype.exportJson = function() {
var blob = new Blob([angular.toJson(this)], {type: "application/json;charset=utf-8"});
saveAs(blob, "lottery-" + moment().format('YYYYMMDD') + ".json");
};
return new DaoLottery();
});
| 解决移除奖项时导致的bug
| app/scripts/services/dao/DaoLottery.js | 解决移除奖项时导致的bug | <ide><path>pp/scripts/services/dao/DaoLottery.js
<ide> var award = _.where(this.awards, {id: awardId});
<ide> };
<ide> DaoLottery.prototype.removeAward = function (award) {
<del> this.awards.splice(this.awards.indexOf(award));
<add> this.awards.splice(this.awards.indexOf(award), 1);
<ide> };
<ide> DaoLottery.prototype.importJson = function(text) {
<ide> var data = angular.fromJson(text); |
|
Java | apache-2.0 | 1277f24a634cc223e0f59729245eb390e20f01db | 0 | ga4gh/dockstore,ga4gh/dockstore,ga4gh/dockstore | package io.github.collaboratory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.HierarchicalINIConfiguration;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.VFS;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.SignerFactory;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.S3ClientOptions;
import com.amazonaws.services.s3.internal.S3Signer;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.gson.Gson;
import io.cwl.avro.CWL;
import io.cwl.avro.CommandInputParameter;
import io.cwl.avro.CommandLineTool;
import io.cwl.avro.CommandOutputParameter;
import io.dockstore.common.Utilities;
/**
* @author boconnor 9/24/15
* @author dyuen
* @author tetron
*/
public class LauncherCWL {
static {
SignerFactory.registerSigner("S3Signer", S3Signer.class);
}
private static final Logger LOG = LoggerFactory.getLogger(LauncherCWL.class);
public static final String S3_ENDPOINT = "s3.endpoint";
public static final String WORKING_DIRECTORY = "working-directory";
public static final String DCC_CLIENT_KEY = "dcc_storage.client";
private final String configFilePath;
private final String imageDescriptorPath;
private final String runtimeDescriptorPath;
private HierarchicalINIConfiguration config;
private String globalWorkingDir;
private final Yaml yaml = new Yaml(new SafeConstructor());
private final Optional<OutputStream> stdoutStream;
private final Optional<OutputStream> stderrStream;
private final Gson gson;
/**
* Constructor for shell-based launch
* @param args raw arguments from the command-line
*/
public LauncherCWL(String[] args) {
// create the command line parser
CommandLineParser parser = new DefaultParser();
// parse command line
CommandLine line = parseCommandLine(parser, args);
configFilePath = line.getOptionValue("config");
imageDescriptorPath = line.getOptionValue("descriptor");
runtimeDescriptorPath = line.getOptionValue("job");
// do not forward stdout and stderr
stdoutStream = Optional.absent();
stderrStream = Optional.absent();
CWL cwl = new CWL();
gson = cwl.getTypeSafeCWLToolDocument();
}
/**
* Constructor for programmatic launch
* @param configFilePath configuration for this launcher
* @param imageDescriptorPath descriptor for the tool itself
* @param runtimeDescriptorPath descriptor for this run of the tool
*/
public LauncherCWL(String configFilePath, String imageDescriptorPath, String runtimeDescriptorPath, OutputStream stdoutStream, OutputStream stderrStream){
this.configFilePath = configFilePath;
this.imageDescriptorPath = imageDescriptorPath;
this.runtimeDescriptorPath = runtimeDescriptorPath;
// programmatically forward stdout and stderr
this.stdoutStream = Optional.of(stdoutStream);
this.stderrStream = Optional.of(stderrStream);
CWL cwl = new CWL();
gson = cwl.getTypeSafeCWLToolDocument();
}
public void run(){
// now read in the INI file
try {
config = new HierarchicalINIConfiguration(configFilePath);
} catch (ConfigurationException e) {
throw new RuntimeException("could not read launcher config ini", e);
}
// parse the CWL tool definition without validation
CWL cwlUtil = new CWL();
final String imageDescriptorContent = cwlUtil.parseCWL(imageDescriptorPath, false).getLeft();
final CommandLineTool cwl = gson.fromJson(imageDescriptorContent, CommandLineTool.class);
if (cwl == null) {
LOG.info("CWL was null");
return;
}
// this is the job parameterization, just a JSON, defines the inputs/outputs in terms or real URLs that are provisioned by the launcher
Map<String, Object> inputsAndOutputsJson = loadJob(runtimeDescriptorPath);
if (inputsAndOutputsJson == null) {
LOG.info("Cannot load job object.");
return;
}
// setup directories
globalWorkingDir = setupDirectories();
// pull input files
final Map<String, FileInfo> inputsId2dockerMountMap = pullFiles(cwl, inputsAndOutputsJson);
// prep outputs, just creates output dir and records what the local output path will be
Map<String, FileInfo> outputMap = prepUploads(cwl, inputsAndOutputsJson);
// create updated JSON inputs document
String newJsonPath = createUpdatedInputsAndOutputsJson(inputsId2dockerMountMap, outputMap, inputsAndOutputsJson);
// run command
LOG.info("RUNNING COMMAND");
Map<String, Object> outputObj = runCWLCommand(imageDescriptorPath, newJsonPath, globalWorkingDir + "/outputs/");
// push output files
pushOutputFiles(outputMap, outputObj);
}
private Map<String, FileInfo> prepUploads(CommandLineTool cwl, Map<String, Object> inputsOutputs) {
Map<String, FileInfo> fileMap = new HashMap<>();
LOG.info("PREPPING UPLOADS...");
final List<CommandOutputParameter> outputs = cwl.getOutputs();
// for each file input from the CWL
for (CommandOutputParameter file : outputs) {
// pull back the name of the input from the CWL
LOG.info(file.toString());
String cwlID = file.getId().toString().substring(1);
LOG.info("ID: {}", cwlID);
// now that I have an input name from the CWL I can find it in the JSON parameterization for this run
LOG.info("JSON: {}", inputsOutputs);
for (Entry<String, Object> stringObjectEntry : inputsOutputs.entrySet()) {
if (stringObjectEntry.getValue() instanceof HashMap) {
Map param = (Map<String, Object>) stringObjectEntry.getValue();
String path = (String) param.get("path");
if (stringObjectEntry.getKey().equals(cwlID)) {
// if it's the current one
LOG.info("PATH TO UPLOAD TO: {} FOR {} FOR {}", path, cwlID, stringObjectEntry.getKey());
// output
// TODO: poor naming here, need to cleanup the variables
// just file name
// the file URL
File filePathObj = new File(cwlID);
//String newDirectory = globalWorkingDir + "/outputs/" + UUID.randomUUID().toString();
String newDirectory = globalWorkingDir + "/outputs";
Utilities.executeCommand("mkdir -p " + newDirectory, stdoutStream, stderrStream);
File newDirectoryFile = new File(newDirectory);
String uuidPath = newDirectoryFile.getAbsolutePath() + "/" + filePathObj.getName();
// VFS call, see https://github.com/abashev/vfs-s3/tree/branch-2.3.x and
// https://commons.apache.org/proper/commons-vfs/filesystems.html
// now add this info to a hash so I can later reconstruct a docker -v command
FileInfo new1 = new FileInfo();
new1.setUrl(path);
new1.setDockerPath(cwlID);
new1.setLocalPath(uuidPath);
fileMap.put(cwlID, new1);
LOG.info("UPLOAD FILE: LOCAL: {} URL: {}", cwlID, path);
}
}
}
}
return fileMap;
}
private String createUpdatedInputsAndOutputsJson(Map<String, FileInfo> fileMap, Map<String, FileInfo> outputMap, Map<String, Object> inputsAndOutputsJson) {
JSONObject newJSON = new JSONObject();
for (String paramName : inputsAndOutputsJson.keySet()) {
final Object currentParam = inputsAndOutputsJson.get(paramName);
if (currentParam instanceof Map) {
Map<String, Object> param = (Map<String, Object>) currentParam;
String path = (String) param.get("path");
LOG.info("PATH: {} PARAM_NAME: {}", path, paramName);
// will be null for output
if (fileMap.get(paramName) != null) {
final String localPath = fileMap.get(paramName).getLocalPath();
param.put("path", localPath);
LOG.info("NEW FULL PATH: {}", localPath);
} else if (outputMap.get(paramName) != null) {
final String localPath = outputMap.get(paramName).getLocalPath();
param.put("path", localPath);
LOG.info("NEW FULL PATH: {}", localPath);
}
// now add to the new JSON structure
JSONObject newRecord = new JSONObject();
newRecord.put("class", param.get("class"));
newRecord.put("path", param.get("path"));
newJSON.put(paramName, newRecord);
// TODO: fill in for all possible types
} else if (currentParam instanceof Integer || currentParam instanceof Float || currentParam instanceof Boolean || currentParam instanceof String) {
newJSON.put(paramName, currentParam);
} else if (currentParam instanceof List) {
List<Map<String, String>> currentParamList = (List<Map<String, String>>)currentParam;
for (Map<String, String> param : currentParamList) {
String path = param.get("path");
LOG.info("PATH: {} PARAM_NAME: {}", path, paramName);
// will be null for output, only dealing with inputs currently
// TODO: can outputs be file arrays too??? Maybe need to do something for globs??? Need to investigate
if (fileMap.get(paramName + ":" + path) != null) {
final String localPath = fileMap.get(paramName + ":" + path).getLocalPath();
param.put("path", localPath);
LOG.info("NEW FULL PATH: {}", localPath);
}
// now add to the new JSON structure
JSONArray exitingArray = (JSONArray) newJSON.get(paramName);
if (exitingArray == null) {
exitingArray = new JSONArray();
}
JSONObject newRecord = new JSONObject();
newRecord.put("class", param.get("class"));
newRecord.put("path", param.get("path"));
exitingArray.add(newRecord);
newJSON.put(paramName, exitingArray);
}
} else {
throw new RuntimeException("we found an unexpected datatype as follows: " + currentParam.getClass() + "\n with content " + currentParam);
}
}
writeJob("foo.json", newJSON);
return "foo.json";
}
private Map<String, Object> loadJob(String jobPath) {
try {
return (Map<String, Object>)yaml.load(new FileInputStream(jobPath));
} catch (FileNotFoundException e) {
throw new RuntimeException("could not load job from yaml",e);
}
}
private void writeJob(String jobOutputPath, JSONObject newJson) {
try {
//TODO: investigate, why is this replacement occurring?
final String replace = newJson.toJSONString().replace("\\", "");
FileUtils.writeStringToFile(new File(jobOutputPath), replace, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Could not write job ", e);
}
}
private String setupDirectories() {
LOG.info("MAKING DIRECTORIES...");
// directory to use, typically a large, encrypted filesystem
String workingDir = config.getString(WORKING_DIRECTORY, "./datastore/");
// make UUID
UUID uuid = UUID.randomUUID();
// setup directories
globalWorkingDir = workingDir + "/launcher-" + uuid;
Utilities.executeCommand("mkdir -p " + workingDir + "/launcher-" + uuid, stdoutStream, stderrStream);
Utilities.executeCommand("mkdir -p " + workingDir + "/launcher-" + uuid + "/configs", stdoutStream, stderrStream);
Utilities.executeCommand("mkdir -p " + workingDir + "/launcher-" + uuid + "/working", stdoutStream, stderrStream);
Utilities.executeCommand("mkdir -p " + workingDir + "/launcher-" + uuid + "/inputs", stdoutStream, stderrStream);
Utilities.executeCommand("mkdir -p " + workingDir + "/launcher-" + uuid + "/logs", stdoutStream, stderrStream);
Utilities.executeCommand("mkdir -p " + workingDir + "/launcher-" + uuid + "/outputs", stdoutStream, stderrStream);
return new File(workingDir + "/launcher-" + uuid).getAbsolutePath();
}
private Map<String, Object> runCWLCommand(String cwlFile, String jsonSettings, String workingDir) {
String[] s = {"cwltool","--non-strict","--outdir", workingDir, cwlFile, jsonSettings};
final ImmutablePair<String, String> execute = Utilities.executeCommand(Joiner.on(" ").join(Arrays.asList(s)), stdoutStream, stderrStream);
Map<String, Object> obj = (Map<String, Object>)yaml.load(execute.getLeft());
return obj;
}
private void pushOutputFiles(Map<String, FileInfo> fileMap, Map<String, Object> outputObject) {
LOG.info("UPLOADING FILES...");
for (String fileName : fileMap.keySet()) {
FileInfo file = fileMap.get(fileName);
String cwlOutputPath = (String)((Map)((Map)outputObject).get(fileName)).get("path");
LOG.info("NAME: {} URL: {} FILENAME: {} CWL OUTPUT PATH: {}", file.getLocalPath(), file.getUrl(), fileName, cwlOutputPath);
if (file.getUrl().startsWith("s3://")) {
AmazonS3 s3Client = new AmazonS3Client(new ClientConfiguration().withSignerOverride("S3Signer"));
if (config.containsKey(S3_ENDPOINT)){
final String endpoint = config.getString(S3_ENDPOINT);
LOG.info("found custom S3 endpoint, setting to {}", endpoint);
s3Client.setEndpoint(endpoint);
s3Client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
}
String trimmedPath = file.getUrl().replace("s3://","");
List<String> splitPathList = Lists.newArrayList(trimmedPath.split("/"));
String bucketName = splitPathList.remove(0);
s3Client.putObject(new PutObjectRequest(bucketName, Joiner.on("/").join(splitPathList), new File(cwlOutputPath)));
} else {
try {
FileSystemManager fsManager;
// trigger a copy from the URL to a local file path that's a UUID to avoid collision
fsManager = VFS.getManager();
FileObject dest = fsManager.resolveFile(file.getUrl());
FileObject src = fsManager.resolveFile(new File(cwlOutputPath).getAbsolutePath());
dest.copyFrom(src, Selectors.SELECT_SELF);
} catch (FileSystemException e) {
throw new RuntimeException("Could not provision output files", e);
}
}
}
}
private String getStorageClient() {
return config.getString(DCC_CLIENT_KEY, "/icgc/dcc-storage/bin/dcc-storage-client");
}
private void downloadFromDccStorage(String objectId, String downloadDir) {
// default layout saves to original_file_name/object_id
// file name is the directory and object id is actual file name
String client = getStorageClient();
String bob = new StringBuilder().append(client).append(" --quiet").append(" download").append(" --object-id ").append(objectId)
.append(" --output-dir ").append(downloadDir).append(" --output-layout id").toString();
Utilities.executeCommand(bob, stdoutStream, stderrStream);
}
private Map<String, FileInfo> pullFiles(CommandLineTool cwl, Map<String, Object> inputsOutputs) {
Map<String, FileInfo> fileMap = new HashMap<>();
LOG.info("DOWNLOADING INPUT FILES...");
final List<CommandInputParameter> files = cwl.getInputs();
// for each file input from the CWL
for (CommandInputParameter file : files) {
// pull back the name of the input from the CWL
LOG.info(file.toString());
// remove the hash from the cwlInputFileID
String cwlInputFileID = file.getId().toString().substring(1);
LOG.info("ID: {}", cwlInputFileID);
// now that I have an input name from the CWL I can find it in the JSON parameterization for this run
LOG.info("JSON: {}", inputsOutputs);
for (Entry<String, Object> stringObjectEntry : inputsOutputs.entrySet()) {
// in this case, the input is an array and not a single instance
if (stringObjectEntry.getValue() instanceof ArrayList) {
List<Map<String, String>> stringObjectEntryList = (List<Map<String, String>>)stringObjectEntry.getValue();
for (Map<String, String> lhm : stringObjectEntryList) {
String path = lhm.get("path");
// notice I'm putting key:path together so they are unique in the hash
if (stringObjectEntry.getKey().equals(cwlInputFileID)) {
doProcessFile(stringObjectEntry.getKey() + ":" + path, path, cwlInputFileID, fileMap);
}
}
// in this case the input is a single instance and not an array
} else if (stringObjectEntry.getValue() instanceof HashMap) {
HashMap param = (HashMap) stringObjectEntry.getValue();
String path = (String) param.get("path");
if (stringObjectEntry.getKey().equals(cwlInputFileID)) {
doProcessFile(stringObjectEntry.getKey(), path, cwlInputFileID, fileMap);
}
}
}
}
return fileMap;
}
/**
* Looks like this is intended to copy one file from source to a local destination
* @param key what is this?
* @param path the path for the source of the file, whether s3 or http
* @param cwlInputFileID looks like the descriptor for a particular path+class pair in the parameter json file, starts with a hash in the CWL file
* @param fileMap store information on each added file as a return type
*/
private void doProcessFile(final String key, final String path, final String cwlInputFileID, Map<String, FileInfo> fileMap) {
// key is unique for that key:download URL, cwlInputFileID is just the key
LOG.info("PATH TO DOWNLOAD FROM: {} FOR {} FOR {}", path, cwlInputFileID, key);
// set up output paths
String downloadDirectory = globalWorkingDir + "/inputs/" + UUID.randomUUID();
Utilities.executeCommand("mkdir -p " + downloadDirectory, stdoutStream, stderrStream);
File downloadDirFileObj = new File(downloadDirectory);
String targetFilePath = downloadDirFileObj.getAbsolutePath() + "/" + cwlInputFileID;
// expects URI in "path": "icgc:eef47481-670d-4139-ab5b-1dad808a92d9"
PathInfo pathInfo = new PathInfo(path);
if (pathInfo.isObjectIdType()) {
String objectId = pathInfo.getObjectId();
downloadFromDccStorage(objectId, downloadDirectory);
// downloaded file
String downloadPath = downloadDirFileObj.getAbsolutePath() + "/" + objectId;
System.out.println("download path: " + downloadPath);
File downloadedFileFileObj = new File(downloadPath);
File targetPathFileObj = new File(targetFilePath);
try {
Files.move(downloadedFileFileObj, targetPathFileObj);
} catch (IOException ioe) {
LOG.error(ioe.getMessage());
throw new RuntimeException("Could not move input file: ", ioe);
}
} else if (path.startsWith("s3://")) {
AmazonS3 s3Client = new AmazonS3Client(new ClientConfiguration().withSignerOverride("S3Signer"));
if (config.containsKey(S3_ENDPOINT)) {
final String endpoint = config.getString(S3_ENDPOINT);
LOG.info("found custom S3 endpoint, setting to {}", endpoint);
s3Client.setEndpoint(endpoint);
s3Client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
}
String trimmedPath = path.replace("s3://", "");
List<String> splitPathList = Lists.newArrayList(trimmedPath.split("/"));
String bucketName = splitPathList.remove(0);
S3Object object = s3Client.getObject(
new GetObjectRequest(bucketName, Joiner.on("/").join(splitPathList)));
try {
FileUtils.copyInputStreamToFile(object.getObjectContent(), new File(targetFilePath));
} catch (IOException e) {
LOG.error(e.getMessage());
throw new RuntimeException("Could not provision input files from S3", e);
}
} else {
// VFS call, see https://github.com/abashev/vfs-s3/tree/branch-2.3.x and
// https://commons.apache.org/proper/commons-vfs/filesystems.html
FileSystemManager fsManager;
try {
// trigger a copy from the URL to a local file path that's a UUID to avoid collision
fsManager = VFS.getManager();
FileObject src = fsManager.resolveFile(path);
FileObject dest = fsManager.resolveFile(new File(targetFilePath).getAbsolutePath());
dest.copyFrom(src, Selectors.SELECT_SELF);
} catch (FileSystemException e) {
LOG.error(e.getMessage());
throw new RuntimeException("Could not provision input files", e);
}
}
// now add this info to a hash so I can later reconstruct a docker -v command
FileInfo info = new FileInfo();
info.setLocalPath(targetFilePath);
info.setLocalPath(targetFilePath);
info.setDockerPath(cwlInputFileID);
info.setUrl(path);
// key may contain either key:download_URL for array inputs or just cwlInputFileID for scalar input
fileMap.put(key, info);
LOG.info("DOWNLOADED FILE: LOCAL: {} URL: {}", cwlInputFileID, path);
}
private CommandLine parseCommandLine(CommandLineParser parser, String[] args) {
try {
// parse the command line arguments
Options options = new Options();
options.addOption("c", "config", true, "the INI config file for this tool");
options.addOption("d", "descriptor", true, "a CWL tool descriptor used to construct the command and run it");
options.addOption("j", "job", true, "a JSON parameterization of the CWL tool, includes URLs for inputs and outputs");
return parser.parse(options, args);
} catch (ParseException exp) {
LOG.error("Unexpected exception:{}", exp.getMessage());
throw new RuntimeException("Could not parse command-line", exp);
}
}
public static class PathInfo {
private static final Logger LOG = LoggerFactory.getLogger(PathInfo.class);
public static final String DCC_STORAGE_SCHEME = "icgc";
private boolean objectIdType;
private String objectId = "";
public boolean isObjectIdType() {
return objectIdType;
}
public String getObjectId() {
return objectId;
}
public PathInfo(String path) {
try {
URI objectIdentifier = URI.create(path); // throws IllegalArgumentException if it isn't a valid URI
if (objectIdentifier.getScheme().equalsIgnoreCase(DCC_STORAGE_SCHEME)) {
objectIdType = true;
objectId = objectIdentifier.getSchemeSpecificPart().toLowerCase();
}
} catch (IllegalArgumentException iae) {
StringBuilder bob = new StringBuilder("Invalid path specified for CWL pre-processor values: ").append(path);
LOG.warn(bob.toString());
objectIdType = false;
}
}
}
public static class FileInfo {
private String localPath;
private String dockerPath;
private String url;
private String defaultLocalPath;
public String getLocalPath() {
return localPath;
}
public void setLocalPath(String localPath) {
this.localPath = localPath;
}
public String getDockerPath() {
return dockerPath;
}
public void setDockerPath(String dockerPath) {
this.dockerPath = dockerPath;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDefaultLocalPath() {
return defaultLocalPath;
}
public void setDefaultLocalPath(String defaultLocalPath) {
this.defaultLocalPath = defaultLocalPath;
}
}
public static void main(String[] args) {
final LauncherCWL launcherCWL = new LauncherCWL(args);
launcherCWL.run();
}
}
| dockstore-launcher/src/main/java/io/github/collaboratory/LauncherCWL.java | package io.github.collaboratory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.HierarchicalINIConfiguration;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.VFS;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.SignerFactory;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.S3ClientOptions;
import com.amazonaws.services.s3.internal.S3Signer;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.gson.Gson;
import io.cwl.avro.CWL;
import io.cwl.avro.CommandInputParameter;
import io.cwl.avro.CommandLineTool;
import io.cwl.avro.CommandOutputParameter;
import io.dockstore.common.Utilities;
/**
* @author boconnor 9/24/15
* @author dyuen
* @author tetron
*/
public class LauncherCWL {
static {
SignerFactory.registerSigner("S3Signer", S3Signer.class);
}
private static final Logger LOG = LoggerFactory.getLogger(LauncherCWL.class);
public static final String S3_ENDPOINT = "s3.endpoint";
public static final String WORKING_DIRECTORY = "working-directory";
public static final String DCC_CLIENT_KEY = "dcc_storage.client";
private final String configFilePath;
private final String imageDescriptorPath;
private final String runtimeDescriptorPath;
private HierarchicalINIConfiguration config;
private String globalWorkingDir;
private final Yaml yaml = new Yaml(new SafeConstructor());
private final Optional<OutputStream> stdoutStream;
private final Optional<OutputStream> stderrStream;
private final Gson gson;
/**
* Constructor for shell-based launch
* @param args raw arguments from the command-line
*/
public LauncherCWL(String[] args) {
// create the command line parser
CommandLineParser parser = new DefaultParser();
// parse command line
CommandLine line = parseCommandLine(parser, args);
configFilePath = line.getOptionValue("config");
imageDescriptorPath = line.getOptionValue("descriptor");
runtimeDescriptorPath = line.getOptionValue("job");
// do not forward stdout and stderr
stdoutStream = Optional.absent();
stderrStream = Optional.absent();
CWL cwl = new CWL();
gson = cwl.getTypeSafeCWLToolDocument();
}
/**
* Constructor for programmatic launch
* @param configFilePath configuration for this launcher
* @param imageDescriptorPath descriptor for the tool itself
* @param runtimeDescriptorPath descriptor for this run of the tool
*/
public LauncherCWL(String configFilePath, String imageDescriptorPath, String runtimeDescriptorPath, OutputStream stdoutStream, OutputStream stderrStream){
this.configFilePath = configFilePath;
this.imageDescriptorPath = imageDescriptorPath;
this.runtimeDescriptorPath = runtimeDescriptorPath;
// programmatically forward stdout and stderr
this.stdoutStream = Optional.of(stdoutStream);
this.stderrStream = Optional.of(stderrStream);
CWL cwl = new CWL();
gson = cwl.getTypeSafeCWLToolDocument();
}
public void run(){
// now read in the INI file
try {
config = new HierarchicalINIConfiguration(configFilePath);
} catch (ConfigurationException e) {
throw new RuntimeException("could not read launcher config ini", e);
}
// parse the CWL tool definition without validation
CWL cwlUtil = new CWL();
final String imageDescriptorContent = cwlUtil.parseCWL(imageDescriptorPath, false).getLeft();
final CommandLineTool cwl = gson.fromJson(imageDescriptorContent, CommandLineTool.class);
if (cwl == null) {
LOG.info("CWL was null");
return;
}
// this is the job parameterization, just a JSON, defines the inputs/outputs in terms or real URLs that are provisioned by the launcher
Map<String, Object> inputsAndOutputsJson = loadJob(runtimeDescriptorPath);
if (inputsAndOutputsJson == null) {
LOG.info("Cannot load job object.");
return;
}
// setup directories
globalWorkingDir = setupDirectories();
// pull input files
final Map<String, FileInfo> inputsId2dockerMountMap = pullFiles(cwl, inputsAndOutputsJson);
// prep outputs, just creates output dir and records what the local output path will be
Map<String, FileInfo> outputMap = prepUploads(cwl, inputsAndOutputsJson);
// create updated JSON inputs document
String newJsonPath = createUpdatedInputsAndOutputsJson(inputsId2dockerMountMap, outputMap, inputsAndOutputsJson);
// run command
LOG.info("RUNNING COMMAND");
Map<String, Object> outputObj = runCWLCommand(imageDescriptorPath, newJsonPath, globalWorkingDir + "/outputs/");
// push output files
pushOutputFiles(outputMap, outputObj);
}
private Map<String, FileInfo> prepUploads(CommandLineTool cwl, Map<String, Object> inputsOutputs) {
Map<String, FileInfo> fileMap = new HashMap<>();
LOG.info("PREPPING UPLOADS...");
final List<CommandOutputParameter> outputs = cwl.getOutputs();
// for each file input from the CWL
for (CommandOutputParameter file : outputs) {
// pull back the name of the input from the CWL
LOG.info(file.toString());
String cwlID = file.getId().toString().substring(1);
LOG.info("ID: {}", cwlID);
// now that I have an input name from the CWL I can find it in the JSON parameterization for this run
LOG.info("JSON: {}", inputsOutputs);
for (Entry<String, Object> stringObjectEntry : inputsOutputs.entrySet()) {
if (stringObjectEntry.getValue() instanceof HashMap) {
Map param = (Map<String, Object>) stringObjectEntry.getValue();
String path = (String) param.get("path");
if (stringObjectEntry.getKey().equals(cwlID)) {
// if it's the current one
LOG.info("PATH TO UPLOAD TO: {} FOR {} FOR {}", path, cwlID, stringObjectEntry.getKey());
// output
// TODO: poor naming here, need to cleanup the variables
// just file name
// the file URL
File filePathObj = new File(cwlID);
//String newDirectory = globalWorkingDir + "/outputs/" + UUID.randomUUID().toString();
String newDirectory = globalWorkingDir + "/outputs";
Utilities.executeCommand("mkdir -p " + newDirectory, stdoutStream, stderrStream);
File newDirectoryFile = new File(newDirectory);
String uuidPath = newDirectoryFile.getAbsolutePath() + "/" + filePathObj.getName();
// VFS call, see https://github.com/abashev/vfs-s3/tree/branch-2.3.x and
// https://commons.apache.org/proper/commons-vfs/filesystems.html
// now add this info to a hash so I can later reconstruct a docker -v command
FileInfo new1 = new FileInfo();
new1.setUrl(path);
new1.setDockerPath(cwlID);
new1.setLocalPath(uuidPath);
fileMap.put(cwlID, new1);
LOG.info("UPLOAD FILE: LOCAL: {} URL: {}", cwlID, path);
}
}
}
}
return fileMap;
}
private String createUpdatedInputsAndOutputsJson(Map<String, FileInfo> fileMap, Map<String, FileInfo> outputMap, Map<String, Object> inputsAndOutputsJson) {
JSONObject newJSON = new JSONObject();
for (String paramName : inputsAndOutputsJson.keySet()) {
final Object currentParam = inputsAndOutputsJson.get(paramName);
if (currentParam instanceof Map) {
Map<String, Object> param = (Map<String, Object>) currentParam;
String path = (String) param.get("path");
LOG.info("PATH: {} PARAM_NAME: {}", path, paramName);
// will be null for output
if (fileMap.get(paramName) != null) {
final String localPath = fileMap.get(paramName).getLocalPath();
param.put("path", localPath);
LOG.info("NEW FULL PATH: {}", localPath);
} else if (outputMap.get(paramName) != null) {
final String localPath = outputMap.get(paramName).getLocalPath();
param.put("path", localPath);
LOG.info("NEW FULL PATH: {}", localPath);
}
// now add to the new JSON structure
JSONObject newRecord = new JSONObject();
newRecord.put("class", param.get("class"));
newRecord.put("path", param.get("path"));
newJSON.put(paramName, newRecord);
// TODO: fill in for all possible types
} else if (currentParam instanceof Integer || currentParam instanceof Float || currentParam instanceof Boolean || currentParam instanceof String) {
newJSON.put(paramName, currentParam);
} else if (currentParam instanceof List) {
List<Map<String, String>> currentParamList = (List<Map<String, String>>)currentParam;
for (Map<String, String> param : currentParamList) {
String path = param.get("path");
LOG.info("PATH: {} PARAM_NAME: {}", path, paramName);
// will be null for output, only dealing with inputs currently
// TODO: can outputs be file arrays too??? Maybe need to do something for globs??? Need to investigate
if (fileMap.get(paramName + ":" + path) != null) {
final String localPath = fileMap.get(paramName + ":" + path).getLocalPath();
param.put("path", localPath);
LOG.info("NEW FULL PATH: {}", localPath);
}
// now add to the new JSON structure
JSONArray exitingArray = (JSONArray) newJSON.get(paramName);
if (exitingArray == null) {
exitingArray = new JSONArray();
}
JSONObject newRecord = new JSONObject();
newRecord.put("class", param.get("class"));
newRecord.put("path", param.get("path"));
exitingArray.add(newRecord);
newJSON.put(paramName, exitingArray);
}
} else {
throw new RuntimeException("we found an unexpected datatype as follows: " + currentParam.getClass() + "\n with content " + currentParam);
}
}
writeJob("foo.json", newJSON);
return "foo.json";
}
private Map<String, Object> loadJob(String jobPath) {
try {
return (Map<String, Object>)yaml.load(new FileInputStream(jobPath));
} catch (FileNotFoundException e) {
throw new RuntimeException("could not load job from yaml",e);
}
}
private void writeJob(String jobOutputPath, JSONObject newJson) {
try {
//TODO: investigate, why is this replacement occurring?
final String replace = newJson.toJSONString().replace("\\", "");
FileUtils.writeStringToFile(new File(jobOutputPath), replace, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Could not write job ", e);
}
}
private String setupDirectories() {
LOG.info("MAKING DIRECTORIES...");
// directory to use, typically a large, encrypted filesystem
String workingDir = config.getString(WORKING_DIRECTORY, "./datastore/");
// make UUID
UUID uuid = UUID.randomUUID();
// setup directories
globalWorkingDir = workingDir + "/launcher-" + uuid;
Utilities.executeCommand("mkdir -p " + workingDir + "/launcher-" + uuid, stdoutStream, stderrStream);
Utilities.executeCommand("mkdir -p " + workingDir + "/launcher-" + uuid + "/configs", stdoutStream, stderrStream);
Utilities.executeCommand("mkdir -p " + workingDir + "/launcher-" + uuid + "/working", stdoutStream, stderrStream);
Utilities.executeCommand("mkdir -p " + workingDir + "/launcher-" + uuid + "/inputs", stdoutStream, stderrStream);
Utilities.executeCommand("mkdir -p " + workingDir + "/launcher-" + uuid + "/logs", stdoutStream, stderrStream);
Utilities.executeCommand("mkdir -p " + workingDir + "/launcher-" + uuid + "/outputs", stdoutStream, stderrStream);
return new File(workingDir + "/launcher-" + uuid).getAbsolutePath();
}
private Map<String, Object> runCWLCommand(String cwlFile, String jsonSettings, String workingDir) {
String[] s = {"cwltool","--non-strict","--outdir", workingDir, cwlFile, jsonSettings};
final ImmutablePair<String, String> execute = Utilities.executeCommand(Joiner.on(" ").join(Arrays.asList(s)), stdoutStream, stderrStream);
Map<String, Object> obj = (Map<String, Object>)yaml.load(execute.getLeft());
return obj;
}
private void pushOutputFiles(Map<String, FileInfo> fileMap, Map<String, Object> outputObject) {
LOG.info("UPLOADING FILES...");
for (String fileName : fileMap.keySet()) {
FileInfo file = fileMap.get(fileName);
String cwlOutputPath = (String)((Map)((Map)outputObject).get(fileName)).get("path");
LOG.info("NAME: {} URL: {} FILENAME: {} CWL OUTPUT PATH: {}", file.getLocalPath(), file.getUrl(), fileName, cwlOutputPath);
if (file.getUrl().startsWith("s3://")) {
AmazonS3 s3Client = new AmazonS3Client(new ClientConfiguration().withSignerOverride("S3Signer"));
if (config.containsKey(S3_ENDPOINT)){
final String endpoint = config.getString(S3_ENDPOINT);
LOG.info("found custom S3 endpoint, setting to {}", endpoint);
s3Client.setEndpoint(endpoint);
s3Client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
}
String trimmedPath = file.getUrl().replace("s3://","");
List<String> splitPathList = Lists.newArrayList(trimmedPath.split("/"));
String bucketName = splitPathList.remove(0);
s3Client.putObject(new PutObjectRequest(bucketName, Joiner.on("/").join(splitPathList), new File(cwlOutputPath)));
} else {
try {
FileSystemManager fsManager;
// trigger a copy from the URL to a local file path that's a UUID to avoid collision
fsManager = VFS.getManager();
FileObject dest = fsManager.resolveFile(file.getUrl());
FileObject src = fsManager.resolveFile(new File(cwlOutputPath).getAbsolutePath());
dest.copyFrom(src, Selectors.SELECT_SELF);
} catch (FileSystemException e) {
throw new RuntimeException("Could not provision output files", e);
}
}
}
}
private String getStorageClient() {
return config.getString(DCC_CLIENT_KEY, "/icgc/dcc-storage/bin/dcc-storage-client");
}
private void downloadFromDccStorage(String objectId, String downloadDir) {
// default layout saves to original_file_name/object_id
// file name is the directory and object id is actual file name
String client = getStorageClient();
String bob = client + " --quiet" + " download" +
" --object-id " + objectId +
" --output-dir " + downloadDir +
" --output-layout id";
Utilities.executeCommand(bob, stdoutStream, stderrStream);
}
private Map<String, FileInfo> pullFiles(CommandLineTool cwl, Map<String, Object> inputsOutputs) {
Map<String, FileInfo> fileMap = new HashMap<>();
LOG.info("DOWNLOADING INPUT FILES...");
final List<CommandInputParameter> files = cwl.getInputs();
// for each file input from the CWL
for (CommandInputParameter file : files) {
// pull back the name of the input from the CWL
LOG.info(file.toString());
// remove the hash from the cwlInputFileID
String cwlInputFileID = file.getId().toString().substring(1);
LOG.info("ID: {}", cwlInputFileID);
// now that I have an input name from the CWL I can find it in the JSON parameterization for this run
LOG.info("JSON: {}", inputsOutputs);
for (Entry<String, Object> stringObjectEntry : inputsOutputs.entrySet()) {
// in this case, the input is an array and not a single instance
if (stringObjectEntry.getValue() instanceof ArrayList) {
List<Map<String, String>> stringObjectEntryList = (List<Map<String, String>>)stringObjectEntry.getValue();
for (Map<String, String> lhm : stringObjectEntryList) {
String path = lhm.get("path");
// notice I'm putting key:path together so they are unique in the hash
if (stringObjectEntry.getKey().equals(cwlInputFileID)) {
doProcessFile(stringObjectEntry.getKey() + ":" + path, path, cwlInputFileID, fileMap);
}
}
// in this case the input is a single instance and not an array
} else if (stringObjectEntry.getValue() instanceof HashMap) {
HashMap param = (HashMap) stringObjectEntry.getValue();
String path = (String) param.get("path");
if (stringObjectEntry.getKey().equals(cwlInputFileID)) {
doProcessFile(stringObjectEntry.getKey(), path, cwlInputFileID, fileMap);
}
}
}
}
return fileMap;
}
/**
* Looks like this is intended to copy one file from source to a local destination
* @param key what is this?
* @param path the path for the source of the file, whether s3 or http
* @param cwlInputFileID looks like the descriptor for a particular path+class pair in the parameter json file, starts with a hash in the CWL file
* @param fileMap store information on each added file as a return type
*/
private void doProcessFile(final String key, final String path, final String cwlInputFileID, Map<String, FileInfo> fileMap) {
// key is unique for that key:download URL, cwlInputFileID is just the key
LOG.info("PATH TO DOWNLOAD FROM: {} FOR {} FOR {}", path, cwlInputFileID, key);
// set up output paths
String downloadDirectory = globalWorkingDir + "/inputs/" + UUID.randomUUID();
Utilities.executeCommand("mkdir -p " + downloadDirectory, stdoutStream, stderrStream);
File downloadDirFileObj = new File(downloadDirectory);
String targetFilePath = downloadDirFileObj.getAbsolutePath() + "/" + cwlInputFileID;
// expects URI in "path": "icgc:eef47481-670d-4139-ab5b-1dad808a92d9"
PathInfo pathInfo = new PathInfo(path);
if (pathInfo.isObjectIdType()) {
String objectId = pathInfo.getObjectId();
downloadFromDccStorage(objectId, downloadDirectory);
// downloaded file
String downloadPath = downloadDirFileObj.getAbsolutePath() + "/" + objectId;
System.out.println("download path: " + downloadPath);
File downloadedFileFileObj = new File(downloadPath);
File targetPathFileObj = new File(targetFilePath);
try {
Files.move(downloadedFileFileObj, targetPathFileObj);
} catch (IOException ioe) {
LOG.error(ioe.getMessage());
throw new RuntimeException("Could not move input file: ", ioe);
}
} else if (path.startsWith("s3://")) {
AmazonS3 s3Client = new AmazonS3Client(new ClientConfiguration().withSignerOverride("S3Signer"));
if (config.containsKey(S3_ENDPOINT)) {
final String endpoint = config.getString(S3_ENDPOINT);
LOG.info("found custom S3 endpoint, setting to {}", endpoint);
s3Client.setEndpoint(endpoint);
s3Client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
}
String trimmedPath = path.replace("s3://", "");
List<String> splitPathList = Lists.newArrayList(trimmedPath.split("/"));
String bucketName = splitPathList.remove(0);
S3Object object = s3Client.getObject(
new GetObjectRequest(bucketName, Joiner.on("/").join(splitPathList)));
try {
FileUtils.copyInputStreamToFile(object.getObjectContent(), new File(targetFilePath));
} catch (IOException e) {
LOG.error(e.getMessage());
throw new RuntimeException("Could not provision input files from S3", e);
}
} else {
// VFS call, see https://github.com/abashev/vfs-s3/tree/branch-2.3.x and
// https://commons.apache.org/proper/commons-vfs/filesystems.html
FileSystemManager fsManager;
try {
// trigger a copy from the URL to a local file path that's a UUID to avoid collision
fsManager = VFS.getManager();
FileObject src = fsManager.resolveFile(path);
FileObject dest = fsManager.resolveFile(new File(targetFilePath).getAbsolutePath());
dest.copyFrom(src, Selectors.SELECT_SELF);
} catch (FileSystemException e) {
LOG.error(e.getMessage());
throw new RuntimeException("Could not provision input files", e);
}
}
// now add this info to a hash so I can later reconstruct a docker -v command
FileInfo info = new FileInfo();
info.setLocalPath(targetFilePath);
info.setLocalPath(targetFilePath);
info.setDockerPath(cwlInputFileID);
info.setUrl(path);
// key may contain either key:download_URL for array inputs or just cwlInputFileID for scalar input
fileMap.put(key, info);
LOG.info("DOWNLOADED FILE: LOCAL: {} URL: {}", cwlInputFileID, path);
}
private CommandLine parseCommandLine(CommandLineParser parser, String[] args) {
try {
// parse the command line arguments
Options options = new Options();
options.addOption("c", "config", true, "the INI config file for this tool");
options.addOption("d", "descriptor", true, "a CWL tool descriptor used to construct the command and run it");
options.addOption("j", "job", true, "a JSON parameterization of the CWL tool, includes URLs for inputs and outputs");
return parser.parse(options, args);
} catch (ParseException exp) {
LOG.error("Unexpected exception:{}", exp.getMessage());
throw new RuntimeException("Could not parse command-line", exp);
}
}
public static class PathInfo {
private static final Logger LOG = LoggerFactory.getLogger(PathInfo.class);
public static final String DCC_STORAGE_SCHEME = "icgc";
private boolean objectIdType;
private String objectId = "";
public boolean isObjectIdType() {
return objectIdType;
}
public String getObjectId() {
return objectId;
}
public PathInfo(String path) {
try {
URI objectIdentifier = URI.create(path); // throws IllegalArgumentException if it isn't a valid URI
if (objectIdentifier.getScheme().equalsIgnoreCase(DCC_STORAGE_SCHEME)) {
objectIdType = true;
objectId = objectIdentifier.getSchemeSpecificPart().toLowerCase();
}
} catch (IllegalArgumentException iae) {
StringBuilder bob = new StringBuilder("Invalid path specified for CWL pre-processor values: ").append(path);
LOG.warn(bob.toString());
objectIdType = false;
}
}
}
public static class FileInfo {
private String localPath;
private String dockerPath;
private String url;
private String defaultLocalPath;
public String getLocalPath() {
return localPath;
}
public void setLocalPath(String localPath) {
this.localPath = localPath;
}
public String getDockerPath() {
return dockerPath;
}
public void setDockerPath(String dockerPath) {
this.dockerPath = dockerPath;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDefaultLocalPath() {
return defaultLocalPath;
}
public void setDefaultLocalPath(String defaultLocalPath) {
this.defaultLocalPath = defaultLocalPath;
}
}
public static void main(String[] args) {
final LauncherCWL launcherCWL = new LauncherCWL(args);
launcherCWL.run();
}
}
| Satisfy checkstyle
| dockstore-launcher/src/main/java/io/github/collaboratory/LauncherCWL.java | Satisfy checkstyle | <ide><path>ockstore-launcher/src/main/java/io/github/collaboratory/LauncherCWL.java
<ide> // default layout saves to original_file_name/object_id
<ide> // file name is the directory and object id is actual file name
<ide> String client = getStorageClient();
<del> String bob = client + " --quiet" + " download" +
<del> " --object-id " + objectId +
<del> " --output-dir " + downloadDir +
<del> " --output-layout id";
<add> String bob = new StringBuilder().append(client).append(" --quiet").append(" download").append(" --object-id ").append(objectId)
<add> .append(" --output-dir ").append(downloadDir).append(" --output-layout id").toString();
<ide> Utilities.executeCommand(bob, stdoutStream, stderrStream);
<ide> }
<ide> |
|
Java | apache-2.0 | 14b5659f835aa70c6593a51161622fdaa573cc92 | 0 | vroyer/elasticassandra,strapdata/elassandra,vroyer/elassandra,vroyer/elassandra,strapdata/elassandra,vroyer/elasticassandra,strapdata/elassandra,vroyer/elasticassandra,vroyer/elassandra,strapdata/elassandra,strapdata/elassandra | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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.
*/
package org.elasticsearch.indices.recovery;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.io.stream.InputStreamStreamInput;
import org.elasticsearch.common.io.stream.OutputStreamStreamOutput;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.seqno.SequenceNumbers;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.test.ESTestCase;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Collections;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static org.elasticsearch.test.VersionUtils.randomVersion;
import static org.hamcrest.Matchers.equalTo;
public class StartRecoveryRequestTests extends ESTestCase {
public void testSerialization() throws Exception {
final Version targetNodeVersion = randomVersion(random());
Store.MetadataSnapshot metadataSnapshot = randomBoolean() ? Store.MetadataSnapshot.EMPTY :
new Store.MetadataSnapshot(Collections.emptyMap(),
Collections.singletonMap(Engine.HISTORY_UUID_KEY, UUIDs.randomBase64UUID()), randomIntBetween(0, 100));
final StartRecoveryRequest outRequest = new StartRecoveryRequest(
new ShardId("test", "_na_", 0),
UUIDs.randomBase64UUID(),
new DiscoveryNode("a", buildNewFakeTransportAddress(), emptyMap(), emptySet(), targetNodeVersion),
new DiscoveryNode("b", buildNewFakeTransportAddress(), emptyMap(), emptySet(), targetNodeVersion),
metadataSnapshot,
randomBoolean(),
randomNonNegativeLong(),
randomBoolean() || metadataSnapshot.getHistoryUUID() == null ?
SequenceNumbers.UNASSIGNED_SEQ_NO : randomNonNegativeLong());
final ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
final OutputStreamStreamOutput out = new OutputStreamStreamOutput(outBuffer);
out.setVersion(targetNodeVersion);
outRequest.writeTo(out);
final ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray());
InputStreamStreamInput in = new InputStreamStreamInput(inBuffer);
in.setVersion(targetNodeVersion);
final StartRecoveryRequest inRequest = new StartRecoveryRequest();
inRequest.readFrom(in);
assertThat(outRequest.shardId(), equalTo(inRequest.shardId()));
assertThat(outRequest.targetAllocationId(), equalTo(inRequest.targetAllocationId()));
assertThat(outRequest.sourceNode(), equalTo(inRequest.sourceNode()));
assertThat(outRequest.targetNode(), equalTo(inRequest.targetNode()));
assertThat(outRequest.metadataSnapshot().asMap(), equalTo(inRequest.metadataSnapshot().asMap()));
assertThat(outRequest.isPrimaryRelocation(), equalTo(inRequest.isPrimaryRelocation()));
assertThat(outRequest.recoveryId(), equalTo(inRequest.recoveryId()));
if (targetNodeVersion.onOrAfter(Version.V_6_0_0_alpha1)) {
assertThat(outRequest.startingSeqNo(), equalTo(inRequest.startingSeqNo()));
} else {
assertThat(SequenceNumbers.UNASSIGNED_SEQ_NO, equalTo(inRequest.startingSeqNo()));
}
}
}
| core/src/test/java/org/elasticsearch/indices/recovery/StartRecoveryRequestTests.java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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.
*/
package org.elasticsearch.indices.recovery;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.io.stream.InputStreamStreamInput;
import org.elasticsearch.common.io.stream.OutputStreamStreamOutput;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.seqno.SequenceNumbers;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.test.ESTestCase;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Collections;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static org.elasticsearch.test.VersionUtils.randomVersion;
import static org.hamcrest.Matchers.equalTo;
public class StartRecoveryRequestTests extends ESTestCase {
public void testSerialization() throws Exception {
final Version targetNodeVersion = randomVersion(random());
Store.MetadataSnapshot metadataSnapshot = randomBoolean() ? Store.MetadataSnapshot.EMPTY :
new Store.MetadataSnapshot(Collections.emptyMap(),
Collections.singletonMap(Engine.HISTORY_UUID_KEY, UUIDs.randomBase64UUID()), randomIntBetween(0, 100));
final StartRecoveryRequest outRequest = new StartRecoveryRequest(
new ShardId("test", "_na_", 0),
UUIDs.randomBase64UUID(),
new DiscoveryNode("a", buildNewFakeTransportAddress(), emptyMap(), emptySet(), targetNodeVersion),
new DiscoveryNode("b", buildNewFakeTransportAddress(), emptyMap(), emptySet(), targetNodeVersion),
Store.MetadataSnapshot.EMPTY,
randomBoolean(),
randomNonNegativeLong(),
randomBoolean() || metadataSnapshot.getHistoryUUID() == null ?
SequenceNumbers.UNASSIGNED_SEQ_NO : randomNonNegativeLong());
final ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
final OutputStreamStreamOutput out = new OutputStreamStreamOutput(outBuffer);
out.setVersion(targetNodeVersion);
outRequest.writeTo(out);
final ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray());
InputStreamStreamInput in = new InputStreamStreamInput(inBuffer);
in.setVersion(targetNodeVersion);
final StartRecoveryRequest inRequest = new StartRecoveryRequest();
inRequest.readFrom(in);
assertThat(outRequest.shardId(), equalTo(inRequest.shardId()));
assertThat(outRequest.targetAllocationId(), equalTo(inRequest.targetAllocationId()));
assertThat(outRequest.sourceNode(), equalTo(inRequest.sourceNode()));
assertThat(outRequest.targetNode(), equalTo(inRequest.targetNode()));
assertThat(outRequest.metadataSnapshot().asMap(), equalTo(inRequest.metadataSnapshot().asMap()));
assertThat(outRequest.isPrimaryRelocation(), equalTo(inRequest.isPrimaryRelocation()));
assertThat(outRequest.recoveryId(), equalTo(inRequest.recoveryId()));
if (targetNodeVersion.onOrAfter(Version.V_6_0_0_alpha1)) {
assertThat(outRequest.startingSeqNo(), equalTo(inRequest.startingSeqNo()));
} else {
assertThat(SequenceNumbers.UNASSIGNED_SEQ_NO, equalTo(inRequest.startingSeqNo()));
}
}
}
| fix StartRecoveryRequestTests.testSerialization
| core/src/test/java/org/elasticsearch/indices/recovery/StartRecoveryRequestTests.java | fix StartRecoveryRequestTests.testSerialization | <ide><path>ore/src/test/java/org/elasticsearch/indices/recovery/StartRecoveryRequestTests.java
<ide> UUIDs.randomBase64UUID(),
<ide> new DiscoveryNode("a", buildNewFakeTransportAddress(), emptyMap(), emptySet(), targetNodeVersion),
<ide> new DiscoveryNode("b", buildNewFakeTransportAddress(), emptyMap(), emptySet(), targetNodeVersion),
<del> Store.MetadataSnapshot.EMPTY,
<add> metadataSnapshot,
<ide> randomBoolean(),
<ide> randomNonNegativeLong(),
<ide> randomBoolean() || metadataSnapshot.getHistoryUUID() == null ? |
|
Java | unlicense | fb63102ecdf6864a3de17cfaf481a685881705c8 | 0 | Kramermp/FoodMood | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testharness;
import foodprofile.model.Food;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Michael Kramer
*/
class FoodTestHarness {
private static int errorCount = 0;
public static void run() {
testConstructors();
testAccessors();
testMutators();
if(errorCount != 0) {
System.err.println("FoodTestHarness completed with " + errorCount
+ " errors.");
} else {
System.out.println("FoodTestHarness completed with " + errorCount
+ " errors.");
}
}
private static void testConstructors() {
Food testFood = new Food();
if(testFood != null) {
System.out.println("The Food Default Constructor successfully"
+ " created the Food object.");
} else {
System.err.println("The Food Default Constructor failed to create"
+ " the Food object.");
errorCount++;
}
}
private static void testAccessors() {
Food testFood = new Food();
Class foodClass = testFood.getClass();
try {
//Test getID
Field idField = foodClass.getDeclaredField("id");
idField.setAccessible(true);
int detectedID = (int) idField.get(testFood);
if(detectedID == testFood.getID()) {
System.out.println("The method Food.getID() successfully"
+ " retrieved the ID.");
} else {
System.err.println("The method Food.getID() failed to retrieve"
+ "the ID.");
errorCount++;
}
//Test getName
Field nameField = foodClass.getDeclaredField("name");
nameField.setAccessible(true);
String detectedName = (String) nameField.get(testFood);
//This should be == this is not a mistake
if(detectedName == testFood.getName()) {
System.out.println("The method Food.getName() successfully"
+ " retrieved the Name.");
} else {
System.err.println("The method Food.getName() failed to retrieve"
+ "the Name.");
errorCount++;
}
//Test getFoodCategories
Field foodCategoriesField = foodClass.getDeclaredField("foodCategories");
foodCategoriesField.setAccessible(true);
ArrayList<String> detectedFoodCategories = (ArrayList<String>) foodCategoriesField.get(testFood);
//This should be == this is not a mistake
if(detectedFoodCategories == testFood.getFoodCategories()) {
System.out.println("The method Food.getFoodCategories() successfully"
+ " retrieved the foodCategories.");
} else {
System.err.println("The method Food.getFoodCategories() failed to retrieve"
+ "the foodCategories.");
errorCount++;
}
//Test getTime
Field timeField = foodClass.getDeclaredField("time");
timeField.setAccessible(true);
GregorianCalendar detectedTime = (GregorianCalendar) timeField.get(testFood);
//This should be == this is not a mistake
if(detectedTime == testFood.getTime()) {
System.out.println("The method Food.getTime() successfully"
+ " retrieved the time.");
} else {
System.err.println("The method Food.getTime() failed to retrieve"
+ "the time.");
errorCount++;
}
//Test getMoods
Field moodsField = foodClass.getDeclaredField("moods");
moodsField.setAccessible(true);
ArrayList<Integer> detectedMoods = (ArrayList<Integer>) moodsField.get(testFood);
//This should be == this is not a mistake
if(detectedMoods == testFood.getMoods()) {
System.out.println("The method Food.getMoods() successfully"
+ " retrieved the moods.");
} else {
System.err.println("The method Food.getMoods() failed to retrieve"
+ "the moods.");
errorCount++;
}
} catch (IllegalArgumentException | IllegalAccessException
| NoSuchFieldException | SecurityException ex) {
System.err.println("An error occured while testing Food Accessors."
+ "\n." + ex.getMessage());
errorCount++;
}
}
private static void testMutators() {
Food testFood = new Food();
Class foodClass = testFood.getClass();
try {
//Test setID
Field idField = foodClass.getDeclaredField("id");
idField.setAccessible(true);
int newID = 77;
int detectedID = (int) idField.get(testFood);
if(detectedID == newID) {
System.out.println("The method Food.setID() successfully"
+ " modified the ID.");
} else {
System.err.println("The method Food.setID() failed to modify"
+ " the ID.");
errorCount++;
}
//Test setName
Field nameField = foodClass.getDeclaredField("name");
nameField.setAccessible(true);
String newName = "New Name";
testFood.setName(newName);
String detectedName = (String) nameField.get(testFood);
//This should be == this is not a mistake
if(detectedName == newName) {
System.out.println("The method Food.setName() successfully"
+ " modified the Name.");
} else {
System.err.println("The method Food.setName() failed to modify"
+ " the Name.");
errorCount++;
}
//Test setFoodCategories
Field foodCategoriesField = foodClass.getDeclaredField("foodCategories");
foodCategoriesField.setAccessible(true);
ArrayList<String> newList = new ArrayList<String>();
testFood.setFoodCategories(newList);
ArrayList<String> detectedFoodCategories = (ArrayList<String>) foodCategoriesField.get(testFood);
//This should be == this is not a mistake
if(detectedFoodCategories == newList) {
System.out.println("The method Food.setFoodCategories() successfully"
+ " modified the foodCategories.");
} else {
System.err.println("The method Food.setFoodCategories() failed to modify"
+ " the foodCategories.");
errorCount++;
}
//Test addFoodCategory
String testFoodCategory = "Test Food Category";
testFood.addFoodCategory(testFoodCategory);
if(detectedFoodCategories.get(0) == testFoodCategory) {
System.out.println("The method Food.addFoodCategory(String)"
+ " successfully modified the food categories.");
} else {
System.err.println("The method Food.addFoodCategory(String)"
+ "failed to modify the food categories.");
errorCount++;
}
//Test deleteFoodCategory
String sampleFoodCategory = "Sample Food Category";
detectedFoodCategories.clear();
detectedFoodCategories.add(sampleFoodCategory);
testFood.deleteFoodCategory("Sample Food Category");
if(!detectedFoodCategories.contains(sampleFoodCategory)) {
System.out.println("The method Food.removeFoodCategory(String)"
+ " successfully modified the food categories.");
} else {
System.err.println("The method Food.removeFoodCategory(String)"
+ " failed to modify the food categories.");
errorCount++;
}
//Test setTime
Field timeField = foodClass.getDeclaredField("time");
timeField.setAccessible(true);
GregorianCalendar newTime = new GregorianCalendar();
testFood.setTime(newTime);
GregorianCalendar detectedTime = (GregorianCalendar) timeField.get(testFood);
//This should be == this is not a mistake
if(detectedTime == newTime) {
System.out.println("The method Food.setTime() successfully"
+ " modified the time.");
} else {
System.err.println("The method Food.setTime() failed to modify"
+ " the time.");
errorCount++;
}
//Test setMoods
Field moodsField = foodClass.getDeclaredField("moods");
moodsField.setAccessible(true);
ArrayList<Integer> newMoods = new ArrayList<Integer>();
testFood.setMoods(newMoods);
ArrayList<Integer> detectedMoods = (ArrayList<Integer>) moodsField.get(testFood);
//This should be == this is not a mistake
if(detectedMoods == newMoods) {
System.out.println("The method Food.setMoods() successfully"
+ " modified the moods.");
} else {
System.err.println("The method Food.setMoods() failed to modify"
+ " the moods.");
errorCount++;
}
//Test addMood
Integer testInt = 3;
testFood.addMood(testInt);
for (int i = 0; i < detectedMoods.size(); i++) {
if(detectedMoods.get(i) == testInt) {
System.out.println("The method Food.addMood(Integer)"
+ " successfully modified the moods.");
break;
}
if(i == detectedMoods.size() - 1) {
System.err.println("The method Food.addMood(Intger)"
+ " failed to modify the moods.");
errorCount++;
}
}
detectedMoods.clear();
//Test deleteMood
detectedMoods.add(testInt);
for (int i = 0; i < detectedMoods.size(); i++) {
if(detectedMoods.get(i) == testInt) {
System.err.println("The method Food.deleteMood(Intger)"
+ " failed to modify the moods.");
errorCount++;
break;
}
if(i == detectedMoods.size() - 1) {
System.out.println("The method Food.deleteMood(Integer)"
+ " successfully modified the moods.");
}
}
} catch (IllegalArgumentException | IllegalAccessException
| NoSuchFieldException | SecurityException ex) {
System.err.println("An error occured while testing Food Accessors."
+ "\n." + ex.getMessage());
errorCount++;
}
}
}
| src/testharness/FoodTestHarness.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testharness;
import foodprofile.model.Food;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Michael Kramer
*/
class FoodTestHarness {
private static int errorCount = 0;
public static void run() {
testConstructors();
testAccessors();
testMutators();
if(errorCount != 0) {
System.err.println("FoodTestHarness completed with " + errorCount
+ " errors.");
} else {
System.out.println("FoodTestHarness completed with " + errorCount
+ " errors.");
}
}
private static void testConstructors() {
Food testFood = new Food();
if(testFood != null) {
System.out.println("The Food Default Constructor successfully"
+ " created the Food object.");
} else {
System.err.println("The Food Default Constructor failed to create"
+ " the Food object.");
errorCount++;
}
}
private static void testAccessors() {
Food testFood = new Food();
Class foodClass = testFood.getClass();
try {
//Test getID
Field idField = foodClass.getDeclaredField("id");
idField.setAccessible(true);
int detectedID = (int) idField.get(testFood);
if(detectedID == testFood.getID()) {
System.out.println("The method Food.getID() successfully"
+ " retrieved the ID.");
} else {
System.err.println("The method Food.getID() failed to retrieve"
+ "the ID.");
errorCount++;
}
//Test getName
Field nameField = foodClass.getDeclaredField("name");
nameField.setAccessible(true);
String detectedName = (String) nameField.get(testFood);
//This should be == this is not a mistake
if(detectedName == testFood.getName()) {
System.out.println("The method Food.getName() successfully"
+ " retrieved the Name.");
} else {
System.err.println("The method Food.getName() failed to retrieve"
+ "the Name.");
errorCount++;
}
//Test getFoodCategories
Field foodCategoriesField = foodClass.getDeclaredField("foodCategories");
foodCategoriesField.setAccessible(true);
ArrayList<String> detectedFoodCategories = (ArrayList<String>) foodCategoriesField.get(testFood);
//This should be == this is not a mistake
if(detectedFoodCategories == testFood.getFoodCategories()) {
System.out.println("The method Food.getFoodCategories() successfully"
+ " retrieved the foodCategories.");
} else {
System.err.println("The method Food.getFoodCategories() failed to retrieve"
+ "the foodCategories.");
errorCount++;
}
//Test getTime
Field timeField = foodClass.getDeclaredField("time");
timeField.setAccessible(true);
GregorianCalendar detectedTime = (GregorianCalendar) timeField.get(testFood);
//This should be == this is not a mistake
if(detectedTime == testFood.getTime()) {
System.out.println("The method Food.getTime() successfully"
+ " retrieved the time.");
} else {
System.err.println("The method Food.getTime() failed to retrieve"
+ "the time.");
errorCount++;
}
//Test getMoods
Field moodsField = foodClass.getDeclaredField("moods");
moodsField.setAccessible(true);
ArrayList<Integer> detectedMoods = (ArrayList<Integer>) moodsField.get(testFood);
//This should be == this is not a mistake
if(detectedMoods == testFood.getMoods()) {
System.out.println("The method Food.getMoods() successfully"
+ " retrieved the moods.");
} else {
System.err.println("The method Food.getMoods() failed to retrieve"
+ "the moods.");
errorCount++;
}
} catch (IllegalArgumentException | IllegalAccessException
| NoSuchFieldException | SecurityException ex) {
System.err.println("An error occured while testing Food Accessors."
+ "\n." + ex.getMessage());
errorCount++;
}
}
private static void testMutators() {
Food testFood = new Food();
Class foodClass = testFood.getClass();
try {
//Test setID
Field idField = foodClass.getDeclaredField("id");
idField.setAccessible(true);
int newID = 77;
testFood.setID(newID);
int detectedID = (int) idField.get(testFood);
if(detectedID == newID) {
System.out.println("The method Food.setID() successfully"
+ " modified the ID.");
} else {
System.err.println("The method Food.setID() failed to modify"
+ " the ID.");
errorCount++;
}
//Test setName
Field nameField = foodClass.getDeclaredField("name");
nameField.setAccessible(true);
String newName = "New Name";
testFood.setName(newName);
String detectedName = (String) nameField.get(testFood);
//This should be == this is not a mistake
if(detectedName == newName) {
System.out.println("The method Food.setName() successfully"
+ " modified the Name.");
} else {
System.err.println("The method Food.setName() failed to modify"
+ " the Name.");
errorCount++;
}
//Test setFoodCategories
Field foodCategoriesField = foodClass.getDeclaredField("foodCategories");
foodCategoriesField.setAccessible(true);
ArrayList<String> newList = new ArrayList<String>();
testFood.setFoodCategories(newList);
ArrayList<String> detectedFoodCategories = (ArrayList<String>) foodCategoriesField.get(testFood);
//This should be == this is not a mistake
if(detectedFoodCategories == newList) {
System.out.println("The method Food.setFoodCategories() successfully"
+ " modified the foodCategories.");
} else {
System.err.println("The method Food.setFoodCategories() failed to modify"
+ " the foodCategories.");
errorCount++;
}
//Test addFoodCategory
String testFoodCategory = "Test Food Category";
testFood.addFoodCategory(testFoodCategory);
if(detectedFoodCategories.get(0) == testFoodCategory) {
System.out.println("The method Food.addFoodCategory(String)"
+ " successfully modified the food categories.");
} else {
System.err.println("The method Food.addFoodCategory(String)"
+ "failed to modify the food categories.");
errorCount++;
}
//Test deleteFoodCategory
String sampleFoodCategory = "Sample Food Category";
detectedFoodCategories.clear();
detectedFoodCategories.add(sampleFoodCategory);
testFood.deleteFoodCategory("Sample Food Category");
if(!detectedFoodCategories.contains(sampleFoodCategory)) {
System.out.println("The method Food.removeFoodCategory(String)"
+ " successfully modified the food categories.");
} else {
System.err.println("The method Food.removeFoodCategory(String)"
+ " failed to modify the food categories.");
errorCount++;
}
//Test setTime
Field timeField = foodClass.getDeclaredField("time");
timeField.setAccessible(true);
GregorianCalendar newTime = new GregorianCalendar();
testFood.setTime(newTime);
GregorianCalendar detectedTime = (GregorianCalendar) timeField.get(testFood);
//This should be == this is not a mistake
if(detectedTime == newTime) {
System.out.println("The method Food.setTime() successfully"
+ " modified the time.");
} else {
System.err.println("The method Food.setTime() failed to modify"
+ " the time.");
errorCount++;
}
//Test setMoods
Field moodsField = foodClass.getDeclaredField("moods");
moodsField.setAccessible(true);
ArrayList<Integer> newMoods = new ArrayList<Integer>();
testFood.setMoods(newMoods);
ArrayList<Integer> detectedMoods = (ArrayList<Integer>) moodsField.get(testFood);
//This should be == this is not a mistake
if(detectedMoods == newMoods) {
System.out.println("The method Food.setMoods() successfully"
+ " modified the moods.");
} else {
System.err.println("The method Food.setMoods() failed to modify"
+ " the moods.");
errorCount++;
}
//Test addMood
Integer testInt = 3;
testFood.addMood(testInt);
for (int i = 0; i < detectedMoods.size(); i++) {
if(detectedMoods.get(i) == testInt) {
System.out.println("The method Food.addMood(Integer)"
+ " successfully modified the moods.");
break;
}
if(i == detectedMoods.size() - 1) {
System.err.println("The method Food.addMood(Intger)"
+ " failed to modify the moods.");
errorCount++;
}
}
detectedMoods.clear();
//Test deleteMood
detectedMoods.add(testInt);
for (int i = 0; i < detectedMoods.size(); i++) {
if(detectedMoods.get(i) == testInt) {
System.err.println("The method Food.deleteMood(Intger)"
+ " failed to modify the moods.");
errorCount++;
break;
}
if(i == detectedMoods.size() - 1) {
System.out.println("The method Food.deleteMood(Integer)"
+ " successfully modified the moods.");
}
}
} catch (IllegalArgumentException | IllegalAccessException
| NoSuchFieldException | SecurityException ex) {
System.err.println("An error occured while testing Food Accessors."
+ "\n." + ex.getMessage());
errorCount++;
}
}
}
| Updating constructors | src/testharness/FoodTestHarness.java | Updating constructors | <ide><path>rc/testharness/FoodTestHarness.java
<ide> Field idField = foodClass.getDeclaredField("id");
<ide> idField.setAccessible(true);
<ide> int newID = 77;
<del> testFood.setID(newID);
<ide> int detectedID = (int) idField.get(testFood);
<ide> if(detectedID == newID) {
<ide> System.out.println("The method Food.setID() successfully" |
|
JavaScript | mit | 7f699fd6d1a632f23f4dceafc0d35c815f14fdc9 | 0 | shannonmpoole/fh-fhc,wei-lee/fh-fhc,david-martin/fh-fhc,paolobueno/fh-fhc,nialldonnellyfh/fh-fhc | var common = require("../../../common");
var fhreq = require("../../../utils/request");
module.exports = domains;
domains.desc = "Manage Domains";
domains.usage= "admin domains create <domainName> <type admin|developer> --theme=<sometheme> --parent=<someparent> ";
function domains(argv,cb){
var args = argv._;
var cmd = args[0];
if("create" == cmd){
return createDomain(argv,cb);
}
else if("check" == cmd){
return checkDomain(argsv,cb);
}
};
function createDomain(args, cb){
var argsArr = args._;
var domain = argsArr[1],
type = argsArr[2],
parent = args.parent,
theme = args.theme || "";
if("admin" !== type && "developer" !== type){
cb("type must be one of admin or developer")
}
var payload = {"domain":domain,"parent":parent,"type":type,"theme":theme};
var url = "/box/api/domains";
common.doApiCall(fhreq.getFeedHenryUrl(), url, payload, "failed to create cluster user",function(err, domain){
if (err) return cb(err);
return cb(err, domain);
});
}
function checkDomain(args,cb){
var domainToCheck = args[1];
var url = '/box/api/domains/check?domain=' + domainToCheck;
common.doGetApiCall(fhreq.getFeedHenryUrl(), url, "Error checking domain availability: ", function(err, res, status) {
cb(err,res);
});
}
| lib/cmd/fh3/admin/domains.js | var common = require("../../../common");
var fhreq = require("../../../utils/request");
module.exports = domains;
domains.desc = "Manage Domains";
domains.usage= "admin domains create <domainName> <type admin|developer> --theme=<sometheme> --parent=<someparent> ";
function domains(argv,cb){
var args = argv._;
var cmd = args[0];
if("create" == cmd){
return createDomain(argv,cb);
}
else if("check" == cmd){
return checkDomain(argsv,cb);
}
};
function createDomain(args, cb){
console.log(args);
var argsArr = args._;
var domain = argsArr[1],
type = argsArr[2],
parent = args.parent,
theme = args.theme || "";
if("admin" !== type && "developer" !== type){
cb("type must be one of admin or developer")
}
var payload = {"domain":domain,"parent":parent,"type":type,"theme":theme};
var url = "/box/api/domains";
common.doApiCall(fhreq.getFeedHenryUrl(), url, payload, "failed to create cluster user",function(err, domain){
if (err) return cb(err);
return cb(err, domain);
});
}
function checkDomain(args,cb){
var domainToCheck = args[1];
var url = '/box/api/domains/check?domain=' + domainToCheck;
common.doGetApiCall(fhreq.getFeedHenryUrl(), url, "Error checking domain availability: ", function(err, res, status) {
cb(err,res);
});
}
| remove console.log
| lib/cmd/fh3/admin/domains.js | remove console.log | <ide><path>ib/cmd/fh3/admin/domains.js
<ide>
<ide>
<ide> function createDomain(args, cb){
<del> console.log(args);
<ide> var argsArr = args._;
<ide> var domain = argsArr[1],
<ide> type = argsArr[2], |
|
Java | agpl-3.0 | 9bd4774f068d10402b510423db8776ba38db59ac | 0 | masters-info-nantes/myLazyClock,masters-info-nantes/myLazyClock,masters-info-nantes/myLazyClock | package org.myLazyClock.travelApi;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Map;
/**
* Created on 03/12/14.
*
* @author david
*/
public class TravelGmapStrategy implements TravelStrategy {
public static final int ID = 1;
@Override
public Integer getId() {
return ID;
}
@Override
public String getName() {
return "traveling with Gmap";
}
@Override
public TravelDuration getDuration(String from, String to, Date dateArrival, Map<String, String> param) {
String requestURI= constructGoogleRequestURI(from, to, dateArrival, param);
int travelTime=0;
try {
URL url = new URL(requestURI);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// création d'un objet Json associer au retour de l'url
JsonParser jp = new JsonParser();
//on ce place a la racine
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject();
// les méthodes get sur un JsonObjet renvoie un JsonArray dans le cas ou sa n'est pas une "feuille"
JsonArray routesArray = (JsonArray) jp.parse(rootobj.get("routes").toString());
JsonElement routes = jp.parse(routesArray.get(0).toString());
JsonObject routesObj = routes.getAsJsonObject();
JsonArray legsArray = (JsonArray) jp.parse(routesObj.get("legs").toString());
JsonElement legs = jp.parse(legsArray.get(0).toString());
JsonObject legsObj = legs.getAsJsonObject();
// on est sur une "feuille" l'objet est directement interprété par le parseur.
JsonObject durationObj = (JsonObject) jp.parse(legsObj.get("duration").toString());
travelTime= durationObj.get("value").getAsInt();
}catch (IOException e) {
e.getMessage();
}
return new TravelDuration(travelTime);
}
/** Méthode de mise en place de l'url d'appel pour le calcul d'itinéraire
* @return void;
*/
private String constructGoogleRequestURI (String from, String to, Date dateArrival, Map<String, String> param){
from=from.replaceAll("\\s","%20");
to=to.replaceAll("\\s","%20");
String googleUri = "https://maps.googleapis.com/maps/api/directions/json?"
+ "origin=" + from
+ "&destination="+ to
+ "&arrival_time="+ dateArrival.getTime();
for(String key:param.keySet()){
googleUri+="&"+key+"="+param.get(key);
}
return googleUri;
}
}
| server-gae/travel-gmap/src/main/java/org/myLazyClock/travelApi/TravelGmapStrategy.java | package org.myLazyClock.travelApi;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Map;
/**
* Created on 03/12/14.
*
* @author david
*/
public class TravelGmapStrategy implements TravelStrategy {
public static final int ID = 1;
@Override
public Integer getId() {
return ID;
}
@Override
public String getName() {
return "traveling with Gmap";
}
@Override
public TravelDuration getDuration(String from, String to, Date dateArrival, Map<String, String> param) {
String requestURI= constructGoogleRequestURI(from, to, dateArrival, param);
int travelTime=0;
try {
URL url = new URL(requestURI);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// création d'un objet Json associer au retour de l'url
JsonParser jp = new JsonParser();
//on ce place a la racine
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject();
// les méthodes get sur un JsonObjet renvoie un JsonArray dans le cas ou sa n'est pas une "feuille"
JsonArray routesArray = (JsonArray) jp.parse(rootobj.get("routes").toString());
JsonElement routes = jp.parse(routesArray.get(0).toString());
JsonObject routesObj = routes.getAsJsonObject();
JsonArray legsArray = (JsonArray) jp.parse(routesObj.get("legs").toString());
JsonElement legs = jp.parse(legsArray.get(0).toString());
JsonObject legsObj = legs.getAsJsonObject();
// on est sur une "feuille" l'objet est directement interprété par le parseur.
JsonObject durationObj = (JsonObject) jp.parse(legsObj.get("duration").toString());
travelTime= durationObj.get("value").getAsInt();
}catch (IOException e) {
e.getMessage();
}
return new TravelDuration(travelTime);
}
/** Méthode de mise en place de l'url d'appel pour le calcul d'itinéraire
* @return void;
*/
private String constructGoogleRequestURI (String from, String to, Date dateArrival, Map<String, String> param){
from=from.replaceAll("\\s","");
to=to.replaceAll("\\s","");
String googleUri = "https://maps.googleapis.com/maps/api/directions/json?"
+ "origin=" + from
+ "&destination="+ to
+ "&arrival_time="+ dateArrival.getTime();
for(String key:param.keySet()){
googleUri+="&"+key+"="+param.get(key);
}
return googleUri;
}
}
| fixes url for gmaps when contain space
| server-gae/travel-gmap/src/main/java/org/myLazyClock/travelApi/TravelGmapStrategy.java | fixes url for gmaps when contain space | <ide><path>erver-gae/travel-gmap/src/main/java/org/myLazyClock/travelApi/TravelGmapStrategy.java
<ide> import com.google.gson.JsonElement;
<ide> import com.google.gson.JsonObject;
<ide> import com.google.gson.JsonParser;
<add>
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<ide> import java.io.InputStreamReader;
<ide> */
<ide>
<ide> private String constructGoogleRequestURI (String from, String to, Date dateArrival, Map<String, String> param){
<del> from=from.replaceAll("\\s","");
<del> to=to.replaceAll("\\s","");
<add> from=from.replaceAll("\\s","%20");
<add> to=to.replaceAll("\\s","%20");
<ide>
<ide> String googleUri = "https://maps.googleapis.com/maps/api/directions/json?"
<ide> + "origin=" + from |
|
Java | apache-2.0 | 9503f89ac26e67a44c50ada69fb855e1a13c3498 | 0 | kuberkaul/artifactory-plugin,arothian/artifactory-plugin,JFrogDev/jenkins-artifactory-plugin,arothian/artifactory-plugin,AlexeiVainshtein/jenkins-artifactory-plugin,grossws/jenkins-artifactory-plugin,JFrogDev/jenkins-artifactory-plugin,shikloshi/jenkins-artifactory-plugin,AlexeiVainshtein/jenkins-artifactory-plugin,nilleb/artifactory-plugin,stephenliang/artifactory-plugin,DimaNevelev/jenkins-artifactory-plugin,nilleb/artifactory-plugin,jglick/artifactory-plugin,christ66/jenkins-artifactory-plugin,stephenliang/artifactory-plugin,grossws/jenkins-artifactory-plugin,stephenliang/artifactory-plugin,shikloshi/jenkins-artifactory-plugin,DimaNevelev/jenkins-artifactory-plugin,JFrogDev/jenkins-artifactory-plugin,recena/artifactory-plugin,grossws/jenkins-artifactory-plugin,recena/artifactory-plugin,kuberkaul/artifactory-plugin,arothian/artifactory-plugin,recena/artifactory-plugin,DimaNevelev/jenkins-artifactory-plugin,kuberkaul/artifactory-plugin,jglick/artifactory-plugin,shikloshi/jenkins-artifactory-plugin,AlexeiVainshtein/jenkins-artifactory-plugin,nilleb/artifactory-plugin,christ66/jenkins-artifactory-plugin,christ66/jenkins-artifactory-plugin | /*
* Copyright (C) 2010 JFrog Ltd.
*
* 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.
*/
package org.jfrog.hudson.maven3;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.*;
import hudson.remoting.VirtualChannel;
import hudson.remoting.Which;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.SlaveComputer;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.tasks.Maven;
import hudson.tools.ToolInstallation;
import hudson.tools.ToolLocationNodeProperty;
import hudson.util.ArgumentListBuilder;
import hudson.util.DescribableList;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jfrog.build.api.BuildInfoConfigProperties;
import org.jfrog.build.extractor.maven.Maven3BuildInfoLogger;
import org.jfrog.hudson.util.PluginDependencyHelper;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.List;
/**
* Maven3 builder. Hudson 1.392 added native support for maven 3 but this one is useful for free style.
*
* @author Yossi Shaul
*/
public class Maven3Builder extends Builder {
public static final String CLASSWORLDS_LAUNCHER = "org.codehaus.plexus.classworlds.launcher.Launcher";
private final String mavenName;
private final String rootPom;
private final String goals;
private final String mavenOpts;
@DataBoundConstructor
public Maven3Builder(String mavenName, String rootPom, String goals, String mavenOpts) {
this.mavenName = mavenName;
this.rootPom = rootPom;
this.goals = goals;
this.mavenOpts = mavenOpts;
}
public String getMavenName() {
return mavenName;
}
public String getRootPom() {
return rootPom;
}
public String getGoals() {
return goals;
}
public String getMavenOpts() {
return mavenOpts;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
EnvVars env = build.getEnvironment(listener);
FilePath workDir = build.getModuleRoot();
ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env);
StringBuilder javaPathBuilder = new StringBuilder();
JDK configuredJdk = build.getProject().getJDK();
if (configuredJdk != null) {
javaPathBuilder.append(build.getProject().getJDK().getBinDir().getCanonicalPath()).append(File.separator);
}
javaPathBuilder.append("java");
if (!launcher.isUnix()) {
javaPathBuilder.append(".exe");
}
String[] cmds = cmdLine.toCommandArray();
try {
//listener.getLogger().println("Executing: " + cmdLine.toStringWithQuote());
int exitValue =
launcher.launch().cmds(new File(javaPathBuilder.toString()), cmds).envs(env).stdout(listener)
.pwd(workDir).join();
boolean success = (exitValue == 0);
build.setResult(success ? Result.SUCCESS : Result.FAILURE);
return success;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed"));
build.setResult(Result.FAILURE);
return false;
}
}
private ArgumentListBuilder buildMavenCmdLine(AbstractBuild<?, ?> build, BuildListener listener,
EnvVars env) throws IOException, InterruptedException {
FilePath mavenHome = getMavenHomeDir(build, listener, env);
if (!mavenHome.exists()) {
listener.error("Couldn't find Maven home: " + mavenHome.getRemote());
throw new Run.RunnerAbortedException();
}
ArgumentListBuilder args = new ArgumentListBuilder();
FilePath mavenBootDir = new FilePath(mavenHome, "boot");
FilePath[] classworldsCandidates = mavenBootDir.list("plexus-classworlds*.jar");
if (classworldsCandidates == null || classworldsCandidates.length == 0) {
listener.error("Couldn't find classworlds jar under " + mavenBootDir.getRemote());
throw new Run.RunnerAbortedException();
}
FilePath classWorldsJar = classworldsCandidates[0];
// classpath
args.add("-classpath");
//String cpSeparator = launcher.isUnix() ? ":" : ";";
args.add(classWorldsJar.getRemote());
String buildInfoPropertiesFile = env.get(BuildInfoConfigProperties.PROP_PROPS_FILE);
boolean artifactoryIntegration = StringUtils.isNotBlank(buildInfoPropertiesFile);
if (artifactoryIntegration) {
args.addKeyValuePair("-D", BuildInfoConfigProperties.PROP_PROPS_FILE, buildInfoPropertiesFile, false);
}
// maven home
args.addKeyValuePair("-D", "maven.home", mavenHome.getRemote(), false);
String classworldsConfPath;
if (artifactoryIntegration) {
// use the classworlds conf packaged with this plugin and resolve the extractor libs
File maven3ExtractorJar = Which.jarFile(Maven3BuildInfoLogger.class);
FilePath actualDependencyDirectory =
PluginDependencyHelper.getActualDependencyDirectory(build, maven3ExtractorJar);
if (getMavenOpts() == null || !getMavenOpts().contains("-Dm3plugin.lib")) {
args.addKeyValuePair("-D", "m3plugin.lib", actualDependencyDirectory.getRemote(), false);
}
URL classworldsResource =
getClass().getClassLoader().getResource("org/jfrog/hudson/maven3/classworlds-freestyle.conf");
File classworldsConfFile = new File(URLDecoder.decode(classworldsResource.getFile(), "utf-8"));
if (!classworldsConfFile.exists()) {
listener.error("Unable to locate classworlds configuration file under " +
classworldsConfFile.getAbsolutePath());
throw new Run.RunnerAbortedException();
}
//If we are on a remote slave, make a temp copy of the customized classworlds conf
if (Computer.currentComputer() instanceof SlaveComputer) {
FilePath remoteClassworlds = build.getWorkspace().createTextTempFile("classworlds", "conf", "", false);
remoteClassworlds.copyFrom(classworldsResource);
classworldsConfPath = remoteClassworlds.getRemote();
} else {
classworldsConfPath = classworldsConfFile.getCanonicalPath();
}
} else {
classworldsConfPath = new FilePath(mavenHome, "bin/m2.conf").getRemote();
}
args.addKeyValuePair("-D", "classworlds.conf", classworldsConfPath, false);
// maven opts
if (StringUtils.isNotBlank(getMavenOpts())) {
String mavenOpts = Util.replaceMacro(getMavenOpts(), build.getBuildVariableResolver());
args.add(mavenOpts);
}
// classworlds launcher main class
args.add(CLASSWORLDS_LAUNCHER);
// pom file to build
String rootPom = getRootPom();
if (StringUtils.isNotBlank(rootPom)) {
args.add("-f", rootPom);
}
// maven goals
args.addTokenized(getGoals());
return args;
}
private FilePath getMavenHomeDir(AbstractBuild<?, ?> build, BuildListener listener, EnvVars env) {
Computer computer = Computer.currentComputer();
VirtualChannel virtualChannel = computer.getChannel();
String mavenHome = null;
//Check for a node defined tool if we are on a slave
if (computer instanceof SlaveComputer) {
mavenHome = getNodeDefinedMavenHome(build);
}
//Either we are on the master or that no node tool was defined
if (StringUtils.isBlank(mavenHome)) {
mavenHome = getJobDefinedMavenInstallation(listener, virtualChannel);
}
//Try to find the home via the env vars
if (StringUtils.isBlank(mavenHome)) {
mavenHome = getEnvDefinedMavenHome(env);
}
return new FilePath(virtualChannel, mavenHome);
}
private String getNodeDefinedMavenHome(AbstractBuild<?, ?> build) {
Node currentNode = build.getBuiltOn();
DescribableList<NodeProperty<?>, NodePropertyDescriptor> properties = currentNode.getNodeProperties();
ToolLocationNodeProperty toolLocation = properties.get(ToolLocationNodeProperty.class);
if (toolLocation != null) {
List<ToolLocationNodeProperty.ToolLocation> locations = toolLocation.getLocations();
if (locations != null) {
for (ToolLocationNodeProperty.ToolLocation location : locations) {
if (location.getType().isSubTypeOf(Maven.MavenInstallation.class)) {
String installationHome = location.getHome();
if (StringUtils.isNotBlank(installationHome)) {
return installationHome;
}
}
}
}
}
return null;
}
private String getEnvDefinedMavenHome(EnvVars env) {
String mavenHome = env.get("MAVEN_HOME");
if (StringUtils.isNotBlank(mavenHome)) {
return mavenHome;
}
return env.get("M2_HOME");
}
private String getJobDefinedMavenInstallation(BuildListener listener, VirtualChannel channel) {
Maven.MavenInstallation mvn = getMavenInstallation();
if (mvn == null) {
listener.error("Maven version is not configured for this project. Can't determine which Maven to run");
throw new Run.RunnerAbortedException();
}
String mvnHome = mvn.getHome();
if (mvnHome == null) {
listener.error("Maven '%s' doesn't have its home set", mvn.getName());
throw new Run.RunnerAbortedException();
}
return mvnHome;
}
public Maven.MavenInstallation getMavenInstallation() {
Maven.MavenInstallation[] installations = getDescriptor().getInstallations();
for (Maven.MavenInstallation installation : installations) {
if (installation.getName().equals(mavenName)) {
return installation;
}
}
// not found, return the first installation if exists
return installations.length > 0 ? installations[0] : null;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
public DescriptorImpl() {
load();
}
protected DescriptorImpl(Class<? extends Maven3Builder> clazz) {
super(clazz);
}
/**
* Obtains the {@link hudson.tasks.Maven.MavenInstallation.DescriptorImpl} instance.
*/
public Maven.MavenInstallation.DescriptorImpl getToolDescriptor() {
return ToolInstallation.all().get(Maven.MavenInstallation.DescriptorImpl.class);
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return jobType.equals(FreeStyleProject.class);
}
@Override
public String getHelpFile() {
return "/plugin/artifactory/maven3/help.html";
}
@Override
public String getDisplayName() {
return Messages.step_displayName();
}
public Maven.DescriptorImpl getMavenDescriptor() {
return Hudson.getInstance().getDescriptorByType(Maven.DescriptorImpl.class);
}
public Maven.MavenInstallation[] getInstallations() {
return getMavenDescriptor().getInstallations();
}
@Override
public Maven3Builder newInstance(StaplerRequest request, JSONObject formData) throws FormException {
return (Maven3Builder) request.bindJSON(clazz, formData);
}
}
}
| src/main/java/org/jfrog/hudson/maven3/Maven3Builder.java | /*
* Copyright (C) 2010 JFrog Ltd.
*
* 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.
*/
package org.jfrog.hudson.maven3;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.*;
import hudson.remoting.VirtualChannel;
import hudson.remoting.Which;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.SlaveComputer;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.tasks.Maven;
import hudson.tools.ToolInstallation;
import hudson.tools.ToolLocationNodeProperty;
import hudson.util.ArgumentListBuilder;
import hudson.util.DescribableList;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jfrog.build.api.BuildInfoConfigProperties;
import org.jfrog.build.extractor.maven.Maven3BuildInfoLogger;
import org.jfrog.hudson.util.PluginDependencyHelper;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.List;
/**
* Maven3 builder. Hudson 1.392 added native support for maven 3 but this one is useful for free style.
*
* @author Yossi Shaul
*/
public class Maven3Builder extends Builder {
public static final String CLASSWORLDS_LAUNCHER = "org.codehaus.plexus.classworlds.launcher.Launcher";
private final String mavenName;
private final String rootPom;
private final String goals;
private final String mavenOpts;
@DataBoundConstructor
public Maven3Builder(String mavenName, String rootPom, String goals, String mavenOpts) {
this.mavenName = mavenName;
this.rootPom = rootPom;
this.goals = goals;
this.mavenOpts = mavenOpts;
}
public String getMavenName() {
return mavenName;
}
public String getRootPom() {
return rootPom;
}
public String getGoals() {
return goals;
}
public String getMavenOpts() {
return mavenOpts;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
EnvVars env = build.getEnvironment(listener);
FilePath workDir = build.getModuleRoot();
ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env);
StringBuilder javaPathBuilder = new StringBuilder();
JDK configuredJdk = build.getProject().getJDK();
if (configuredJdk != null) {
javaPathBuilder.append(build.getProject().getJDK().getBinDir().getCanonicalPath()).append(File.separator);
}
javaPathBuilder.append("java");
if (!launcher.isUnix()) {
javaPathBuilder.append(".exe");
}
String[] cmds = cmdLine.toCommandArray();
try {
//listener.getLogger().println("Executing: " + cmdLine.toStringWithQuote());
int exitValue =
launcher.launch().cmds(new File(javaPathBuilder.toString()), cmds).envs(env).stdout(listener)
.pwd(workDir).join();
boolean success = (exitValue == 0);
build.setResult(success ? Result.SUCCESS : Result.FAILURE);
return success;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed"));
build.setResult(Result.FAILURE);
return false;
}
}
private ArgumentListBuilder buildMavenCmdLine(AbstractBuild<?, ?> build, BuildListener listener,
EnvVars env) throws IOException, InterruptedException {
FilePath mavenHome = getMavenHomeDir(build, listener, env);
if (!mavenHome.exists()) {
listener.error("Couldn't find Maven home: " + mavenHome.getRemote());
throw new Run.RunnerAbortedException();
}
ArgumentListBuilder args = new ArgumentListBuilder();
FilePath mavenBootDir = new FilePath(mavenHome, "boot");
FilePath[] classworldsCandidates = mavenBootDir.list("plexus-classworlds*.jar");
if (classworldsCandidates == null || classworldsCandidates.length == 0) {
listener.error("Couldn't find classworlds jar under " + mavenBootDir.getRemote());
throw new Run.RunnerAbortedException();
}
FilePath classWorldsJar = classworldsCandidates[0];
// classpath
args.add("-classpath");
//String cpSeparator = launcher.isUnix() ? ":" : ";";
args.add(classWorldsJar.getRemote());
String buildInfoPropertiesFile = env.get(BuildInfoConfigProperties.PROP_PROPS_FILE);
boolean artifactoryIntegration = StringUtils.isNotBlank(buildInfoPropertiesFile);
if (artifactoryIntegration) {
args.addKeyValuePair("-D", BuildInfoConfigProperties.PROP_PROPS_FILE, buildInfoPropertiesFile, false);
}
// maven home
args.addKeyValuePair("-D", "maven.home", mavenHome.getRemote(), false);
String classworldsConfPath;
if (artifactoryIntegration) {
// use the classworlds conf packaged with this plugin and resolve the extractor libs
File maven3ExtractorJar = Which.jarFile(Maven3BuildInfoLogger.class);
FilePath actualDependencyDirectory =
PluginDependencyHelper.getActualDependencyDirectory(build, maven3ExtractorJar);
if (StringUtils.isNotBlank(getMavenOpts()) && !getMavenOpts().contains("m3plugin.lib")) {
args.addKeyValuePair("-D", "m3plugin.lib", actualDependencyDirectory.getRemote(), false);
}
URL classworldsResource =
getClass().getClassLoader().getResource("org/jfrog/hudson/maven3/classworlds-freestyle.conf");
File classworldsConfFile = new File(URLDecoder.decode(classworldsResource.getFile(), "utf-8"));
if (!classworldsConfFile.exists()) {
listener.error("Unable to locate classworlds configuration file under " +
classworldsConfFile.getAbsolutePath());
throw new Run.RunnerAbortedException();
}
//If we are on a remote slave, make a temp copy of the customized classworlds conf
if (Computer.currentComputer() instanceof SlaveComputer) {
FilePath remoteClassworlds = build.getWorkspace().createTextTempFile("classworlds", "conf", "", false);
remoteClassworlds.copyFrom(classworldsResource);
classworldsConfPath = remoteClassworlds.getRemote();
} else {
classworldsConfPath = classworldsConfFile.getCanonicalPath();
}
} else {
classworldsConfPath = new FilePath(mavenHome, "bin/m2.conf").getRemote();
}
args.addKeyValuePair("-D", "classworlds.conf", classworldsConfPath, false);
// maven opts
if (StringUtils.isNotBlank(getMavenOpts())) {
String mavenOpts = Util.replaceMacro(getMavenOpts(), build.getBuildVariableResolver());
args.add(mavenOpts);
}
// classworlds launcher main class
args.add(CLASSWORLDS_LAUNCHER);
// pom file to build
String rootPom = getRootPom();
if (StringUtils.isNotBlank(rootPom)) {
args.add("-f", rootPom);
}
// maven goals
args.addTokenized(getGoals());
return args;
}
private FilePath getMavenHomeDir(AbstractBuild<?, ?> build, BuildListener listener, EnvVars env) {
Computer computer = Computer.currentComputer();
VirtualChannel virtualChannel = computer.getChannel();
String mavenHome = null;
//Check for a node defined tool if we are on a slave
if (computer instanceof SlaveComputer) {
mavenHome = getNodeDefinedMavenHome(build);
}
//Either we are on the master or that no node tool was defined
if (StringUtils.isBlank(mavenHome)) {
mavenHome = getJobDefinedMavenInstallation(listener, virtualChannel);
}
//Try to find the home via the env vars
if (StringUtils.isBlank(mavenHome)) {
mavenHome = getEnvDefinedMavenHome(env);
}
return new FilePath(virtualChannel, mavenHome);
}
private String getNodeDefinedMavenHome(AbstractBuild<?, ?> build) {
Node currentNode = build.getBuiltOn();
DescribableList<NodeProperty<?>, NodePropertyDescriptor> properties = currentNode.getNodeProperties();
ToolLocationNodeProperty toolLocation = properties.get(ToolLocationNodeProperty.class);
if (toolLocation != null) {
List<ToolLocationNodeProperty.ToolLocation> locations = toolLocation.getLocations();
if (locations != null) {
for (ToolLocationNodeProperty.ToolLocation location : locations) {
if (location.getType().isSubTypeOf(Maven.MavenInstallation.class)) {
String installationHome = location.getHome();
if (StringUtils.isNotBlank(installationHome)) {
return installationHome;
}
}
}
}
}
return null;
}
private String getEnvDefinedMavenHome(EnvVars env) {
String mavenHome = env.get("MAVEN_HOME");
if (StringUtils.isNotBlank(mavenHome)) {
return mavenHome;
}
return env.get("M2_HOME");
}
private String getJobDefinedMavenInstallation(BuildListener listener, VirtualChannel channel) {
Maven.MavenInstallation mvn = getMavenInstallation();
if (mvn == null) {
listener.error("Maven version is not configured for this project. Can't determine which Maven to run");
throw new Run.RunnerAbortedException();
}
String mvnHome = mvn.getHome();
if (mvnHome == null) {
listener.error("Maven '%s' doesn't have its home set", mvn.getName());
throw new Run.RunnerAbortedException();
}
return mvnHome;
}
public Maven.MavenInstallation getMavenInstallation() {
Maven.MavenInstallation[] installations = getDescriptor().getInstallations();
for (Maven.MavenInstallation installation : installations) {
if (installation.getName().equals(mavenName)) {
return installation;
}
}
// not found, return the first installation if exists
return installations.length > 0 ? installations[0] : null;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
public DescriptorImpl() {
load();
}
protected DescriptorImpl(Class<? extends Maven3Builder> clazz) {
super(clazz);
}
/**
* Obtains the {@link hudson.tasks.Maven.MavenInstallation.DescriptorImpl} instance.
*/
public Maven.MavenInstallation.DescriptorImpl getToolDescriptor() {
return ToolInstallation.all().get(Maven.MavenInstallation.DescriptorImpl.class);
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return jobType.equals(FreeStyleProject.class);
}
@Override
public String getHelpFile() {
return "/plugin/artifactory/maven3/help.html";
}
@Override
public String getDisplayName() {
return Messages.step_displayName();
}
public Maven.DescriptorImpl getMavenDescriptor() {
return Hudson.getInstance().getDescriptorByType(Maven.DescriptorImpl.class);
}
public Maven.MavenInstallation[] getInstallations() {
return getMavenDescriptor().getInstallations();
}
@Override
public Maven3Builder newInstance(StaplerRequest request, JSONObject formData) throws FormException {
return (Maven3Builder) request.bindJSON(clazz, formData);
}
}
}
| HAP-230 - Fixed property condition test
| src/main/java/org/jfrog/hudson/maven3/Maven3Builder.java | HAP-230 - Fixed property condition test | <ide><path>rc/main/java/org/jfrog/hudson/maven3/Maven3Builder.java
<ide> FilePath actualDependencyDirectory =
<ide> PluginDependencyHelper.getActualDependencyDirectory(build, maven3ExtractorJar);
<ide>
<del> if (StringUtils.isNotBlank(getMavenOpts()) && !getMavenOpts().contains("m3plugin.lib")) {
<add> if (getMavenOpts() == null || !getMavenOpts().contains("-Dm3plugin.lib")) {
<ide> args.addKeyValuePair("-D", "m3plugin.lib", actualDependencyDirectory.getRemote(), false);
<ide> }
<ide> |
|
Java | apache-2.0 | 1f3f5f35bb66fe9345bc74cc17bec691914500c2 | 0 | apereo/cas,apereo/cas,fogbeam/cas_mirror,leleuj/cas,Jasig/cas,fogbeam/cas_mirror,philliprower/cas,leleuj/cas,rkorn86/cas,pdrados/cas,philliprower/cas,apereo/cas,pdrados/cas,philliprower/cas,rkorn86/cas,fogbeam/cas_mirror,Jasig/cas,leleuj/cas,pdrados/cas,philliprower/cas,apereo/cas,fogbeam/cas_mirror,rkorn86/cas,pdrados/cas,philliprower/cas,leleuj/cas,philliprower/cas,apereo/cas,leleuj/cas,fogbeam/cas_mirror,Jasig/cas,Jasig/cas,apereo/cas,apereo/cas,philliprower/cas,pdrados/cas,fogbeam/cas_mirror,pdrados/cas,rkorn86/cas,leleuj/cas | /*
* Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license
* distributed with this file and available online at
* http://www.ja-sig.org/products/cas/overview/license/
*/
package org.jasig.cas;
import org.jasig.cas.authentication.Authentication;
import org.jasig.cas.authentication.ImmutableAuthentication;
import org.jasig.cas.authentication.principal.*;
import org.jasig.cas.validation.Assertion;
import org.jasig.cas.validation.ImmutableAssertionImpl;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.validation.BindException;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.test.MockRequestContext;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.0.2
*/
public final class TestUtils {
public static final String CONST_USERNAME = "test";
private static final String CONST_PASSWORD = "test1";
private static final String CONST_BAD_URL = "http://www.acs.rutgers.edu";
private static final String CONST_CREDENTIALS = "credentials";
private static final String CONST_WEBFLOW_BIND_EXCEPTION = "org.springframework.validation.BindException.credentials";
private static final String[] CONST_NO_PRINCIPALS = new String[0];
public static final String CONST_EXCEPTION_EXPECTED = "Exception expected.";
public static final String CONST_EXCEPTION_NON_EXPECTED = "Exception not expected.";
public static final String CONST_GOOD_URL = "https://github.com/";
private TestUtils() {
// do not instanciate
}
public static UsernamePasswordCredentials getCredentialsWithSameUsernameAndPassword() {
return getCredentialsWithSameUsernameAndPassword(CONST_USERNAME);
}
public static UsernamePasswordCredentials getCredentialsWithSameUsernameAndPassword(
final String username) {
return getCredentialsWithDifferentUsernameAndPassword(username,
username);
}
public static UsernamePasswordCredentials getCredentialsWithDifferentUsernameAndPassword() {
return getCredentialsWithDifferentUsernameAndPassword(CONST_USERNAME,
CONST_PASSWORD);
}
public static UsernamePasswordCredentials getCredentialsWithDifferentUsernameAndPassword(
final String username, final String password) {
// noinspection LocalVariableOfConcreteClass
final UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials();
usernamePasswordCredentials.setUsername(username);
usernamePasswordCredentials.setPassword(password);
return usernamePasswordCredentials;
}
public static HttpBasedServiceCredentials getHttpBasedServiceCredentials() {
return getHttpBasedServiceCredentials(CONST_GOOD_URL);
}
public static HttpBasedServiceCredentials getBadHttpBasedServiceCredentials() {
return getHttpBasedServiceCredentials(CONST_BAD_URL);
}
public static HttpBasedServiceCredentials getHttpBasedServiceCredentials(
final String url) {
try {
return new HttpBasedServiceCredentials(new URL(url));
} catch (MalformedURLException e) {
throw new IllegalArgumentException();
}
}
public static Principal getPrincipal() {
return getPrincipal(CONST_USERNAME);
}
public static Principal getPrincipal(final String name) {
return new SimplePrincipal(name);
}
public static Service getService() {
return getService(CONST_USERNAME);
}
public static Service getService(final String name) {
final MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("service", name);
return SimpleWebApplicationServiceImpl.createServiceFrom(request);
}
public static Authentication getAuthentication() {
return new ImmutableAuthentication(getPrincipal());
}
public static Authentication getAuthenticationWithService() {
return new ImmutableAuthentication(getService());
}
public static Authentication getAuthentication(final String name) {
return new ImmutableAuthentication(getPrincipal(name));
}
public static Assertion getAssertion(final boolean fromNewLogin) {
return getAssertion(fromNewLogin, CONST_NO_PRINCIPALS);
}
public static Assertion getAssertion(final boolean fromNewLogin,
final String[] extraPrincipals) {
final List<Authentication> list = new ArrayList<Authentication>();
list.add(TestUtils.getAuthentication());
for (int i = 0; i < extraPrincipals.length; i++) {
list.add(TestUtils.getAuthentication(extraPrincipals[i]));
}
return new ImmutableAssertionImpl(list, TestUtils.getService(),
fromNewLogin);
}
public static MockRequestContext getContext() {
return getContext(new MockHttpServletRequest());
}
public static MockRequestContext getContext(
final MockHttpServletRequest request) {
return getContext(request, new MockHttpServletResponse());
}
public static MockRequestContext getContext(
final MockHttpServletRequest request,
final MockHttpServletResponse response) {
final MockRequestContext context = new MockRequestContext();
context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
return context;
}
public static MockRequestContext getContextWithCredentials(
final MockHttpServletRequest request) {
return getContextWithCredentials(request, new MockHttpServletResponse());
}
public static MockRequestContext getContextWithCredentials(
final MockHttpServletRequest request,
final MockHttpServletResponse response) {
final MockRequestContext context = getContext(request, response);
context.getRequestScope().put(CONST_CREDENTIALS, TestUtils
.getCredentialsWithSameUsernameAndPassword());
context.getRequestScope().put(CONST_WEBFLOW_BIND_EXCEPTION,
new BindException(TestUtils
.getCredentialsWithSameUsernameAndPassword(),
CONST_CREDENTIALS));
return context;
}
}
| cas-server-core/src/test/java/org/jasig/cas/TestUtils.java | /*
* Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license
* distributed with this file and available online at
* http://www.ja-sig.org/products/cas/overview/license/
*/
package org.jasig.cas;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.jasig.cas.authentication.Authentication;
import org.jasig.cas.authentication.ImmutableAuthentication;
import org.jasig.cas.authentication.principal.HttpBasedServiceCredentials;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.authentication.principal.SimplePrincipal;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.jasig.cas.authentication.principal.SimpleWebApplicationServiceImpl;
import org.jasig.cas.validation.Assertion;
import org.jasig.cas.validation.ImmutableAssertionImpl;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.validation.BindException;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.test.MockRequestContext;
/**
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.0.2
*/
public final class TestUtils {
public static final String CONST_USERNAME = "test";
private static final String CONST_PASSWORD = "test1";
private static final String CONST_BAD_URL = "http://www.acs.rutgers.edu";
private static final String CONST_CREDENTIALS = "credentials";
private static final String CONST_WEBFLOW_BIND_EXCEPTION = "org.springframework.validation.BindException.credentials";
private static final String[] CONST_NO_PRINCIPALS = new String[0];
public static final String CONST_EXCEPTION_EXPECTED = "Exception expected.";
public static final String CONST_EXCEPTION_NON_EXPECTED = "Exception not expected.";
public static final String CONST_GOOD_URL = "https://wwws.mint.com/";
private TestUtils() {
// do not instanciate
}
public static UsernamePasswordCredentials getCredentialsWithSameUsernameAndPassword() {
return getCredentialsWithSameUsernameAndPassword(CONST_USERNAME);
}
public static UsernamePasswordCredentials getCredentialsWithSameUsernameAndPassword(
final String username) {
return getCredentialsWithDifferentUsernameAndPassword(username,
username);
}
public static UsernamePasswordCredentials getCredentialsWithDifferentUsernameAndPassword() {
return getCredentialsWithDifferentUsernameAndPassword(CONST_USERNAME,
CONST_PASSWORD);
}
public static UsernamePasswordCredentials getCredentialsWithDifferentUsernameAndPassword(
final String username, final String password) {
// noinspection LocalVariableOfConcreteClass
final UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials();
usernamePasswordCredentials.setUsername(username);
usernamePasswordCredentials.setPassword(password);
return usernamePasswordCredentials;
}
public static HttpBasedServiceCredentials getHttpBasedServiceCredentials() {
return getHttpBasedServiceCredentials(CONST_GOOD_URL);
}
public static HttpBasedServiceCredentials getBadHttpBasedServiceCredentials() {
return getHttpBasedServiceCredentials(CONST_BAD_URL);
}
public static HttpBasedServiceCredentials getHttpBasedServiceCredentials(
final String url) {
try {
return new HttpBasedServiceCredentials(new URL(url));
} catch (MalformedURLException e) {
throw new IllegalArgumentException();
}
}
public static Principal getPrincipal() {
return getPrincipal(CONST_USERNAME);
}
public static Principal getPrincipal(final String name) {
return new SimplePrincipal(name);
}
public static Service getService() {
return getService(CONST_USERNAME);
}
public static Service getService(final String name) {
final MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("service", name);
return SimpleWebApplicationServiceImpl.createServiceFrom(request);
}
public static Authentication getAuthentication() {
return new ImmutableAuthentication(getPrincipal());
}
public static Authentication getAuthenticationWithService() {
return new ImmutableAuthentication(getService());
}
public static Authentication getAuthentication(final String name) {
return new ImmutableAuthentication(getPrincipal(name));
}
public static Assertion getAssertion(final boolean fromNewLogin) {
return getAssertion(fromNewLogin, CONST_NO_PRINCIPALS);
}
public static Assertion getAssertion(final boolean fromNewLogin,
final String[] extraPrincipals) {
final List<Authentication> list = new ArrayList<Authentication>();
list.add(TestUtils.getAuthentication());
for (int i = 0; i < extraPrincipals.length; i++) {
list.add(TestUtils.getAuthentication(extraPrincipals[i]));
}
return new ImmutableAssertionImpl(list, TestUtils.getService(),
fromNewLogin);
}
public static MockRequestContext getContext() {
return getContext(new MockHttpServletRequest());
}
public static MockRequestContext getContext(
final MockHttpServletRequest request) {
return getContext(request, new MockHttpServletResponse());
}
public static MockRequestContext getContext(
final MockHttpServletRequest request,
final MockHttpServletResponse response) {
final MockRequestContext context = new MockRequestContext();
context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
return context;
}
public static MockRequestContext getContextWithCredentials(
final MockHttpServletRequest request) {
return getContextWithCredentials(request, new MockHttpServletResponse());
}
public static MockRequestContext getContextWithCredentials(
final MockHttpServletRequest request,
final MockHttpServletResponse response) {
final MockRequestContext context = getContext(request, response);
context.getRequestScope().put(CONST_CREDENTIALS, TestUtils
.getCredentialsWithSameUsernameAndPassword());
context.getRequestScope().put(CONST_WEBFLOW_BIND_EXCEPTION,
new BindException(TestUtils
.getCredentialsWithSameUsernameAndPassword(),
CONST_CREDENTIALS));
return context;
}
}
| Switch to https://github.com for valid SSL host. Resolves build issues on some platforms (e.g. Linux).
| cas-server-core/src/test/java/org/jasig/cas/TestUtils.java | Switch to https://github.com for valid SSL host. Resolves build issues on some platforms (e.g. Linux). | <ide><path>as-server-core/src/test/java/org/jasig/cas/TestUtils.java
<ide> */
<ide> package org.jasig.cas;
<ide>
<del>import java.net.MalformedURLException;
<del>import java.net.URL;
<del>import java.util.ArrayList;
<del>import java.util.List;
<del>
<ide> import org.jasig.cas.authentication.Authentication;
<ide> import org.jasig.cas.authentication.ImmutableAuthentication;
<del>import org.jasig.cas.authentication.principal.HttpBasedServiceCredentials;
<del>import org.jasig.cas.authentication.principal.Principal;
<del>import org.jasig.cas.authentication.principal.Service;
<del>import org.jasig.cas.authentication.principal.SimplePrincipal;
<del>import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
<del>import org.jasig.cas.authentication.principal.SimpleWebApplicationServiceImpl;
<add>import org.jasig.cas.authentication.principal.*;
<ide> import org.jasig.cas.validation.Assertion;
<ide> import org.jasig.cas.validation.ImmutableAssertionImpl;
<ide> import org.springframework.mock.web.MockHttpServletRequest;
<ide> import org.springframework.validation.BindException;
<ide> import org.springframework.webflow.context.servlet.ServletExternalContext;
<ide> import org.springframework.webflow.test.MockRequestContext;
<add>
<add>import java.net.MalformedURLException;
<add>import java.net.URL;
<add>import java.util.ArrayList;
<add>import java.util.List;
<ide>
<ide> /**
<ide> * @author Scott Battaglia
<ide>
<ide> public static final String CONST_EXCEPTION_NON_EXPECTED = "Exception not expected.";
<ide>
<del> public static final String CONST_GOOD_URL = "https://wwws.mint.com/";
<add> public static final String CONST_GOOD_URL = "https://github.com/";
<ide>
<ide> private TestUtils() {
<ide> // do not instanciate |
|
Java | mit | e7c9680dd24a84229df234abf82277115d3f4f00 | 0 | wmcmahan/react-native-calendar-events,wmcmahan/react-native-calendar-events,wmcmahan/react-native-calendar-events | package com.calendarevents;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.SharedPreferences;
import android.Manifest;
import android.net.Uri;
import android.provider.CalendarContract;
import androidx.core.content.ContextCompat;
import android.database.Cursor;
import android.accounts.Account;
import android.accounts.AccountManager;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.bridge.Dynamic;
import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener;
import java.sql.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.TimeZone;
import android.util.Log;
public class RNCalendarEvents extends ReactContextBaseJavaModule implements PermissionListener {
private static int PERMISSION_REQUEST_CODE = 37;
private final ReactContext reactContext;
private static final String RNC_PREFS = "REACT_NATIVE_CALENDAR_PREFERENCES";
private static final HashMap<Integer, Promise> permissionsPromises = new HashMap<>();
public RNCalendarEvents(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}
@Override
public String getName() {
return "RNCalendarEvents";
}
//region Calendar Permissions
private void requestCalendarReadWritePermission(final Promise promise)
{
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
promise.reject("E_ACTIVITY_DOES_NOT_EXIST", "Activity doesn't exist");
return;
}
if (!(currentActivity instanceof PermissionAwareActivity)) {
promise.reject("E_ACTIVITY_NOT_PERMISSION_AWARE", "Activity does not implement the PermissionAwareActivity interface");
return;
}
PermissionAwareActivity activity = (PermissionAwareActivity)currentActivity;
PERMISSION_REQUEST_CODE++;
permissionsPromises.put(PERMISSION_REQUEST_CODE, promise);
activity.requestPermissions(new String[]{
Manifest.permission.WRITE_CALENDAR,
Manifest.permission.READ_CALENDAR
}, PERMISSION_REQUEST_CODE, this);
}
@Override
public boolean onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (permissionsPromises.containsKey(requestCode)) {
// If request is cancelled, the result arrays are empty.
Promise permissionsPromise = permissionsPromises.get(requestCode);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
permissionsPromise.resolve("authorized");
} else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
permissionsPromise.resolve("denied");
} else if (permissionsPromises.size() == 1) {
permissionsPromise.reject("permissions - unknown error", grantResults.length > 0 ? String.valueOf(grantResults[0]) : "Request was cancelled");
}
permissionsPromises.remove(requestCode);
}
return permissionsPromises.size() == 0;
}
private boolean haveCalendarReadWritePermissions() {
int writePermission = ContextCompat.checkSelfPermission(reactContext, Manifest.permission.WRITE_CALENDAR);
int readPermission = ContextCompat.checkSelfPermission(reactContext, Manifest.permission.READ_CALENDAR);
return writePermission == PackageManager.PERMISSION_GRANTED &&
readPermission == PackageManager.PERMISSION_GRANTED;
}
private boolean shouldShowRequestPermissionRationale() {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
Log.w(this.getName(), "Activity doesn't exist");
return false;
}
if (!(currentActivity instanceof PermissionAwareActivity)) {
Log.w(this.getName(), "Activity does not implement the PermissionAwareActivity interface");
return false;
}
PermissionAwareActivity activity = (PermissionAwareActivity)currentActivity;
return activity.shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CALENDAR);
}
//endregion
private WritableNativeArray findEventCalendars() {
Cursor cursor;
ContentResolver cr = reactContext.getContentResolver();
Uri uri = CalendarContract.Calendars.CONTENT_URI;
String IS_PRIMARY = CalendarContract.Calendars.IS_PRIMARY == null ? "0" : CalendarContract.Calendars.IS_PRIMARY;
cursor = cr.query(uri, new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.ACCOUNT_NAME,
IS_PRIMARY,
CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
CalendarContract.Calendars.ALLOWED_AVAILABILITY,
CalendarContract.Calendars.ACCOUNT_TYPE,
CalendarContract.Calendars.CALENDAR_COLOR
}, null, null, null);
return serializeEventCalendars(cursor);
}
private WritableNativeMap findCalendarById(String calendarID) {
WritableNativeMap result;
Cursor cursor;
ContentResolver cr = reactContext.getContentResolver();
Uri uri = ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, Integer.parseInt(calendarID));
String IS_PRIMARY = CalendarContract.Calendars.IS_PRIMARY == null ? "0" : CalendarContract.Calendars.IS_PRIMARY;
cursor = cr.query(uri, new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.ACCOUNT_NAME,
IS_PRIMARY,
CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
CalendarContract.Calendars.ALLOWED_AVAILABILITY,
CalendarContract.Calendars.ACCOUNT_TYPE,
CalendarContract.Calendars.CALENDAR_COLOR
}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
result = serializeEventCalendar(cursor);
cursor.close();
} else {
result = null;
}
return result;
}
private Integer calAccessConstantMatchingString(String string) {
if (string.equals("contributor")) {
return CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR;
}
if (string.equals("editor")) {
return CalendarContract.Calendars.CAL_ACCESS_EDITOR;
}
if (string.equals("freebusy")) {
return CalendarContract.Calendars.CAL_ACCESS_FREEBUSY;
}
if (string.equals("override")) {
return CalendarContract.Calendars.CAL_ACCESS_OVERRIDE;
}
if (string.equals("owner")) {
return CalendarContract.Calendars.CAL_ACCESS_OWNER;
}
if (string.equals("read")) {
return CalendarContract.Calendars.CAL_ACCESS_READ;
}
if (string.equals("respond")) {
return CalendarContract.Calendars.CAL_ACCESS_RESPOND;
}
if (string.equals("root")) {
return CalendarContract.Calendars.CAL_ACCESS_ROOT;
}
return CalendarContract.Calendars.CAL_ACCESS_NONE;
}
private int addCalendar(ReadableMap details) throws Exception, SecurityException {
ContentResolver cr = reactContext.getContentResolver();
ContentValues calendarValues = new ContentValues();
// required fields for new calendars
if (!details.hasKey("source")) {
throw new Exception("new calendars require `source` object");
}
if (!details.hasKey("name")) {
throw new Exception("new calendars require `name`");
}
if (!details.hasKey("title")) {
throw new Exception("new calendars require `title`");
}
if (!details.hasKey("color")) {
throw new Exception("new calendars require `color`");
}
if (!details.hasKey("accessLevel")) {
throw new Exception("new calendars require `accessLevel`");
}
if (!details.hasKey("ownerAccount")) {
throw new Exception("new calendars require `ownerAccount`");
}
ReadableMap source = details.getMap("source");
if (!source.hasKey("name")) {
throw new Exception("new calendars require a `source` object with a `name`");
}
Boolean isLocalAccount = false;
if (source.hasKey("isLocalAccount")) {
isLocalAccount = source.getBoolean("isLocalAccount");
}
if (!source.hasKey("type") && isLocalAccount == false) {
throw new Exception("new calendars require a `source` object with a `type`, or `isLocalAccount`: true");
}
calendarValues.put(CalendarContract.Calendars.ACCOUNT_NAME, source.getString("name"));
calendarValues.put(CalendarContract.Calendars.ACCOUNT_TYPE, isLocalAccount ? CalendarContract.ACCOUNT_TYPE_LOCAL : source.getString("type"));
calendarValues.put(CalendarContract.Calendars.CALENDAR_COLOR, details.getInt("color"));
calendarValues.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, calAccessConstantMatchingString(details.getString("accessLevel")));
calendarValues.put(CalendarContract.Calendars.OWNER_ACCOUNT, details.getString("ownerAccount"));
calendarValues.put(CalendarContract.Calendars.NAME, details.getString("name"));
calendarValues.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, details.getString("title"));
// end required fields
Uri.Builder uriBuilder = CalendarContract.Calendars.CONTENT_URI.buildUpon();
uriBuilder.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true");
uriBuilder.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, source.getString("name"));
uriBuilder.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, isLocalAccount ? CalendarContract.ACCOUNT_TYPE_LOCAL : source.getString("type"));
Uri calendarsUri = uriBuilder.build();
Uri calendarUri = cr.insert(calendarsUri, calendarValues);
return Integer.parseInt(calendarUri.getLastPathSegment());
}
private boolean removeCalendar(String calendarID) {
int rows = 0;
try {
ContentResolver cr = reactContext.getContentResolver();
Uri uri = ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, (long) Integer.parseInt(calendarID));
rows = cr.delete(uri, null, null);
} catch (Exception e) {
e.printStackTrace();
}
return rows > 0;
}
private WritableNativeArray findAttendeesByEventId(String eventID) {
WritableNativeArray result;
Cursor cursor;
ContentResolver cr = reactContext.getContentResolver();
String query = "(" + CalendarContract.Attendees.EVENT_ID + " = ?)";
String[] args = new String[]{eventID};
cursor = cr.query(CalendarContract.Attendees.CONTENT_URI, new String[]{
CalendarContract.Attendees._ID,
CalendarContract.Attendees.EVENT_ID,
CalendarContract.Attendees.ATTENDEE_NAME,
CalendarContract.Attendees.ATTENDEE_EMAIL,
CalendarContract.Attendees.ATTENDEE_TYPE,
CalendarContract.Attendees.ATTENDEE_RELATIONSHIP,
CalendarContract.Attendees.ATTENDEE_STATUS,
CalendarContract.Attendees.ATTENDEE_IDENTITY,
CalendarContract.Attendees.ATTENDEE_ID_NAMESPACE
}, query, args, null);
if (cursor != null && cursor.moveToFirst()) {
result = serializeAttendeeCalendar(cursor);
cursor.close();
} else {
WritableNativeArray emptyAttendees = new WritableNativeArray();
result = emptyAttendees;
}
return result;
}
//region Event Accessors
private WritableNativeArray findEvents(Dynamic startDate, Dynamic endDate, ReadableArray calendars) {
String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar eStartDate = Calendar.getInstance();
Calendar eEndDate = Calendar.getInstance();
try {
if (startDate.getType() == ReadableType.String) {
eStartDate.setTime(sdf.parse(startDate.asString()));
} else if (startDate.getType() == ReadableType.Number) {
eStartDate.setTimeInMillis((long)startDate.asDouble());
}
if (endDate.getType() == ReadableType.String) {
eEndDate.setTime(sdf.parse(endDate.asString()));
} else if (endDate.getType() == ReadableType.Number) {
eEndDate.setTimeInMillis((long)endDate.asDouble());
}
} catch (ParseException e) {
e.printStackTrace();
}
Cursor cursor;
ContentResolver cr = reactContext.getContentResolver();
Uri.Builder uriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(uriBuilder, eStartDate.getTimeInMillis());
ContentUris.appendId(uriBuilder, eEndDate.getTimeInMillis());
Uri uri = uriBuilder.build();
String selection = "((" + CalendarContract.Instances.BEGIN + " >= " + eStartDate.getTimeInMillis() + ") " +
"AND (" + CalendarContract.Instances.END + " <= " + eEndDate.getTimeInMillis() + ") " +
"AND (" + CalendarContract.Instances.VISIBLE + " = 1) " +
"AND (" + CalendarContract.Instances.STATUS + " IS NOT " + CalendarContract.Events.STATUS_CANCELED + ") ";
if (calendars.size() > 0) {
String calendarQuery = "AND (";
for (int i = 0; i < calendars.size(); i++) {
calendarQuery += CalendarContract.Instances.CALENDAR_ID + " = " + calendars.getString(i);
if (i != calendars.size() - 1) {
calendarQuery += " OR ";
}
}
calendarQuery += ")";
selection += calendarQuery;
}
selection += ")";
cursor = cr.query(uri, new String[]{
CalendarContract.Instances.EVENT_ID,
CalendarContract.Instances.TITLE,
CalendarContract.Instances.DESCRIPTION,
CalendarContract.Instances.BEGIN,
CalendarContract.Instances.END,
CalendarContract.Instances.ALL_DAY,
CalendarContract.Instances.EVENT_LOCATION,
CalendarContract.Instances.RRULE,
CalendarContract.Instances.CALENDAR_ID,
CalendarContract.Instances.AVAILABILITY,
CalendarContract.Instances.HAS_ALARM,
CalendarContract.Instances.ORIGINAL_ID,
CalendarContract.Instances.EVENT_ID,
CalendarContract.Instances.DURATION,
CalendarContract.Instances.ORIGINAL_SYNC_ID,
}, selection, null, null);
return serializeEvents(cursor);
}
private WritableNativeMap findEventById(String eventID) {
WritableNativeMap result;
Cursor cursor = null;
ContentResolver cr = reactContext.getContentResolver();
Uri uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, Integer.parseInt(eventID));
String selection = "((" + CalendarContract.Events.DELETED + " != 1))";
cursor = cr.query(uri, new String[]{
CalendarContract.Events._ID,
CalendarContract.Events.TITLE,
CalendarContract.Events.DESCRIPTION,
CalendarContract.Events.DTSTART,
CalendarContract.Events.DTEND,
CalendarContract.Events.ALL_DAY,
CalendarContract.Events.EVENT_LOCATION,
CalendarContract.Events.RRULE,
CalendarContract.Events.CALENDAR_ID,
CalendarContract.Events.AVAILABILITY,
CalendarContract.Events.HAS_ALARM,
CalendarContract.Instances.DURATION
}, selection, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
result = serializeEvent(cursor);
} else {
result = null;
}
cursor.close();
return result;
}
private WritableNativeMap findEventInstanceById(String eventID) {
WritableNativeMap result;
Cursor cursor;
ContentResolver cr = reactContext.getContentResolver();
Uri.Builder uriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(uriBuilder, Long.MIN_VALUE);
ContentUris.appendId(uriBuilder, Long.MAX_VALUE);
Uri uri = uriBuilder.build();
String selection = "(Instances._ID = " + eventID + ")";
cursor = cr.query(uri, new String[]{
CalendarContract.Instances._ID,
CalendarContract.Instances.TITLE,
CalendarContract.Instances.DESCRIPTION,
CalendarContract.Instances.BEGIN,
CalendarContract.Instances.END,
CalendarContract.Instances.ALL_DAY,
CalendarContract.Instances.EVENT_LOCATION,
CalendarContract.Instances.RRULE,
CalendarContract.Instances.CALENDAR_ID,
CalendarContract.Instances.AVAILABILITY,
CalendarContract.Instances.HAS_ALARM,
CalendarContract.Instances.ORIGINAL_ID,
CalendarContract.Instances.EVENT_ID,
CalendarContract.Instances.DURATION
}, selection, null, null);
if (cursor != null && cursor.moveToFirst()) {
result = serializeEvent(cursor);
cursor.close();
} else {
result = null;
}
return result;
}
private int addEvent(String title, ReadableMap details, ReadableMap options) throws ParseException {
String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
boolean skipTimezone = false;
if(details.hasKey("skipAndroidTimezone") && details.getBoolean("skipAndroidTimezone")){
skipTimezone = true;
}
if(!skipTimezone){
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
}
ContentResolver cr = reactContext.getContentResolver();
ContentValues eventValues = new ContentValues();
if (title != null) {
eventValues.put(CalendarContract.Events.TITLE, title);
}
if (details.hasKey("description")) {
eventValues.put(CalendarContract.Events.DESCRIPTION, details.getString("description"));
}
if (details.hasKey("location")) {
eventValues.put(CalendarContract.Events.EVENT_LOCATION, details.getString("location"));
}
if (details.hasKey("startDate")) {
Calendar startCal = Calendar.getInstance();
ReadableType type = details.getType("startDate");
try {
if (type == ReadableType.String) {
startCal.setTime(sdf.parse(details.getString("startDate")));
eventValues.put(CalendarContract.Events.DTSTART, startCal.getTimeInMillis());
} else if (type == ReadableType.Number) {
eventValues.put(CalendarContract.Events.DTSTART, (long)details.getDouble("startDate"));
}
} catch (ParseException e) {
e.printStackTrace();
throw e;
}
}
if (details.hasKey("endDate")) {
Calendar endCal = Calendar.getInstance();
ReadableType type = details.getType("endDate");
try {
if (type == ReadableType.String) {
endCal.setTime(sdf.parse(details.getString("endDate")));
eventValues.put(CalendarContract.Events.DTEND, endCal.getTimeInMillis());
} else if (type == ReadableType.Number) {
eventValues.put(CalendarContract.Events.DTEND, (long)details.getDouble("endDate"));
}
} catch (ParseException e) {
e.printStackTrace();
throw e;
}
}
if (details.hasKey("recurrence")) {
String rule = createRecurrenceRule(details.getString("recurrence"), null, null, null, null, null, null);
if (rule != null) {
eventValues.put(CalendarContract.Events.RRULE, rule);
}
}
if (details.hasKey("recurrenceRule")) {
ReadableMap recurrenceRule = details.getMap("recurrenceRule");
if (recurrenceRule.hasKey("frequency")) {
String frequency = recurrenceRule.getString("frequency");
String duration = "PT1H";
Integer interval = null;
Integer occurrence = null;
String endDate = null;
ReadableArray daysOfWeek = null;
String weekStart = null;
Integer weekPositionInMonth = null;
if (recurrenceRule.hasKey("interval")) {
interval = recurrenceRule.getInt("interval");
}
if (recurrenceRule.hasKey("duration")) {
duration = recurrenceRule.getString("duration");
}
if (recurrenceRule.hasKey("occurrence")) {
occurrence = recurrenceRule.getInt("occurrence");
}
if (recurrenceRule.hasKey("endDate")) {
ReadableType type = recurrenceRule.getType("endDate");
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
if (type == ReadableType.String) {
endDate = format.format(sdf.parse(recurrenceRule.getString("endDate")));
} else if (type == ReadableType.Number) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis((long)recurrenceRule.getDouble("endDate"));
endDate = format.format(calendar.getTime());
}
}
if (recurrenceRule.hasKey("daysOfWeek")) {
daysOfWeek = recurrenceRule.getArray("daysOfWeek");
}
if (recurrenceRule.hasKey("weekStart")) {
weekStart = recurrenceRule.getString("weekStart");
}
if (recurrenceRule.hasKey("weekPositionInMonth")) {
weekPositionInMonth = recurrenceRule.getInt("weekPositionInMonth");
}
String rule = createRecurrenceRule(frequency, interval, endDate, occurrence, daysOfWeek, weekStart, weekPositionInMonth);
if (duration != null) {
eventValues.put(CalendarContract.Events.DURATION, duration);
}
if (rule != null) {
eventValues.put(CalendarContract.Events.RRULE, rule);
}
}
}
if (details.hasKey("allDay")) {
eventValues.put(CalendarContract.Events.ALL_DAY, details.getBoolean("allDay") ? 1 : 0);
}
if (details.hasKey("timeZone")) {
eventValues.put(CalendarContract.Events.EVENT_TIMEZONE, details.getString("timeZone"));
} else {
eventValues.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
}
if (details.hasKey("endTimeZone")) {
eventValues.put(CalendarContract.Events.EVENT_END_TIMEZONE, details.getString("endTimeZone"));
} else {
eventValues.put(CalendarContract.Events.EVENT_END_TIMEZONE, TimeZone.getDefault().getID());
}
if (details.hasKey("alarms")) {
eventValues.put(CalendarContract.Events.HAS_ALARM, true);
}
if (details.hasKey("availability")) {
eventValues.put(CalendarContract.Events.AVAILABILITY, availabilityConstantMatchingString(details.getString("availability")));
}
if (details.hasKey("id")) {
int eventID = Integer.parseInt(details.getString("id"));
WritableMap eventInstance = findEventById(details.getString("id"));
if (eventInstance != null) {
ReadableMap eventCalendar = eventInstance.getMap("calendar");
if (!options.hasKey("exceptionDate")) {
Uri updateUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID);
if (options.hasKey("sync") && options.getBoolean("sync")) {
syncCalendar(cr, eventInstance.getMap("calendar").getString("id"));
updateUri = eventUriAsSyncAdapter(updateUri, eventCalendar.getString("source"), eventCalendar.getString("type"));
}
cr.update(updateUri, eventValues, null, null);
} else {
Calendar exceptionStart = Calendar.getInstance();
ReadableType type = options.getType("exceptionDate");
try {
if (type == ReadableType.String) {
exceptionStart.setTime(sdf.parse(options.getString("exceptionDate")));
eventValues.put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, exceptionStart.getTimeInMillis());
} else if (type == ReadableType.Number) {
eventValues.put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, (long) options.getDouble("exceptionDate"));
}
} catch (ParseException e) {
e.printStackTrace();
throw e;
}
Uri exceptionUri = Uri.withAppendedPath(CalendarContract.Events.CONTENT_EXCEPTION_URI, Integer.toString(eventID));
if (options.hasKey("sync") && options.getBoolean("sync")) {
syncCalendar(cr, eventInstance.getMap("calendar").getString("id"));
eventUriAsSyncAdapter(exceptionUri, eventCalendar.getString("source"), eventCalendar.getString("type"));
}
try {
Uri eventUri = cr.insert(exceptionUri, eventValues);
if (eventUri != null) {
eventID = Integer.parseInt(eventUri.getLastPathSegment());
}
} catch (Exception e) {
Log.d(this.getName(), "Event exception error", e);
}
}
}
if (details.hasKey("alarms")) {
createRemindersForEvent(cr, Integer.parseInt(details.getString("id")), details.getArray("alarms"));
}
if (details.hasKey("attendees")) {
createAttendeesForEvent(cr, Integer.parseInt(details.getString("id")), details.getArray("attendees"));
}
return eventID;
} else {
WritableNativeMap calendar;
int eventID = -1;
if (details.hasKey("calendarId")) {
calendar = findCalendarById(details.getString("calendarId"));
if (calendar != null) {
eventValues.put(CalendarContract.Events.CALENDAR_ID, Integer.parseInt(calendar.getString("id")));
} else {
eventValues.put(CalendarContract.Events.CALENDAR_ID, 1);
}
} else {
calendar = findCalendarById("1");
eventValues.put(CalendarContract.Events.CALENDAR_ID, 1);
}
Uri createEventUri = CalendarContract.Events.CONTENT_URI;
if (options.hasKey("sync") && options.getBoolean("sync")) {
syncCalendar(cr, calendar.getString("id"));
createEventUri = eventUriAsSyncAdapter(CalendarContract.Events.CONTENT_URI, calendar.getString("source"), calendar.getString("type"));
}
Uri eventUri = cr.insert(createEventUri, eventValues);
if (eventUri != null) {
String rowId = eventUri.getLastPathSegment();
if (rowId != null) {
eventID = Integer.parseInt(rowId);
if (details.hasKey("alarms")) {
createRemindersForEvent(cr, eventID, details.getArray("alarms"));
}
if (details.hasKey("attendees")) {
createAttendeesForEvent(cr, eventID, details.getArray("attendees"));
}
return eventID;
}
}
return eventID;
}
}
private boolean removeEvent(String eventID, ReadableMap options) {
int rows = 0;
try {
ContentResolver cr = reactContext.getContentResolver();
WritableMap eventInstance = findEventById(eventID);
ReadableMap eventCalendar = eventInstance.getMap("calendar");
if (!options.hasKey("exceptionDate")) {
Uri uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, (long) Integer.parseInt(eventID));
if (options.hasKey("sync") && options.getBoolean("sync")) {
syncCalendar(cr, eventCalendar.getString("id"));
uri = eventUriAsSyncAdapter(uri, eventCalendar.getString("source"), eventCalendar.getString("type"));
}
rows = cr.delete(uri, null, null);
} else {
ContentValues eventValues = new ContentValues();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar exceptionStart = Calendar.getInstance();
ReadableType type = options.getType("exceptionDate");
try {
if (type == ReadableType.String) {
exceptionStart.setTime(sdf.parse(options.getString("exceptionDate")));
eventValues.put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, exceptionStart.getTimeInMillis());
} else if (type == ReadableType.Number) {
eventValues.put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, (long) options.getDouble("exceptionDate"));
}
} catch (ParseException e) {
e.printStackTrace();
throw e;
}
eventValues.put(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_CANCELED);
Uri uri = Uri.withAppendedPath(CalendarContract.Events.CONTENT_EXCEPTION_URI, eventID);
if (options.hasKey("sync") && options.getBoolean("sync")) {
uri = eventUriAsSyncAdapter(uri, eventCalendar.getString("source"), eventCalendar.getString("type"));
}
Uri exceptionUri = cr.insert(uri, eventValues);
if (exceptionUri != null) {
rows = 1;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return rows > 0;
}
//sync adaptors
private Uri eventUriAsSyncAdapter (Uri uri, String accountName, String accountType) {
uri = uri.buildUpon()
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, accountName)
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, accountType)
.build();
return uri;
}
public static void syncCalendar(ContentResolver cr, String calendarId) {
ContentValues values = new ContentValues();
values.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
values.put(CalendarContract.Calendars.VISIBLE, 1);
cr.update(ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, Long.parseLong(calendarId)), values, null, null);
}
//endregion
//region Attendees
private void createAttendeesForEvent(ContentResolver resolver, int eventID, ReadableArray attendees) {
Cursor cursor = CalendarContract.Attendees.query(resolver, eventID, new String[] {
CalendarContract.Attendees._ID
});
while (cursor.moveToNext()) {
long attendeeId = cursor.getLong(0);
Uri attendeeUri = ContentUris.withAppendedId(CalendarContract.Attendees.CONTENT_URI, attendeeId);
resolver.delete(attendeeUri, null, null);
}
cursor.close();
for (int i = 0; i < attendees.size(); i++) {
ReadableMap attendee = attendees.getMap(i);
ReadableType type = attendee.getType("url");
ReadableType fNameType = attendee.getType("firstName");
if (type == ReadableType.String) {
ContentValues attendeeValues = new ContentValues();
attendeeValues.put(CalendarContract.Attendees.EVENT_ID, eventID);
attendeeValues.put(CalendarContract.Attendees.ATTENDEE_EMAIL, attendee.getString("url"));
attendeeValues.put(CalendarContract.Attendees.ATTENDEE_RELATIONSHIP, CalendarContract.Attendees.RELATIONSHIP_ATTENDEE);
if (fNameType == ReadableType.String) {
attendeeValues.put(CalendarContract.Attendees.ATTENDEE_NAME, attendee.getString("firstName"));
}
resolver.insert(CalendarContract.Attendees.CONTENT_URI, attendeeValues);
}
}
}
//endregion
//region Reminders
private void createRemindersForEvent(ContentResolver resolver, int eventID, ReadableArray reminders) {
Cursor cursor = null;
if (resolver != null) {
cursor = CalendarContract.Reminders.query(resolver, eventID, new String[] {
CalendarContract.Reminders._ID
});
}
while (cursor != null && cursor.moveToNext()) {
Uri reminderUri = null;
long reminderId = cursor.getLong(0);
if (reminderId > 0) {
reminderUri = ContentUris.withAppendedId(CalendarContract.Reminders.CONTENT_URI, reminderId);
}
if (reminderUri != null) {
resolver.delete(reminderUri, null, null);
}
}
if (cursor != null) {
cursor.close();
}
for (int i = 0; i < reminders.size(); i++) {
ReadableMap reminder = reminders.getMap(i);
ReadableType type = reminder.getType("date");
if (type == ReadableType.Number) {
int minutes = reminder.getInt("date");
ContentValues reminderValues = new ContentValues();
reminderValues.put(CalendarContract.Reminders.EVENT_ID, eventID);
reminderValues.put(CalendarContract.Reminders.MINUTES, minutes);
reminderValues.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
resolver.insert(CalendarContract.Reminders.CONTENT_URI, reminderValues);
}
}
}
private WritableNativeArray findReminderByEventId(String eventID, long startDate) {
WritableNativeArray results = new WritableNativeArray();
ContentResolver cr = reactContext.getContentResolver();
String selection = "(" + CalendarContract.Reminders.EVENT_ID + " = ?)";
Cursor cursor = cr.query(CalendarContract.Reminders.CONTENT_URI, new String[]{
CalendarContract.Reminders.MINUTES
}, selection, new String[] {eventID}, null);
while (cursor != null && cursor.moveToNext()) {
WritableNativeMap alarm = new WritableNativeMap();
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis(startDate);
int minutes;
try {
minutes = cursor.getInt(0);
} catch (Exception e) {
Log.d(this.getName(), "Error parsing event minutes", e);
continue;
}
cal.add(Calendar.MINUTE, minutes);
alarm.putString("date", sdf.format(cal.getTime()));
results.pushMap(alarm);
}
if (cursor != null) {
cursor.close();
}
return results;
}
//endregion
//region Availability
private WritableNativeArray calendarAllowedAvailabilitiesFromDBString(String dbString) {
WritableNativeArray availabilitiesStrings = new WritableNativeArray();
for(String availabilityStr: dbString.split(",")) {
int availabilityId = -1;
try {
availabilityId = Integer.parseInt(availabilityStr);
} catch(NumberFormatException e) {
// Some devices seem to just use strings.
if (availabilityStr.equals("AVAILABILITY_BUSY")) {
availabilityId = CalendarContract.Events.AVAILABILITY_BUSY;
} else if (availabilityStr.equals("AVAILABILITY_FREE")) {
availabilityId = CalendarContract.Events.AVAILABILITY_FREE;
} else if (availabilityStr.equals("AVAILABILITY_TENTATIVE")) {
availabilityId = CalendarContract.Events.AVAILABILITY_TENTATIVE;
}
}
switch(availabilityId) {
case CalendarContract.Events.AVAILABILITY_BUSY:
availabilitiesStrings.pushString("busy");
break;
case CalendarContract.Events.AVAILABILITY_FREE:
availabilitiesStrings.pushString("free");
break;
case CalendarContract.Events.AVAILABILITY_TENTATIVE:
availabilitiesStrings.pushString("tentative");
break;
}
}
return availabilitiesStrings;
}
private String availabilityStringMatchingConstant(Integer constant)
{
switch(constant) {
case CalendarContract.Events.AVAILABILITY_BUSY:
default:
return "busy";
case CalendarContract.Events.AVAILABILITY_FREE:
return "free";
case CalendarContract.Events.AVAILABILITY_TENTATIVE:
return "tentative";
}
}
private Integer availabilityConstantMatchingString(String string) throws IllegalArgumentException {
if (string.equals("free")){
return CalendarContract.Events.AVAILABILITY_FREE;
}
if (string.equals("tentative")){
return CalendarContract.Events.AVAILABILITY_TENTATIVE;
}
return CalendarContract.Events.AVAILABILITY_BUSY;
}
//endregion
private String ReadableArrayToString (ReadableArray strArr) {
ArrayList<Object> array = strArr.toArrayList();
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < array.size(); i++) {
strBuilder.append(array.get(i).toString() + ',');
}
String newString = strBuilder.toString();
newString = newString.substring(0, newString.length() - 1);
return newString;
}
//region Recurrence Rule
private String createRecurrenceRule(String recurrence, Integer interval, String endDate, Integer occurrence, ReadableArray daysOfWeek, String weekStart, Integer weekPositionInMonth) {
String rrule;
if (recurrence.equals("daily")) {
rrule= "FREQ=DAILY";
} else if (recurrence.equals("weekly")) {
rrule = "FREQ=WEEKLY";
} else if (recurrence.equals("monthly")) {
rrule = "FREQ=MONTHLY";
} else if (recurrence.equals("yearly")) {
rrule = "FREQ=YEARLY";
} else {
return null;
}
if (daysOfWeek != null && recurrence.equals("weekly")) {
rrule += ";BYDAY=" + ReadableArrayToString(daysOfWeek);
}
if (recurrence.equals("monthly") && daysOfWeek != null && weekPositionInMonth != null) {
rrule += ";BYSETPOS=" + weekPositionInMonth;
rrule += ";BYDAY=" + ReadableArrayToString(daysOfWeek);
}
if (weekStart != null) {
rrule += ";WKST=" + weekStart;
}
if (interval != null) {
rrule += ";INTERVAL=" + interval;
}
if (endDate != null) {
rrule += ";UNTIL=" + endDate;
} else if (occurrence != null) {
rrule += ";COUNT=" + occurrence;
}
return rrule;
}
//endregion
// region Serialize Events
private WritableNativeArray serializeEvents(Cursor cursor) {
WritableNativeArray results = new WritableNativeArray();
if (cursor != null) {
while (cursor.moveToNext()) {
results.pushMap(serializeEvent(cursor));
}
cursor.close();
}
return results;
}
private WritableNativeMap serializeEvent(Cursor cursor) {
WritableNativeMap event = new WritableNativeMap();
String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar foundStartDate = Calendar.getInstance();
Calendar foundEndDate = Calendar.getInstance();
boolean allDay = false;
String startDateUTC = "";
String endDateUTC = "";
if (cursor.getString(3) != null) {
foundStartDate.setTimeInMillis(Long.parseLong(cursor.getString(3)));
startDateUTC = sdf.format(foundStartDate.getTime());
}
if (cursor.getString(4) != null) {
foundEndDate.setTimeInMillis(Long.parseLong(cursor.getString(4)));
endDateUTC = sdf.format(foundEndDate.getTime());
}
if (cursor.getString(5) != null) {
allDay = cursor.getInt(5) != 0;
}
if (cursor.getString(7) != null) {
WritableNativeMap recurrenceRule = new WritableNativeMap();
String[] recurrenceRules = cursor.getString(7).split(";");
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
if (recurrenceRules.length > 0 && recurrenceRules[0].split("=").length > 1) {
event.putString("recurrence", recurrenceRules[0].split("=")[1].toLowerCase());
recurrenceRule.putString("frequency", recurrenceRules[0].split("=")[1].toLowerCase());
}
if (cursor.getColumnIndex(CalendarContract.Events.DURATION) != -1 && cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DURATION)) != null) {
recurrenceRule.putString("duration", cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DURATION)));
}
if (recurrenceRules.length >= 2 && recurrenceRules[1].split("=")[0].equals("INTERVAL")) {
recurrenceRule.putInt("interval", Integer.parseInt(recurrenceRules[1].split("=")[1]));
}
if (recurrenceRules.length >= 3) {
if (recurrenceRules[2].split("=")[0].equals("UNTIL")) {
try {
recurrenceRule.putString("endDate", sdf.format(format.parse(recurrenceRules[2].split("=")[1])));
} catch (ParseException e) {
e.printStackTrace();
}
} else if (recurrenceRules[2].split("=")[0].equals("COUNT")) {
recurrenceRule.putInt("occurrence", Integer.parseInt(recurrenceRules[2].split("=")[1]));
}
}
event.putMap("recurrenceRule", recurrenceRule);
}
event.putString("id", cursor.getString(0));
event.putMap("calendar", findCalendarById(cursor.getString(cursor.getColumnIndex("calendar_id"))));
event.putString("title", cursor.getString(cursor.getColumnIndex("title")));
event.putString("description", cursor.getString(2));
event.putString("startDate", startDateUTC);
event.putString("endDate", endDateUTC);
event.putBoolean("allDay", allDay);
event.putString("location", cursor.getString(6));
event.putString("availability", availabilityStringMatchingConstant(cursor.getInt(9)));
event.putArray("attendees", (WritableArray) findAttendeesByEventId(cursor.getString(0)));
if (cursor.getInt(10) > 0) {
event.putArray("alarms", findReminderByEventId(cursor.getString(0), Long.parseLong(cursor.getString(3))));
} else {
WritableNativeArray emptyAlarms = new WritableNativeArray();
event.putArray("alarms", emptyAlarms);
}
if (cursor.getColumnIndex(CalendarContract.Events.ORIGINAL_ID) != -1 && cursor.getString(cursor.getColumnIndex(CalendarContract.Events.ORIGINAL_ID)) != null) {
event.putString("originalId", cursor.getString(cursor.getColumnIndex(CalendarContract.Events.ORIGINAL_ID)));
}
if (cursor.getColumnIndex(CalendarContract.Instances.ORIGINAL_SYNC_ID) != -1 && cursor.getString(cursor.getColumnIndex(CalendarContract.Instances.ORIGINAL_SYNC_ID)) != null) {
event.putString("syncId", cursor.getString(cursor.getColumnIndex(CalendarContract.Instances.ORIGINAL_SYNC_ID)));
}
return event;
}
private WritableNativeArray serializeEventCalendars(Cursor cursor) {
WritableNativeArray results = new WritableNativeArray();
if (cursor != null) {
while (cursor.moveToNext()) {
results.pushMap(serializeEventCalendar(cursor));
}
cursor.close();
}
return results;
}
private WritableNativeMap serializeEventCalendar(Cursor cursor) {
WritableNativeMap calendar = new WritableNativeMap();
calendar.putString("id", cursor.getString(0));
calendar.putString("title", cursor.getString(1));
calendar.putString("source", cursor.getString(2));
calendar.putArray("allowedAvailabilities", calendarAllowedAvailabilitiesFromDBString(cursor.getString(5)));
calendar.putString("type", cursor.getString(6));
String colorHex = "#FFFFFF";
try {
colorHex = String.format("#%06X", (0xFFFFFF & cursor.getInt(7)));
} catch (Exception e) {
Log.d(this.getName(), "Error parsing calendar color", e);
}
calendar.putString("color", colorHex);
if (cursor.getString(3) != null) {
calendar.putBoolean("isPrimary", cursor.getString(3).equals("1"));
}
int accesslevel = cursor.getInt(4);
if (accesslevel == CalendarContract.Calendars.CAL_ACCESS_ROOT ||
accesslevel == CalendarContract.Calendars.CAL_ACCESS_OWNER ||
accesslevel == CalendarContract.Calendars.CAL_ACCESS_EDITOR ||
accesslevel == CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR) {
calendar.putBoolean("allowsModifications", true);
} else {
calendar.putBoolean("allowsModifications", false);
}
return calendar;
}
private WritableNativeArray serializeAttendeeCalendar(Cursor cursor) {
WritableNativeArray results = new WritableNativeArray();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
WritableNativeMap attendee = new WritableNativeMap();
attendee.putString("name", cursor.getString( 2));
attendee.putString("email", cursor.getString(3));
attendee.putString("type", cursor.getString(4));
attendee.putString("relationship", cursor.getString(5));
attendee.putString("status", cursor.getString(6));
attendee.putString("identity", cursor.getString(7));
attendee.putString("id_namespace", cursor.getString(8));
results.pushMap(attendee);
}
return results;
}
// endregion
//region React Native Methods
@ReactMethod
public void getCalendarPermissions(Promise promise) {
SharedPreferences sharedPreferences = reactContext.getSharedPreferences(RNC_PREFS, ReactContext.MODE_PRIVATE);
boolean permissionRequested = sharedPreferences.getBoolean("permissionRequested", false);
if (this.haveCalendarReadWritePermissions()) {
promise.resolve("authorized");
} else if (!permissionRequested) {
promise.resolve("undetermined");
} else if(this.shouldShowRequestPermissionRationale()) {
promise.resolve("denied");
} else {
promise.resolve("restricted");
}
}
@ReactMethod
public void requestCalendarPermissions(Promise promise) {
SharedPreferences sharedPreferences = reactContext.getSharedPreferences(RNC_PREFS, ReactContext.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("permissionRequested", true);
editor.apply();
if (this.haveCalendarReadWritePermissions()) {
promise.resolve("authorized");
} else {
this.requestCalendarReadWritePermission(promise);
}
}
@ReactMethod
public void findCalendars(final Promise promise) {
if (this.haveCalendarReadWritePermissions()) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
WritableArray calendars = findEventCalendars();
promise.resolve(calendars);
}
});
thread.start();
} catch (Exception e) {
promise.reject("calendar request error", e.getMessage());
}
} else {
promise.reject("add event error", "you don't have permissions to retrieve an event to the users calendar");
}
}
@ReactMethod
public void saveCalendar(final ReadableMap options, final Promise promise) {
if (!this.haveCalendarReadWritePermissions()) {
promise.reject("save calendar error", "unauthorized to access calendar");
return;
}
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
Integer calendarID = addCalendar(options);
promise.resolve(calendarID.toString());
} catch (Exception e) {
promise.reject("save calendar error", e.getMessage());
}
}
});
thread.start();
} catch (Exception e) {
promise.reject("save calendar error", "Calendar could not be saved", e);
}
}
@ReactMethod
public void removeCalendar(final String CalendarID, final Promise promise) {
if (this.haveCalendarReadWritePermissions()) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
boolean successful = removeCalendar(CalendarID);
promise.resolve(successful);
}
});
thread.start();
} catch (Exception e) {
promise.reject("error removing calendar", e.getMessage());
}
} else {
promise.reject("remove calendar error", "you don't have permissions to remove a calendar");
}
}
@ReactMethod
public void saveEvent(final String title, final ReadableMap details, final ReadableMap options, final Promise promise) {
if (this.haveCalendarReadWritePermissions()) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
int eventId;
try {
eventId = addEvent(title, details, options);
if (eventId > -1) {
promise.resolve(Integer.toString(eventId));
} else {
promise.reject("add event error", "Unable to save event");
}
} catch (ParseException e) {
promise.reject("add event error", e.getMessage());
}
}
});
thread.start();
} catch (Exception e) {
promise.reject("add event error", e.getMessage());
}
} else {
promise.reject("add event error", "you don't have permissions to add an event to the users calendar");
}
}
@ReactMethod
public void findAllEvents(final Dynamic startDate, final Dynamic endDate, final ReadableArray calendars, final Promise promise) {
if (this.haveCalendarReadWritePermissions()) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
WritableNativeArray results = findEvents(startDate, endDate, calendars);
promise.resolve(results);
}
});
thread.start();
} catch (Exception e) {
promise.reject("find event error", e.getMessage());
}
} else {
promise.reject("find event error", "you don't have permissions to read an event from the users calendar");
}
}
@ReactMethod
public void findById(final String eventID, final Promise promise) {
if (this.haveCalendarReadWritePermissions()) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
WritableMap results = findEventById(eventID);
promise.resolve(results);
}
});
thread.start();
} catch (Exception e) {
promise.reject("find event error", e.getMessage());
}
} else {
promise.reject("find event error", "you don't have permissions to read an event from the users calendar");
}
}
@ReactMethod
public void removeEvent(final String eventID, final ReadableMap options, final Promise promise) {
if (this.haveCalendarReadWritePermissions()) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
boolean successful = removeEvent(eventID, options);
promise.resolve(successful);
}
});
thread.start();
} catch (Exception e) {
promise.reject("error removing event", e.getMessage());
}
} else {
promise.reject("remove event error", "you don't have permissions to remove an event from the users calendar");
}
}
@ReactMethod
public void openEventInCalendar(int eventID) {
Uri uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID);
Intent sendIntent = new Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setData(uri);
if (sendIntent.resolveActivity(reactContext.getPackageManager()) != null) {
reactContext.startActivity(sendIntent);
}
}
@ReactMethod
public void uriForCalendar(Promise promise) {
promise.resolve(CalendarContract.Events.CONTENT_URI.toString());
}
//endregion
}
| android/src/main/java/com/calendarevents/RNCalendarEvents.java | package com.calendarevents;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.SharedPreferences;
import android.Manifest;
import android.net.Uri;
import android.provider.CalendarContract;
import androidx.core.content.ContextCompat;
import android.database.Cursor;
import android.accounts.Account;
import android.accounts.AccountManager;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.bridge.Dynamic;
import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener;
import java.sql.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.TimeZone;
import android.util.Log;
public class RNCalendarEvents extends ReactContextBaseJavaModule implements PermissionListener {
private static int PERMISSION_REQUEST_CODE = 37;
private final ReactContext reactContext;
private static final String RNC_PREFS = "REACT_NATIVE_CALENDAR_PREFERENCES";
private static final HashMap<Integer, Promise> permissionsPromises = new HashMap<>();
public RNCalendarEvents(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}
@Override
public String getName() {
return "RNCalendarEvents";
}
//region Calendar Permissions
private void requestCalendarReadWritePermission(final Promise promise)
{
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
promise.reject("E_ACTIVITY_DOES_NOT_EXIST", "Activity doesn't exist");
return;
}
if (!(currentActivity instanceof PermissionAwareActivity)) {
promise.reject("E_ACTIVITY_NOT_PERMISSION_AWARE", "Activity does not implement the PermissionAwareActivity interface");
return;
}
PermissionAwareActivity activity = (PermissionAwareActivity)currentActivity;
PERMISSION_REQUEST_CODE++;
permissionsPromises.put(PERMISSION_REQUEST_CODE, promise);
activity.requestPermissions(new String[]{
Manifest.permission.WRITE_CALENDAR,
Manifest.permission.READ_CALENDAR
}, PERMISSION_REQUEST_CODE, this);
}
@Override
public boolean onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (permissionsPromises.containsKey(requestCode)) {
// If request is cancelled, the result arrays are empty.
Promise permissionsPromise = permissionsPromises.get(requestCode);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
permissionsPromise.resolve("authorized");
} else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
permissionsPromise.resolve("denied");
} else if (permissionsPromises.size() == 1) {
permissionsPromise.reject("permissions - unknown error", grantResults.length > 0 ? String.valueOf(grantResults[0]) : "Request was cancelled");
}
permissionsPromises.remove(requestCode);
}
return permissionsPromises.size() == 0;
}
private boolean haveCalendarReadWritePermissions() {
int writePermission = ContextCompat.checkSelfPermission(reactContext, Manifest.permission.WRITE_CALENDAR);
int readPermission = ContextCompat.checkSelfPermission(reactContext, Manifest.permission.READ_CALENDAR);
return writePermission == PackageManager.PERMISSION_GRANTED &&
readPermission == PackageManager.PERMISSION_GRANTED;
}
private boolean shouldShowRequestPermissionRationale() {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
Log.w(this.getName(), "Activity doesn't exist");
return false;
}
if (!(currentActivity instanceof PermissionAwareActivity)) {
Log.w(this.getName(), "Activity does not implement the PermissionAwareActivity interface");
return false;
}
PermissionAwareActivity activity = (PermissionAwareActivity)currentActivity;
return activity.shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CALENDAR);
}
//endregion
private WritableNativeArray findEventCalendars() {
Cursor cursor;
ContentResolver cr = reactContext.getContentResolver();
Uri uri = CalendarContract.Calendars.CONTENT_URI;
String IS_PRIMARY = CalendarContract.Calendars.IS_PRIMARY == null ? "0" : CalendarContract.Calendars.IS_PRIMARY;
cursor = cr.query(uri, new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.ACCOUNT_NAME,
IS_PRIMARY,
CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
CalendarContract.Calendars.ALLOWED_AVAILABILITY,
CalendarContract.Calendars.ACCOUNT_TYPE,
CalendarContract.Calendars.CALENDAR_COLOR
}, null, null, null);
return serializeEventCalendars(cursor);
}
private WritableNativeMap findCalendarById(String calendarID) {
WritableNativeMap result;
Cursor cursor;
ContentResolver cr = reactContext.getContentResolver();
Uri uri = ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, Integer.parseInt(calendarID));
String IS_PRIMARY = CalendarContract.Calendars.IS_PRIMARY == null ? "0" : CalendarContract.Calendars.IS_PRIMARY;
cursor = cr.query(uri, new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.ACCOUNT_NAME,
IS_PRIMARY,
CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
CalendarContract.Calendars.ALLOWED_AVAILABILITY,
CalendarContract.Calendars.ACCOUNT_TYPE,
CalendarContract.Calendars.CALENDAR_COLOR
}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
result = serializeEventCalendar(cursor);
cursor.close();
} else {
result = null;
}
return result;
}
private Integer calAccessConstantMatchingString(String string) {
if (string.equals("contributor")) {
return CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR;
}
if (string.equals("editor")) {
return CalendarContract.Calendars.CAL_ACCESS_EDITOR;
}
if (string.equals("freebusy")) {
return CalendarContract.Calendars.CAL_ACCESS_FREEBUSY;
}
if (string.equals("override")) {
return CalendarContract.Calendars.CAL_ACCESS_OVERRIDE;
}
if (string.equals("owner")) {
return CalendarContract.Calendars.CAL_ACCESS_OWNER;
}
if (string.equals("read")) {
return CalendarContract.Calendars.CAL_ACCESS_READ;
}
if (string.equals("respond")) {
return CalendarContract.Calendars.CAL_ACCESS_RESPOND;
}
if (string.equals("root")) {
return CalendarContract.Calendars.CAL_ACCESS_ROOT;
}
return CalendarContract.Calendars.CAL_ACCESS_NONE;
}
private int addCalendar(ReadableMap details) throws Exception, SecurityException {
ContentResolver cr = reactContext.getContentResolver();
ContentValues calendarValues = new ContentValues();
// required fields for new calendars
if (!details.hasKey("source")) {
throw new Exception("new calendars require `source` object");
}
if (!details.hasKey("name")) {
throw new Exception("new calendars require `name`");
}
if (!details.hasKey("title")) {
throw new Exception("new calendars require `title`");
}
if (!details.hasKey("color")) {
throw new Exception("new calendars require `color`");
}
if (!details.hasKey("accessLevel")) {
throw new Exception("new calendars require `accessLevel`");
}
if (!details.hasKey("ownerAccount")) {
throw new Exception("new calendars require `ownerAccount`");
}
ReadableMap source = details.getMap("source");
if (!source.hasKey("name")) {
throw new Exception("new calendars require a `source` object with a `name`");
}
Boolean isLocalAccount = false;
if (source.hasKey("isLocalAccount")) {
isLocalAccount = source.getBoolean("isLocalAccount");
}
if (!source.hasKey("type") && isLocalAccount == false) {
throw new Exception("new calendars require a `source` object with a `type`, or `isLocalAccount`: true");
}
calendarValues.put(CalendarContract.Calendars.ACCOUNT_NAME, source.getString("name"));
calendarValues.put(CalendarContract.Calendars.ACCOUNT_TYPE, isLocalAccount ? CalendarContract.ACCOUNT_TYPE_LOCAL : source.getString("type"));
calendarValues.put(CalendarContract.Calendars.CALENDAR_COLOR, details.getInt("color"));
calendarValues.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, calAccessConstantMatchingString(details.getString("accessLevel")));
calendarValues.put(CalendarContract.Calendars.OWNER_ACCOUNT, details.getString("ownerAccount"));
calendarValues.put(CalendarContract.Calendars.NAME, details.getString("name"));
calendarValues.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, details.getString("title"));
// end required fields
Uri.Builder uriBuilder = CalendarContract.Calendars.CONTENT_URI.buildUpon();
uriBuilder.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true");
uriBuilder.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, source.getString("name"));
uriBuilder.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, isLocalAccount ? CalendarContract.ACCOUNT_TYPE_LOCAL : source.getString("type"));
Uri calendarsUri = uriBuilder.build();
Uri calendarUri = cr.insert(calendarsUri, calendarValues);
return Integer.parseInt(calendarUri.getLastPathSegment());
}
private boolean removeCalendar(String calendarID) {
int rows = 0;
try {
ContentResolver cr = reactContext.getContentResolver();
Uri uri = ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, (long) Integer.parseInt(calendarID));
rows = cr.delete(uri, null, null);
} catch (Exception e) {
e.printStackTrace();
}
return rows > 0;
}
private WritableNativeArray findAttendeesByEventId(String eventID) {
WritableNativeArray result;
Cursor cursor;
ContentResolver cr = reactContext.getContentResolver();
String query = "(" + CalendarContract.Attendees.EVENT_ID + " = ?)";
String[] args = new String[]{eventID};
cursor = cr.query(CalendarContract.Attendees.CONTENT_URI, new String[]{
CalendarContract.Attendees._ID,
CalendarContract.Attendees.EVENT_ID,
CalendarContract.Attendees.ATTENDEE_NAME,
CalendarContract.Attendees.ATTENDEE_EMAIL,
CalendarContract.Attendees.ATTENDEE_TYPE,
CalendarContract.Attendees.ATTENDEE_RELATIONSHIP,
CalendarContract.Attendees.ATTENDEE_STATUS,
CalendarContract.Attendees.ATTENDEE_IDENTITY,
CalendarContract.Attendees.ATTENDEE_ID_NAMESPACE
}, query, args, null);
if (cursor != null && cursor.moveToFirst()) {
result = serializeAttendeeCalendar(cursor);
cursor.close();
} else {
WritableNativeArray emptyAttendees = new WritableNativeArray();
result = emptyAttendees;
}
return result;
}
//region Event Accessors
private WritableNativeArray findEvents(Dynamic startDate, Dynamic endDate, ReadableArray calendars) {
String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar eStartDate = Calendar.getInstance();
Calendar eEndDate = Calendar.getInstance();
try {
if (startDate.getType() == ReadableType.String) {
eStartDate.setTime(sdf.parse(startDate.asString()));
} else if (startDate.getType() == ReadableType.Number) {
eStartDate.setTimeInMillis((long)startDate.asDouble());
}
if (endDate.getType() == ReadableType.String) {
eEndDate.setTime(sdf.parse(endDate.asString()));
} else if (endDate.getType() == ReadableType.Number) {
eEndDate.setTimeInMillis((long)endDate.asDouble());
}
} catch (ParseException e) {
e.printStackTrace();
}
Cursor cursor;
ContentResolver cr = reactContext.getContentResolver();
Uri.Builder uriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(uriBuilder, eStartDate.getTimeInMillis());
ContentUris.appendId(uriBuilder, eEndDate.getTimeInMillis());
Uri uri = uriBuilder.build();
String selection = "((" + CalendarContract.Instances.BEGIN + " >= " + eStartDate.getTimeInMillis() + ") " +
"AND (" + CalendarContract.Instances.END + " <= " + eEndDate.getTimeInMillis() + ") " +
"AND (" + CalendarContract.Instances.VISIBLE + " = 1) " +
"AND (" + CalendarContract.Instances.STATUS + " IS NOT " + CalendarContract.Events.STATUS_CANCELED + ") ";
if (calendars.size() > 0) {
String calendarQuery = "AND (";
for (int i = 0; i < calendars.size(); i++) {
calendarQuery += CalendarContract.Instances.CALENDAR_ID + " = " + calendars.getString(i);
if (i != calendars.size() - 1) {
calendarQuery += " OR ";
}
}
calendarQuery += ")";
selection += calendarQuery;
}
selection += ")";
cursor = cr.query(uri, new String[]{
CalendarContract.Instances.EVENT_ID,
CalendarContract.Instances.TITLE,
CalendarContract.Instances.DESCRIPTION,
CalendarContract.Instances.BEGIN,
CalendarContract.Instances.END,
CalendarContract.Instances.ALL_DAY,
CalendarContract.Instances.EVENT_LOCATION,
CalendarContract.Instances.RRULE,
CalendarContract.Instances.CALENDAR_ID,
CalendarContract.Instances.AVAILABILITY,
CalendarContract.Instances.HAS_ALARM,
CalendarContract.Instances.ORIGINAL_ID,
CalendarContract.Instances.EVENT_ID,
CalendarContract.Instances.DURATION,
CalendarContract.Instances.ORIGINAL_SYNC_ID,
}, selection, null, null);
return serializeEvents(cursor);
}
private WritableNativeMap findEventById(String eventID) {
WritableNativeMap result;
Cursor cursor = null;
ContentResolver cr = reactContext.getContentResolver();
Uri uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, Integer.parseInt(eventID));
String selection = "((" + CalendarContract.Events.DELETED + " != 1))";
cursor = cr.query(uri, new String[]{
CalendarContract.Events._ID,
CalendarContract.Events.TITLE,
CalendarContract.Events.DESCRIPTION,
CalendarContract.Events.DTSTART,
CalendarContract.Events.DTEND,
CalendarContract.Events.ALL_DAY,
CalendarContract.Events.EVENT_LOCATION,
CalendarContract.Events.RRULE,
CalendarContract.Events.CALENDAR_ID,
CalendarContract.Events.AVAILABILITY,
CalendarContract.Events.HAS_ALARM,
CalendarContract.Instances.DURATION
}, selection, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
result = serializeEvent(cursor);
} else {
result = null;
}
cursor.close();
return result;
}
private WritableNativeMap findEventInstanceById(String eventID) {
WritableNativeMap result;
Cursor cursor;
ContentResolver cr = reactContext.getContentResolver();
Uri.Builder uriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(uriBuilder, Long.MIN_VALUE);
ContentUris.appendId(uriBuilder, Long.MAX_VALUE);
Uri uri = uriBuilder.build();
String selection = "(Instances._ID = " + eventID + ")";
cursor = cr.query(uri, new String[]{
CalendarContract.Instances._ID,
CalendarContract.Instances.TITLE,
CalendarContract.Instances.DESCRIPTION,
CalendarContract.Instances.BEGIN,
CalendarContract.Instances.END,
CalendarContract.Instances.ALL_DAY,
CalendarContract.Instances.EVENT_LOCATION,
CalendarContract.Instances.RRULE,
CalendarContract.Instances.CALENDAR_ID,
CalendarContract.Instances.AVAILABILITY,
CalendarContract.Instances.HAS_ALARM,
CalendarContract.Instances.ORIGINAL_ID,
CalendarContract.Instances.EVENT_ID,
CalendarContract.Instances.DURATION
}, selection, null, null);
if (cursor != null && cursor.moveToFirst()) {
result = serializeEvent(cursor);
cursor.close();
} else {
result = null;
}
return result;
}
private int addEvent(String title, ReadableMap details, ReadableMap options) throws ParseException {
String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
boolean skipTimezone = false;
if(details.hasKey("skipAndroidTimezone") && details.getBoolean("skipAndroidTimezone")){
skipTimezone = true;
}
if(!skipTimezone){
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
}
ContentResolver cr = reactContext.getContentResolver();
ContentValues eventValues = new ContentValues();
if (title != null) {
eventValues.put(CalendarContract.Events.TITLE, title);
}
if (details.hasKey("description")) {
eventValues.put(CalendarContract.Events.DESCRIPTION, details.getString("description"));
}
if (details.hasKey("location")) {
eventValues.put(CalendarContract.Events.EVENT_LOCATION, details.getString("location"));
}
if (details.hasKey("startDate")) {
Calendar startCal = Calendar.getInstance();
ReadableType type = details.getType("startDate");
try {
if (type == ReadableType.String) {
startCal.setTime(sdf.parse(details.getString("startDate")));
eventValues.put(CalendarContract.Events.DTSTART, startCal.getTimeInMillis());
} else if (type == ReadableType.Number) {
eventValues.put(CalendarContract.Events.DTSTART, (long)details.getDouble("startDate"));
}
} catch (ParseException e) {
e.printStackTrace();
throw e;
}
}
if (details.hasKey("endDate")) {
Calendar endCal = Calendar.getInstance();
ReadableType type = details.getType("endDate");
try {
if (type == ReadableType.String) {
endCal.setTime(sdf.parse(details.getString("endDate")));
eventValues.put(CalendarContract.Events.DTEND, endCal.getTimeInMillis());
} else if (type == ReadableType.Number) {
eventValues.put(CalendarContract.Events.DTEND, (long)details.getDouble("endDate"));
}
} catch (ParseException e) {
e.printStackTrace();
throw e;
}
}
if (details.hasKey("recurrence")) {
String rule = createRecurrenceRule(details.getString("recurrence"), null, null, null, null, null, null);
if (rule != null) {
eventValues.put(CalendarContract.Events.RRULE, rule);
}
}
if (details.hasKey("recurrenceRule")) {
ReadableMap recurrenceRule = details.getMap("recurrenceRule");
if (recurrenceRule.hasKey("frequency")) {
String frequency = recurrenceRule.getString("frequency");
String duration = "PT1H";
Integer interval = null;
Integer occurrence = null;
String endDate = null;
ReadableArray daysOfWeek = null;
String weekStart = null;
Integer weekPositionInMonth = null;
if (recurrenceRule.hasKey("interval")) {
interval = recurrenceRule.getInt("interval");
}
if (recurrenceRule.hasKey("duration")) {
duration = recurrenceRule.getString("duration");
}
if (recurrenceRule.hasKey("occurrence")) {
occurrence = recurrenceRule.getInt("occurrence");
}
if (recurrenceRule.hasKey("endDate")) {
ReadableType type = recurrenceRule.getType("endDate");
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
if (type == ReadableType.String) {
endDate = format.format(sdf.parse(recurrenceRule.getString("endDate")));
} else if (type == ReadableType.Number) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis((long)recurrenceRule.getDouble("endDate"));
endDate = format.format(calendar.getTime());
}
}
if (recurrenceRule.hasKey("daysOfWeek")) {
daysOfWeek = recurrenceRule.getArray("daysOfWeek");
}
if (recurrenceRule.hasKey("weekStart")) {
weekStart = recurrenceRule.getString("weekStart");
}
if (recurrenceRule.hasKey("weekPositionInMonth")) {
weekPositionInMonth = recurrenceRule.getInt("weekPositionInMonth");
}
String rule = createRecurrenceRule(frequency, interval, endDate, occurrence, daysOfWeek, weekStart, weekPositionInMonth);
if (duration != null) {
eventValues.put(CalendarContract.Events.DURATION, duration);
}
if (rule != null) {
eventValues.put(CalendarContract.Events.RRULE, rule);
}
}
}
if (details.hasKey("allDay")) {
eventValues.put(CalendarContract.Events.ALL_DAY, details.getBoolean("allDay") ? 1 : 0);
}
if (details.hasKey("timeZone")) {
eventValues.put(CalendarContract.Events.EVENT_TIMEZONE, details.getString("timeZone"));
} else {
eventValues.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
}
if (details.hasKey("endTimeZone")) {
eventValues.put(CalendarContract.Events.EVENT_END_TIMEZONE, details.getString("endTimeZone"));
} else {
eventValues.put(CalendarContract.Events.EVENT_END_TIMEZONE, TimeZone.getDefault().getID());
}
if (details.hasKey("alarms")) {
eventValues.put(CalendarContract.Events.HAS_ALARM, true);
}
if (details.hasKey("availability")) {
eventValues.put(CalendarContract.Events.AVAILABILITY, availabilityConstantMatchingString(details.getString("availability")));
}
if (details.hasKey("id")) {
int eventID = Integer.parseInt(details.getString("id"));
WritableMap eventInstance = findEventById(details.getString("id"));
if (eventInstance != null) {
ReadableMap eventCalendar = eventInstance.getMap("calendar");
if (!options.hasKey("exceptionDate")) {
Uri updateUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID);
if (options.hasKey("sync") && options.getBoolean("sync")) {
syncCalendar(cr, eventInstance.getMap("calendar").getString("id"));
updateUri = eventUriAsSyncAdapter(updateUri, eventCalendar.getString("source"), eventCalendar.getString("type"));
}
cr.update(updateUri, eventValues, null, null);
} else {
Calendar exceptionStart = Calendar.getInstance();
ReadableType type = options.getType("exceptionDate");
try {
if (type == ReadableType.String) {
exceptionStart.setTime(sdf.parse(options.getString("exceptionDate")));
eventValues.put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, exceptionStart.getTimeInMillis());
} else if (type == ReadableType.Number) {
eventValues.put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, (long) options.getDouble("exceptionDate"));
}
} catch (ParseException e) {
e.printStackTrace();
throw e;
}
Uri exceptionUri = Uri.withAppendedPath(CalendarContract.Events.CONTENT_EXCEPTION_URI, Integer.toString(eventID));
if (options.hasKey("sync") && options.getBoolean("sync")) {
syncCalendar(cr, eventInstance.getMap("calendar").getString("id"));
eventUriAsSyncAdapter(exceptionUri, eventCalendar.getString("source"), eventCalendar.getString("type"));
}
try {
Uri eventUri = cr.insert(exceptionUri, eventValues);
if (eventUri != null) {
eventID = Integer.parseInt(eventUri.getLastPathSegment());
}
} catch (Exception e) {
Log.d(this.getName(), "Event exception error", e);
}
}
}
if (details.hasKey("alarms")) {
createRemindersForEvent(cr, Integer.parseInt(details.getString("id")), details.getArray("alarms"));
}
if (details.hasKey("attendees")) {
createAttendeesForEvent(cr, Integer.parseInt(details.getString("id")), details.getArray("attendees"));
}
return eventID;
} else {
WritableNativeMap calendar;
int eventID = -1;
if (details.hasKey("calendarId")) {
calendar = findCalendarById(details.getString("calendarId"));
if (calendar != null) {
eventValues.put(CalendarContract.Events.CALENDAR_ID, Integer.parseInt(calendar.getString("id")));
} else {
eventValues.put(CalendarContract.Events.CALENDAR_ID, 1);
}
} else {
calendar = findCalendarById("1");
eventValues.put(CalendarContract.Events.CALENDAR_ID, 1);
}
Uri createEventUri = CalendarContract.Events.CONTENT_URI;
if (options.hasKey("sync") && options.getBoolean("sync")) {
syncCalendar(cr, calendar.getString("id"));
createEventUri = eventUriAsSyncAdapter(CalendarContract.Events.CONTENT_URI, calendar.getString("source"), calendar.getString("type"));
}
Uri eventUri = cr.insert(createEventUri, eventValues);
if (eventUri != null) {
String rowId = eventUri.getLastPathSegment();
if (rowId != null) {
eventID = Integer.parseInt(rowId);
if (details.hasKey("alarms")) {
createRemindersForEvent(cr, eventID, details.getArray("alarms"));
}
if (details.hasKey("attendees")) {
createAttendeesForEvent(cr, eventID, details.getArray("attendees"));
}
return eventID;
}
}
return eventID;
}
}
private boolean removeEvent(String eventID, ReadableMap options) {
int rows = 0;
try {
ContentResolver cr = reactContext.getContentResolver();
WritableMap eventInstance = findEventById(eventID);
ReadableMap eventCalendar = eventInstance.getMap("calendar");
if (!options.hasKey("exceptionDate")) {
Uri uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, (long) Integer.parseInt(eventID));
if (options.hasKey("sync") && options.getBoolean("sync")) {
syncCalendar(cr, eventCalendar.getString("id"));
uri = eventUriAsSyncAdapter(uri, eventCalendar.getString("source"), eventCalendar.getString("type"));
}
rows = cr.delete(uri, null, null);
} else {
ContentValues eventValues = new ContentValues();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar exceptionStart = Calendar.getInstance();
ReadableType type = options.getType("exceptionDate");
try {
if (type == ReadableType.String) {
exceptionStart.setTime(sdf.parse(options.getString("exceptionDate")));
eventValues.put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, exceptionStart.getTimeInMillis());
} else if (type == ReadableType.Number) {
eventValues.put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, (long) options.getDouble("exceptionDate"));
}
} catch (ParseException e) {
e.printStackTrace();
throw e;
}
eventValues.put(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_CANCELED);
Uri uri = Uri.withAppendedPath(CalendarContract.Events.CONTENT_EXCEPTION_URI, eventID);
if (options.hasKey("sync") && options.getBoolean("sync")) {
uri = eventUriAsSyncAdapter(uri, eventCalendar.getString("source"), eventCalendar.getString("type"));
}
Uri exceptionUri = cr.insert(uri, eventValues);
if (exceptionUri != null) {
rows = 1;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return rows > 0;
}
//sync adaptors
private Uri eventUriAsSyncAdapter (Uri uri, String accountName, String accountType) {
uri = uri.buildUpon()
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, accountName)
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, accountType)
.build();
return uri;
}
public static void syncCalendar(ContentResolver cr, String calendarId) {
ContentValues values = new ContentValues();
values.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
values.put(CalendarContract.Calendars.VISIBLE, 1);
cr.update(ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, Long.parseLong(calendarId)), values, null, null);
}
//endregion
//region Attendees
private void createAttendeesForEvent(ContentResolver resolver, int eventID, ReadableArray attendees) {
Cursor cursor = CalendarContract.Attendees.query(resolver, eventID, new String[] {
CalendarContract.Attendees._ID
});
while (cursor.moveToNext()) {
long attendeeId = cursor.getLong(0);
Uri attendeeUri = ContentUris.withAppendedId(CalendarContract.Attendees.CONTENT_URI, attendeeId);
resolver.delete(attendeeUri, null, null);
}
cursor.close();
for (int i = 0; i < attendees.size(); i++) {
ReadableMap attendee = attendees.getMap(i);
ReadableType type = attendee.getType("url");
ReadableType fNameType = attendee.getType("firstName");
if (type == ReadableType.String) {
ContentValues attendeeValues = new ContentValues();
attendeeValues.put(CalendarContract.Attendees.EVENT_ID, eventID);
attendeeValues.put(CalendarContract.Attendees.ATTENDEE_EMAIL, attendee.getString("url"));
attendeeValues.put(CalendarContract.Attendees.ATTENDEE_RELATIONSHIP, CalendarContract.Attendees.RELATIONSHIP_ATTENDEE);
if (fNameType == ReadableType.String) {
attendeeValues.put(CalendarContract.Attendees.ATTENDEE_NAME, attendee.getString("firstName"));
}
resolver.insert(CalendarContract.Attendees.CONTENT_URI, attendeeValues);
}
}
}
//endregion
//region Reminders
private void createRemindersForEvent(ContentResolver resolver, int eventID, ReadableArray reminders) {
Cursor cursor = null;
if (resolver != null) {
cursor = CalendarContract.Reminders.query(resolver, eventID, new String[] {
CalendarContract.Reminders._ID
});
}
while (cursor != null && cursor.moveToNext()) {
Uri reminderUri = null;
long reminderId = cursor.getLong(0);
if (reminderId > 0) {
reminderUri = ContentUris.withAppendedId(CalendarContract.Reminders.CONTENT_URI, reminderId);
}
if (reminderUri != null) {
resolver.delete(reminderUri, null, null);
}
}
if (cursor != null) {
cursor.close();
}
for (int i = 0; i < reminders.size(); i++) {
ReadableMap reminder = reminders.getMap(i);
ReadableType type = reminder.getType("date");
if (type == ReadableType.Number) {
int minutes = reminder.getInt("date");
ContentValues reminderValues = new ContentValues();
reminderValues.put(CalendarContract.Reminders.EVENT_ID, eventID);
reminderValues.put(CalendarContract.Reminders.MINUTES, minutes);
reminderValues.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
resolver.insert(CalendarContract.Reminders.CONTENT_URI, reminderValues);
}
}
}
private WritableNativeArray findReminderByEventId(String eventID, long startDate) {
WritableNativeArray results = new WritableNativeArray();
ContentResolver cr = reactContext.getContentResolver();
String selection = "(" + CalendarContract.Reminders.EVENT_ID + " = ?)";
Cursor cursor = cr.query(CalendarContract.Reminders.CONTENT_URI, new String[]{
CalendarContract.Reminders.MINUTES
}, selection, new String[] {eventID}, null);
while (cursor != null && cursor.moveToNext()) {
WritableNativeMap alarm = new WritableNativeMap();
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis(startDate);
int minutes;
try {
minutes = cursor.getInt(0);
} catch (Exception e) {
Log.d(this.getName(), "Error parsing event minutes", e);
continue;
}
cal.add(Calendar.MINUTE, minutes);
alarm.putString("date", sdf.format(cal.getTime()));
results.pushMap(alarm);
}
if (cursor != null) {
cursor.close();
}
return results;
}
//endregion
//region Availability
private WritableNativeArray calendarAllowedAvailabilitiesFromDBString(String dbString) {
WritableNativeArray availabilitiesStrings = new WritableNativeArray();
for(String availabilityStr: dbString.split(",")) {
int availabilityId = -1;
try {
availabilityId = Integer.parseInt(availabilityStr);
} catch(NumberFormatException e) {
// Some devices seem to just use strings.
if (availabilityStr.equals("AVAILABILITY_BUSY")) {
availabilityId = CalendarContract.Events.AVAILABILITY_BUSY;
} else if (availabilityStr.equals("AVAILABILITY_FREE")) {
availabilityId = CalendarContract.Events.AVAILABILITY_FREE;
} else if (availabilityStr.equals("AVAILABILITY_TENTATIVE")) {
availabilityId = CalendarContract.Events.AVAILABILITY_TENTATIVE;
}
}
switch(availabilityId) {
case CalendarContract.Events.AVAILABILITY_BUSY:
availabilitiesStrings.pushString("busy");
break;
case CalendarContract.Events.AVAILABILITY_FREE:
availabilitiesStrings.pushString("free");
break;
case CalendarContract.Events.AVAILABILITY_TENTATIVE:
availabilitiesStrings.pushString("tentative");
break;
}
}
return availabilitiesStrings;
}
private String availabilityStringMatchingConstant(Integer constant)
{
switch(constant) {
case CalendarContract.Events.AVAILABILITY_BUSY:
default:
return "busy";
case CalendarContract.Events.AVAILABILITY_FREE:
return "free";
case CalendarContract.Events.AVAILABILITY_TENTATIVE:
return "tentative";
}
}
private Integer availabilityConstantMatchingString(String string) throws IllegalArgumentException {
if (string.equals("free")){
return CalendarContract.Events.AVAILABILITY_FREE;
}
if (string.equals("tentative")){
return CalendarContract.Events.AVAILABILITY_TENTATIVE;
}
return CalendarContract.Events.AVAILABILITY_BUSY;
}
//endregion
private String ReadableArrayToString (ReadableArray strArr) {
ArrayList<Object> array = strArr.toArrayList();
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < array.size(); i++) {
strBuilder.append(array.get(i).toString() + ',');
}
String newString = strBuilder.toString();
newString = newString.substring(0, newString.length() - 1);
return newString;
}
//region Recurrence Rule
private String createRecurrenceRule(String recurrence, Integer interval, String endDate, Integer occurrence, ReadableArray daysOfWeek, String weekStart, Integer weekPositionInMonth) {
String rrule;
if (recurrence.equals("daily")) {
rrule= "FREQ=DAILY";
} else if (recurrence.equals("weekly")) {
rrule = "FREQ=WEEKLY";
} else if (recurrence.equals("monthly")) {
rrule = "FREQ=MONTHLY";
} else if (recurrence.equals("yearly")) {
rrule = "FREQ=YEARLY";
} else {
return null;
}
if (daysOfWeek != null && recurrence.equals("weekly")) {
rrule += ";BYDAY=" + ReadableArrayToString(daysOfWeek);
}
if (recurrence.equals("monthly") && daysOfWeek != null && weekPositionInMonth != null) {
rrule += ";BYSETPOS=" + weekPositionInMonth;
rrule += ";BYDAY=" + ReadableArrayToString(daysOfWeek);
}
if (weekStart != null) {
rrule += ";WKST=" + weekStart;
}
if (interval != null) {
rrule += ";INTERVAL=" + interval;
}
if (endDate != null) {
rrule += ";UNTIL=" + endDate;
} else if (occurrence != null) {
rrule += ";COUNT=" + occurrence;
}
return rrule;
}
//endregion
// region Serialize Events
private WritableNativeArray serializeEvents(Cursor cursor) {
WritableNativeArray results = new WritableNativeArray();
if (cursor != null) {
while (cursor.moveToNext()) {
results.pushMap(serializeEvent(cursor));
}
cursor.close();
}
return results;
}
private WritableNativeMap serializeEvent(Cursor cursor) {
WritableNativeMap event = new WritableNativeMap();
String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar foundStartDate = Calendar.getInstance();
Calendar foundEndDate = Calendar.getInstance();
boolean allDay = false;
String startDateUTC = "";
String endDateUTC = "";
if (cursor.getString(3) != null) {
foundStartDate.setTimeInMillis(Long.parseLong(cursor.getString(3)));
startDateUTC = sdf.format(foundStartDate.getTime());
}
if (cursor.getString(4) != null) {
foundEndDate.setTimeInMillis(Long.parseLong(cursor.getString(4)));
endDateUTC = sdf.format(foundEndDate.getTime());
}
if (cursor.getString(5) != null) {
allDay = cursor.getInt(5) != 0;
}
if (cursor.getString(7) != null) {
WritableNativeMap recurrenceRule = new WritableNativeMap();
String[] recurrenceRules = cursor.getString(7).split(";");
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
if (recurrenceRules.length > 0 && recurrenceRules[0].split("=").length > 1) {
event.putString("recurrence", recurrenceRules[0].split("=")[1].toLowerCase());
recurrenceRule.putString("frequency", recurrenceRules[0].split("=")[1].toLowerCase());
}
if (cursor.getColumnIndex(CalendarContract.Events.DURATION) != -1 && cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DURATION)) != null) {
recurrenceRule.putString("duration", cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DURATION)));
}
if (recurrenceRules.length >= 2 && recurrenceRules[1].split("=")[0].equals("INTERVAL")) {
recurrenceRule.putInt("interval", Integer.parseInt(recurrenceRules[1].split("=")[1]));
}
if (recurrenceRules.length >= 3) {
if (recurrenceRules[2].split("=")[0].equals("UNTIL")) {
try {
recurrenceRule.putString("endDate", sdf.format(format.parse(recurrenceRules[2].split("=")[1])));
} catch (ParseException e) {
e.printStackTrace();
}
} else if (recurrenceRules[2].split("=")[0].equals("COUNT")) {
recurrenceRule.putInt("occurrence", Integer.parseInt(recurrenceRules[2].split("=")[1]));
}
}
event.putMap("recurrenceRule", recurrenceRule);
}
event.putString("id", cursor.getString(0));
event.putMap("calendar", findCalendarById(cursor.getString(cursor.getColumnIndex("calendar_id"))));
event.putString("title", cursor.getString(cursor.getColumnIndex("title")));
event.putString("description", cursor.getString(2));
event.putString("startDate", startDateUTC);
event.putString("endDate", endDateUTC);
event.putBoolean("allDay", allDay);
event.putString("location", cursor.getString(6));
event.putString("availability", availabilityStringMatchingConstant(cursor.getInt(9)));
event.putArray("attendees", (WritableArray) findAttendeesByEventId(cursor.getString(0)));
if (cursor.getInt(10) > 0) {
event.putArray("alarms", findReminderByEventId(cursor.getString(0), Long.parseLong(cursor.getString(3))));
} else {
WritableNativeArray emptyAlarms = new WritableNativeArray();
event.putArray("alarms", emptyAlarms);
}
if (cursor.getColumnIndex(CalendarContract.Events.ORIGINAL_ID) != -1 && cursor.getString(cursor.getColumnIndex(CalendarContract.Events.ORIGINAL_ID)) != null) {
event.putString("originalId", cursor.getString(cursor.getColumnIndex(CalendarContract.Events.ORIGINAL_ID)));
}
if (cursor.getColumnIndex(CalendarContract.Instances.ORIGINAL_SYNC_ID) != -1 && cursor.getString(cursor.getColumnIndex(CalendarContract.Instances.ORIGINAL_SYNC_ID)) != null) {
event.putString("syncId", cursor.getString(cursor.getColumnIndex(CalendarContract.Instances.ORIGINAL_SYNC_ID)));
}
return event;
}
private WritableNativeArray serializeEventCalendars(Cursor cursor) {
WritableNativeArray results = new WritableNativeArray();
while (cursor.moveToNext()) {
results.pushMap(serializeEventCalendar(cursor));
}
cursor.close();
return results;
}
private WritableNativeMap serializeEventCalendar(Cursor cursor) {
WritableNativeMap calendar = new WritableNativeMap();
calendar.putString("id", cursor.getString(0));
calendar.putString("title", cursor.getString(1));
calendar.putString("source", cursor.getString(2));
calendar.putArray("allowedAvailabilities", calendarAllowedAvailabilitiesFromDBString(cursor.getString(5)));
calendar.putString("type", cursor.getString(6));
String colorHex = "#FFFFFF";
try {
colorHex = String.format("#%06X", (0xFFFFFF & cursor.getInt(7)));
} catch (Exception e) {
Log.d(this.getName(), "Error parsing calendar color", e);
}
calendar.putString("color", colorHex);
if (cursor.getString(3) != null) {
calendar.putBoolean("isPrimary", cursor.getString(3).equals("1"));
}
int accesslevel = cursor.getInt(4);
if (accesslevel == CalendarContract.Calendars.CAL_ACCESS_ROOT ||
accesslevel == CalendarContract.Calendars.CAL_ACCESS_OWNER ||
accesslevel == CalendarContract.Calendars.CAL_ACCESS_EDITOR ||
accesslevel == CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR) {
calendar.putBoolean("allowsModifications", true);
} else {
calendar.putBoolean("allowsModifications", false);
}
return calendar;
}
private WritableNativeArray serializeAttendeeCalendar(Cursor cursor) {
WritableNativeArray results = new WritableNativeArray();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
WritableNativeMap attendee = new WritableNativeMap();
attendee.putString("name", cursor.getString( 2));
attendee.putString("email", cursor.getString(3));
attendee.putString("type", cursor.getString(4));
attendee.putString("relationship", cursor.getString(5));
attendee.putString("status", cursor.getString(6));
attendee.putString("identity", cursor.getString(7));
attendee.putString("id_namespace", cursor.getString(8));
results.pushMap(attendee);
}
return results;
}
// endregion
//region React Native Methods
@ReactMethod
public void getCalendarPermissions(Promise promise) {
SharedPreferences sharedPreferences = reactContext.getSharedPreferences(RNC_PREFS, ReactContext.MODE_PRIVATE);
boolean permissionRequested = sharedPreferences.getBoolean("permissionRequested", false);
if (this.haveCalendarReadWritePermissions()) {
promise.resolve("authorized");
} else if (!permissionRequested) {
promise.resolve("undetermined");
} else if(this.shouldShowRequestPermissionRationale()) {
promise.resolve("denied");
} else {
promise.resolve("restricted");
}
}
@ReactMethod
public void requestCalendarPermissions(Promise promise) {
SharedPreferences sharedPreferences = reactContext.getSharedPreferences(RNC_PREFS, ReactContext.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("permissionRequested", true);
editor.apply();
if (this.haveCalendarReadWritePermissions()) {
promise.resolve("authorized");
} else {
this.requestCalendarReadWritePermission(promise);
}
}
@ReactMethod
public void findCalendars(final Promise promise) {
if (this.haveCalendarReadWritePermissions()) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
WritableArray calendars = findEventCalendars();
promise.resolve(calendars);
}
});
thread.start();
} catch (Exception e) {
promise.reject("calendar request error", e.getMessage());
}
} else {
promise.reject("add event error", "you don't have permissions to retrieve an event to the users calendar");
}
}
@ReactMethod
public void saveCalendar(final ReadableMap options, final Promise promise) {
if (!this.haveCalendarReadWritePermissions()) {
promise.reject("save calendar error", "unauthorized to access calendar");
return;
}
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
Integer calendarID = addCalendar(options);
promise.resolve(calendarID.toString());
} catch (Exception e) {
promise.reject("save calendar error", e.getMessage());
}
}
});
thread.start();
} catch (Exception e) {
promise.reject("save calendar error", "Calendar could not be saved", e);
}
}
@ReactMethod
public void removeCalendar(final String CalendarID, final Promise promise) {
if (this.haveCalendarReadWritePermissions()) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
boolean successful = removeCalendar(CalendarID);
promise.resolve(successful);
}
});
thread.start();
} catch (Exception e) {
promise.reject("error removing calendar", e.getMessage());
}
} else {
promise.reject("remove calendar error", "you don't have permissions to remove a calendar");
}
}
@ReactMethod
public void saveEvent(final String title, final ReadableMap details, final ReadableMap options, final Promise promise) {
if (this.haveCalendarReadWritePermissions()) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
int eventId;
try {
eventId = addEvent(title, details, options);
if (eventId > -1) {
promise.resolve(Integer.toString(eventId));
} else {
promise.reject("add event error", "Unable to save event");
}
} catch (ParseException e) {
promise.reject("add event error", e.getMessage());
}
}
});
thread.start();
} catch (Exception e) {
promise.reject("add event error", e.getMessage());
}
} else {
promise.reject("add event error", "you don't have permissions to add an event to the users calendar");
}
}
@ReactMethod
public void findAllEvents(final Dynamic startDate, final Dynamic endDate, final ReadableArray calendars, final Promise promise) {
if (this.haveCalendarReadWritePermissions()) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
WritableNativeArray results = findEvents(startDate, endDate, calendars);
promise.resolve(results);
}
});
thread.start();
} catch (Exception e) {
promise.reject("find event error", e.getMessage());
}
} else {
promise.reject("find event error", "you don't have permissions to read an event from the users calendar");
}
}
@ReactMethod
public void findById(final String eventID, final Promise promise) {
if (this.haveCalendarReadWritePermissions()) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
WritableMap results = findEventById(eventID);
promise.resolve(results);
}
});
thread.start();
} catch (Exception e) {
promise.reject("find event error", e.getMessage());
}
} else {
promise.reject("find event error", "you don't have permissions to read an event from the users calendar");
}
}
@ReactMethod
public void removeEvent(final String eventID, final ReadableMap options, final Promise promise) {
if (this.haveCalendarReadWritePermissions()) {
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
boolean successful = removeEvent(eventID, options);
promise.resolve(successful);
}
});
thread.start();
} catch (Exception e) {
promise.reject("error removing event", e.getMessage());
}
} else {
promise.reject("remove event error", "you don't have permissions to remove an event from the users calendar");
}
}
@ReactMethod
public void openEventInCalendar(int eventID) {
Uri uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID);
Intent sendIntent = new Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setData(uri);
if (sendIntent.resolveActivity(reactContext.getPackageManager()) != null) {
reactContext.startActivity(sendIntent);
}
}
@ReactMethod
public void uriForCalendar(Promise promise) {
promise.resolve(CalendarContract.Events.CONTENT_URI.toString());
}
//endregion
}
| Fixed `'boolean android.database.Cursor.moveToNext()' on a null object reference` error
Closes #259
Closes #255
| android/src/main/java/com/calendarevents/RNCalendarEvents.java | Fixed `'boolean android.database.Cursor.moveToNext()' on a null object reference` error | <ide><path>ndroid/src/main/java/com/calendarevents/RNCalendarEvents.java
<ide> Cursor cursor = CalendarContract.Attendees.query(resolver, eventID, new String[] {
<ide> CalendarContract.Attendees._ID
<ide> });
<del>
<add>
<ide> while (cursor.moveToNext()) {
<ide> long attendeeId = cursor.getLong(0);
<ide> Uri attendeeUri = ContentUris.withAppendedId(CalendarContract.Attendees.CONTENT_URI, attendeeId);
<ide> private WritableNativeArray serializeEventCalendars(Cursor cursor) {
<ide> WritableNativeArray results = new WritableNativeArray();
<ide>
<del> while (cursor.moveToNext()) {
<del> results.pushMap(serializeEventCalendar(cursor));
<del> }
<del>
<del> cursor.close();
<add> if (cursor != null) {
<add> while (cursor.moveToNext()) {
<add> results.pushMap(serializeEventCalendar(cursor));
<add> }
<add> cursor.close();
<add> }
<ide>
<ide> return results;
<ide> } |
|
Java | apache-2.0 | ffd17dc53a30565f1f765b8ec7b3f3f85dd651e9 | 0 | leokraemer/mathosphere,TU-Berlin/mathosphere,leokraemer/mathosphere,TU-Berlin/mathosphere | package mlp.pojos;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import mlp.text.WikiTextUtils;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static mlp.text.WikiTextUtilsTest.getTestResource;
/**
* Created by Moritz on 30.09.2015.
*/
public class MathTagTest {
@Test
public void testGetContentHash() throws Exception {
MathTag t = new MathTag(1, "<math><mrow><mo>x</mo><mrow></math>", WikiTextUtils.MathMarkUpType.MATHML);
assertEquals("2cf05995ef521b456aa419201d160406", t.getContentHash());
}
@Test
public void testPlaceholder() throws Exception {
}
@Test
public void testGetMarkUpType() throws Exception {
}
@Test
public void testGetIdentifier() throws Exception {
MathTag tagX = new MathTag(1, "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mrow><mi>x</mi></mrow></math>", WikiTextUtils.MathMarkUpType.MATHML);
assertEquals(ImmutableSet.of("x"), tagX.getIdentifier(true, true).elementSet());
assertEquals(ImmutableSet.of("x"), tagX.getIdentifier(false, true).elementSet());
MathTag schrödinger = new MathTag(1,getTestResource("schrödinger_eq.xml"),WikiTextUtils.MathMarkUpType.MATHML);
//MathTag schrödingerTex = new MathTag(1,"i\\hbar\\frac{\\partial}{\\partial t}\\Psi(\\mathbb{r},\\,t)=-\\frac{\\hbar^{2}}{2m}" +
// "\\nabla^{2}\\Psi(\\mathbb{r},\\,t)+V(\\mathbb{r})\\Psi(\\mathbb{r},\\,t).", WikiTextUtils.MathMarkUpType.LATEX);
ImmutableMultiset<String> lIds = ImmutableMultiset.of("i",
"\\hbar", "\\hbar",
"t", "t", "t", "t",
"\\Psi", "\\Psi", "\\Psi",
"\\mathbb{r}", "\\mathbb{r}", "\\mathbb{r}", "\\mathbb{r}",
"V",
"m");
assertEquals(lIds,schrödinger.getIdentifier(true,false));
}
}
| mlp/src/test/java/mlp/pojos/MathTagTest.java | package mlp.pojos;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import mlp.text.WikiTextUtils;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static mlp.text.WikiTextUtilsTest.getTestResource;
/**
* Created by Moritz on 30.09.2015.
*/
public class MathTagTest {
@Test
public void testGetContentHash() throws Exception {
MathTag t = new MathTag(1, "<math><mrow><mo>x</mo></mrow></math>", WikiTextUtils.MathMarkUpType.MATHML);
assertEquals("2cf05995ef521b456aa419201d160406", t.getContentHash());
}
@Test
public void testPlaceholder() throws Exception {
}
@Test
public void testGetMarkUpType() throws Exception {
}
@Test
public void testGetIdentifier() throws Exception {
MathTag tagX = new MathTag(1, "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mrow><mi>x</mi></mrow></math>", WikiTextUtils.MathMarkUpType.MATHML);
assertEquals(ImmutableSet.of("x"), tagX.getIdentifier(true, true).elementSet());
assertEquals(ImmutableSet.of("x"), tagX.getIdentifier(false, true).elementSet());
MathTag schrödinger = new MathTag(1,getTestResource("schrödinger_eq.xml"),WikiTextUtils.MathMarkUpType.MATHML);
//MathTag schrödingerTex = new MathTag(1,"i\\hbar\\frac{\\partial}{\\partial t}\\Psi(\\mathbb{r},\\,t)=-\\frac{\\hbar^{2}}{2m}" +
// "\\nabla^{2}\\Psi(\\mathbb{r},\\,t)+V(\\mathbb{r})\\Psi(\\mathbb{r},\\,t).", WikiTextUtils.MathMarkUpType.LATEX);
ImmutableMultiset<String> lIds = ImmutableMultiset.of("i",
"\\hbar", "\\hbar",
"t", "t", "t", "t",
"\\Psi", "\\Psi", "\\Psi",
"\\mathbb{r}", "\\mathbb{r}", "\\mathbb{r}", "\\mathbb{r}",
"V",
"m");
assertEquals(lIds,schrödinger.getIdentifier(true,false));
}
}
| fix test undo stupid change in last PS
* the content was changed but not the hash
| mlp/src/test/java/mlp/pojos/MathTagTest.java | fix test undo stupid change in last PS | <ide><path>lp/src/test/java/mlp/pojos/MathTagTest.java
<ide>
<ide> @Test
<ide> public void testGetContentHash() throws Exception {
<del> MathTag t = new MathTag(1, "<math><mrow><mo>x</mo></mrow></math>", WikiTextUtils.MathMarkUpType.MATHML);
<add> MathTag t = new MathTag(1, "<math><mrow><mo>x</mo><mrow></math>", WikiTextUtils.MathMarkUpType.MATHML);
<ide> assertEquals("2cf05995ef521b456aa419201d160406", t.getContentHash());
<ide> }
<ide> |
|
Java | apache-2.0 | 639c7c100d7931bde189b19d9ec70cd953dc590f | 0 | nezda/yawni,nezda/yawni,nezda/yawni,nezda/yawni,nezda/yawni | /*
* Copyright 1998 by Oliver Steele. You can use this software freely so long as you preserve
* the copyright notice and this restriction, and label your changes.
*/
package edu.brandeis.cs.steele.wn;
import java.util.*;
import static edu.brandeis.cs.steele.wn.PointerTypeFlag.*;
/** Instances of this class enumerate the possible WordNet pointer types, and
* are used to label {@link Pointer}s.
* Each <code>PointerType</code> carries additional information:
* <ul>
* <li> a human-readable label </li>
* <li> an optional symmetric (i.e. reflexive) type that labels links pointing the opposite direction </li>
* <li> an encoding of parts-of-speech that it applies to </li>
* <li> a short string (lemma) that represents it in the dictionary files </li>
* </ul>
*
* @see <a href="http://wordnet.princeton.edu/man/wnsearch.3WN#sect4>http://wordnet.princeton.edu/man/wnsearch.3WN#sect4</a>
* @see <a href="http://wordnet.princeton.edu/man/wngloss.7WN.html#sect4">Glossary of WordNet Terms</a>
* @see Pointer
* @see POS
* @author Oliver Steele, [email protected]
* @version 1.0
*/
public enum PointerType {
// consider Unicde ellipsis: "…" instead of "..."
// Nouns and Verbs
HYPERNYM("hypernym", "@", N | V, "Hypernyms (%s is a kind of ...)", "Hypernyms (%s is one way to ...)"),
INSTANCE_HYPERNYM("instance hypernym", "@i", N | V, "Instance Hypernyms (%s is an instance of ...)"),
HYPONYM("hyponym", "~", N | V, "Hyponyms (... is a kind of %s)", "Troponyms (... are particular ways to %s)"),
INSTANCE_HYPONYM("instance hyponym", "~i", N | V, "Instance Hyponyms (... is an instance of %s)"),
DERIVATIONALLY_RELATED("derivationally related", "+", N | V, "Derivationally related forms"),
// Nouns and Adjectives
ATTRIBUTE("attribute", "=", N | ADJ, "Attribute (%s is a value of ...)"),
SEE_ALSO("also see", "^", N | ADJ | LEXICAL),
// Verbs
ENTAILMENT("entailment", "*", V, "%s entails doing ..."),
CAUSE("cause", ">", V, null, "%s causes ..."),
VERB_GROUP("verb group", "$", V),
// Nouns
/**
* A word that names a part of a larger whole, aka "part name".
* Pure-virtual PointerType.
* @see PointerType#MEMBER_MERONYM
* @see PointerType#SUBSTANCE_MERONYM
* @see PointerType#PART_MERONYM
*/
MERONYM("meronym", "%" /* non-existent */, N),
MEMBER_MERONYM("member meronym", "%m", N, "Member Meronyms (... are members of %s)"),
PART_MERONYM("part meronym", "%p", N, "Part Meronyms (... are parts of %s)"),
SUBSTANCE_MERONYM("substance meronym", "%s", N, "Substance Meronyms (... are substances of %s)"),
/**
* A word that names the whole of which a given word is a part.
* Pure-virtual PointerType.
* @see PointerType#MEMBER_HOLONYM
* @see PointerType#SUBSTANCE_HOLONYM
* @see PointerType#PART_HOLONYM
*/
HOLONYM("holonym", "#" /* non-existent up */, N),
MEMBER_HOLONYM("member holonym", "#m", N, "Member Holonyms (%s is a member of ...)"),
SUBSTANCE_HOLONYM("substance holonym", "#s", N, "Substance Holonyms (%s is a substance of ...)"),
PART_HOLONYM("part holonym", "#p", N, "Part Holonyms (%s is a part of ...)"),
MEMBER_OF_TOPIC_DOMAIN("Member of TOPIC domain", "-c", N), // topic term
MEMBER_OF_REGION_DOMAIN("Member of REGION domain", "-r", N), // regional term
MEMBER_OF_USAGE_DOMAIN("Member of USAGE domain", "-u", N), // ?
// Adjectives
SIMILAR_TO("similar to", "&", ADJ),
PARTICIPLE_OF("participle of", "<", ADJ | LEXICAL),
PERTAINYM("pertainym", "\\", ADJ | LEXICAL, "... are nouns related to %s"),
// Adverbs
DERIVED("derived from", "\\", ADV), // from adjective
// All parts of speech
ANTONYM("antonym", "!", N | V | ADJ | ADV | LEXICAL, "Antonyms (... is the opposite of %s)"),
DOMAIN_OF_TOPIC("Domain of synset - TOPIC", ";c", N | V | ADJ | ADV), // a domain
DOMAIN_OF_REGION("Domain of synset - REGION", ";r", N | V | ADJ | ADV), // a region
DOMAIN_OF_USAGE("Domain of synset - USAGE", ";u", N | V | ADJ | ADV), // ?
/**
* Pure-virtual PointerType.
* @see PointerType#MEMBER_OF_TOPIC_DOMAIN
* @see PointerType#MEMBER_OF_REGION_DOMAIN
* @see PointerType#MEMBER_OF_USAGE_DOMAIN
*/
DOMAIN_MEMBER("Domain Member", "-", N | V | ADJ | ADV),
/**
* Pure-virtual PointerType.
* @see PointerType#DOMAIN_OF_TOPIC
* @see PointerType#DOMAIN_OF_REGION
* @see PointerType#DOMAIN_OF_USAGE
*/
DOMAIN("Domain", ";", N | V | ADJ | ADV);
private static final int[] POS_MASK = {N, V, ADJ, ADV, SAT_ADJ, LEXICAL};
/** A list of all <code>PointerType</code>s. */
public static final EnumSet<PointerType> TYPES = EnumSet.of(
ANTONYM, HYPERNYM, HYPONYM, ATTRIBUTE, SEE_ALSO,
ENTAILMENT, CAUSE, VERB_GROUP,
MEMBER_MERONYM, SUBSTANCE_MERONYM, PART_MERONYM,
MEMBER_HOLONYM, SUBSTANCE_HOLONYM, PART_HOLONYM,
SIMILAR_TO, PARTICIPLE_OF, PERTAINYM, DERIVED,
DOMAIN_OF_TOPIC, DOMAIN_OF_USAGE, DOMAIN_OF_REGION,
MEMBER_OF_TOPIC_DOMAIN, MEMBER_OF_REGION_DOMAIN, MEMBER_OF_USAGE_DOMAIN,
DERIVATIONALLY_RELATED,
INSTANCE_HYPERNYM, INSTANCE_HYPONYM
);
//XXX this seems to indicate DOMAIN implies DOMAIN_PART
public static final Set<PointerType> INDEX_ONLY = EnumSet.of(DOMAIN_MEMBER, DOMAIN, HOLONYM, MERONYM);
static {
assert EnumSet.complementOf(TYPES).equals(INDEX_ONLY);
}
static private void setSymmetric(final PointerType a, final PointerType b) {
a.symmetricType = b;
b.symmetricType = a;
}
/**
* A "pure-virtual" concept (ie one that cannot be directly instantiated).
* Index-only pointer types are used only for parsing index file records.
* <code>isIndexOnly</code> <code>PointerType</code>s are not used to determine relationships between words.
* @param pointerType
* @return <code>true</code> if the <code>pointerType</code> is an index-only pointer type, otherwise <code>false</code>.
*/
public static boolean isIndexOnly(final PointerType pointerType) {
return INDEX_ONLY.contains(pointerType);
}
static {
setSymmetric(ANTONYM, ANTONYM);
setSymmetric(HYPERNYM, HYPONYM);
setSymmetric(INSTANCE_HYPERNYM, INSTANCE_HYPONYM);
setSymmetric(MEMBER_MERONYM, MEMBER_HOLONYM);
setSymmetric(SUBSTANCE_MERONYM, SUBSTANCE_HOLONYM);
setSymmetric(PART_MERONYM, PART_HOLONYM);
setSymmetric(SIMILAR_TO, SIMILAR_TO);
setSymmetric(ATTRIBUTE, ATTRIBUTE);
setSymmetric(DERIVATIONALLY_RELATED, DERIVATIONALLY_RELATED);
setSymmetric(DOMAIN_OF_TOPIC, MEMBER_OF_TOPIC_DOMAIN);
setSymmetric(DOMAIN_OF_REGION, MEMBER_OF_REGION_DOMAIN);
setSymmetric(DOMAIN_OF_USAGE, MEMBER_OF_USAGE_DOMAIN);
setSymmetric(DOMAIN_OF_TOPIC, DOMAIN_MEMBER);
setSymmetric(DOMAIN_OF_REGION, DOMAIN_MEMBER);
setSymmetric(DOMAIN_OF_USAGE, DOMAIN_MEMBER);
setSymmetric(VERB_GROUP, VERB_GROUP);
/**
* Some PointerTypes are "abstract/virtual/meta", though most are concrete.<br>
* "virtual" means has superTypes and/or subTypes.<br>
* Compare to "concrete" (isolated) and "pure virtual" (incomplete) types.<br>
* It does not make sense to search for a pure-virtual type.<br>
* <br>
* virtual:
* <ul>
* <li> Hyponym, Instance </li>
* <li> Hypernym, Instance </li>
* </ul>
* <br>
* pure-virtual:
* <ul>
* <li> Holonym:: Part, Member, Substance </li>
* <li> Meronym:: Part, Member, Substance </li>
*
* <li> Domain:: {Member, Domain} X {Topic, Region, Usage} </li>
* </ul>
*
* Adjective - not sure how this fits in
* Similar To
*
* Also see -- verb only ?
*/
/**
* Usage of types, subTypes and superTypes:
* <ul>
* <li> if superTypes exist, search them, then current type </li>
* <li> if current type exists, search it, then if subTypes exist, search them </li>
* </ul>
*
* Example 1:
* { George Bush } --instance hyper--> { President of the United States }
* George Bush, <i>the instance</i>, does not particpate in any other hyper/hypo relationships.
* That said, how does he get linked to hypernym { person } ?
*
* MORE GENERAL: { President of the United States } --hyper--> { head of state } --hyper-->
* { representative } ... hyper--> ... { person } ...
* MORE_SPECIFIC: { President of the United States } --instance hypo--> { George Bush, ... }
*
* Axioms
* - if ∃ x, y s.t. InstanceHyponym(x, y), then InstanceHypernym(y, z) (symmetric)
* e.g. x=GW, y=PofUS
* - "inflection point" ? InstanceHyponym is root-tip (e.g. opposite of leaf) in ontology,
* while InstanceHypernym is leaf (living tree-sense, top/edgemost)
* - if ∃ x, y s.t. InstanceHypernym(x, y), then ∃ z s.t. Hypernym(y, z)
* e.g. x=GW, y=PofUS, z=person
* - "inheritance" ?
*/
// e.g. "Bill Clinton" has instance hypernym "president"#2
// which in turn has normal hypernyms
HYPERNYM.superTypes = Arrays.asList(INSTANCE_HYPERNYM);
// e.g. "president"#2 (* the Synset) has instance hyponyms ("George Washington", ...) AND
// normal hyponyms ("chief of state", ...). Note that while "president"#2 also
// has normal hyponyms, "President of the United States" does NOT since
// it is more lexically specified.
// FIXME this example seems to show a bad, unneeded asymmetry
HYPONYM.subTypes = Arrays.asList(INSTANCE_HYPONYM);
MERONYM.subTypes = Arrays.asList(MEMBER_MERONYM, PART_MERONYM, SUBSTANCE_MERONYM);
// don't assign superTypes since MERONYM is pure-virtual
HOLONYM.subTypes = Arrays.asList(MEMBER_HOLONYM, PART_HOLONYM, SUBSTANCE_HOLONYM);
// don't assign superTypes since HOLONYM is pure-virtual
DOMAIN.subTypes = Arrays.asList(DOMAIN_OF_TOPIC, DOMAIN_OF_REGION, DOMAIN_OF_USAGE);
// don't assign superTypes since DOMAIN is pure-virtual
}
private static final PointerType[] VALUES = values();
static PointerType fromOrdinal(final byte ordinal) {
return VALUES[ordinal];
}
/**
* @return the <code>PointerType</code> whose key matches <var>key</var>.
* @exception NoSuchElementException If <var>key</var> doesn't name any <code>PointerType</code>.
*/
public static PointerType parseKey(final CharSequence key) {
for (final PointerType pType : VALUES) {
if (pType.key.contentEquals(key)) {
return pType;
}
}
throw new NoSuchElementException("unknown link type " + key);
}
/*
* Instance Interface
*/
private final String label;
private final String longNounLabel;
private final String longVerbLabel;
private final String key;
private final int flags;
private final String toString;
private PointerType symmetricType;
private List<PointerType> subTypes;
private List<PointerType> superTypes;
PointerType(final String label, final String key, final int flags) {
this(label, key, flags, null, null);
}
PointerType(final String label, final String key, final int flags, final String longNounLabel) {
this(label, key, flags, longNounLabel, null);
}
PointerType(final String label, final String key, final int flags, final String longNounLabel, final String longVerbLabel) {
this.label = label;
this.key = key;
this.flags = flags;
this.toString = getLabel()+" "+getKey();
if (longNounLabel != null) {
this.longNounLabel = longNounLabel;
} else {
this.longNounLabel = label;
}
if (longVerbLabel != null) {
this.longVerbLabel = longVerbLabel;
} else {
if (longNounLabel != null) {
this.longVerbLabel = longNounLabel;
} else {
this.longVerbLabel = label;
}
}
this.superTypes = Collections.emptyList();
this.subTypes = Collections.emptyList();
//XXX System.err.println(this+" longNounLabel: "+this.longNounLabel+" longVerbLabel: "+this.longVerbLabel+" label: "+this.label);
}
@Override public String toString() {
return toString;
}
/**
* @return human-readable label.
*/
public String getLabel() {
return label;
}
/**
* @return labels with <code>"%s"</code> variables which can be substituted
* for to create textual content of WordNet interfaces.
*/
public String getFormatLabel(final POS pos) {
switch(pos) {
case NOUN: return longNounLabel;
case VERB: return longVerbLabel;
default: return longNounLabel;
}
}
public String getKey() {
return this.key;
}
/**
* Some <code>PointerType</code>s only apply to certain {@link POS}.
*/
public boolean appliesTo(final POS pos) {
return (flags & POS_MASK[pos.ordinal()]) != 0;
}
/**
* <code>type</code> is the opposite concept of <code>this</code>.
* For example <code>{@link PointerType#HYPERNYM}.symmetricTo({@link PointerType#HYPONYM}<code>).
*/
public boolean symmetricTo(final PointerType type) {
return symmetricType != null && symmetricType.equals(type);
}
public List<PointerType> getSuperTypes() {
return this.superTypes;
}
public List<PointerType> getSubTypes() {
return this.subTypes;
}
}
/**
* Flags for tagging a pointer type with the POS types it apples to.
* Separate class to allow PointerType enum constructor to reference it.
*/
class PointerTypeFlag {
static final int N = 1;
static final int V = 2;
static final int ADJ = 4;
static final int ADV = 8;
static final int SAT_ADJ = 16;
static final int LEXICAL = 32;
}
| src/edu/brandeis/cs/steele/wn/PointerType.java | /*
* WordNet-Java
*
* Copyright 1998 by Oliver Steele. You can use this software freely so long as you preserve
* the copyright notice and this restriction, and label your changes.
*/
package edu.brandeis.cs.steele.wn;
import java.util.*;
import static edu.brandeis.cs.steele.wn.PointerTypeFlags.*;
/** Instances of this class enumerate the possible WordNet pointer types, and
* are used to label <code>PointerType</code>s.
* Each <code>PointerType</code> carries additional information:
* <ul>
* <li> a human-readable label </li>
* <li> an optional reflexive type that labels links pointing the opposite direction </li>
* <li> an encoding of parts-of-speech that it applies to </li>
* <li> a short string (lemma) that represents it in the dictionary files </li>
* </ul>
*
* @see Pointer
* @see POS
* @author Oliver Steele, [email protected]
* @version 1.0
*/
public enum PointerType {
//consider Unicde ellipsis: …
// Nouns and Verbs
HYPERNYM("hypernym", "@", N | V, "Hypernyms (%s is a kind of ...)", "Hypernyms (%s is one way to ...)"),
INSTANCE_HYPERNYM("instance hypernym", "@i", N | V, "Instance Hypernyms (%s is an instance of ...)"),
HYPONYM("hyponym", "~", N | V, "Hyponyms (... is a kind of %s)", "Troponyms (... are particular ways to %s)"),
INSTANCE_HYPONYM("instance hyponym", "~i", N | V, "Instance Hyponyms (... is an instance of %s)"),
DERIVATIONALLY_RELATED("derivationally related", "+", N | V, "Derivationally related forms"),
// Nouns and Adjectives
ATTRIBUTE("attribute", "=", N | ADJ, "%s is a value of ..."),
SEE_ALSO("also see", "^", N | ADJ | LEXICAL),
// Verbs
ENTAILMENT("entailment", "*", V, "%s entails doing ..."),
CAUSE("cause", ">", V, null, "%s causes ..."),
VERB_GROUP("verb group", "$", V),
// Nouns
MEMBER_MERONYM("member meronym", "%m", N, "Meronyms (parts of %s)"),
SUBSTANCE_MERONYM("substance meronym", "%s", N),
PART_MERONYM("part meronym", "%p", N),
MEMBER_HOLONYM("member holonym", "#m", N),
SUBSTANCE_HOLONYM("substance holonym", "#s", N),
PART_HOLONYM("part holonym", "#p", N, "Holonyms (%s is part of ...)"),
MEMBER_OF_TOPIC_DOMAIN("Member of TOPIC domain", "-c", N),
MEMBER_OF_REGION_DOMAIN("Member of REGION domain", "-r", N),
MEMBER_OF_USAGE_DOMAIN("Member of USAGE domain", "-u", N),
// Adjectives
SIMILAR_TO("similar to", "&", ADJ),
PARTICIPLE_OF("participle of", "<", ADJ | LEXICAL),
PERTAINYM("pertainym", "\\", ADJ | LEXICAL, "... are nouns related to %s"),
// Adverbs
DERIVED("derived from", "\\", ADV), // from adjective
// All parts of speech
ANTONYM("antonym", "!", N | V | ADJ | ADV | LEXICAL, "Antonyms"),
DOMAIN_OF_TOPIC("Domain of synset - TOPIC", ";c", N | V | ADJ | ADV),
///**/MEMBER_OF_THIS_DOMAIN_TOPIC("Member of this domain - TOPIC", "-c", N | V | ADJ | ADV),
DOMAIN_OF_REGION("Domain of synset - REGION", ";r", N | V | ADJ | ADV),
///**/MEMBER_OF_THIS_DOMAIN_REGION("Member of this domain - REGION", "-r", N | V | ADJ | ADV),
DOMAIN_OF_USAGE("Domain of synset - USAGE", ";u", N | V | ADJ | ADV),
///**/MEMBER_OF_THIS_DOMAIN_USAGE("Member of this domain - USAGE", "-u", N | V | ADJ | ADV),
DOMAIN_MEMBER("Domain Member", "-", N | V | ADJ | ADV),
DOMAIN("Domain", ";", N | V | ADJ | ADV);
//OLD private static final POS[] CATS = {POS.NOUN, POS.VERB, POS.ADJ, POS.ADV, POS.SAT_ADJ};
private static final int[] POS_MASK = {N, V, ADJ, ADV, SAT_ADJ, LEXICAL};
/** A list of all <code>PointerType</code>s. */
public static final EnumSet<PointerType> TYPES = EnumSet.of(
ANTONYM, HYPERNYM, HYPONYM, ATTRIBUTE, SEE_ALSO,
ENTAILMENT, CAUSE, VERB_GROUP,
MEMBER_MERONYM, SUBSTANCE_MERONYM, PART_MERONYM,
MEMBER_HOLONYM, SUBSTANCE_HOLONYM, PART_HOLONYM,
SIMILAR_TO, PARTICIPLE_OF, PERTAINYM, DERIVED,
DOMAIN_OF_TOPIC, DOMAIN_OF_USAGE, DOMAIN_OF_REGION,
///**/MEMBER_OF_THIS_DOMAIN_TOPIC,
///**/MEMBER_OF_THIS_DOMAIN_REGION,
///**/MEMBER_OF_THIS_DOMAIN_USAGE,
MEMBER_OF_TOPIC_DOMAIN, MEMBER_OF_REGION_DOMAIN, MEMBER_OF_USAGE_DOMAIN,
DERIVATIONALLY_RELATED,
INSTANCE_HYPERNYM, INSTANCE_HYPONYM
);
public static final Set<PointerType> INDEX_ONLY = EnumSet.of(DOMAIN_MEMBER, DOMAIN);
static {
assert EnumSet.complementOf(TYPES).equals(INDEX_ONLY);
}
static private void setSymmetric(final PointerType a, final PointerType b) {
a.symmetricType = b;
b.symmetricType = a;
}
/**
* Index-only pointer types are used for the sole purpose of parsing index file records.
* They are not used to determine relationships between words.
* @param pType
* @return True if the pType is an index-only pointer type. Otherwise, it is false.
*/
public static boolean isIndexOnly(final PointerType pType) {
return INDEX_ONLY.contains(pType);
}
static {
setSymmetric(ANTONYM, ANTONYM);
setSymmetric(HYPERNYM, HYPONYM);
setSymmetric(INSTANCE_HYPERNYM, INSTANCE_HYPONYM);
setSymmetric(MEMBER_MERONYM, MEMBER_HOLONYM);
setSymmetric(SUBSTANCE_MERONYM, SUBSTANCE_HOLONYM);
setSymmetric(PART_MERONYM, PART_HOLONYM);
setSymmetric(SIMILAR_TO, SIMILAR_TO);
setSymmetric(ATTRIBUTE, ATTRIBUTE);
setSymmetric(DERIVATIONALLY_RELATED, DERIVATIONALLY_RELATED);
setSymmetric(DOMAIN_OF_TOPIC, MEMBER_OF_TOPIC_DOMAIN);
setSymmetric(DOMAIN_OF_REGION, MEMBER_OF_REGION_DOMAIN);
setSymmetric(DOMAIN_OF_USAGE, MEMBER_OF_USAGE_DOMAIN);
setSymmetric(DOMAIN_OF_TOPIC, DOMAIN_MEMBER);
setSymmetric(DOMAIN_OF_REGION, DOMAIN_MEMBER);
setSymmetric(DOMAIN_OF_USAGE, DOMAIN_MEMBER);
setSymmetric(VERB_GROUP, VERB_GROUP);
}
private static final PointerType[] VALUES = values();
static PointerType fromOrdinal(final byte ordinal) {
return VALUES[ordinal];
}
/** Return the <code>PointerType</code> whose key matches <var>key</var>.
* @exception NoSuchElementException If <var>key</var> doesn't name any <code>PointerType</code>.
*/
public static PointerType parseKey(final CharSequence key) {
for (final PointerType pType : VALUES) {
if (pType.key.contentEquals(key)) {
return pType;
}
}
throw new NoSuchElementException("unknown link type " + key);
}
/*
* Instance Interface
*/
private final String label;
private final String longNounLabel;
private final String longVerbLabel;
private final String key;
private final int flags;
private final String toString;
private PointerType symmetricType;
PointerType(final String label, final String key, final int flags) {
this(label, key, flags, null, null);
}
PointerType(final String label, final String key, final int flags, final String longNounLabel) {
this(label, key, flags, longNounLabel, null);
}
PointerType(final String label, final String key, final int flags, final String longNounLabel, final String longVerbLabel) {
this.label = label;
this.key = key;
this.flags = flags;
this.toString = getLabel()+" "+getKey();
if (longNounLabel != null) {
this.longNounLabel = longNounLabel;
} else {
this.longNounLabel = label;
}
if (longVerbLabel != null) {
this.longVerbLabel = longVerbLabel;
} else {
if(longNounLabel != null) {
this.longVerbLabel = longNounLabel;
} else {
this.longVerbLabel = label;
}
}
//XXX System.err.println(this+" longNounLabel: "+this.longNounLabel+" longVerbLabel: "+this.longVerbLabel+" label: "+this.label);
}
@Override public String toString() {
return toString;
}
public String getLabel() {
return label;
}
public String getFormatLabel(final POS pos) {
switch(pos) {
case NOUN: return longNounLabel;
case VERB: return longVerbLabel;
default: return longNounLabel;
}
}
public String getKey() {
return this.key;
}
public boolean appliesTo(final POS pos) {
return (flags & POS_MASK[pos.ordinal()]) != 0;
}
public boolean symmetricTo(final PointerType type) {
return symmetricType != null && symmetricType.equals(type);
}
}
/**
* Flags for tagging a pointer type with the POS types it apples to.
* Separate class to allow PointerType enum constructor to reference it.
*/
class PointerTypeFlags {
static final int N = 1;
static final int V = 2;
static final int ADJ = 4;
static final int ADV = 8;
static final int SAT_ADJ = 16;
static final int LEXICAL = 32;
}
| tentative getSuperTypes()/getSubTypes(), comments, removed dead commented code
git-svn-id: 0f0e769425a95b277772daee6ac27d370147d87f@182 158bccb4-7c0b-4fb3-968f-7c40bf2d9062
| src/edu/brandeis/cs/steele/wn/PointerType.java | tentative getSuperTypes()/getSubTypes(), comments, removed dead commented code | <ide><path>rc/edu/brandeis/cs/steele/wn/PointerType.java
<ide> /*
<del> * WordNet-Java
<del> *
<ide> * Copyright 1998 by Oliver Steele. You can use this software freely so long as you preserve
<ide> * the copyright notice and this restriction, and label your changes.
<ide> */
<ide> package edu.brandeis.cs.steele.wn;
<ide>
<ide> import java.util.*;
<del>import static edu.brandeis.cs.steele.wn.PointerTypeFlags.*;
<add>import static edu.brandeis.cs.steele.wn.PointerTypeFlag.*;
<ide>
<ide> /** Instances of this class enumerate the possible WordNet pointer types, and
<del> * are used to label <code>PointerType</code>s.
<add> * are used to label {@link Pointer}s.
<ide> * Each <code>PointerType</code> carries additional information:
<ide> * <ul>
<ide> * <li> a human-readable label </li>
<del> * <li> an optional reflexive type that labels links pointing the opposite direction </li>
<add> * <li> an optional symmetric (i.e. reflexive) type that labels links pointing the opposite direction </li>
<ide> * <li> an encoding of parts-of-speech that it applies to </li>
<ide> * <li> a short string (lemma) that represents it in the dictionary files </li>
<ide> * </ul>
<ide> *
<add> * @see <a href="http://wordnet.princeton.edu/man/wnsearch.3WN#sect4>http://wordnet.princeton.edu/man/wnsearch.3WN#sect4</a>
<add> * @see <a href="http://wordnet.princeton.edu/man/wngloss.7WN.html#sect4">Glossary of WordNet Terms</a>
<ide> * @see Pointer
<ide> * @see POS
<ide> * @author Oliver Steele, [email protected]
<ide> * @version 1.0
<ide> */
<ide> public enum PointerType {
<del> //consider Unicde ellipsis: …
<add> // consider Unicde ellipsis: "…" instead of "..."
<ide>
<ide> // Nouns and Verbs
<ide> HYPERNYM("hypernym", "@", N | V, "Hypernyms (%s is a kind of ...)", "Hypernyms (%s is one way to ...)"),
<ide> DERIVATIONALLY_RELATED("derivationally related", "+", N | V, "Derivationally related forms"),
<ide>
<ide> // Nouns and Adjectives
<del> ATTRIBUTE("attribute", "=", N | ADJ, "%s is a value of ..."),
<add> ATTRIBUTE("attribute", "=", N | ADJ, "Attribute (%s is a value of ...)"),
<ide> SEE_ALSO("also see", "^", N | ADJ | LEXICAL),
<ide>
<ide> // Verbs
<ide> VERB_GROUP("verb group", "$", V),
<ide>
<ide> // Nouns
<del> MEMBER_MERONYM("member meronym", "%m", N, "Meronyms (parts of %s)"),
<del> SUBSTANCE_MERONYM("substance meronym", "%s", N),
<del> PART_MERONYM("part meronym", "%p", N),
<del> MEMBER_HOLONYM("member holonym", "#m", N),
<del> SUBSTANCE_HOLONYM("substance holonym", "#s", N),
<del> PART_HOLONYM("part holonym", "#p", N, "Holonyms (%s is part of ...)"),
<del> MEMBER_OF_TOPIC_DOMAIN("Member of TOPIC domain", "-c", N),
<del> MEMBER_OF_REGION_DOMAIN("Member of REGION domain", "-r", N),
<del> MEMBER_OF_USAGE_DOMAIN("Member of USAGE domain", "-u", N),
<add> /**
<add> * A word that names a part of a larger whole, aka "part name".
<add> * Pure-virtual PointerType.
<add> * @see PointerType#MEMBER_MERONYM
<add> * @see PointerType#SUBSTANCE_MERONYM
<add> * @see PointerType#PART_MERONYM
<add> */
<add> MERONYM("meronym", "%" /* non-existent */, N),
<add> MEMBER_MERONYM("member meronym", "%m", N, "Member Meronyms (... are members of %s)"),
<add> PART_MERONYM("part meronym", "%p", N, "Part Meronyms (... are parts of %s)"),
<add> SUBSTANCE_MERONYM("substance meronym", "%s", N, "Substance Meronyms (... are substances of %s)"),
<add>
<add> /**
<add> * A word that names the whole of which a given word is a part.
<add> * Pure-virtual PointerType.
<add> * @see PointerType#MEMBER_HOLONYM
<add> * @see PointerType#SUBSTANCE_HOLONYM
<add> * @see PointerType#PART_HOLONYM
<add> */
<add> HOLONYM("holonym", "#" /* non-existent up */, N),
<add> MEMBER_HOLONYM("member holonym", "#m", N, "Member Holonyms (%s is a member of ...)"),
<add> SUBSTANCE_HOLONYM("substance holonym", "#s", N, "Substance Holonyms (%s is a substance of ...)"),
<add> PART_HOLONYM("part holonym", "#p", N, "Part Holonyms (%s is a part of ...)"),
<add>
<add> MEMBER_OF_TOPIC_DOMAIN("Member of TOPIC domain", "-c", N), // topic term
<add> MEMBER_OF_REGION_DOMAIN("Member of REGION domain", "-r", N), // regional term
<add> MEMBER_OF_USAGE_DOMAIN("Member of USAGE domain", "-u", N), // ?
<ide>
<ide> // Adjectives
<ide> SIMILAR_TO("similar to", "&", ADJ),
<ide> DERIVED("derived from", "\\", ADV), // from adjective
<ide>
<ide> // All parts of speech
<del> ANTONYM("antonym", "!", N | V | ADJ | ADV | LEXICAL, "Antonyms"),
<del> DOMAIN_OF_TOPIC("Domain of synset - TOPIC", ";c", N | V | ADJ | ADV),
<del> ///**/MEMBER_OF_THIS_DOMAIN_TOPIC("Member of this domain - TOPIC", "-c", N | V | ADJ | ADV),
<del> DOMAIN_OF_REGION("Domain of synset - REGION", ";r", N | V | ADJ | ADV),
<del> ///**/MEMBER_OF_THIS_DOMAIN_REGION("Member of this domain - REGION", "-r", N | V | ADJ | ADV),
<del> DOMAIN_OF_USAGE("Domain of synset - USAGE", ";u", N | V | ADJ | ADV),
<del> ///**/MEMBER_OF_THIS_DOMAIN_USAGE("Member of this domain - USAGE", "-u", N | V | ADJ | ADV),
<add> ANTONYM("antonym", "!", N | V | ADJ | ADV | LEXICAL, "Antonyms (... is the opposite of %s)"),
<add>
<add> DOMAIN_OF_TOPIC("Domain of synset - TOPIC", ";c", N | V | ADJ | ADV), // a domain
<add> DOMAIN_OF_REGION("Domain of synset - REGION", ";r", N | V | ADJ | ADV), // a region
<add> DOMAIN_OF_USAGE("Domain of synset - USAGE", ";u", N | V | ADJ | ADV), // ?
<add>
<add> /**
<add> * Pure-virtual PointerType.
<add> * @see PointerType#MEMBER_OF_TOPIC_DOMAIN
<add> * @see PointerType#MEMBER_OF_REGION_DOMAIN
<add> * @see PointerType#MEMBER_OF_USAGE_DOMAIN
<add> */
<ide> DOMAIN_MEMBER("Domain Member", "-", N | V | ADJ | ADV),
<add>
<add> /**
<add> * Pure-virtual PointerType.
<add> * @see PointerType#DOMAIN_OF_TOPIC
<add> * @see PointerType#DOMAIN_OF_REGION
<add> * @see PointerType#DOMAIN_OF_USAGE
<add> */
<ide> DOMAIN("Domain", ";", N | V | ADJ | ADV);
<ide>
<del>
<del> //OLD private static final POS[] CATS = {POS.NOUN, POS.VERB, POS.ADJ, POS.ADV, POS.SAT_ADJ};
<ide> private static final int[] POS_MASK = {N, V, ADJ, ADV, SAT_ADJ, LEXICAL};
<del>
<ide>
<ide> /** A list of all <code>PointerType</code>s. */
<ide> public static final EnumSet<PointerType> TYPES = EnumSet.of(
<ide> MEMBER_HOLONYM, SUBSTANCE_HOLONYM, PART_HOLONYM,
<ide> SIMILAR_TO, PARTICIPLE_OF, PERTAINYM, DERIVED,
<ide> DOMAIN_OF_TOPIC, DOMAIN_OF_USAGE, DOMAIN_OF_REGION,
<del> ///**/MEMBER_OF_THIS_DOMAIN_TOPIC,
<del> ///**/MEMBER_OF_THIS_DOMAIN_REGION,
<del> ///**/MEMBER_OF_THIS_DOMAIN_USAGE,
<ide> MEMBER_OF_TOPIC_DOMAIN, MEMBER_OF_REGION_DOMAIN, MEMBER_OF_USAGE_DOMAIN,
<ide> DERIVATIONALLY_RELATED,
<ide> INSTANCE_HYPERNYM, INSTANCE_HYPONYM
<ide> );
<ide>
<del> public static final Set<PointerType> INDEX_ONLY = EnumSet.of(DOMAIN_MEMBER, DOMAIN);
<add> //XXX this seems to indicate DOMAIN implies DOMAIN_PART
<add> public static final Set<PointerType> INDEX_ONLY = EnumSet.of(DOMAIN_MEMBER, DOMAIN, HOLONYM, MERONYM);
<ide>
<ide> static {
<ide> assert EnumSet.complementOf(TYPES).equals(INDEX_ONLY);
<ide> }
<ide>
<ide> /**
<del> * Index-only pointer types are used for the sole purpose of parsing index file records.
<del> * They are not used to determine relationships between words.
<del> * @param pType
<del> * @return True if the pType is an index-only pointer type. Otherwise, it is false.
<del> */
<del> public static boolean isIndexOnly(final PointerType pType) {
<del> return INDEX_ONLY.contains(pType);
<add> * A "pure-virtual" concept (ie one that cannot be directly instantiated).
<add> * Index-only pointer types are used only for parsing index file records.
<add> * <code>isIndexOnly</code> <code>PointerType</code>s are not used to determine relationships between words.
<add> * @param pointerType
<add> * @return <code>true</code> if the <code>pointerType</code> is an index-only pointer type, otherwise <code>false</code>.
<add> */
<add> public static boolean isIndexOnly(final PointerType pointerType) {
<add> return INDEX_ONLY.contains(pointerType);
<ide> }
<ide>
<ide> static {
<ide> setSymmetric(DOMAIN_OF_REGION, DOMAIN_MEMBER);
<ide> setSymmetric(DOMAIN_OF_USAGE, DOMAIN_MEMBER);
<ide> setSymmetric(VERB_GROUP, VERB_GROUP);
<add>
<add> /**
<add> * Some PointerTypes are "abstract/virtual/meta", though most are concrete.<br>
<add> * "virtual" means has superTypes and/or subTypes.<br>
<add> * Compare to "concrete" (isolated) and "pure virtual" (incomplete) types.<br>
<add> * It does not make sense to search for a pure-virtual type.<br>
<add> * <br>
<add> * virtual:
<add> * <ul>
<add> * <li> Hyponym, Instance </li>
<add> * <li> Hypernym, Instance </li>
<add> * </ul>
<add> * <br>
<add> * pure-virtual:
<add> * <ul>
<add> * <li> Holonym:: Part, Member, Substance </li>
<add> * <li> Meronym:: Part, Member, Substance </li>
<add> *
<add> * <li> Domain:: {Member, Domain} X {Topic, Region, Usage} </li>
<add> * </ul>
<add> *
<add> * Adjective - not sure how this fits in
<add> * Similar To
<add> *
<add> * Also see -- verb only ?
<add> */
<add>
<add> /**
<add> * Usage of types, subTypes and superTypes:
<add> * <ul>
<add> * <li> if superTypes exist, search them, then current type </li>
<add> * <li> if current type exists, search it, then if subTypes exist, search them </li>
<add> * </ul>
<add> *
<add> * Example 1:
<add> * { George Bush } --instance hyper--> { President of the United States }
<add> * George Bush, <i>the instance</i>, does not particpate in any other hyper/hypo relationships.
<add> * That said, how does he get linked to hypernym { person } ?
<add> *
<add> * MORE GENERAL: { President of the United States } --hyper--> { head of state } --hyper-->
<add> * { representative } ... hyper--> ... { person } ...
<add> * MORE_SPECIFIC: { President of the United States } --instance hypo--> { George Bush, ... }
<add> *
<add> * Axioms
<add> * - if ∃ x, y s.t. InstanceHyponym(x, y), then InstanceHypernym(y, z) (symmetric)
<add> * e.g. x=GW, y=PofUS
<add> * - "inflection point" ? InstanceHyponym is root-tip (e.g. opposite of leaf) in ontology,
<add> * while InstanceHypernym is leaf (living tree-sense, top/edgemost)
<add> * - if ∃ x, y s.t. InstanceHypernym(x, y), then ∃ z s.t. Hypernym(y, z)
<add> * e.g. x=GW, y=PofUS, z=person
<add> * - "inheritance" ?
<add> */
<add>
<add> // e.g. "Bill Clinton" has instance hypernym "president"#2
<add> // which in turn has normal hypernyms
<add> HYPERNYM.superTypes = Arrays.asList(INSTANCE_HYPERNYM);
<add> // e.g. "president"#2 (* the Synset) has instance hyponyms ("George Washington", ...) AND
<add> // normal hyponyms ("chief of state", ...). Note that while "president"#2 also
<add> // has normal hyponyms, "President of the United States" does NOT since
<add> // it is more lexically specified.
<add> // FIXME this example seems to show a bad, unneeded asymmetry
<add> HYPONYM.subTypes = Arrays.asList(INSTANCE_HYPONYM);
<add>
<add> MERONYM.subTypes = Arrays.asList(MEMBER_MERONYM, PART_MERONYM, SUBSTANCE_MERONYM);
<add> // don't assign superTypes since MERONYM is pure-virtual
<add> HOLONYM.subTypes = Arrays.asList(MEMBER_HOLONYM, PART_HOLONYM, SUBSTANCE_HOLONYM);
<add> // don't assign superTypes since HOLONYM is pure-virtual
<add>
<add> DOMAIN.subTypes = Arrays.asList(DOMAIN_OF_TOPIC, DOMAIN_OF_REGION, DOMAIN_OF_USAGE);
<add> // don't assign superTypes since DOMAIN is pure-virtual
<ide> }
<ide>
<ide> private static final PointerType[] VALUES = values();
<ide> return VALUES[ordinal];
<ide> }
<ide>
<del> /** Return the <code>PointerType</code> whose key matches <var>key</var>.
<add> /**
<add> * @return the <code>PointerType</code> whose key matches <var>key</var>.
<ide> * @exception NoSuchElementException If <var>key</var> doesn't name any <code>PointerType</code>.
<ide> */
<ide> public static PointerType parseKey(final CharSequence key) {
<ide> private final int flags;
<ide> private final String toString;
<ide> private PointerType symmetricType;
<add> private List<PointerType> subTypes;
<add> private List<PointerType> superTypes;
<ide>
<ide> PointerType(final String label, final String key, final int flags) {
<ide> this(label, key, flags, null, null);
<ide> if (longVerbLabel != null) {
<ide> this.longVerbLabel = longVerbLabel;
<ide> } else {
<del> if(longNounLabel != null) {
<add> if (longNounLabel != null) {
<ide> this.longVerbLabel = longNounLabel;
<ide> } else {
<ide> this.longVerbLabel = label;
<ide> }
<ide> }
<add> this.superTypes = Collections.emptyList();
<add> this.subTypes = Collections.emptyList();
<ide> //XXX System.err.println(this+" longNounLabel: "+this.longNounLabel+" longVerbLabel: "+this.longVerbLabel+" label: "+this.label);
<ide> }
<ide>
<ide> return toString;
<ide> }
<ide>
<add> /**
<add> * @return human-readable label.
<add> */
<ide> public String getLabel() {
<ide> return label;
<ide> }
<ide>
<add> /**
<add> * @return labels with <code>"%s"</code> variables which can be substituted
<add> * for to create textual content of WordNet interfaces.
<add> */
<ide> public String getFormatLabel(final POS pos) {
<ide> switch(pos) {
<ide> case NOUN: return longNounLabel;
<ide> return this.key;
<ide> }
<ide>
<add> /**
<add> * Some <code>PointerType</code>s only apply to certain {@link POS}.
<add> */
<ide> public boolean appliesTo(final POS pos) {
<ide> return (flags & POS_MASK[pos.ordinal()]) != 0;
<ide> }
<ide>
<add> /**
<add> * <code>type</code> is the opposite concept of <code>this</code>.
<add> * For example <code>{@link PointerType#HYPERNYM}.symmetricTo({@link PointerType#HYPONYM}<code>).
<add> */
<ide> public boolean symmetricTo(final PointerType type) {
<ide> return symmetricType != null && symmetricType.equals(type);
<add> }
<add>
<add> public List<PointerType> getSuperTypes() {
<add> return this.superTypes;
<add> }
<add>
<add> public List<PointerType> getSubTypes() {
<add> return this.subTypes;
<ide> }
<ide> }
<ide>
<ide> * Flags for tagging a pointer type with the POS types it apples to.
<ide> * Separate class to allow PointerType enum constructor to reference it.
<ide> */
<del>class PointerTypeFlags {
<add>class PointerTypeFlag {
<ide> static final int N = 1;
<ide> static final int V = 2;
<ide> static final int ADJ = 4; |
|
Java | mit | error: pathspec 'app/src/main/java/com/uic/sandeep/phonepark/DisplayNearestParkBlock.java' did not match any file(s) known to git
| 930783400b389f84e98a6c4d0953495253c24124 | 1 | sandeepsas/PhonePark | package com.uic.sandeep.phonepark;
/**
* Created by Sandeep on 3/15/2016.
*/
import android.location.Location;
import android.os.AsyncTask;
import com.google.android.gms.maps.model.LatLng;
import com.uic.sandeep.phonepark.blocksmap.ParkingBlock;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sandeep on 1/23/2016.
*/
/* Inner class to get response */
class DisplayNearestParkBlock extends AsyncTask<Void, Void, List<ParkingBlock>> {
StringBuffer chaine = new StringBuffer("");
List<ParkingBlock> nearestParkingBlocks = new ArrayList<ParkingBlock>();
//List<ParkingBlock> pb_list = new ArrayList<ParkingBlock>();
List<LatLng> pt_list = new ArrayList<LatLng>();
Location loc;
DisplayNearestParkBlock(Location location){
this.loc = location;
}
protected void onPreExecute(Void aVoid) {
MainActivity.text_navigation.setText("Connecting to server ...");
}
@Override
protected List<ParkingBlock> doInBackground(Void... voids) {
try {
///* http://73.247.220.84:8080/hello?UserID=a108eec35f0daf33&Latitude=41.8693826&Longitude=-87.6630133&TimeStamp=Current*/
StringBuilder urlString = new StringBuilder();
urlString.append(Constants.SYSTEM_IP+"/nn");
urlString.append("?UserID=");
urlString.append(MainActivity.userID);
urlString.append("&Latitude=");
urlString.append(loc.getLatitude());
urlString.append("&Longitude=");
urlString.append(loc.getLongitude());
URL url = new URL(urlString.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
System.out.println("URL"+urlString.toString());
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
String[] line_split = line.split(",");
for(int i=0;i<line_split.length-1;i=i+6){
double lat1 = Double.parseDouble(line_split[i]);
double lon1 = Double.parseDouble(line_split[i+1]);
double lat2 = Double.parseDouble(line_split[i+2]);
double lon2 = Double.parseDouble(line_split[i+3]);
double probability = Double.parseDouble(line_split[i+4]);
String streetID = line_split[i+5];
ParkingBlock near_block = new ParkingBlock(streetID,
new LatLng(0.0,0.0),
new LatLng(lat1,lon1),
new LatLng(lat2,lon2),
probability);
nearestParkingBlocks.add(near_block);
}
chaine.append(line);
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return this.nearestParkingBlocks;
}
@Override
protected void onPostExecute(List<ParkingBlock> blocks) {
super.onPostExecute(blocks);
MainActivity.showNearestAvailabilityMap(blocks);
/*DisplayRouteAsyncTask searchPark = new DisplayRouteAsyncTask(loc);
searchPark.execute();*/
new SearchParkAsyncTask(loc).execute();
}
}
| app/src/main/java/com/uic/sandeep/phonepark/DisplayNearestParkBlock.java | Beta version release v2.01
| app/src/main/java/com/uic/sandeep/phonepark/DisplayNearestParkBlock.java | Beta version release v2.01 | <ide><path>pp/src/main/java/com/uic/sandeep/phonepark/DisplayNearestParkBlock.java
<add>package com.uic.sandeep.phonepark;
<add>
<add>/**
<add> * Created by Sandeep on 3/15/2016.
<add> */
<add>
<add>import android.location.Location;
<add>import android.os.AsyncTask;
<add>
<add>import com.google.android.gms.maps.model.LatLng;
<add>import com.uic.sandeep.phonepark.blocksmap.ParkingBlock;
<add>
<add>import java.io.BufferedReader;
<add>import java.io.InputStream;
<add>import java.io.InputStreamReader;
<add>import java.net.HttpURLConnection;
<add>import java.net.URL;
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>/**
<add> * Created by Sandeep on 1/23/2016.
<add> */
<add>/* Inner class to get response */
<add>class DisplayNearestParkBlock extends AsyncTask<Void, Void, List<ParkingBlock>> {
<add> StringBuffer chaine = new StringBuffer("");
<add>
<add> List<ParkingBlock> nearestParkingBlocks = new ArrayList<ParkingBlock>();
<add> //List<ParkingBlock> pb_list = new ArrayList<ParkingBlock>();
<add> List<LatLng> pt_list = new ArrayList<LatLng>();
<add> Location loc;
<add> DisplayNearestParkBlock(Location location){
<add> this.loc = location;
<add> }
<add>
<add>
<add> protected void onPreExecute(Void aVoid) {
<add> MainActivity.text_navigation.setText("Connecting to server ...");
<add> }
<add> @Override
<add> protected List<ParkingBlock> doInBackground(Void... voids) {
<add>
<add> try {
<add>///* http://73.247.220.84:8080/hello?UserID=a108eec35f0daf33&Latitude=41.8693826&Longitude=-87.6630133&TimeStamp=Current*/
<add> StringBuilder urlString = new StringBuilder();
<add> urlString.append(Constants.SYSTEM_IP+"/nn");
<add>
<add> urlString.append("?UserID=");
<add> urlString.append(MainActivity.userID);
<add> urlString.append("&Latitude=");
<add> urlString.append(loc.getLatitude());
<add> urlString.append("&Longitude=");
<add> urlString.append(loc.getLongitude());
<add>
<add> URL url = new URL(urlString.toString());
<add> HttpURLConnection connection = (HttpURLConnection) url.openConnection();
<add> System.out.println("URL"+urlString.toString());
<add>
<add> connection.connect();
<add>
<add> InputStream inputStream = connection.getInputStream();
<add>
<add>
<add> BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
<add> String line = "";
<add> while ((line = rd.readLine()) != null) {
<add> String[] line_split = line.split(",");
<add> for(int i=0;i<line_split.length-1;i=i+6){
<add>
<add> double lat1 = Double.parseDouble(line_split[i]);
<add> double lon1 = Double.parseDouble(line_split[i+1]);
<add>
<add> double lat2 = Double.parseDouble(line_split[i+2]);
<add> double lon2 = Double.parseDouble(line_split[i+3]);
<add>
<add> double probability = Double.parseDouble(line_split[i+4]);
<add>
<add> String streetID = line_split[i+5];
<add>
<add> ParkingBlock near_block = new ParkingBlock(streetID,
<add> new LatLng(0.0,0.0),
<add> new LatLng(lat1,lon1),
<add> new LatLng(lat2,lon2),
<add> probability);
<add> nearestParkingBlocks.add(near_block);
<add> }
<add>
<add> chaine.append(line);
<add> System.out.println(line);
<add> }
<add>
<add> } catch (Exception e) {
<add> e.printStackTrace();
<add> }
<add> return this.nearestParkingBlocks;
<add> }
<add>
<add> @Override
<add> protected void onPostExecute(List<ParkingBlock> blocks) {
<add> super.onPostExecute(blocks);
<add> MainActivity.showNearestAvailabilityMap(blocks);
<add> /*DisplayRouteAsyncTask searchPark = new DisplayRouteAsyncTask(loc);
<add> searchPark.execute();*/
<add> new SearchParkAsyncTask(loc).execute();
<add> }
<add>
<add>
<add>}
<add>
<add> |
|
Java | mit | e0785a2228c7eee6cbb5aa43d0567c2f830b995f | 0 | Stolpersteine/stolpersteine-android | package com.dreiri.stolpersteine.activities;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import com.dreiri.stolpersteine.R;
import com.dreiri.stolpersteine.api.NetworkService;
import com.dreiri.stolpersteine.api.NetworkService.Callback;
import com.dreiri.stolpersteine.api.SearchData;
import com.dreiri.stolpersteine.api.SynchronizationController;
import com.dreiri.stolpersteine.api.model.Stolperstein;
import com.dreiri.stolpersteine.clustering.MapClusterController;
import com.dreiri.stolpersteine.utils.AndroidVersionsUnification;
import com.dreiri.stolpersteine.utils.LocationFinder;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapActivity extends Activity implements OnInfoWindowClickListener, SynchronizationController.Listener {
private LatLng berlinLatLng;
private int berlinZoom;
private final int autoCompleteDropDownListSize = 10;
private final int autoCompleteActivationMinLength = 3;
private NetworkService networkService = new NetworkService();
private SynchronizationController synchronizationController = new SynchronizationController(networkService);
private MapClusterController<Stolperstein> mapClusterController;
private GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_map);
// Set up map and clustering
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.fragmentMap)).getMap();
berlinLatLng = getLocationLatLng(R.array.Berlin);
berlinZoom = 12;
CameraUpdate region = CameraUpdateFactory.newLatLngZoom(berlinLatLng, berlinZoom);
map.moveCamera(region);
map.setOnInfoWindowClickListener(this);
mapClusterController = new MapClusterController<Stolperstein>(map);
// Start synchronizing data
synchronizationController.setListener(this);
synchronizationController.synchronize();
// Search interface
final AutoCompleteTextView autoCompleteTextViewQuery = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextViewQuery);
Drawable background = new ColorDrawable(Color.GRAY);
background.setAlpha(128);
AndroidVersionsUnification.setBackgroundForView(autoCompleteTextViewQuery, background);
autoCompleteTextViewQuery.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
SearchData searchData = new SearchData();
searchData.setKeyword(s.toString());
networkService.retrieveStolpersteine(searchData, 0, autoCompleteDropDownListSize, new Callback() {
@Override
public void onStolpersteineRetrieved(List<Stolperstein> stolpersteine) {
String[] suggestions = new String[stolpersteine.size()];
ListIterator<Stolperstein> iterator = stolpersteine.listIterator();
while (iterator.hasNext()) {
int idx = iterator.nextIndex();
Stolperstein matchedStolperstein = iterator.next();
String name = matchedStolperstein.getPerson().getNameAsString();
String street = matchedStolperstein.getLocation().getStreet();
suggestions[idx] = name + ", " + street;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MapActivity.this, android.R.layout.simple_dropdown_item_1line, suggestions);
autoCompleteTextViewQuery.setThreshold(autoCompleteActivationMinLength);
autoCompleteTextViewQuery.setAdapter(adapter);
}
});
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_positioning:
LocationFinder locationFinder = new LocationFinder(MapActivity.this);
LatLng currentLocation = new LatLng(locationFinder.getLat(), locationFinder.getLng());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15));
map.animateCamera(CameraUpdateFactory.zoomTo(16), 2000, null);
break;
default:
break;
}
return true;
}
@Override
public void onInfoWindowClick(Marker marker) {
ArrayList<Stolperstein> stolpersteine = mapClusterController.getItems(marker);
if (!stolpersteine.isEmpty()) {
Intent intent = new Intent(MapActivity.this, InfoActivity.class);
intent.putParcelableArrayListExtra("stolpersteine", stolpersteine);
startActivity(intent);
}
}
@Override
public void onStolpersteineAdded(List<Stolperstein> stolpersteine) {
ArrayList<MarkerOptions> optionsList = new ArrayList<MarkerOptions>(stolpersteine.size());
for (Stolperstein stolperstein : stolpersteine) {
MarkerOptions markerOptions = new MarkerOptions().position(stolperstein.getLocation().getCoordinates())
.title(stolperstein.getPerson().getNameAsString())
.snippet(stolperstein.getLocation().getAddressAsString())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.stolpersteine_tile));
optionsList.add(markerOptions);
}
mapClusterController.addMarkers(optionsList, stolpersteine);
}
private LatLng getLocationLatLng(int location) {
String[] locationCoordinates = getResources().getStringArray(location);
double lat = Double.valueOf(locationCoordinates[0]);
double lng = Double.valueOf(locationCoordinates[1]);
return new LatLng(lat, lng);
}
} | Stolpersteine/src/com/dreiri/stolpersteine/activities/MapActivity.java | package com.dreiri.stolpersteine.activities;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import com.dreiri.stolpersteine.R;
import com.dreiri.stolpersteine.api.NetworkService;
import com.dreiri.stolpersteine.api.NetworkService.Callback;
import com.dreiri.stolpersteine.api.SearchData;
import com.dreiri.stolpersteine.api.SynchronizationController;
import com.dreiri.stolpersteine.api.model.Stolperstein;
import com.dreiri.stolpersteine.clustering.MapClusterController;
import com.dreiri.stolpersteine.utils.AndroidVersionsUnification;
import com.dreiri.stolpersteine.utils.LocationFinder;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapActivity extends Activity implements OnInfoWindowClickListener, SynchronizationController.Listener {
private LatLng berlinLatLng;
private int berlinZoom;
private final int autoCompleteDropDownListSize = 10;
private final int autoCompleteActivationMinLength = 3;
private NetworkService networkService = new NetworkService();
private SynchronizationController synchronizationController = new SynchronizationController(networkService);
private MapClusterController<Stolperstein> mapClusterController;
private GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Set up map and clustering
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.fragmentMap)).getMap();
berlinLatLng = getLocationLatLng(R.array.Berlin);
berlinZoom = 12;
CameraUpdate region = CameraUpdateFactory.newLatLngZoom(berlinLatLng, berlinZoom);
map.moveCamera(region);
map.setOnInfoWindowClickListener(this);
mapClusterController = new MapClusterController<Stolperstein>(map);
// Start synchronizing data
synchronizationController.setListener(this);
synchronizationController.synchronize();
// Search interface
final AutoCompleteTextView autoCompleteTextViewQuery = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextViewQuery);
Drawable background = new ColorDrawable(Color.GRAY);
background.setAlpha(128);
AndroidVersionsUnification.setBackgroundForView(autoCompleteTextViewQuery, background);
autoCompleteTextViewQuery.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
SearchData searchData = new SearchData();
searchData.setKeyword(s.toString());
networkService.retrieveStolpersteine(searchData, 0, autoCompleteDropDownListSize, new Callback() {
@Override
public void onStolpersteineRetrieved(List<Stolperstein> stolpersteine) {
String[] suggestions = new String[stolpersteine.size()];
ListIterator<Stolperstein> iterator = stolpersteine.listIterator();
while (iterator.hasNext()) {
int idx = iterator.nextIndex();
Stolperstein matchedStolperstein = iterator.next();
String name = matchedStolperstein.getPerson().getNameAsString();
String street = matchedStolperstein.getLocation().getStreet();
suggestions[idx] = name + ", " + street;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MapActivity.this, android.R.layout.simple_dropdown_item_1line, suggestions);
autoCompleteTextViewQuery.setThreshold(autoCompleteActivationMinLength);
autoCompleteTextViewQuery.setAdapter(adapter);
}
});
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_positioning:
LocationFinder locationFinder = new LocationFinder(MapActivity.this);
LatLng currentLocation = new LatLng(locationFinder.getLat(), locationFinder.getLng());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15));
map.animateCamera(CameraUpdateFactory.zoomTo(16), 2000, null);
break;
default:
break;
}
return true;
}
@Override
public void onInfoWindowClick(Marker marker) {
ArrayList<Stolperstein> stolpersteine = mapClusterController.getItems(marker);
if (!stolpersteine.isEmpty()) {
Intent intent = new Intent(MapActivity.this, InfoActivity.class);
intent.putParcelableArrayListExtra("stolpersteine", stolpersteine);
startActivity(intent);
}
}
@Override
public void onStolpersteineAdded(List<Stolperstein> stolpersteine) {
ArrayList<MarkerOptions> optionsList = new ArrayList<MarkerOptions>(stolpersteine.size());
for (Stolperstein stolperstein : stolpersteine) {
MarkerOptions markerOptions = new MarkerOptions().position(stolperstein.getLocation().getCoordinates())
.title(stolperstein.getPerson().getNameAsString())
.snippet(stolperstein.getLocation().getAddressAsString())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.stolpersteine_tile));
optionsList.add(markerOptions);
}
mapClusterController.addMarkers(optionsList, stolpersteine);
}
private LatLng getLocationLatLng(int location) {
String[] locationCoordinates = getResources().getStringArray(location);
double lat = Double.valueOf(locationCoordinates[0]);
double lng = Double.valueOf(locationCoordinates[1]);
return new LatLng(lat, lng);
}
} | Disable action bar in map activity
| Stolpersteine/src/com/dreiri/stolpersteine/activities/MapActivity.java | Disable action bar in map activity | <ide><path>tolpersteine/src/com/dreiri/stolpersteine/activities/MapActivity.java
<ide> import android.text.TextWatcher;
<ide> import android.view.Menu;
<ide> import android.view.MenuItem;
<add>import android.view.Window;
<ide> import android.widget.ArrayAdapter;
<ide> import android.widget.AutoCompleteTextView;
<ide>
<ide> @Override
<ide> protected void onCreate(Bundle savedInstanceState) {
<ide> super.onCreate(savedInstanceState);
<add> requestWindowFeature(Window.FEATURE_NO_TITLE);
<ide> setContentView(R.layout.activity_map);
<ide>
<ide> // Set up map and clustering
<ide> }
<ide> });
<ide> }
<del>
<add>
<ide> @Override
<ide> public boolean onCreateOptionsMenu(Menu menu) {
<ide> // Inflate the menu; this adds items to the action bar if it is present. |
|
Java | bsd-3-clause | 379d5a4f69e578a362a47025954f95d5668947da | 0 | hanmomhanda/DesignPatterns,hanmomhanda/DesignPatterns,hanmomhanda/DesignPatterns,hanmomhanda/DesignPatterns | package TemplateCallback.java;
import java.io.*;
public class TemplateCallbackPattern {
public static void main(String[] args){
String filePath = "TemplateCallback/data.txt";
Template template = new Template();
// Client 입장에서 파일을 다루면서도,
// Template 덕분에 try/catch 같은 것을 신경 쓸 필요가 없다.
// biz 로직만 callback으로 템플릿에게 주입해준다.
template.processFile(filePath, 0, new CallBack<Integer>() {
@Override
public Integer processFileContents(String currVal, Integer prevVal) {
return Integer.valueOf(currVal) + prevVal;
}
});
// try/catch 불필요
// 곱하기 로직을 callback으로 템플릿에게 주입
template.processFile(filePath, new Long(1), new CallBack<Long>() {
@Override
public Long processFileContents(String currVal, Long prevVal) {
return Long.valueOf(currVal) * prevVal;
}
});
template.processFile(filePath, "", new CallBack<String>() {
@Override
public String processFileContents(String currVal, String prevVal) {
return currVal + prevVal;
}
});
}
}
class Template {
/**
* 파일 열기, 읽기, 자원반환, 예외 처리 등의 반복적인 항목은 템플릿에서 처리
* 파일 내용의 처리는 callback에 위임
*
* @param filePath
* @param initValue
* @param callback
*/
public <T> void processFile(String filePath, T initValue, CallBack<T> callback){
FileReader fr = null;
BufferedReader br = null;
T result = initValue;
try {
fr = new FileReader(filePath);
br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null){
// 아래의 biz 로직을 callback에게 위임
result = callback.processFileContents(line, result);
}
System.out.println(result);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
interface CallBack<T> {
T processFileContents(String currVal, T prevVal);
} | TemplateCallback/java/TemplateCallbackPattern.java | package TemplateCallback.java;
import java.io.*;
public class TemplateCallbackPattern {
public static void main(String[] args){
String filePath = "TemplateCallback/data.txt";
Template template = new Template();
// Client 입장에서 파일을 다루면서도,
// Template 덕분에 try/catch 같은 것을 신경 쓸 필요가 없다.
// biz 로직만 callback으로 템플릿에게 주입해준다.
template.processFile(filePath, 0, new CallBack<Integer>() {
@Override
public Integer processFileContents(String currVal, Integer prevVal) {
return Integer.valueOf(currVal) + prevVal;
}
});
// try/catch 불필요
// 곱하기 로직을 callback으로 템플릿에게 주입
template.processFile(filePath, new Long(1), new CallBack<Long>() {
@Override
public Long processFileContents(String currVal, Long prevVal) {
return Long.valueOf(currVal) * prevVal;
}
});
template.processFile(filePath, "", new CallBack<String>() {
@Override
public String processFileContents(String currVal, String prevVal) {
return currVal + prevVal;
}
});
}
}
class Template {
/**
* 파일 열기, 읽기, 자원반환, 예외 처리 등의 반복적인 항목은 템플릿에서 처리
* 파일 내용의 처리는 callback에 위임
*
* @param filePath
* @param initValue
* @param callback
*/
public <T> void processFile(String filePath, T initValue, CallBack<T> callback){
BufferedReader br = null;
T result = initValue;
try {
br = new BufferedReader(new FileReader(filePath));
String line;
while ((line = br.readLine()) != null){
// 아래의 biz 로직을 callback에게 위임
result = callback.processFileContents(line, result);
}
System.out.println(result);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
interface CallBack<T> {
T processFileContents(String currVal, T prevVal);
} | 자바 템플릿 메서드 패턴에 FileReader를 close() 안 해주는 오류 수정
| TemplateCallback/java/TemplateCallbackPattern.java | 자바 템플릿 메서드 패턴에 FileReader를 close() 안 해주는 오류 수정 | <ide><path>emplateCallback/java/TemplateCallbackPattern.java
<ide> * @param callback
<ide> */
<ide> public <T> void processFile(String filePath, T initValue, CallBack<T> callback){
<add> FileReader fr = null;
<ide> BufferedReader br = null;
<add>
<ide> T result = initValue;
<ide> try {
<del> br = new BufferedReader(new FileReader(filePath));
<add> fr = new FileReader(filePath);
<add> br = new BufferedReader(fr);
<ide> String line;
<ide> while ((line = br.readLine()) != null){
<ide> // 아래의 biz 로직을 callback에게 위임
<ide> } catch (IOException e) {
<ide> e.printStackTrace();
<ide> } finally {
<add> if (fr != null) {
<add> try {
<add> fr.close();
<add> } catch (IOException e) {
<add> e.printStackTrace();
<add> }
<add> }
<add>
<ide> if (br != null) {
<ide> try {
<ide> br.close(); |
|
Java | apache-2.0 | 6528a0101493415ddfb8f2dc434ad8a2fa53a78e | 0 | stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck | /*
* This file is part of dependency-check-maven.
*
* 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.
*
* Copyright (c) 2014 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.maven;
import com.github.packageurl.MalformedPackageURLException;
import com.github.packageurl.PackageURL.StandardTypes;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.doxia.sink.Sink;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.License;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.DefaultProjectBuildingRequest;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.reporting.MavenReport;
import org.apache.maven.reporting.MavenReportException;
import org.apache.maven.settings.Proxy;
import org.apache.maven.settings.Server;
import org.apache.maven.shared.transfer.artifact.ArtifactCoordinate;
import org.apache.maven.shared.transfer.artifact.DefaultArtifactCoordinate;
import org.apache.maven.shared.transfer.artifact.TransferUtils;
import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolver;
import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolverException;
import org.eclipse.aether.artifact.ArtifactType;
import org.apache.maven.shared.artifact.filter.PatternExcludesArtifactFilter;
import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder;
import org.apache.maven.shared.dependency.graph.DependencyGraphBuilderException;
import org.apache.maven.shared.dependency.graph.DependencyNode;
import org.apache.maven.shared.dependency.graph.filter.ArtifactDependencyNodeFilter;
import org.apache.maven.shared.dependency.graph.internal.DefaultDependencyNode;
import org.apache.maven.shared.model.fileset.FileSet;
import org.apache.maven.shared.model.fileset.util.FileSetManager;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.JarAnalyzer;
import org.owasp.dependencycheck.data.nexus.MavenArtifact;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.EvidenceType;
import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.exception.DependencyNotFoundException;
import org.owasp.dependencycheck.exception.ExceptionCollection;
import org.owasp.dependencycheck.exception.ReportException;
import org.owasp.dependencycheck.utils.Checksum;
import org.owasp.dependencycheck.utils.Filter;
import org.owasp.dependencycheck.utils.Settings;
import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher;
import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher;
import org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.Restriction;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.shared.dependency.graph.traversal.CollectingDependencyNodeVisitor;
import org.owasp.dependencycheck.agent.DependencyCheckScanAgent;
import org.owasp.dependencycheck.dependency.naming.GenericIdentifier;
import org.owasp.dependencycheck.dependency.naming.Identifier;
import org.owasp.dependencycheck.dependency.naming.PurlIdentifier;
import org.apache.maven.shared.dependency.graph.traversal.DependencyNodeVisitor;
import org.apache.maven.shared.dependency.graph.traversal.FilteringDependencyNodeVisitor;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.reporting.ReportGenerator;
import org.owasp.dependencycheck.utils.SeverityUtil;
import org.owasp.dependencycheck.xml.pom.Model;
import org.owasp.dependencycheck.xml.pom.PomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
/**
* @author Jeremy Long
*/
public abstract class BaseDependencyCheckMojo extends AbstractMojo implements MavenReport {
//<editor-fold defaultstate="collapsed" desc="Private fields">
/**
* The properties file location.
*/
private static final String PROPERTIES_FILE = "mojo.properties";
/**
* System specific new line character.
*/
private static final String NEW_LINE = System.getProperty("line.separator", "\n").intern();
/**
* Pattern to include all files in a FileSet.
*/
private static final String INCLUDE_ALL = "**/*";
/**
* A flag indicating whether or not the Maven site is being generated.
*/
private boolean generatingSite = false;
/**
* The configured settings.
*/
private Settings settings = null;
//</editor-fold>
// <editor-fold defaultstate="collapsed" desc="Maven bound parameters and components">
/**
* Sets whether or not the mojo should fail if an error occurs.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "failOnError", defaultValue = "true", required = true)
private boolean failOnError;
/**
* The Maven Project Object.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "project", required = true, readonly = true)
private MavenProject project;
/**
* List of Maven project of the current build
*/
@SuppressWarnings("CanBeFinal")
@Parameter(readonly = true, required = true, property = "reactorProjects")
private List<MavenProject> reactorProjects;
/**
* The entry point towards a Maven version independent way of resolving
* artifacts (handles both Maven 3.0 Sonatype and Maven 3.1+ eclipse Aether
* implementations).
*/
@SuppressWarnings("CanBeFinal")
@Component
private ArtifactResolver artifactResolver;
/**
* The Maven Session.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(defaultValue = "${session}", readonly = true, required = true)
private MavenSession session;
/**
* Component within Maven to build the dependency graph.
*/
@Component
private DependencyGraphBuilder dependencyGraphBuilder;
/**
* The output directory. This generally maps to "target".
*/
@SuppressWarnings("CanBeFinal")
@Parameter(defaultValue = "${project.build.directory}", required = true)
private File outputDirectory;
/**
* This is a reference to the >reporting< sections
* <code>outputDirectory</code>. This cannot be configured in the
* dependency-check mojo directly. This generally maps to "target/site".
*/
@Parameter(property = "project.reporting.outputDirectory", readonly = true)
private File reportOutputDirectory;
/**
* Specifies if the build should be failed if a CVSS score above a specified
* level is identified. The default is 11 which means since the CVSS scores
* are 0-10, by default the build will never fail.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "failBuildOnCVSS", defaultValue = "11", required = true)
private float failBuildOnCVSS = 11;
/**
* Specifies the CVSS score that is considered a "test" failure when
* generating a jUnit style report. The default value is 0 - all
* vulnerabilities are considered a failure.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "junitFailOnCVSS", defaultValue = "0", required = true)
private float junitFailOnCVSS = 0;
/**
* Fail the build if any dependency has a vulnerability listed.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "failBuildOnAnyVulnerability", defaultValue = "false", required = true)
private boolean failBuildOnAnyVulnerability = false;
/**
* Sets whether auto-updating of the NVD CVE/CPE data is enabled. It is not
* recommended that this be turned to false. Default is true.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "autoUpdate")
private Boolean autoUpdate;
/**
* Sets whether Experimental analyzers are enabled. Default is false.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "enableExperimental")
private Boolean enableExperimental;
/**
* Sets whether retired analyzers are enabled. Default is false.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "enableRetired")
private Boolean enableRetired;
/**
* Sets whether the Golang Dependency analyzer is enabled. Default is true.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "golangDepEnabled")
private Boolean golangDepEnabled;
/**
* Sets whether Golang Module Analyzer is enabled; this requires `go` to be
* installed. Default is true.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "golangModEnabled")
private Boolean golangModEnabled;
/**
* Sets the path to `go`.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "pathToGo")
private String pathToGo;
/**
* Use pom dependency information for snapshot dependencies that are part of
* the Maven reactor while aggregate scanning a multi-module project.
*/
@Parameter(property = "dependency-check.virtualSnapshotsFromReactor", defaultValue = "true")
private Boolean virtualSnapshotsFromReactor;
/**
* The report format to be generated (HTML, XML, JUNIT, CSV, JSON, ALL).
* Multiple formats can be selected using a comma delineated list.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "format", defaultValue = "HTML", required = true)
private String format = "HTML";
/**
* Whether or not the XML and JSON report formats should be pretty printed.
* The default is false.
*/
@Parameter(property = "prettyPrint")
private Boolean prettyPrint;
/**
* The report format to be generated (HTML, XML, JUNIT, CSV, JSON, ALL).
* Multiple formats can be selected using a comma delineated list.
*/
@Parameter(property = "formats", required = true)
private String[] formats;
/**
* The Maven settings.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "mavenSettings", defaultValue = "${settings}")
private org.apache.maven.settings.Settings mavenSettings;
/**
* The maven settings proxy id.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "mavenSettingsProxyId")
private String mavenSettingsProxyId;
/**
* The Connection Timeout.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "connectionTimeout")
private String connectionTimeout;
/**
* Sets whether dependency-check should check if there is a new version
* available.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "versionCheckEnabled", defaultValue = "true")
private boolean versionCheckEnabled;
/**
* The paths to the suppression files. The parameter value can be a local
* file path, a URL to a suppression file, or even a reference to a file on
* the class path (see
* https://github.com/jeremylong/DependencyCheck/issues/1878#issuecomment-487533799)
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "suppressionFiles")
private String[] suppressionFiles;
/**
* The paths to the suppression file. The parameter value can be a local
* file path, a URL to a suppression file, or even a reference to a file on
* the class path (see
* https://github.com/jeremylong/DependencyCheck/issues/1878#issuecomment-487533799)
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "suppressionFile")
private String suppressionFile;
/**
* The path to the hints file.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "hintsFile")
private String hintsFile;
/**
* Flag indicating whether or not to show a summary in the output.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "showSummary", defaultValue = "true")
private boolean showSummary = true;
/**
* Whether or not the Jar Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "jarAnalyzerEnabled")
private Boolean jarAnalyzerEnabled;
/**
* Whether or not the Archive Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "archiveAnalyzerEnabled")
private Boolean archiveAnalyzerEnabled;
/**
* Sets whether the Python Distribution Analyzer will be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "pyDistributionAnalyzerEnabled")
private Boolean pyDistributionAnalyzerEnabled;
/**
* Sets whether the Python Package Analyzer will be used.
*/
@Parameter(property = "pyPackageAnalyzerEnabled")
private Boolean pyPackageAnalyzerEnabled;
/**
* Sets whether the Ruby Gemspec Analyzer will be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "rubygemsAnalyzerEnabled")
private Boolean rubygemsAnalyzerEnabled;
/**
* Sets whether or not the openssl Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "opensslAnalyzerEnabled")
private Boolean opensslAnalyzerEnabled;
/**
* Sets whether or not the CMake Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "cmakeAnalyzerEnabled")
private Boolean cmakeAnalyzerEnabled;
/**
* Sets whether or not the autoconf Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "autoconfAnalyzerEnabled")
private Boolean autoconfAnalyzerEnabled;
/**
* Sets whether or not the pip Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "pipAnalyzerEnabled")
private Boolean pipAnalyzerEnabled;
/**
* Sets whether or not the pipfile Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "pipfileAnalyzerEnabled")
private Boolean pipfileAnalyzerEnabled;
/**
* Sets whether or not the PHP Composer Lock File Analyzer should be used.
*/
@Parameter(property = "composerAnalyzerEnabled")
private Boolean composerAnalyzerEnabled;
/**
* Sets whether or not the Node.js Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nodeAnalyzerEnabled")
private Boolean nodeAnalyzerEnabled;
/**
* Sets whether or not the Node Audit Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nodeAuditAnalyzerEnabled")
private Boolean nodeAuditAnalyzerEnabled;
/**
* Sets whether or not the Node Audit Analyzer should use a local cache.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nodeAuditAnalyzerUseCache")
private Boolean nodeAuditAnalyzerUseCache;
/**
* Sets whether or not the Node Audit Analyzer should skip devDependencies.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nodeAuditSkipDevDependencies")
private Boolean nodeAuditSkipDevDependencies;
/**
* Sets whether or not the Retirejs Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "retireJsAnalyzerEnabled")
private Boolean retireJsAnalyzerEnabled;
/**
* The Retire JS repository URL.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "retireJsUrl")
private String retireJsUrl;
/**
* Whether the Retire JS repository will be updated regardless of the
* `autoupdate` settings.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "retireJsForceUpdate")
private Boolean retireJsForceUpdate;
/**
* Whether or not the .NET Assembly Analyzer is enabled.
*/
@Parameter(property = "assemblyAnalyzerEnabled")
private Boolean assemblyAnalyzerEnabled;
/**
* Whether or not the .NET Nuspec Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nuspecAnalyzerEnabled")
private Boolean nuspecAnalyzerEnabled;
/**
* Whether or not the .NET packages.config Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nugetconfAnalyzerEnabled")
private Boolean nugetconfAnalyzerEnabled;
/**
* Whether or not the Central Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "centralAnalyzerEnabled")
private Boolean centralAnalyzerEnabled;
/**
* Whether or not the Central Analyzer should use a local cache.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "centralAnalyzerUseCache")
private Boolean centralAnalyzerUseCache;
/**
* Whether or not the Artifactory Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerEnabled")
private Boolean artifactoryAnalyzerEnabled;
/**
* The serverId inside the settings.xml containing the username and token to
* access artifactory
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerServerId")
private String artifactoryAnalyzerServerId;
/**
* The username (only used with API token) to connect to Artifactory
* instance
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerUsername")
private String artifactoryAnalyzerUsername;
/**
* The API token to connect to Artifactory instance
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerApiToken")
private String artifactoryAnalyzerApiToken;
/**
* The bearer token to connect to Artifactory instance
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerBearerToken")
private String artifactoryAnalyzerBearerToken;
/**
* The Artifactory URL for the Artifactory analyzer.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerUrl")
private String artifactoryAnalyzerUrl;
/**
* Whether Artifactory should be accessed through a proxy or not
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerUseProxy")
private Boolean artifactoryAnalyzerUseProxy;
/**
* Whether the Artifactory analyzer should be run in parallel or not.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerParallelAnalysis", defaultValue = "true")
private Boolean artifactoryAnalyzerParallelAnalysis;
/**
* Whether or not the Nexus Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nexusAnalyzerEnabled")
private Boolean nexusAnalyzerEnabled;
/**
* Whether or not the Sonatype OSS Index analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "ossindexAnalyzerEnabled")
private Boolean ossindexAnalyzerEnabled;
/**
* Whether or not the Sonatype OSS Index analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "ossindexAnalyzerUseCache")
private Boolean ossindexAnalyzerUseCache;
/**
* URL of the Sonatype OSS Index service.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "ossindexAnalyzerUrl")
private String ossindexAnalyzerUrl;
/**
* The id of a server defined in the settings.xml that configures the
* credentials (username and password) for a OSS Index service.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "ossIndexServerId")
private String ossIndexServerId;
/**
* Whether or not the Elixir Mix Audit Analyzer is enabled.
*/
@Parameter(property = "mixAuditAnalyzerEnabled")
private Boolean mixAuditAnalyzerEnabled;
/**
* Sets the path for the mix_audit binary.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "mixAuditPath")
private String mixAuditPath;
/**
* Whether or not the Ruby Bundle Audit Analyzer is enabled.
*/
@Parameter(property = "bundleAuditAnalyzerEnabled")
private Boolean bundleAuditAnalyzerEnabled;
/**
* Sets the path for the bundle-audit binary.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "bundleAuditPath")
private String bundleAuditPath;
/**
* Sets the path for the working directory that the bundle-audit binary
* should be executed from.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "bundleAuditWorkingDirectory")
private String bundleAuditWorkingDirectory;
/**
* Whether or not the CocoaPods Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "cocoapodsAnalyzerEnabled")
private Boolean cocoapodsAnalyzerEnabled;
/**
* Whether or not the Swift package Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "swiftPackageManagerAnalyzerEnabled")
private Boolean swiftPackageManagerAnalyzerEnabled;
/**
* The URL of a Nexus server's REST API end point
* (http://domain/nexus/service/local).
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nexusUrl")
private String nexusUrl;
/**
* The id of a server defined in the settings.xml that configures the
* credentials (username and password) for a Nexus server's REST API end
* point. When not specified the communication with the Nexus server's REST
* API will be unauthenticated.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nexusServerId")
private String nexusServerId;
/**
* Whether or not the configured proxy is used to connect to Nexus.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nexusUsesProxy")
private Boolean nexusUsesProxy;
/**
* The database connection string.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "connectionString")
private String connectionString;
/**
* The database driver name. An example would be org.h2.Driver.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "databaseDriverName")
private String databaseDriverName;
/**
* The path to the database driver if it is not on the class path.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "databaseDriverPath")
private String databaseDriverPath;
/**
* The server id in the settings.xml; used to retrieve encrypted passwords
* from the settings.xml.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "serverId")
private String serverId;
/**
* A reference to the settings.xml settings.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(defaultValue = "${settings}", readonly = true, required = true)
private org.apache.maven.settings.Settings settingsXml;
/**
* The security dispatcher that can decrypt passwords in the settings.xml.
*/
@Component(role = SecDispatcher.class, hint = "default")
private SecDispatcher securityDispatcher;
/**
* The database user name.
*/
@Parameter(property = "databaseUser")
private String databaseUser;
/**
* The password to use when connecting to the database.
*/
@Parameter(property = "databasePassword")
private String databasePassword;
/**
* A comma-separated list of file extensions to add to analysis next to jar,
* zip, ....
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "zipExtensions")
private String zipExtensions;
/**
* Skip Dependency Check altogether.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "dependency-check.skip", defaultValue = "false")
private boolean skip = false;
/**
* Skip Analysis for Test Scope Dependencies.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "skipTestScope", defaultValue = "true")
private boolean skipTestScope = true;
/**
* Skip Analysis for Runtime Scope Dependencies.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "skipRuntimeScope", defaultValue = "false")
private boolean skipRuntimeScope = false;
/**
* Skip Analysis for Provided Scope Dependencies.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "skipProvidedScope", defaultValue = "false")
private boolean skipProvidedScope = false;
/**
* Skip Analysis for System Scope Dependencies.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "skipSystemScope", defaultValue = "false")
private boolean skipSystemScope = false;
/**
* Skip Analysis for dependencyManagement section.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "skipDependencyManagement", defaultValue = "true")
private boolean skipDependencyManagement = true;
/**
* Skip analysis for dependencies which type matches this regular
* expression. This filters on the `type` of dependency as defined in the
* dependency section: jar, pom, test-jar, etc.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "skipArtifactType")
private String skipArtifactType;
/**
* The data directory, hold DC SQL DB.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "dataDirectory")
private String dataDirectory;
/**
* The name of the DC DB.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "dbFilename")
private String dbFilename;
/**
* Data Mirror URL for CVE 1.2.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "cveUrlModified")
private String cveUrlModified;
/**
* Base Data Mirror URL for CVE 1.2.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "cveUrlBase")
private String cveUrlBase;
/**
* The username to use when connecting to the CVE-URL.
*/
@Parameter(property = "cveUser")
private String cveUser;
/**
* The password to authenticate to the CVE-URL.
*/
@Parameter(property = "cvePassword")
private String cvePassword;
/**
* The server id in the settings.xml; used to retrieve encrypted passwords
* from the settings.xml for cve-URLs.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "cveServerId")
private String cveServerId;
/**
* /**
* Optionally skip excessive CVE update checks for a designated duration in
* hours.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "cveValidForHours")
private Integer cveValidForHours;
/**
* The path to dotnet core.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "pathToCore")
private String pathToCore;
/**
* The RetireJS Analyzer configuration:
* <pre>
* filters: an array of filter patterns that are used to exclude JS files that contain a match
* filterNonVulnerable: a boolean that when true will remove non-vulnerable JS from the report
*
* Example:
* <retirejs>
* <filters>
* <filter>copyright 2018\(c\) Jeremy Long</filter>
* </filters>
* <filterNonVulnerable>true</filterNonVulnerable>
* </retirejs>
* </pre>
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "retirejs")
private Retirejs retirejs;
/**
* The list of artifacts (and their transitive dependencies) to exclude from
* the check.
*/
@Parameter
private List<String> excludes;
/**
* The artifact scope filter.
*/
private Filter<String> artifactScopeExcluded;
/**
* Filter for artifact type.
*/
private Filter<String> artifactTypeExcluded;
/**
* An collection of <code>fileSet</code>s that specify additional files
* and/or directories (from the basedir) to analyze as part of the scan. If
* not specified, defaults to Maven conventions of: src/main/resources,
* src/main/filters, and src/main/webapp. Note, this cannot be set via the
* command line - use `scanDirectory` instead.
*/
@Parameter
private List<FileSet> scanSet;
/**
* A list of directories to scan. Note, this should only be used via the
* command line - if configuring the directories to scan consider using the
* `scanSet` instead.
*/
@Parameter(property = "scanDirectory")
private List<String> scanDirectory;
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="Base Maven implementation">
/**
* Determines if the groupId, artifactId, and version of the Maven
* dependency and artifact match.
*
* @param d the Maven dependency
* @param a the Maven artifact
* @return true if the groupId, artifactId, and version match
*/
private static boolean artifactsMatch(org.apache.maven.model.Dependency d, Artifact a) {
return isEqualOrNull(a.getArtifactId(), d.getArtifactId())
&& isEqualOrNull(a.getGroupId(), d.getGroupId())
&& isEqualOrNull(a.getVersion(), d.getVersion());
}
/**
* Compares two strings for equality; if both strings are null they are
* considered equal.
*
* @param left the first string to compare
* @param right the second string to compare
* @return true if the strings are equal or if they are both null; otherwise
* false.
*/
private static boolean isEqualOrNull(String left, String right) {
return (left != null && left.equals(right)) || (left == null && right == null);
}
/**
* Executes dependency-check.
*
* @throws MojoExecutionException thrown if there is an exception executing
* the mojo
* @throws MojoFailureException thrown if dependency-check failed the build
*/
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
generatingSite = false;
final boolean shouldSkip = Boolean.parseBoolean(System.getProperty("dependency-check.skip", Boolean.toString(skip)));
if (shouldSkip) {
getLog().info("Skipping " + getName(Locale.US));
} else {
project.setContextValue("dependency-check-output-dir", this.outputDirectory);
runCheck();
}
}
/**
* Generates the Dependency-Check Site Report.
*
* @param sink the sink to write the report to
* @param locale the locale to use when generating the report
* @throws MavenReportException if a maven report exception occurs
* @deprecated use
* {@link #generate(org.apache.maven.doxia.sink.Sink, java.util.Locale)}
* instead.
*/
@Override
@Deprecated
public final void generate(@SuppressWarnings("deprecation") org.codehaus.doxia.sink.Sink sink, Locale locale) throws MavenReportException {
generate((Sink) sink, locale);
}
/**
* Returns true if the Maven site is being generated.
*
* @return true if the Maven site is being generated
*/
protected boolean isGeneratingSite() {
return generatingSite;
}
/**
* Returns the connection string.
*
* @return the connection string
*/
protected String getConnectionString() {
return connectionString;
}
/**
* Returns if the mojo should fail the build if an exception occurs.
*
* @return whether or not the mojo should fail the build
*/
protected boolean isFailOnError() {
return failOnError;
}
/**
* Generates the Dependency-Check Site Report.
*
* @param sink the sink to write the report to
* @param locale the locale to use when generating the report
* @throws MavenReportException if a maven report exception occurs
*/
public void generate(Sink sink, Locale locale) throws MavenReportException {
final boolean shouldSkip = Boolean.parseBoolean(System.getProperty("dependency-check.skip", Boolean.toString(skip)));
if (shouldSkip) {
getLog().info("Skipping report generation " + getName(Locale.US));
return;
}
generatingSite = true;
project.setContextValue("dependency-check-output-dir", getReportOutputDirectory());
try {
runCheck();
} catch (MojoExecutionException ex) {
throw new MavenReportException(ex.getMessage(), ex);
} catch (MojoFailureException ex) {
getLog().warn("Vulnerabilities were identifies that exceed the CVSS threshold for failing the build");
}
}
/**
* Returns the correct output directory depending on if a site is being
* executed or not.
*
* @return the directory to write the report(s)
* @throws MojoExecutionException thrown if there is an error loading the
* file path
*/
protected File getCorrectOutputDirectory() throws MojoExecutionException {
return getCorrectOutputDirectory(this.project);
}
/**
* Returns the correct output directory depending on if a site is being
* executed or not.
*
* @param current the Maven project to get the output directory from
* @return the directory to write the report(s)
*/
protected File getCorrectOutputDirectory(MavenProject current) {
final Object obj = current.getContextValue("dependency-check-output-dir");
if (obj != null && obj instanceof File) {
return (File) obj;
}
//else we guess
File target = new File(current.getBuild().getDirectory());
if (target.getParentFile() != null && "target".equals(target.getParentFile().getName())) {
target = target.getParentFile();
}
return target;
}
/**
* Scans the project's artifacts and adds them to the engine's dependency
* list.
*
* @param project the project to scan the dependencies of
* @param engine the engine to use to scan the dependencies
* @return a collection of exceptions that may have occurred while resolving
* and scanning the dependencies
*/
protected ExceptionCollection scanArtifacts(MavenProject project, Engine engine) {
return scanArtifacts(project, engine, false);
}
/**
* Scans the project's artifacts and adds them to the engine's dependency
* list.
*
* @param project the project to scan the dependencies of
* @param engine the engine to use to scan the dependencies
* @param aggregate whether the scan is part of an aggregate build
* @return a collection of exceptions that may have occurred while resolving
* and scanning the dependencies
*/
protected ExceptionCollection scanArtifacts(MavenProject project, Engine engine, boolean aggregate) {
try {
final List<String> filterItems = Collections.singletonList(String.format("%s:%s", project.getGroupId(), project.getArtifactId()));
final ProjectBuildingRequest buildingRequest = newResolveArtifactProjectBuildingRequest(project);
//For some reason the filter does not filter out the project being analyzed
//if we pass in the filter below instead of null to the dependencyGraphBuilder
final DependencyNode dn = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, null, reactorProjects);
final CollectingDependencyNodeVisitor collectorVisitor = new CollectingDependencyNodeVisitor();
// exclude artifact by pattern and its dependencies
final DependencyNodeVisitor transitiveFilterVisitor = new FilteringDependencyTransitiveNodeVisitor(collectorVisitor,
new ArtifactDependencyNodeFilter(new PatternExcludesArtifactFilter(getExcludes())));
// exclude exact artifact but not its dependencies, this filter must be appied on the root for first otherwise
// in case the exclude has the same groupId of the current bundle its direct dependencies are not visited
final DependencyNodeVisitor artifactFilter = new FilteringDependencyNodeVisitor(transitiveFilterVisitor,
new ArtifactDependencyNodeFilter(new ExcludesArtifactFilter(filterItems)));
dn.accept(artifactFilter);
//collect dependencies with the filter - see comment above.
final List<DependencyNode> nodes = new ArrayList<>(collectorVisitor.getNodes());
return collectDependencies(engine, project, nodes, buildingRequest, aggregate);
} catch (DependencyGraphBuilderException ex) {
final String msg = String.format("Unable to build dependency graph on project %s", project.getName());
getLog().debug(msg, ex);
return new ExceptionCollection(ex);
}
}
/**
* Converts the dependency to a dependency node object.
*
* @param nodes the list of dependency nodes
* @param buildingRequest the Maven project building request
* @param parent the parent node
* @param dependency the dependency to convert
* @return the resulting dependency node
* @throws ArtifactResolverException thrown if the artifact could not be
* retrieved
*/
private DependencyNode toDependencyNode(List<DependencyNode> nodes, ProjectBuildingRequest buildingRequest,
DependencyNode parent, org.apache.maven.model.Dependency dependency) throws ArtifactResolverException {
final DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate();
coordinate.setGroupId(dependency.getGroupId());
coordinate.setArtifactId(dependency.getArtifactId());
String version = null;
final VersionRange vr;
try {
vr = VersionRange.createFromVersionSpec(dependency.getVersion());
} catch (InvalidVersionSpecificationException ex) {
throw new ArtifactResolverException("Invalid version specification: "
+ dependency.getGroupId() + ":"
+ dependency.getArtifactId() + ":"
+ dependency.getVersion(), ex);
}
if (vr.hasRestrictions()) {
version = findVersion(nodes, dependency.getGroupId(), dependency.getArtifactId());
if (version == null) {
//TODO - this still may fail if the restriction is not a valid version number (i.e. only 2.9 instead of 2.9.1)
//need to get available versions and filter on the restrictions.
if (vr.getRecommendedVersion() != null) {
version = vr.getRecommendedVersion().toString();
} else if (vr.hasRestrictions()) {
for (Restriction restriction : vr.getRestrictions()) {
if (restriction.getLowerBound() != null) {
version = restriction.getLowerBound().toString();
}
if (restriction.getUpperBound() != null) {
version = restriction.getUpperBound().toString();
}
}
} else {
version = vr.toString();
}
}
}
if (version == null) {
version = dependency.getVersion();
}
coordinate.setVersion(version);
final ArtifactType type = session.getRepositorySession().getArtifactTypeRegistry().get(dependency.getType());
coordinate.setExtension(type.getExtension());
coordinate.setClassifier((null == dependency.getClassifier() || dependency.getClassifier().isEmpty())
? type.getClassifier() : dependency.getClassifier());
final Artifact artifact = artifactResolver.resolveArtifact(buildingRequest, coordinate).getArtifact();
artifact.setScope(dependency.getScope());
return new DefaultDependencyNode(parent, artifact, dependency.getVersion(), dependency.getScope(), null);
}
/**
* Returns the version from the list of nodes that match the given groupId
* and artifactID.
*
* @param nodes the nodes to search
* @param groupId the group id to find
* @param artifactId the artifact id to find
* @return the version from the list of nodes that match the given groupId
* and artifactID; otherwise <code>null</code> is returned
*/
private String findVersion(List<DependencyNode> nodes, String groupId, String artifactId) {
final Optional<DependencyNode> f = nodes.stream().filter(p
-> groupId.equals(p.getArtifact().getGroupId())
&& artifactId.equals(p.getArtifact().getArtifactId())).findFirst();
if (f.isPresent()) {
return f.get().getArtifact().getVersion();
}
return null;
}
/**
* Collect dependencies from the dependency management section.
*
* @param engine reference to the ODC engine
* @param buildingRequest the Maven project building request
* @param project the project being analyzed
* @param nodes the list of dependency nodes
* @param aggregate whether or not this is an aggregate analysis
* @return a collection of exceptions if any occurred; otherwise
* <code>null</code>
*/
private ExceptionCollection collectDependencyManagementDependencies(Engine engine, ProjectBuildingRequest buildingRequest,
MavenProject project, List<DependencyNode> nodes, boolean aggregate) {
if (skipDependencyManagement || project.getDependencyManagement() == null) {
return null;
}
ExceptionCollection exCol = null;
for (org.apache.maven.model.Dependency dependency : project.getDependencyManagement().getDependencies()) {
try {
nodes.add(toDependencyNode(nodes, buildingRequest, null, dependency));
} catch (ArtifactResolverException ex) {
getLog().debug(String.format("Aggregate : %s", aggregate));
boolean addException = true;
//CSOFF: EmptyBlock
if (!aggregate) {
// do nothing, exception is to be reported
} else if (addReactorDependency(engine,
new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(),
dependency.getVersion(), dependency.getScope(), dependency.getType(), dependency.getClassifier(),
new DefaultArtifactHandler()))) {
addException = false;
}
//CSON: EmptyBlock
if (addException) {
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(ex);
}
}
}
return exCol;
}
/**
* Resolves the projects artifacts using Aether and scans the resulting
* dependencies.
*
* @param engine the core dependency-check engine
* @param project the project being scanned
* @param nodes the list of dependency nodes, generally obtained via the
* DependencyGraphBuilder
* @param buildingRequest the Maven project building request
* @param aggregate whether the scan is part of an aggregate build
* @return a collection of exceptions that may have occurred while resolving
* and scanning the dependencies
*/
private ExceptionCollection collectMavenDependencies(Engine engine, MavenProject project,
List<DependencyNode> nodes, ProjectBuildingRequest buildingRequest, boolean aggregate) {
ExceptionCollection exCol = collectDependencyManagementDependencies(engine, buildingRequest, project, nodes, aggregate);
for (DependencyNode dependencyNode : nodes) {
if (artifactScopeExcluded.passes(dependencyNode.getArtifact().getScope())
|| artifactTypeExcluded.passes(dependencyNode.getArtifact().getType())) {
continue;
}
boolean isResolved = false;
File artifactFile = null;
String artifactId = null;
String groupId = null;
String version = null;
List<ArtifactVersion> availableVersions = null;
if (org.apache.maven.artifact.Artifact.SCOPE_SYSTEM.equals(dependencyNode.getArtifact().getScope())) {
final Artifact a = dependencyNode.getArtifact();
if (a.isResolved() && a.getFile().isFile()) {
artifactFile = a.getFile();
isResolved = artifactFile.isFile();
groupId = a.getGroupId();
artifactId = a.getArtifactId();
version = a.getVersion();
availableVersions = a.getAvailableVersions();
} else {
for (org.apache.maven.model.Dependency d : project.getDependencies()) {
if (d.getSystemPath() != null && artifactsMatch(d, a)) {
artifactFile = new File(d.getSystemPath());
isResolved = artifactFile.isFile();
groupId = a.getGroupId();
artifactId = a.getArtifactId();
version = a.getVersion();
availableVersions = a.getAvailableVersions();
break;
}
}
}
if (!isResolved) {
getLog().error("Unable to resolve system scoped dependency: " + dependencyNode.toNodeString());
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(new DependencyNotFoundException("Unable to resolve system scoped dependency: "
+ dependencyNode.toNodeString()));
}
} else {
final Artifact dependencyArtifact = dependencyNode.getArtifact();
final Artifact result;
if (dependencyArtifact.isResolved()) {
//All transitive dependencies, excluding reactor and dependencyManagement artifacts should
//have been resolved by Maven prior to invoking the plugin - resolving the dependencies
//manually is unnecessary, and does not work in some cases (issue-1751)
getLog().debug(String.format("Skipping artifact %s, already resolved", dependencyArtifact.getArtifactId()));
result = dependencyArtifact;
} else {
final ArtifactCoordinate coordinate = TransferUtils.toArtifactCoordinate(dependencyNode.getArtifact());
try {
result = artifactResolver.resolveArtifact(buildingRequest, coordinate).getArtifact();
} catch (ArtifactResolverException ex) {
getLog().debug(String.format("Aggregate : %s", aggregate));
boolean addException = true;
//CSOFF: EmptyBlock
if (!aggregate) {
// do nothing - the exception is to be reported
} else if (addReactorDependency(engine, dependencyNode.getArtifact())) {
// successfully resolved as a reactor dependency - swallow the exception
addException = false;
}
//CSON: //CSOFF: EmptyBlock
if (addException) {
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(ex);
}
continue;
}
}
if (aggregate && virtualSnapshotsFromReactor
&& dependencyNode.getArtifact().isSnapshot()
&& addSnapshotReactorDependency(engine, dependencyNode.getArtifact())) {
continue;
}
isResolved = result.isResolved();
artifactFile = result.getFile();
groupId = result.getGroupId();
artifactId = result.getArtifactId();
version = result.getVersion();
availableVersions = result.getAvailableVersions();
}
if (isResolved && artifactFile != null) {
final List<Dependency> deps = engine.scan(artifactFile.getAbsoluteFile(),
createProjectReferenceName(project, dependencyNode));
if (deps != null) {
Dependency d = null;
if (deps.size() == 1) {
d = deps.get(0);
} else {
for (Dependency possible : deps) {
if (artifactFile.getAbsoluteFile().equals(possible.getActualFile())) {
d = possible;
break;
}
}
}
if (d != null) {
final MavenArtifact ma = new MavenArtifact(groupId, artifactId, version);
d.addAsEvidence("pom", ma, Confidence.HIGHEST);
if (availableVersions != null) {
for (ArtifactVersion av : availableVersions) {
d.addAvailableVersion(av.toString());
}
}
getLog().debug(String.format("Adding project reference %s on dependency %s",
project.getName(), d.getDisplayFileName()));
} else if (getLog().isDebugEnabled()) {
final String msg = String.format("More than 1 dependency was identified in first pass scan of '%s' in project %s",
dependencyNode.getArtifact().getId(), project.getName());
getLog().debug(msg);
}
} else if ("import".equals(dependencyNode.getArtifact().getScope())) {
final String msg = String.format("Skipping '%s:%s' in project %s as it uses an `import` scope",
dependencyNode.getArtifact().getId(), dependencyNode.getArtifact().getScope(), project.getName());
getLog().debug(msg);
} else if ("pom".equals(dependencyNode.getArtifact().getType())) {
try {
final Dependency d = new Dependency(artifactFile.getAbsoluteFile());
final Model pom = PomUtils.readPom(artifactFile.getAbsoluteFile());
JarAnalyzer.setPomEvidence(d, pom, null, true);
engine.addDependency(d);
} catch (AnalysisException ex) {
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(ex);
getLog().debug("Error reading pom " + artifactFile.getAbsoluteFile(), ex);
}
} else {
final String msg = String.format("No analyzer could be found for '%s:%s' in project %s",
dependencyNode.getArtifact().getId(), dependencyNode.getArtifact().getScope(), project.getName());
getLog().warn(msg);
}
} else {
final String msg = String.format("Unable to resolve '%s' in project %s",
dependencyNode.getArtifact().getId(), project.getName());
getLog().debug(msg);
if (exCol == null) {
exCol = new ExceptionCollection();
}
}
}
return exCol;
}
/**
* @param project the {@link MavenProject}
* @param dependencyNode the {@link DependencyNode}
* @return the name to be used when creating a
* {@link Dependency#getProjectReferences() project reference} in a
* {@link Dependency}. The behavior of this method returns {@link MavenProject#getName() project.getName()}<code> + ":" +
* </code>
* {@link DependencyNode#getArtifact() dependencyNode.getArtifact()}{@link Artifact#getScope() .getScope()}.
*/
protected String createProjectReferenceName(MavenProject project, DependencyNode dependencyNode) {
return project.getName() + ":" + dependencyNode.getArtifact().getScope();
}
/**
* Scans the projects dependencies including the default (or defined)
* FileSets.
*
* @param engine the core dependency-check engine
* @param project the project being scanned
* @param nodes the list of dependency nodes, generally obtained via the
* DependencyGraphBuilder
* @param buildingRequest the Maven project building request
* @param aggregate whether the scan is part of an aggregate build
* @return a collection of exceptions that may have occurred while resolving
* and scanning the dependencies
*/
private ExceptionCollection collectDependencies(Engine engine, MavenProject project,
List<DependencyNode> nodes, ProjectBuildingRequest buildingRequest, boolean aggregate) {
ExceptionCollection exCol;
exCol = collectMavenDependencies(engine, project, nodes, buildingRequest, aggregate);
final List<FileSet> projectScan;
if (scanDirectory != null && !scanDirectory.isEmpty()) {
if (scanSet == null) {
scanSet = new ArrayList<>();
}
scanDirectory.stream().forEach(d -> {
final FileSet fs = new FileSet();
fs.setDirectory(d);
fs.addInclude(INCLUDE_ALL);
scanSet.add(fs);
});
}
if (scanSet == null || scanSet.isEmpty()) {
// Define the default FileSets
final FileSet resourcesSet = new FileSet();
final FileSet filtersSet = new FileSet();
final FileSet webappSet = new FileSet();
final FileSet mixedLangSet = new FileSet();
try {
resourcesSet.setDirectory(new File(project.getBasedir(), "src/main/resources").getCanonicalPath());
resourcesSet.addInclude(INCLUDE_ALL);
filtersSet.setDirectory(new File(project.getBasedir(), "src/main/filters").getCanonicalPath());
filtersSet.addInclude(INCLUDE_ALL);
webappSet.setDirectory(new File(project.getBasedir(), "src/main/webapp").getCanonicalPath());
webappSet.addInclude(INCLUDE_ALL);
mixedLangSet.setDirectory(project.getBasedir().getCanonicalPath());
mixedLangSet.addInclude("package.json");
mixedLangSet.addInclude("package-lock.json");
mixedLangSet.addInclude("npm-shrinkwrap.json");
mixedLangSet.addInclude("Gopkg.lock");
mixedLangSet.addInclude("go.mod");
} catch (IOException ex) {
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(ex);
}
projectScan = new ArrayList<>();
projectScan.add(resourcesSet);
projectScan.add(filtersSet);
projectScan.add(webappSet);
projectScan.add(mixedLangSet);
} else if (aggregate) {
projectScan = new ArrayList<>();
for (FileSet copyFrom : scanSet) {
//deep copy of the FileSet - modifying the directory if it is not absolute.
final FileSet fsCopy = new FileSet();
final File f = new File(copyFrom.getDirectory());
if (f.isAbsolute()) {
fsCopy.setDirectory(copyFrom.getDirectory());
} else {
try {
fsCopy.setDirectory(new File(project.getBasedir(), copyFrom.getDirectory()).getCanonicalPath());
} catch (IOException ex) {
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(ex);
fsCopy.setDirectory(copyFrom.getDirectory());
}
}
fsCopy.setDirectoryMode(copyFrom.getDirectoryMode());
fsCopy.setExcludes(copyFrom.getExcludes());
fsCopy.setFileMode(copyFrom.getFileMode());
fsCopy.setFollowSymlinks(copyFrom.isFollowSymlinks());
fsCopy.setIncludes(copyFrom.getIncludes());
fsCopy.setLineEnding(copyFrom.getLineEnding());
fsCopy.setMapper(copyFrom.getMapper());
fsCopy.setModelEncoding(copyFrom.getModelEncoding());
fsCopy.setOutputDirectory(copyFrom.getOutputDirectory());
fsCopy.setUseDefaultExcludes(copyFrom.isUseDefaultExcludes());
projectScan.add(fsCopy);
}
} else {
projectScan = scanSet;
}
// Iterate through FileSets and scan included files
final FileSetManager fileSetManager = new FileSetManager();
for (FileSet fileSet : projectScan) {
getLog().debug("Scanning fileSet: " + fileSet.getDirectory());
final String[] includedFiles = fileSetManager.getIncludedFiles(fileSet);
for (String include : includedFiles) {
final File includeFile = new File(fileSet.getDirectory(), include).getAbsoluteFile();
if (includeFile.exists()) {
engine.scan(includeFile, project.getName());
}
}
}
return exCol;
}
/**
* Checks if the current artifact is actually in the reactor projects that
* have not yet been built. If true a virtual dependency is created based on
* the evidence in the project.
*
* @param engine a reference to the engine being used to scan
* @param artifact the artifact being analyzed in the mojo
* @return <code>true</code> if the artifact is in the reactor; otherwise
* <code>false</code>
*/
private boolean addReactorDependency(Engine engine, Artifact artifact) {
return addVirtualDependencyFromReactor(engine, artifact, "Unable to resolve %s as it has not been built yet "
+ "- creating a virtual dependency instead.");
}
/**
* Checks if the current artifact is actually in the reactor projects. If
* true a virtual dependency is created based on the evidence in the
* project.
*
* @param engine a reference to the engine being used to scan
* @param artifact the artifact being analyzed in the mojo
* @param infoLogTemplate the template for the infoLog entry written when a
* virtual dependency is added. Needs a single %s placeholder for the
* location of the displayName in the message
* @return <code>true</code> if the artifact is in the reactor; otherwise
* <code>false</code>
*/
private boolean addVirtualDependencyFromReactor(Engine engine, Artifact artifact, String infoLogTemplate) {
getLog().debug(String.format("Checking the reactor projects (%d) for %s:%s:%s",
reactorProjects.size(),
artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()));
for (MavenProject prj : reactorProjects) {
getLog().debug(String.format("Comparing %s:%s:%s to %s:%s:%s",
artifact.getGroupId(), artifact.getArtifactId(), artifact.getBaseVersion(),
prj.getGroupId(), prj.getArtifactId(), prj.getVersion()));
if (prj.getArtifactId().equals(artifact.getArtifactId())
&& prj.getGroupId().equals(artifact.getGroupId())
&& prj.getVersion().equals(artifact.getBaseVersion())) {
final String displayName = String.format("%s:%s:%s",
prj.getGroupId(), prj.getArtifactId(), prj.getVersion());
getLog().info(String.format(infoLogTemplate,
displayName));
final File pom = new File(prj.getBasedir(), "pom.xml");
final Dependency d;
if (pom.isFile()) {
getLog().debug("Adding virtual dependency from pom.xml");
d = new Dependency(pom, true);
} else {
d = new Dependency(true);
}
final String key = String.format("%s:%s:%s", prj.getGroupId(), prj.getArtifactId(), prj.getVersion());
d.setSha1sum(Checksum.getSHA1Checksum(key));
d.setSha256sum(Checksum.getSHA256Checksum(key));
d.setMd5sum(Checksum.getMD5Checksum(key));
d.setEcosystem(JarAnalyzer.DEPENDENCY_ECOSYSTEM);
d.setDisplayFileName(displayName);
d.addEvidence(EvidenceType.PRODUCT, "project", "artifactid", prj.getArtifactId(), Confidence.HIGHEST);
d.addEvidence(EvidenceType.VENDOR, "project", "artifactid", prj.getArtifactId(), Confidence.LOW);
d.addEvidence(EvidenceType.VENDOR, "project", "groupid", prj.getGroupId(), Confidence.HIGHEST);
d.addEvidence(EvidenceType.PRODUCT, "project", "groupid", prj.getGroupId(), Confidence.LOW);
d.setEcosystem(JarAnalyzer.DEPENDENCY_ECOSYSTEM);
Identifier id;
try {
id = new PurlIdentifier(StandardTypes.MAVEN, artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion(), Confidence.HIGHEST);
} catch (MalformedPackageURLException ex) {
getLog().debug("Unable to create PackageURL object:" + key);
id = new GenericIdentifier("maven:" + key, Confidence.HIGHEST);
}
d.addSoftwareIdentifier(id);
//TODO unify the setName/version and package path - they are equivelent ideas submitted by two seperate committers
d.setName(String.format("%s:%s", prj.getGroupId(), prj.getArtifactId()));
d.setVersion(prj.getVersion());
d.setPackagePath(displayName);
if (prj.getDescription() != null) {
JarAnalyzer.addDescription(d, prj.getDescription(), "project", "description");
}
for (License l : prj.getLicenses()) {
final StringBuilder license = new StringBuilder();
if (l.getName() != null) {
license.append(l.getName());
}
if (l.getUrl() != null) {
license.append(" ").append(l.getUrl());
}
if (d.getLicense() == null) {
d.setLicense(license.toString());
} else if (!d.getLicense().contains(license)) {
d.setLicense(String.format("%s%n%s", d.getLicense(), license.toString()));
}
}
engine.addDependency(d);
return true;
}
}
return false;
}
/**
* Checks if the current artifact is actually in the reactor projects. If
* true a virtual dependency is created based on the evidence in the
* project.
*
* @param engine a reference to the engine being used to scan
* @param artifact the artifact being analyzed in the mojo
* @return <code>true</code> if the artifact is a snapshot artifact in the
* reactor; otherwise <code>false</code>
*/
private boolean addSnapshotReactorDependency(Engine engine, Artifact artifact) {
if (!artifact.isSnapshot()) {
return false;
}
return addVirtualDependencyFromReactor(engine, artifact, "Found snapshot reactor project in aggregate for %s - "
+ "creating a virtual dependency as the snapshot found in the repository may contain outdated dependencies.");
}
/**
* @param project The target project to create a building request for.
* @return Returns a new ProjectBuildingRequest populated from the current
* session and the target project remote repositories, used to resolve
* artifacts.
*/
public ProjectBuildingRequest newResolveArtifactProjectBuildingRequest(MavenProject project) {
final ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
buildingRequest.setRemoteRepositories(new ArrayList<>(project.getRemoteArtifactRepositories()));
buildingRequest.setProject(project);
return buildingRequest;
}
/**
* Executes the dependency-check scan and generates the necessary report.
*
* @throws MojoExecutionException thrown if there is an exception running
* the scan
* @throws MojoFailureException thrown if dependency-check is configured to
* fail the build
*/
protected void runCheck() throws MojoExecutionException, MojoFailureException {
muteJCS();
try (Engine engine = initializeEngine()) {
ExceptionCollection exCol = scanDependencies(engine);
try {
engine.analyzeDependencies();
} catch (ExceptionCollection ex) {
exCol = handleAnalysisExceptions(exCol, ex);
}
if (exCol == null || !exCol.isFatal()) {
File outputDir = getCorrectOutputDirectory(this.getProject());
if (outputDir == null) {
//in some regards we shouldn't be writing this, but we are anyway.
//we shouldn't write this because nothing is configured to generate this report.
outputDir = new File(this.getProject().getBuild().getDirectory());
}
try {
final MavenProject p = this.getProject();
for (String f : getFormats()) {
engine.writeReports(p.getName(), p.getGroupId(), p.getArtifactId(), p.getVersion(), outputDir, f, exCol);
}
} catch (ReportException ex) {
if (exCol == null) {
exCol = new ExceptionCollection(ex);
} else {
exCol.addException(ex);
}
if (this.isFailOnError()) {
throw new MojoExecutionException("One or more exceptions occurred during dependency-check analysis", exCol);
} else {
getLog().debug("Error writing the report", ex);
}
}
showSummary(this.getProject(), engine.getDependencies());
checkForFailure(engine.getDependencies());
if (exCol != null && this.isFailOnError()) {
throw new MojoExecutionException("One or more exceptions occurred during dependency-check analysis", exCol);
}
}
} catch (DatabaseException ex) {
if (getLog().isDebugEnabled()) {
getLog().debug("Database connection error", ex);
}
final String msg = "An exception occurred connecting to the local database. Please see the log file for more details.";
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, ex);
}
getLog().error(msg, ex);
} finally {
getSettings().cleanup();
}
}
/**
* Combines the two exception collections and if either are fatal, throw an
* MojoExecutionException
*
* @param currentEx the primary exception collection
* @param newEx the new exception collection to add
* @return the combined exception collection
* @throws MojoExecutionException thrown if dependency-check is configured
* to fail on errors
*/
private ExceptionCollection handleAnalysisExceptions(ExceptionCollection currentEx, ExceptionCollection newEx) throws MojoExecutionException {
ExceptionCollection returnEx = currentEx;
if (returnEx == null) {
returnEx = newEx;
} else {
returnEx.getExceptions().addAll(newEx.getExceptions());
if (newEx.isFatal()) {
returnEx.setFatal(true);
}
}
if (returnEx.isFatal()) {
final String msg = String.format("Fatal exception(s) analyzing %s", getProject().getName());
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, returnEx);
}
getLog().error(msg);
if (getLog().isDebugEnabled()) {
getLog().debug(returnEx);
}
} else {
final String msg = String.format("Exception(s) analyzing %s", getProject().getName());
if (getLog().isDebugEnabled()) {
getLog().debug(msg, returnEx);
}
}
return returnEx;
}
/**
* Scans the dependencies of the projects in aggregate.
*
* @param engine the engine used to perform the scanning
* @return a collection of exceptions
* @throws MojoExecutionException thrown if a fatal exception occurs
*/
protected abstract ExceptionCollection scanDependencies(Engine engine) throws MojoExecutionException;
/**
* Returns the report output directory.
*
* @return the report output directory
*/
@Override
public File getReportOutputDirectory() {
return reportOutputDirectory;
}
/**
* Sets the Reporting output directory.
*
* @param directory the output directory
*/
@Override
public void setReportOutputDirectory(File directory) {
reportOutputDirectory = directory;
}
/**
* Returns the output directory.
*
* @return the output directory
*/
public File getOutputDirectory() {
return outputDirectory;
}
/**
* Returns whether this is an external report. This method always returns
* true.
*
* @return <code>true</code>
*/
@Override
public final boolean isExternalReport() {
return true;
}
/**
* Returns the output name.
*
* @return the output name
*/
@Override
public String getOutputName() {
final Set<String> selectedFormats = getFormats();
if (selectedFormats.contains("HTML") || selectedFormats.contains("ALL") || selectedFormats.size() > 1) {
return "dependency-check-report";
} else if (selectedFormats.contains("XML")) {
return "dependency-check-report.xml";
} else if (selectedFormats.contains("JUNIT")) {
return "dependency-check-junit.xml";
} else if (selectedFormats.contains("JSON")) {
return "dependency-check-report.json";
} else if (selectedFormats.contains("CSV")) {
return "dependency-check-report.csv";
} else {
getLog().warn("Unknown report format used during site generation.");
return "dependency-check-report";
}
}
/**
* Returns the category name.
*
* @return the category name
*/
@Override
public String getCategoryName() {
return MavenReport.CATEGORY_PROJECT_REPORTS;
}
//</editor-fold>
/**
* Initializes a new <code>Engine</code> that can be used for scanning. This
* method should only be called in a try-with-resources to ensure that the
* engine is properly closed.
*
* @return a newly instantiated <code>Engine</code>
* @throws DatabaseException thrown if there is a database exception
*/
protected Engine initializeEngine() throws DatabaseException {
populateSettings();
return new Engine(settings);
}
/**
* Takes the properties supplied and updates the dependency-check settings.
* Additionally, this sets the system properties required to change the
* proxy URL, port, and connection timeout.
*/
protected void populateSettings() {
settings = new Settings();
InputStream mojoProperties = null;
try {
mojoProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
settings.mergeProperties(mojoProperties);
} catch (IOException ex) {
getLog().warn("Unable to load the dependency-check maven mojo.properties file.");
if (getLog().isDebugEnabled()) {
getLog().debug("", ex);
}
} finally {
if (mojoProperties != null) {
try {
mojoProperties.close();
} catch (IOException ex) {
if (getLog().isDebugEnabled()) {
getLog().debug("", ex);
}
}
}
}
settings.setBooleanIfNotNull(Settings.KEYS.AUTO_UPDATE, autoUpdate);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, enableExperimental);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RETIRED_ENABLED, enableRetired);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_GOLANG_DEP_ENABLED, golangDepEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_GOLANG_MOD_ENABLED, golangModEnabled);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_GOLANG_PATH, pathToGo);
final Proxy proxy = getMavenProxy();
if (proxy != null) {
settings.setString(Settings.KEYS.PROXY_SERVER, proxy.getHost());
settings.setString(Settings.KEYS.PROXY_PORT, Integer.toString(proxy.getPort()));
final String userName = proxy.getUsername();
String password = proxy.getPassword();
if (password != null && !password.isEmpty()) {
if (settings.getBoolean(Settings.KEYS.PROXY_DISABLE_SCHEMAS, true)) {
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
}
try {
password = decryptPasswordFromSettings(password);
} catch (SecDispatcherException ex) {
password = handleSecDispatcherException("proxy", proxy.getId(), password, ex);
}
}
settings.setStringIfNotNull(Settings.KEYS.PROXY_USERNAME, userName);
settings.setStringIfNotNull(Settings.KEYS.PROXY_PASSWORD, password);
settings.setStringIfNotNull(Settings.KEYS.PROXY_NON_PROXY_HOSTS, proxy.getNonProxyHosts());
}
final String[] suppressions = determineSuppressions();
settings.setArrayIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressions);
settings.setBooleanIfNotNull(Settings.KEYS.UPDATE_VERSION_CHECK_ENABLED, versionCheckEnabled);
settings.setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout);
settings.setStringIfNotEmpty(Settings.KEYS.HINTS_FILE, hintsFile);
settings.setFloat(Settings.KEYS.JUNIT_FAIL_ON_CVSS, junitFailOnCVSS);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_JAR_ENABLED, jarAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, nuspecAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NUGETCONF_ENABLED, nugetconfAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, centralAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CENTRAL_USE_CACHE, centralAnalyzerUseCache);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_ENABLED, artifactoryAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_ENABLED, nexusAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, assemblyAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, archiveAnalyzerEnabled);
settings.setStringIfNotEmpty(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, zipExtensions);
settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_ASSEMBLY_DOTNET_PATH, pathToCore);
settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl);
configureServerCredentials(nexusServerId, Settings.KEYS.ANALYZER_NEXUS_USER, Settings.KEYS.ANALYZER_NEXUS_PASSWORD);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY, nexusUsesProxy);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_URL, artifactoryAnalyzerUrl);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_USES_PROXY, artifactoryAnalyzerUseProxy);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_PARALLEL_ANALYSIS, artifactoryAnalyzerParallelAnalysis);
if (Boolean.TRUE.equals(artifactoryAnalyzerEnabled)) {
if (artifactoryAnalyzerServerId != null) {
configureServerCredentials(artifactoryAnalyzerServerId, Settings.KEYS.ANALYZER_ARTIFACTORY_API_USERNAME,
Settings.KEYS.ANALYZER_ARTIFACTORY_API_TOKEN);
} else {
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_API_USERNAME, artifactoryAnalyzerUsername);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_API_TOKEN, artifactoryAnalyzerApiToken);
}
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_BEARER_TOKEN, artifactoryAnalyzerBearerToken);
}
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, pyDistributionAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED, pyPackageAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RUBY_GEMSPEC_ENABLED, rubygemsAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_OPENSSL_ENABLED, opensslAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CMAKE_ENABLED, cmakeAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_AUTOCONF_ENABLED, autoconfAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PIP_ENABLED, pipAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PIPFILE_ENABLED, pipfileAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_COMPOSER_LOCK_ENABLED, composerAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED, nodeAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED, nodeAuditAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_AUDIT_USE_CACHE, nodeAuditAnalyzerUseCache);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_AUDIT_SKIPDEV, nodeAuditSkipDevDependencies);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RETIREJS_ENABLED, retireJsAnalyzerEnabled);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_RETIREJS_REPO_JS_URL, retireJsUrl);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RETIREJS_FORCEUPDATE, retireJsForceUpdate);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_MIX_AUDIT_ENABLED, mixAuditAnalyzerEnabled);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_MIX_AUDIT_PATH, mixAuditPath);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_ENABLED, bundleAuditAnalyzerEnabled);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, bundleAuditPath);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_WORKING_DIRECTORY, bundleAuditWorkingDirectory);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_COCOAPODS_ENABLED, cocoapodsAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_SWIFT_PACKAGE_MANAGER_ENABLED, swiftPackageManagerAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_OSSINDEX_ENABLED, ossindexAnalyzerEnabled);
settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_OSSINDEX_URL, ossindexAnalyzerUrl);
configureServerCredentials(ossIndexServerId, Settings.KEYS.ANALYZER_OSSINDEX_USER, Settings.KEYS.ANALYZER_OSSINDEX_PASSWORD);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_OSSINDEX_USE_CACHE, ossindexAnalyzerUseCache);
if (retirejs != null) {
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RETIREJS_FILTER_NON_VULNERABLE, retirejs.getFilterNonVulnerable());
settings.setArrayIfNotEmpty(Settings.KEYS.ANALYZER_RETIREJS_FILTERS, retirejs.getFilters());
}
//Database configuration
settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName);
settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath);
settings.setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
if (databaseUser == null && databasePassword == null && serverId != null) {
configureServerCredentials(serverId, Settings.KEYS.DB_USER, Settings.KEYS.DB_PASSWORD);
} else {
settings.setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser);
settings.setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword);
}
settings.setStringIfNotEmpty(Settings.KEYS.DATA_DIRECTORY, dataDirectory);
settings.setStringIfNotEmpty(Settings.KEYS.DB_FILE_NAME, dbFilename);
settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_JSON, cveUrlModified);
settings.setStringIfNotEmpty(Settings.KEYS.CVE_BASE_JSON, cveUrlBase);
settings.setIntIfNotNull(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, cveValidForHours);
settings.setBooleanIfNotNull(Settings.KEYS.PRETTY_PRINT, prettyPrint);
artifactScopeExcluded = new ArtifactScopeExcluded(skipTestScope, skipProvidedScope, skipSystemScope, skipRuntimeScope);
artifactTypeExcluded = new ArtifactTypeExcluded(skipArtifactType);
if (cveUser == null && cvePassword == null && cveServerId != null) {
configureServerCredentials(cveServerId, Settings.KEYS.CVE_USER, Settings.KEYS.CVE_PASSWORD);
} else {
settings.setStringIfNotEmpty(Settings.KEYS.CVE_USER, cveUser);
settings.setStringIfNotEmpty(Settings.KEYS.CVE_PASSWORD, cvePassword);
}
}
/**
* Retrieves the server credentials from the settings.xml, decrypts the
* password, and places the values into the settings under the given key
* names.
*
* @param serverId the server id
* @param userSettingKey the property name for the username
* @param passwordSettingKey the property name for the password
*/
private void configureServerCredentials(String serverId, String userSettingKey, String passwordSettingKey) {
if (serverId != null) {
final Server server = settingsXml.getServer(serverId);
if (server != null) {
final String username = server.getUsername();
String password = null;
try {
password = decryptPasswordFromSettings(server.getPassword());
} catch (SecDispatcherException ex) {
password = handleSecDispatcherException("server", serverId, server.getPassword(), ex);
}
settings.setStringIfNotEmpty(userSettingKey, username);
settings.setStringIfNotEmpty(passwordSettingKey, password);
} else {
getLog().error(String.format("Server '%s' not found in the settings.xml file", serverId));
}
}
}
//CSOFF: LineLength
/**
* Decrypts a password from the Maven settings if it needs to be decrypted.
* If it's not encrypted the input password will be returned unchanged.
*
* @param the original password value from the settings.xml
* @return the decrypted password from the Maven configuration
* @throws SecDispatcherException thrown if there is an error decrypting the
* password
*/
private String decryptPasswordFromSettings(String password) throws SecDispatcherException {
//The following fix was copied from:
// https://github.com/bsorrentino/maven-confluence-plugin/blob/master/maven-confluence-reporting-plugin/src/main/java/org/bsc/maven/confluence/plugin/AbstractBaseConfluenceMojo.java
//
// FIX to resolve
// org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException:
// java.io.FileNotFoundException: ~/.settings-security.xml (No such file or directory)
//
if (securityDispatcher instanceof DefaultSecDispatcher) {
((DefaultSecDispatcher) securityDispatcher).setConfigurationFile("~/.m2/settings-security.xml");
}
return securityDispatcher.decrypt(password);
}
//CSON: LineLength
/**
* Handles a SecDispatcherException that was thrown at an attempt to decrypt an encrypted password from the Maven settings.
*
* @param settingsElementName - "server" or "proxy"
* @param settingsElementId - value of the id attribute of the proxy resp. server element to which the password belongs
* @param passwordValueFromSettings - original, undecrypted password value from the settings
* @param ex - the Exception to handle
* @return the password fallback value to go on with, might be a not working one.
*/
private String handleSecDispatcherException(String settingsElementName, String settingsElementId, String passwordValueFromSettings,
SecDispatcherException ex) {
String password = passwordValueFromSettings;
if (ex.getCause() instanceof FileNotFoundException
|| (ex.getCause() != null && ex.getCause().getCause() instanceof FileNotFoundException)) {
//maybe its not encrypted?
final String tmp = passwordValueFromSettings;
if (tmp.startsWith("{") && tmp.endsWith("}")) {
getLog().error(String.format(
"Unable to decrypt the %s password for %s id '%s' in settings.xml%n\tCause: %s",
settingsElementName, settingsElementName, settingsElementId, ex.getMessage()));
} else {
password = tmp;
}
} else {
getLog().error(String.format(
"Unable to decrypt the %s password for %s id '%s' in settings.xml%n\tCause: %s",
settingsElementName, settingsElementName, settingsElementId, ex.getMessage()));
}
return password;
}
/**
* Combines the configured suppressionFile and suppressionFiles into a
* single array.
*
* @return an array of suppression file paths
*/
private String[] determineSuppressions() {
String[] suppressions = suppressionFiles;
if (suppressionFile != null) {
if (suppressions == null) {
suppressions = new String[]{suppressionFile};
} else {
suppressions = Arrays.copyOf(suppressions, suppressions.length + 1);
suppressions[suppressions.length - 1] = suppressionFile;
}
}
return suppressions;
}
/**
* Hacky method of muting the noisy logging from JCS. Implemented using a
* solution from SO: https://stackoverflow.com/a/50723801
*/
private void muteJCS() {
final String[] noisyLoggers = {
"org.apache.commons.jcs.auxiliary.disk.AbstractDiskCache",
"org.apache.commons.jcs.engine.memory.AbstractMemoryCache",
"org.apache.commons.jcs.engine.control.CompositeCache",
"org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCache",
"org.apache.commons.jcs.engine.control.CompositeCache",
"org.apache.commons.jcs.engine.memory.AbstractMemoryCache",
"org.apache.commons.jcs.engine.control.event.ElementEventQueue",
"org.apache.commons.jcs.engine.memory.AbstractDoubleLinkedListMemoryCache",
"org.apache.commons.jcs.auxiliary.AuxiliaryCacheConfigurator",
"org.apache.commons.jcs.engine.control.CompositeCacheManager",
"org.apache.commons.jcs.utils.threadpool.ThreadPoolManager",
"org.apache.commons.jcs.engine.control.CompositeCacheConfigurator"};
for (String loggerName : noisyLoggers) {
try {
//This is actually a MavenSimpleLogger, but due to various classloader issues, can't work with the directly.
final Logger l = LoggerFactory.getLogger(loggerName);
final Field f = l.getClass().getSuperclass().getDeclaredField("currentLogLevel");
f.setAccessible(true);
f.set(l, LocationAwareLogger.ERROR_INT);
} catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException e) {
getLog().debug("Failed to reset the log level of " + loggerName + ", it will continue being noisy.");
}
}
}
/**
* Returns the maven proxy.
*
* @return the maven proxy
*/
private Proxy getMavenProxy() {
if (mavenSettings != null) {
final List<Proxy> proxies = mavenSettings.getProxies();
if (proxies != null && !proxies.isEmpty()) {
if (mavenSettingsProxyId != null) {
for (Proxy proxy : proxies) {
if (mavenSettingsProxyId.equalsIgnoreCase(proxy.getId())) {
return proxy;
}
}
} else {
for (Proxy aProxy : proxies) {
if (aProxy.isActive()) {
return aProxy;
}
}
}
}
}
return null;
}
/**
* Returns a reference to the current project. This method is used instead
* of auto-binding the project via component annotation in concrete
* implementations of this. If the child has a
* <code>@Component MavenProject project;</code> defined then the abstract
* class (i.e. this class) will not have access to the current project (just
* the way Maven works with the binding).
*
* @return returns a reference to the current project
*/
protected MavenProject getProject() {
return project;
}
/**
* Returns the list of Maven Projects in this build.
*
* @return the list of Maven Projects in this build
*/
protected List<MavenProject> getReactorProjects() {
return reactorProjects;
}
/**
* Combines the format and formats properties into a single collection.
*
* @return the selected report formats
*/
private Set<String> getFormats() {
final Set<String> invalid = new HashSet<>();
final Set<String> selectedFormats = formats == null || formats.length == 0 ? new HashSet<>() : new HashSet<>(Arrays.asList(formats));
selectedFormats.forEach((s) -> {
try {
ReportGenerator.Format.valueOf(s.toUpperCase());
} catch (IllegalArgumentException ex) {
invalid.add(s);
}
});
invalid.forEach((s) -> {
getLog().warn("Invalid report format specified: " + s);
});
if (selectedFormats.contains("true")) {
selectedFormats.remove("true");
}
if (format != null && selectedFormats.isEmpty()) {
selectedFormats.add(format);
}
return selectedFormats;
}
/**
* Returns the list of excluded artifacts based on either artifact id or
* group id and artifact id.
*
* @return a list of artifact to exclude
*/
public List<String> getExcludes() {
if (excludes == null) {
excludes = new ArrayList<>();
}
return excludes;
}
/**
* Returns the artifact scope excluded filter.
*
* @return the artifact scope excluded filter
*/
protected Filter<String> getArtifactScopeExcluded() {
return artifactScopeExcluded;
}
/**
* Returns the configured settings.
*
* @return the configured settings
*/
protected Settings getSettings() {
return settings;
}
//<editor-fold defaultstate="collapsed" desc="Methods to fail build or show summary">
/**
* Checks to see if a vulnerability has been identified with a CVSS score
* that is above the threshold set in the configuration.
*
* @param dependencies the list of dependency objects
* @throws MojoFailureException thrown if a CVSS score is found that is
* higher then the threshold set
*/
protected void checkForFailure(Dependency[] dependencies) throws MojoFailureException {
final StringBuilder ids = new StringBuilder();
for (Dependency d : dependencies) {
boolean addName = true;
for (Vulnerability v : d.getVulnerabilities()) {
if (failBuildOnAnyVulnerability || (v.getCvssV2() != null && v.getCvssV2().getScore() >= failBuildOnCVSS)
|| (v.getCvssV3() != null && v.getCvssV3().getBaseScore() >= failBuildOnCVSS)
|| (v.getUnscoredSeverity() != null && SeverityUtil.estimateCvssV2(v.getUnscoredSeverity()) >= failBuildOnCVSS)) {
if (addName) {
addName = false;
ids.append(NEW_LINE).append(d.getFileName()).append(": ");
ids.append(v.getName());
} else {
ids.append(", ").append(v.getName());
}
}
}
}
if (ids.length() > 0) {
final String msg;
if (showSummary) {
if (failBuildOnAnyVulnerability) {
msg = String.format("%n%nOne or more dependencies were identified with vulnerabilities: %n%s%n%n"
+ "See the dependency-check report for more details.%n%n", ids.toString());
} else {
msg = String.format("%n%nOne or more dependencies were identified with vulnerabilities that have a CVSS score greater than or "
+ "equal to '%.1f': %n%s%n%nSee the dependency-check report for more details.%n%n", failBuildOnCVSS, ids.toString());
}
} else {
msg = String.format("%n%nOne or more dependencies were identified with vulnerabilities.%n%n"
+ "See the dependency-check report for more details.%n%n");
}
throw new MojoFailureException(msg);
}
}
/**
* Generates a warning message listing a summary of dependencies and their
* associated CPE and CVE entries.
*
* @param mp the Maven project for which the summary is shown
* @param dependencies a list of dependency objects
*/
protected void showSummary(MavenProject mp, Dependency[] dependencies) {
if (showSummary) {
DependencyCheckScanAgent.showSummary(mp.getName(), dependencies);
}
}
//</editor-fold>
}
| maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java | /*
* This file is part of dependency-check-maven.
*
* 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.
*
* Copyright (c) 2014 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.maven;
import com.github.packageurl.MalformedPackageURLException;
import com.github.packageurl.PackageURL.StandardTypes;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.doxia.sink.Sink;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.License;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.DefaultProjectBuildingRequest;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.reporting.MavenReport;
import org.apache.maven.reporting.MavenReportException;
import org.apache.maven.settings.Proxy;
import org.apache.maven.settings.Server;
import org.apache.maven.shared.transfer.artifact.ArtifactCoordinate;
import org.apache.maven.shared.transfer.artifact.DefaultArtifactCoordinate;
import org.apache.maven.shared.transfer.artifact.TransferUtils;
import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolver;
import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolverException;
import org.eclipse.aether.artifact.ArtifactType;
import org.apache.maven.shared.artifact.filter.PatternExcludesArtifactFilter;
import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder;
import org.apache.maven.shared.dependency.graph.DependencyGraphBuilderException;
import org.apache.maven.shared.dependency.graph.DependencyNode;
import org.apache.maven.shared.dependency.graph.filter.ArtifactDependencyNodeFilter;
import org.apache.maven.shared.dependency.graph.internal.DefaultDependencyNode;
import org.apache.maven.shared.model.fileset.FileSet;
import org.apache.maven.shared.model.fileset.util.FileSetManager;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.JarAnalyzer;
import org.owasp.dependencycheck.data.nexus.MavenArtifact;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.EvidenceType;
import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.exception.DependencyNotFoundException;
import org.owasp.dependencycheck.exception.ExceptionCollection;
import org.owasp.dependencycheck.exception.ReportException;
import org.owasp.dependencycheck.utils.Checksum;
import org.owasp.dependencycheck.utils.Filter;
import org.owasp.dependencycheck.utils.Settings;
import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher;
import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher;
import org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.Restriction;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.shared.dependency.graph.traversal.CollectingDependencyNodeVisitor;
import org.owasp.dependencycheck.agent.DependencyCheckScanAgent;
import org.owasp.dependencycheck.dependency.naming.GenericIdentifier;
import org.owasp.dependencycheck.dependency.naming.Identifier;
import org.owasp.dependencycheck.dependency.naming.PurlIdentifier;
import org.apache.maven.shared.dependency.graph.traversal.DependencyNodeVisitor;
import org.apache.maven.shared.dependency.graph.traversal.FilteringDependencyNodeVisitor;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.reporting.ReportGenerator;
import org.owasp.dependencycheck.utils.SeverityUtil;
import org.owasp.dependencycheck.xml.pom.Model;
import org.owasp.dependencycheck.xml.pom.PomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
/**
* @author Jeremy Long
*/
public abstract class BaseDependencyCheckMojo extends AbstractMojo implements MavenReport {
//<editor-fold defaultstate="collapsed" desc="Private fields">
/**
* The properties file location.
*/
private static final String PROPERTIES_FILE = "mojo.properties";
/**
* System specific new line character.
*/
private static final String NEW_LINE = System.getProperty("line.separator", "\n").intern();
/**
* Pattern to include all files in a FileSet.
*/
private static final String INCLUDE_ALL = "**/*";
/**
* A flag indicating whether or not the Maven site is being generated.
*/
private boolean generatingSite = false;
/**
* The configured settings.
*/
private Settings settings = null;
//</editor-fold>
// <editor-fold defaultstate="collapsed" desc="Maven bound parameters and components">
/**
* Sets whether or not the mojo should fail if an error occurs.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "failOnError", defaultValue = "true", required = true)
private boolean failOnError;
/**
* The Maven Project Object.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "project", required = true, readonly = true)
private MavenProject project;
/**
* List of Maven project of the current build
*/
@SuppressWarnings("CanBeFinal")
@Parameter(readonly = true, required = true, property = "reactorProjects")
private List<MavenProject> reactorProjects;
/**
* The entry point towards a Maven version independent way of resolving
* artifacts (handles both Maven 3.0 Sonatype and Maven 3.1+ eclipse Aether
* implementations).
*/
@SuppressWarnings("CanBeFinal")
@Component
private ArtifactResolver artifactResolver;
/**
* The Maven Session.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(defaultValue = "${session}", readonly = true, required = true)
private MavenSession session;
/**
* Component within Maven to build the dependency graph.
*/
@Component
private DependencyGraphBuilder dependencyGraphBuilder;
/**
* The output directory. This generally maps to "target".
*/
@SuppressWarnings("CanBeFinal")
@Parameter(defaultValue = "${project.build.directory}", required = true)
private File outputDirectory;
/**
* This is a reference to the >reporting< sections
* <code>outputDirectory</code>. This cannot be configured in the
* dependency-check mojo directly. This generally maps to "target/site".
*/
@Parameter(property = "project.reporting.outputDirectory", readonly = true)
private File reportOutputDirectory;
/**
* Specifies if the build should be failed if a CVSS score above a specified
* level is identified. The default is 11 which means since the CVSS scores
* are 0-10, by default the build will never fail.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "failBuildOnCVSS", defaultValue = "11", required = true)
private float failBuildOnCVSS = 11;
/**
* Specifies the CVSS score that is considered a "test" failure when
* generating a jUnit style report. The default value is 0 - all
* vulnerabilities are considered a failure.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "junitFailOnCVSS", defaultValue = "0", required = true)
private float junitFailOnCVSS = 0;
/**
* Fail the build if any dependency has a vulnerability listed.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "failBuildOnAnyVulnerability", defaultValue = "false", required = true)
private boolean failBuildOnAnyVulnerability = false;
/**
* Sets whether auto-updating of the NVD CVE/CPE data is enabled. It is not
* recommended that this be turned to false. Default is true.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "autoUpdate")
private Boolean autoUpdate;
/**
* Sets whether Experimental analyzers are enabled. Default is false.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "enableExperimental")
private Boolean enableExperimental;
/**
* Sets whether retired analyzers are enabled. Default is false.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "enableRetired")
private Boolean enableRetired;
/**
* Sets whether the Golang Dependency analyzer is enabled. Default is true.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "golangDepEnabled")
private Boolean golangDepEnabled;
/**
* Sets whether Golang Module Analyzer is enabled; this requires `go` to be
* installed. Default is true.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "golangModEnabled")
private Boolean golangModEnabled;
/**
* Sets the path to `go`.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "pathToGo")
private String pathToGo;
/**
* Use pom dependency information for snapshot dependencies that are part of
* the Maven reactor while aggregate scanning a multi-module project.
*/
@Parameter(property = "dependency-check.virtualSnapshotsFromReactor", defaultValue = "true")
private Boolean virtualSnapshotsFromReactor;
/**
* The report format to be generated (HTML, XML, JUNIT, CSV, JSON, ALL).
* Multiple formats can be selected using a comma delineated list.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "format", defaultValue = "HTML", required = true)
private String format = "HTML";
/**
* Whether or not the XML and JSON report formats should be pretty printed.
* The default is false.
*/
@Parameter(property = "prettyPrint")
private Boolean prettyPrint;
/**
* The report format to be generated (HTML, XML, JUNIT, CSV, JSON, ALL).
* Multiple formats can be selected using a comma delineated list.
*/
@Parameter(property = "formats", required = true)
private String[] formats;
/**
* The Maven settings.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "mavenSettings", defaultValue = "${settings}")
private org.apache.maven.settings.Settings mavenSettings;
/**
* The maven settings proxy id.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "mavenSettingsProxyId")
private String mavenSettingsProxyId;
/**
* The Connection Timeout.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "connectionTimeout")
private String connectionTimeout;
/**
* Sets whether dependency-check should check if there is a new version
* available.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "versionCheckEnabled", defaultValue = "true")
private boolean versionCheckEnabled;
/**
* The paths to the suppression files. The parameter value can be a local
* file path, a URL to a suppression file, or even a reference to a file on
* the class path (see
* https://github.com/jeremylong/DependencyCheck/issues/1878#issuecomment-487533799)
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "suppressionFiles")
private String[] suppressionFiles;
/**
* The paths to the suppression file. The parameter value can be a local
* file path, a URL to a suppression file, or even a reference to a file on
* the class path (see
* https://github.com/jeremylong/DependencyCheck/issues/1878#issuecomment-487533799)
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "suppressionFile")
private String suppressionFile;
/**
* The path to the hints file.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "hintsFile")
private String hintsFile;
/**
* Flag indicating whether or not to show a summary in the output.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "showSummary", defaultValue = "true")
private boolean showSummary = true;
/**
* Whether or not the Jar Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "jarAnalyzerEnabled")
private Boolean jarAnalyzerEnabled;
/**
* Whether or not the Archive Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "archiveAnalyzerEnabled")
private Boolean archiveAnalyzerEnabled;
/**
* Sets whether the Python Distribution Analyzer will be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "pyDistributionAnalyzerEnabled")
private Boolean pyDistributionAnalyzerEnabled;
/**
* Sets whether the Python Package Analyzer will be used.
*/
@Parameter(property = "pyPackageAnalyzerEnabled")
private Boolean pyPackageAnalyzerEnabled;
/**
* Sets whether the Ruby Gemspec Analyzer will be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "rubygemsAnalyzerEnabled")
private Boolean rubygemsAnalyzerEnabled;
/**
* Sets whether or not the openssl Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "opensslAnalyzerEnabled")
private Boolean opensslAnalyzerEnabled;
/**
* Sets whether or not the CMake Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "cmakeAnalyzerEnabled")
private Boolean cmakeAnalyzerEnabled;
/**
* Sets whether or not the autoconf Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "autoconfAnalyzerEnabled")
private Boolean autoconfAnalyzerEnabled;
/**
* Sets whether or not the pip Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "pipAnalyzerEnabled")
private Boolean pipAnalyzerEnabled;
/**
* Sets whether or not the pipfile Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "pipfileAnalyzerEnabled")
private Boolean pipfileAnalyzerEnabled;
/**
* Sets whether or not the PHP Composer Lock File Analyzer should be used.
*/
@Parameter(property = "composerAnalyzerEnabled")
private Boolean composerAnalyzerEnabled;
/**
* Sets whether or not the Node.js Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nodeAnalyzerEnabled")
private Boolean nodeAnalyzerEnabled;
/**
* Sets whether or not the Node Audit Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nodeAuditAnalyzerEnabled")
private Boolean nodeAuditAnalyzerEnabled;
/**
* Sets whether or not the Node Audit Analyzer should use a local cache.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nodeAuditAnalyzerUseCache")
private Boolean nodeAuditAnalyzerUseCache;
/**
* Sets whether or not the Node Audit Analyzer should skip devDependencies.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nodeAuditSkipDevDependencies")
private Boolean nodeAuditSkipDevDependencies;
/**
* Sets whether or not the Retirejs Analyzer should be used.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "retireJsAnalyzerEnabled")
private Boolean retireJsAnalyzerEnabled;
/**
* The Retire JS repository URL.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "retireJsUrl")
private String retireJsUrl;
/**
* Whether the Retire JS repository will be updated regardless of the
* `autoupdate` settings.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "retireJsForceUpdate")
private Boolean retireJsForceUpdate;
/**
* Whether or not the .NET Assembly Analyzer is enabled.
*/
@Parameter(property = "assemblyAnalyzerEnabled")
private Boolean assemblyAnalyzerEnabled;
/**
* Whether or not the .NET Nuspec Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nuspecAnalyzerEnabled")
private Boolean nuspecAnalyzerEnabled;
/**
* Whether or not the .NET packages.config Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nugetconfAnalyzerEnabled")
private Boolean nugetconfAnalyzerEnabled;
/**
* Whether or not the Central Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "centralAnalyzerEnabled")
private Boolean centralAnalyzerEnabled;
/**
* Whether or not the Central Analyzer should use a local cache.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "centralAnalyzerUseCache")
private Boolean centralAnalyzerUseCache;
/**
* Whether or not the Artifactory Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerEnabled")
private Boolean artifactoryAnalyzerEnabled;
/**
* The serverId inside the settings.xml containing the username and token to
* access artifactory
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerServerId")
private String artifactoryAnalyzerServerId;
/**
* The username (only used with API token) to connect to Artifactory
* instance
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerUsername")
private String artifactoryAnalyzerUsername;
/**
* The API token to connect to Artifactory instance
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerApiToken")
private String artifactoryAnalyzerApiToken;
/**
* The bearer token to connect to Artifactory instance
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerBearerToken")
private String artifactoryAnalyzerBearerToken;
/**
* The Artifactory URL for the Artifactory analyzer.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerUrl")
private String artifactoryAnalyzerUrl;
/**
* Whether Artifactory should be accessed through a proxy or not
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerUseProxy")
private Boolean artifactoryAnalyzerUseProxy;
/**
* Whether the Artifactory analyzer should be run in parallel or not.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "artifactoryAnalyzerParallelAnalysis", defaultValue = "true")
private Boolean artifactoryAnalyzerParallelAnalysis;
/**
* Whether or not the Nexus Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nexusAnalyzerEnabled")
private Boolean nexusAnalyzerEnabled;
/**
* Whether or not the Sonatype OSS Index analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "ossindexAnalyzerEnabled")
private Boolean ossindexAnalyzerEnabled;
/**
* Whether or not the Sonatype OSS Index analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "ossindexAnalyzerUseCache")
private Boolean ossindexAnalyzerUseCache;
/**
* URL of the Sonatype OSS Index service.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "ossindexAnalyzerUrl")
private String ossindexAnalyzerUrl;
/**
* The id of a server defined in the settings.xml that configures the
* credentials (username and password) for a OSS Index service.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "ossIndexServerId")
private String ossIndexServerId;
/**
* Whether or not the Elixir Mix Audit Analyzer is enabled.
*/
@Parameter(property = "mixAuditAnalyzerEnabled")
private Boolean mixAuditAnalyzerEnabled;
/**
* Sets the path for the mix_audit binary.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "mixAuditPath")
private String mixAuditPath;
/**
* Whether or not the Ruby Bundle Audit Analyzer is enabled.
*/
@Parameter(property = "bundleAuditAnalyzerEnabled")
private Boolean bundleAuditAnalyzerEnabled;
/**
* Sets the path for the bundle-audit binary.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "bundleAuditPath")
private String bundleAuditPath;
/**
* Sets the path for the working directory that the bundle-audit binary
* should be executed from.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "bundleAuditWorkingDirectory")
private String bundleAuditWorkingDirectory;
/**
* Whether or not the CocoaPods Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "cocoapodsAnalyzerEnabled")
private Boolean cocoapodsAnalyzerEnabled;
/**
* Whether or not the Swift package Analyzer is enabled.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "swiftPackageManagerAnalyzerEnabled")
private Boolean swiftPackageManagerAnalyzerEnabled;
/**
* The URL of a Nexus server's REST API end point
* (http://domain/nexus/service/local).
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nexusUrl")
private String nexusUrl;
/**
* The id of a server defined in the settings.xml that configures the
* credentials (username and password) for a Nexus server's REST API end
* point. When not specified the communication with the Nexus server's REST
* API will be unauthenticated.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nexusServerId")
private String nexusServerId;
/**
* Whether or not the configured proxy is used to connect to Nexus.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "nexusUsesProxy")
private Boolean nexusUsesProxy;
/**
* The database connection string.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "connectionString")
private String connectionString;
/**
* The database driver name. An example would be org.h2.Driver.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "databaseDriverName")
private String databaseDriverName;
/**
* The path to the database driver if it is not on the class path.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "databaseDriverPath")
private String databaseDriverPath;
/**
* The server id in the settings.xml; used to retrieve encrypted passwords
* from the settings.xml.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "serverId")
private String serverId;
/**
* A reference to the settings.xml settings.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(defaultValue = "${settings}", readonly = true, required = true)
private org.apache.maven.settings.Settings settingsXml;
/**
* The security dispatcher that can decrypt passwords in the settings.xml.
*/
@Component(role = SecDispatcher.class, hint = "default")
private SecDispatcher securityDispatcher;
/**
* The database user name.
*/
@Parameter(property = "databaseUser")
private String databaseUser;
/**
* The password to use when connecting to the database.
*/
@Parameter(property = "databasePassword")
private String databasePassword;
/**
* A comma-separated list of file extensions to add to analysis next to jar,
* zip, ....
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "zipExtensions")
private String zipExtensions;
/**
* Skip Dependency Check altogether.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "dependency-check.skip", defaultValue = "false")
private boolean skip = false;
/**
* Skip Analysis for Test Scope Dependencies.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "skipTestScope", defaultValue = "true")
private boolean skipTestScope = true;
/**
* Skip Analysis for Runtime Scope Dependencies.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "skipRuntimeScope", defaultValue = "false")
private boolean skipRuntimeScope = false;
/**
* Skip Analysis for Provided Scope Dependencies.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "skipProvidedScope", defaultValue = "false")
private boolean skipProvidedScope = false;
/**
* Skip Analysis for System Scope Dependencies.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "skipSystemScope", defaultValue = "false")
private boolean skipSystemScope = false;
/**
* Skip Analysis for dependencyManagement section.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "skipDependencyManagement", defaultValue = "true")
private boolean skipDependencyManagement = true;
/**
* Skip analysis for dependencies which type matches this regular
* expression. This filters on the `type` of dependency as defined in the
* dependency section: jar, pom, test-jar, etc.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "skipArtifactType")
private String skipArtifactType;
/**
* The data directory, hold DC SQL DB.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "dataDirectory")
private String dataDirectory;
/**
* The name of the DC DB.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "dbFilename")
private String dbFilename;
/**
* Data Mirror URL for CVE 1.2.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "cveUrlModified")
private String cveUrlModified;
/**
* Base Data Mirror URL for CVE 1.2.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "cveUrlBase")
private String cveUrlBase;
/**
* The username to use when connecting to the CVE-URL.
*/
@Parameter(property = "cveUser")
private String cveUser;
/**
* The password to authenticate to the CVE-URL.
*/
@Parameter(property = "cvePassword")
private String cvePassword;
/**
* The server id in the settings.xml; used to retrieve encrypted passwords
* from the settings.xml for cve-URLs.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "cveServerId")
private String cveServerId;
/**
* /**
* Optionally skip excessive CVE update checks for a designated duration in
* hours.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "cveValidForHours")
private Integer cveValidForHours;
/**
* The path to dotnet core.
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "pathToCore")
private String pathToCore;
/**
* The RetireJS Analyzer configuration:
* <pre>
* filters: an array of filter patterns that are used to exclude JS files that contain a match
* filterNonVulnerable: a boolean that when true will remove non-vulnerable JS from the report
*
* Example:
* <retirejs>
* <filters>
* <filter>copyright 2018\(c\) Jeremy Long</filter>
* </filters>
* <filterNonVulnerable>true</filterNonVulnerable>
* </retirejs>
* </pre>
*/
@SuppressWarnings("CanBeFinal")
@Parameter(property = "retirejs")
private Retirejs retirejs;
/**
* The list of artifacts (and their transitive dependencies) to exclude from
* the check.
*/
@Parameter
private List<String> excludes;
/**
* The artifact scope filter.
*/
private Filter<String> artifactScopeExcluded;
/**
* Filter for artifact type.
*/
private Filter<String> artifactTypeExcluded;
/**
* An collection of <code>fileSet</code>s that specify additional files
* and/or directories (from the basedir) to analyze as part of the scan. If
* not specified, defaults to Maven conventions of: src/main/resources,
* src/main/filters, and src/main/webapp. Note, this cannot be set via the
* command line - use `scanDirectory` instead.
*/
@Parameter
private List<FileSet> scanSet;
/**
* A list of directories to scan. Note, this should only be used via the
* command line - if configuring the directories to scan consider using the
* `scanSet` instead.
*/
@Parameter(property = "scanDirectory")
private List<String> scanDirectory;
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="Base Maven implementation">
/**
* Determines if the groupId, artifactId, and version of the Maven
* dependency and artifact match.
*
* @param d the Maven dependency
* @param a the Maven artifact
* @return true if the groupId, artifactId, and version match
*/
private static boolean artifactsMatch(org.apache.maven.model.Dependency d, Artifact a) {
return isEqualOrNull(a.getArtifactId(), d.getArtifactId())
&& isEqualOrNull(a.getGroupId(), d.getGroupId())
&& isEqualOrNull(a.getVersion(), d.getVersion());
}
/**
* Compares two strings for equality; if both strings are null they are
* considered equal.
*
* @param left the first string to compare
* @param right the second string to compare
* @return true if the strings are equal or if they are both null; otherwise
* false.
*/
private static boolean isEqualOrNull(String left, String right) {
return (left != null && left.equals(right)) || (left == null && right == null);
}
/**
* Executes dependency-check.
*
* @throws MojoExecutionException thrown if there is an exception executing
* the mojo
* @throws MojoFailureException thrown if dependency-check failed the build
*/
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
generatingSite = false;
final boolean shouldSkip = Boolean.parseBoolean(System.getProperty("dependency-check.skip", Boolean.toString(skip)));
if (shouldSkip) {
getLog().info("Skipping " + getName(Locale.US));
} else {
project.setContextValue("dependency-check-output-dir", this.outputDirectory);
runCheck();
}
}
/**
* Generates the Dependency-Check Site Report.
*
* @param sink the sink to write the report to
* @param locale the locale to use when generating the report
* @throws MavenReportException if a maven report exception occurs
* @deprecated use
* {@link #generate(org.apache.maven.doxia.sink.Sink, java.util.Locale)}
* instead.
*/
@Override
@Deprecated
public final void generate(@SuppressWarnings("deprecation") org.codehaus.doxia.sink.Sink sink, Locale locale) throws MavenReportException {
generate((Sink) sink, locale);
}
/**
* Returns true if the Maven site is being generated.
*
* @return true if the Maven site is being generated
*/
protected boolean isGeneratingSite() {
return generatingSite;
}
/**
* Returns the connection string.
*
* @return the connection string
*/
protected String getConnectionString() {
return connectionString;
}
/**
* Returns if the mojo should fail the build if an exception occurs.
*
* @return whether or not the mojo should fail the build
*/
protected boolean isFailOnError() {
return failOnError;
}
/**
* Generates the Dependency-Check Site Report.
*
* @param sink the sink to write the report to
* @param locale the locale to use when generating the report
* @throws MavenReportException if a maven report exception occurs
*/
public void generate(Sink sink, Locale locale) throws MavenReportException {
final boolean shouldSkip = Boolean.parseBoolean(System.getProperty("dependency-check.skip", Boolean.toString(skip)));
if (shouldSkip) {
getLog().info("Skipping report generation " + getName(Locale.US));
return;
}
generatingSite = true;
project.setContextValue("dependency-check-output-dir", getReportOutputDirectory());
try {
runCheck();
} catch (MojoExecutionException ex) {
throw new MavenReportException(ex.getMessage(), ex);
} catch (MojoFailureException ex) {
getLog().warn("Vulnerabilities were identifies that exceed the CVSS threshold for failing the build");
}
}
/**
* Returns the correct output directory depending on if a site is being
* executed or not.
*
* @return the directory to write the report(s)
* @throws MojoExecutionException thrown if there is an error loading the
* file path
*/
protected File getCorrectOutputDirectory() throws MojoExecutionException {
return getCorrectOutputDirectory(this.project);
}
/**
* Returns the correct output directory depending on if a site is being
* executed or not.
*
* @param current the Maven project to get the output directory from
* @return the directory to write the report(s)
*/
protected File getCorrectOutputDirectory(MavenProject current) {
final Object obj = current.getContextValue("dependency-check-output-dir");
if (obj != null && obj instanceof File) {
return (File) obj;
}
//else we guess
File target = new File(current.getBuild().getDirectory());
if (target.getParentFile() != null && "target".equals(target.getParentFile().getName())) {
target = target.getParentFile();
}
return target;
}
/**
* Scans the project's artifacts and adds them to the engine's dependency
* list.
*
* @param project the project to scan the dependencies of
* @param engine the engine to use to scan the dependencies
* @return a collection of exceptions that may have occurred while resolving
* and scanning the dependencies
*/
protected ExceptionCollection scanArtifacts(MavenProject project, Engine engine) {
return scanArtifacts(project, engine, false);
}
/**
* Scans the project's artifacts and adds them to the engine's dependency
* list.
*
* @param project the project to scan the dependencies of
* @param engine the engine to use to scan the dependencies
* @param aggregate whether the scan is part of an aggregate build
* @return a collection of exceptions that may have occurred while resolving
* and scanning the dependencies
*/
protected ExceptionCollection scanArtifacts(MavenProject project, Engine engine, boolean aggregate) {
try {
final List<String> filterItems = Collections.singletonList(String.format("%s:%s", project.getGroupId(), project.getArtifactId()));
final ProjectBuildingRequest buildingRequest = newResolveArtifactProjectBuildingRequest(project);
//For some reason the filter does not filter out the project being analyzed
//if we pass in the filter below instead of null to the dependencyGraphBuilder
final DependencyNode dn = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, null, reactorProjects);
final CollectingDependencyNodeVisitor collectorVisitor = new CollectingDependencyNodeVisitor();
// exclude artifact by pattern and its dependencies
final DependencyNodeVisitor transitiveFilterVisitor = new FilteringDependencyTransitiveNodeVisitor(collectorVisitor,
new ArtifactDependencyNodeFilter(new PatternExcludesArtifactFilter(getExcludes())));
// exclude exact artifact but not its dependencies, this filter must be appied on the root for first otherwise
// in case the exclude has the same groupId of the current bundle its direct dependencies are not visited
final DependencyNodeVisitor artifactFilter = new FilteringDependencyNodeVisitor(transitiveFilterVisitor,
new ArtifactDependencyNodeFilter(new ExcludesArtifactFilter(filterItems)));
dn.accept(artifactFilter);
//collect dependencies with the filter - see comment above.
final List<DependencyNode> nodes = new ArrayList<>(collectorVisitor.getNodes());
return collectDependencies(engine, project, nodes, buildingRequest, aggregate);
} catch (DependencyGraphBuilderException ex) {
final String msg = String.format("Unable to build dependency graph on project %s", project.getName());
getLog().debug(msg, ex);
return new ExceptionCollection(ex);
}
}
/**
* Converts the dependency to a dependency node object.
*
* @param nodes the list of dependency nodes
* @param buildingRequest the Maven project building request
* @param parent the parent node
* @param dependency the dependency to convert
* @return the resulting dependency node
* @throws ArtifactResolverException thrown if the artifact could not be
* retrieved
*/
private DependencyNode toDependencyNode(List<DependencyNode> nodes, ProjectBuildingRequest buildingRequest,
DependencyNode parent, org.apache.maven.model.Dependency dependency) throws ArtifactResolverException {
final DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate();
coordinate.setGroupId(dependency.getGroupId());
coordinate.setArtifactId(dependency.getArtifactId());
String version = null;
final VersionRange vr;
try {
vr = VersionRange.createFromVersionSpec(dependency.getVersion());
} catch (InvalidVersionSpecificationException ex) {
throw new ArtifactResolverException("Invalid version specification: "
+ dependency.getGroupId() + ":"
+ dependency.getArtifactId() + ":"
+ dependency.getVersion(), ex);
}
if (vr.hasRestrictions()) {
version = findVersion(nodes, dependency.getGroupId(), dependency.getArtifactId());
if (version == null) {
//TODO - this still may fail if the restriction is not a valid version number (i.e. only 2.9 instead of 2.9.1)
//need to get available versions and filter on the restrictions.
if (vr.getRecommendedVersion() != null) {
version = vr.getRecommendedVersion().toString();
} else if (vr.hasRestrictions()) {
for (Restriction restriction : vr.getRestrictions()) {
if (restriction.getLowerBound() != null) {
version = restriction.getLowerBound().toString();
}
if (restriction.getUpperBound() != null) {
version = restriction.getUpperBound().toString();
}
}
} else {
version = vr.toString();
}
}
}
if (version == null) {
version = dependency.getVersion();
}
coordinate.setVersion(version);
final ArtifactType type = session.getRepositorySession().getArtifactTypeRegistry().get(dependency.getType());
coordinate.setExtension(type.getExtension());
coordinate.setClassifier((null == dependency.getClassifier() || dependency.getClassifier().isEmpty())
? type.getClassifier() : dependency.getClassifier());
final Artifact artifact = artifactResolver.resolveArtifact(buildingRequest, coordinate).getArtifact();
artifact.setScope(dependency.getScope());
return new DefaultDependencyNode(parent, artifact, dependency.getVersion(), dependency.getScope(), null);
}
/**
* Returns the version from the list of nodes that match the given groupId
* and artifactID.
*
* @param nodes the nodes to search
* @param groupId the group id to find
* @param artifactId the artifact id to find
* @return the version from the list of nodes that match the given groupId
* and artifactID; otherwise <code>null</code> is returned
*/
private String findVersion(List<DependencyNode> nodes, String groupId, String artifactId) {
final Optional<DependencyNode> f = nodes.stream().filter(p
-> groupId.equals(p.getArtifact().getGroupId())
&& artifactId.equals(p.getArtifact().getArtifactId())).findFirst();
if (f.isPresent()) {
return f.get().getArtifact().getVersion();
}
return null;
}
/**
* Collect dependencies from the dependency management section.
*
* @param engine reference to the ODC engine
* @param buildingRequest the Maven project building request
* @param project the project being analyzed
* @param nodes the list of dependency nodes
* @param aggregate whether or not this is an aggregate analysis
* @return a collection of exceptions if any occurred; otherwise
* <code>null</code>
*/
private ExceptionCollection collectDependencyManagementDependencies(Engine engine, ProjectBuildingRequest buildingRequest,
MavenProject project, List<DependencyNode> nodes, boolean aggregate) {
if (skipDependencyManagement || project.getDependencyManagement() == null) {
return null;
}
ExceptionCollection exCol = null;
for (org.apache.maven.model.Dependency dependency : project.getDependencyManagement().getDependencies()) {
try {
nodes.add(toDependencyNode(nodes, buildingRequest, null, dependency));
} catch (ArtifactResolverException ex) {
getLog().debug(String.format("Aggregate : %s", aggregate));
boolean addException = true;
//CSOFF: EmptyBlock
if (!aggregate) {
// do nothing, exception is to be reported
} else if (addReactorDependency(engine,
new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(),
dependency.getVersion(), dependency.getScope(), dependency.getType(), dependency.getClassifier(),
new DefaultArtifactHandler()))) {
addException = false;
}
//CSON: EmptyBlock
if (addException) {
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(ex);
}
}
}
return exCol;
}
/**
* Resolves the projects artifacts using Aether and scans the resulting
* dependencies.
*
* @param engine the core dependency-check engine
* @param project the project being scanned
* @param nodes the list of dependency nodes, generally obtained via the
* DependencyGraphBuilder
* @param buildingRequest the Maven project building request
* @param aggregate whether the scan is part of an aggregate build
* @return a collection of exceptions that may have occurred while resolving
* and scanning the dependencies
*/
private ExceptionCollection collectMavenDependencies(Engine engine, MavenProject project,
List<DependencyNode> nodes, ProjectBuildingRequest buildingRequest, boolean aggregate) {
ExceptionCollection exCol = collectDependencyManagementDependencies(engine, buildingRequest, project, nodes, aggregate);
for (DependencyNode dependencyNode : nodes) {
if (artifactScopeExcluded.passes(dependencyNode.getArtifact().getScope())
|| artifactTypeExcluded.passes(dependencyNode.getArtifact().getType())) {
continue;
}
boolean isResolved = false;
File artifactFile = null;
String artifactId = null;
String groupId = null;
String version = null;
List<ArtifactVersion> availableVersions = null;
if (org.apache.maven.artifact.Artifact.SCOPE_SYSTEM.equals(dependencyNode.getArtifact().getScope())) {
final Artifact a = dependencyNode.getArtifact();
if (a.isResolved() && a.getFile().isFile()) {
artifactFile = a.getFile();
isResolved = artifactFile.isFile();
groupId = a.getGroupId();
artifactId = a.getArtifactId();
version = a.getVersion();
availableVersions = a.getAvailableVersions();
} else {
for (org.apache.maven.model.Dependency d : project.getDependencies()) {
if (d.getSystemPath() != null && artifactsMatch(d, a)) {
artifactFile = new File(d.getSystemPath());
isResolved = artifactFile.isFile();
groupId = a.getGroupId();
artifactId = a.getArtifactId();
version = a.getVersion();
availableVersions = a.getAvailableVersions();
break;
}
}
}
if (!isResolved) {
getLog().error("Unable to resolve system scoped dependency: " + dependencyNode.toNodeString());
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(new DependencyNotFoundException("Unable to resolve system scoped dependency: "
+ dependencyNode.toNodeString()));
}
} else {
final Artifact dependencyArtifact = dependencyNode.getArtifact();
final Artifact result;
if (dependencyArtifact.isResolved()) {
//All transitive dependencies, excluding reactor and dependencyManagement artifacts should
//have been resolved by Maven prior to invoking the plugin - resolving the dependencies
//manually is unnecessary, and does not work in some cases (issue-1751)
getLog().debug(String.format("Skipping artifact %s, already resolved", dependencyArtifact.getArtifactId()));
result = dependencyArtifact;
} else {
final ArtifactCoordinate coordinate = TransferUtils.toArtifactCoordinate(dependencyNode.getArtifact());
try {
result = artifactResolver.resolveArtifact(buildingRequest, coordinate).getArtifact();
} catch (ArtifactResolverException ex) {
getLog().debug(String.format("Aggregate : %s", aggregate));
boolean addException = true;
//CSOFF: EmptyBlock
if (!aggregate) {
// do nothing - the exception is to be reported
} else if (addReactorDependency(engine, dependencyNode.getArtifact())) {
// successfully resolved as a reactor dependency - swallow the exception
addException = false;
}
//CSON: //CSOFF: EmptyBlock
if (addException) {
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(ex);
}
continue;
}
}
if (aggregate && virtualSnapshotsFromReactor
&& dependencyNode.getArtifact().isSnapshot()
&& addSnapshotReactorDependency(engine, dependencyNode.getArtifact())) {
continue;
}
isResolved = result.isResolved();
artifactFile = result.getFile();
groupId = result.getGroupId();
artifactId = result.getArtifactId();
version = result.getVersion();
availableVersions = result.getAvailableVersions();
}
if (isResolved && artifactFile != null) {
final List<Dependency> deps = engine.scan(artifactFile.getAbsoluteFile(),
createProjectReferenceName(project, dependencyNode));
if (deps != null) {
Dependency d = null;
if (deps.size() == 1) {
d = deps.get(0);
} else {
for (Dependency possible : deps) {
if (artifactFile.getAbsoluteFile().equals(possible.getActualFile())) {
d = possible;
break;
}
}
}
if (d != null) {
final MavenArtifact ma = new MavenArtifact(groupId, artifactId, version);
d.addAsEvidence("pom", ma, Confidence.HIGHEST);
if (availableVersions != null) {
for (ArtifactVersion av : availableVersions) {
d.addAvailableVersion(av.toString());
}
}
getLog().debug(String.format("Adding project reference %s on dependency %s",
project.getName(), d.getDisplayFileName()));
} else if (getLog().isDebugEnabled()) {
final String msg = String.format("More than 1 dependency was identified in first pass scan of '%s' in project %s",
dependencyNode.getArtifact().getId(), project.getName());
getLog().debug(msg);
}
} else if ("import".equals(dependencyNode.getArtifact().getScope())) {
final String msg = String.format("Skipping '%s:%s' in project %s as it uses an `import` scope",
dependencyNode.getArtifact().getId(), dependencyNode.getArtifact().getScope(), project.getName());
getLog().debug(msg);
} else if ("pom".equals(dependencyNode.getArtifact().getType())) {
try {
final Dependency d = new Dependency(artifactFile.getAbsoluteFile());
final Model pom = PomUtils.readPom(artifactFile.getAbsoluteFile());
JarAnalyzer.setPomEvidence(d, pom, null, true);
engine.addDependency(d);
} catch (AnalysisException ex) {
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(ex);
getLog().debug("Error reading pom " + artifactFile.getAbsoluteFile(), ex);
}
} else {
final String msg = String.format("No analyzer could be found for '%s:%s' in project %s",
dependencyNode.getArtifact().getId(), dependencyNode.getArtifact().getScope(), project.getName());
getLog().warn(msg);
}
} else {
final String msg = String.format("Unable to resolve '%s' in project %s",
dependencyNode.getArtifact().getId(), project.getName());
getLog().debug(msg);
if (exCol == null) {
exCol = new ExceptionCollection();
}
}
}
return exCol;
}
/**
* @param project the {@link MavenProject}
* @param dependencyNode the {@link DependencyNode}
* @return the name to be used when creating a
* {@link Dependency#getProjectReferences() project reference} in a
* {@link Dependency}. The behavior of this method returns {@link MavenProject#getName() project.getName()}<code> + ":" +
* </code>
* {@link DependencyNode#getArtifact() dependencyNode.getArtifact()}{@link Artifact#getScope() .getScope()}.
*/
protected String createProjectReferenceName(MavenProject project, DependencyNode dependencyNode) {
return project.getName() + ":" + dependencyNode.getArtifact().getScope();
}
/**
* Scans the projects dependencies including the default (or defined)
* FileSets.
*
* @param engine the core dependency-check engine
* @param project the project being scanned
* @param nodes the list of dependency nodes, generally obtained via the
* DependencyGraphBuilder
* @param buildingRequest the Maven project building request
* @param aggregate whether the scan is part of an aggregate build
* @return a collection of exceptions that may have occurred while resolving
* and scanning the dependencies
*/
private ExceptionCollection collectDependencies(Engine engine, MavenProject project,
List<DependencyNode> nodes, ProjectBuildingRequest buildingRequest, boolean aggregate) {
ExceptionCollection exCol;
exCol = collectMavenDependencies(engine, project, nodes, buildingRequest, aggregate);
final List<FileSet> projectScan;
if (scanDirectory != null && !scanDirectory.isEmpty()) {
if (scanSet == null) {
scanSet = new ArrayList<>();
}
scanDirectory.stream().forEach(d -> {
final FileSet fs = new FileSet();
fs.setDirectory(d);
fs.addInclude(INCLUDE_ALL);
scanSet.add(fs);
});
}
if (scanSet == null || scanSet.isEmpty()) {
// Define the default FileSets
final FileSet resourcesSet = new FileSet();
final FileSet filtersSet = new FileSet();
final FileSet webappSet = new FileSet();
final FileSet mixedLangSet = new FileSet();
try {
resourcesSet.setDirectory(new File(project.getBasedir(), "src/main/resources").getCanonicalPath());
resourcesSet.addInclude(INCLUDE_ALL);
filtersSet.setDirectory(new File(project.getBasedir(), "src/main/filters").getCanonicalPath());
filtersSet.addInclude(INCLUDE_ALL);
webappSet.setDirectory(new File(project.getBasedir(), "src/main/webapp").getCanonicalPath());
webappSet.addInclude(INCLUDE_ALL);
mixedLangSet.setDirectory(project.getBasedir().getCanonicalPath());
mixedLangSet.addInclude("package.json");
mixedLangSet.addInclude("package-lock.json");
mixedLangSet.addInclude("npm-shrinkwrap.json");
mixedLangSet.addInclude("Gopkg.lock");
mixedLangSet.addInclude("go.mod");
} catch (IOException ex) {
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(ex);
}
projectScan = new ArrayList<>();
projectScan.add(resourcesSet);
projectScan.add(filtersSet);
projectScan.add(webappSet);
projectScan.add(mixedLangSet);
} else if (aggregate) {
projectScan = new ArrayList<>();
for (FileSet copyFrom : scanSet) {
//deep copy of the FileSet - modifying the directory if it is not absolute.
final FileSet fsCopy = new FileSet();
final File f = new File(copyFrom.getDirectory());
if (f.isAbsolute()) {
fsCopy.setDirectory(copyFrom.getDirectory());
} else {
try {
fsCopy.setDirectory(new File(project.getBasedir(), copyFrom.getDirectory()).getCanonicalPath());
} catch (IOException ex) {
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(ex);
fsCopy.setDirectory(copyFrom.getDirectory());
}
}
fsCopy.setDirectoryMode(copyFrom.getDirectoryMode());
fsCopy.setExcludes(copyFrom.getExcludes());
fsCopy.setFileMode(copyFrom.getFileMode());
fsCopy.setFollowSymlinks(copyFrom.isFollowSymlinks());
fsCopy.setIncludes(copyFrom.getIncludes());
fsCopy.setLineEnding(copyFrom.getLineEnding());
fsCopy.setMapper(copyFrom.getMapper());
fsCopy.setModelEncoding(copyFrom.getModelEncoding());
fsCopy.setOutputDirectory(copyFrom.getOutputDirectory());
fsCopy.setUseDefaultExcludes(copyFrom.isUseDefaultExcludes());
projectScan.add(fsCopy);
}
} else {
projectScan = scanSet;
}
// Iterate through FileSets and scan included files
final FileSetManager fileSetManager = new FileSetManager();
for (FileSet fileSet : projectScan) {
getLog().debug("Scanning fileSet: " + fileSet.getDirectory());
final String[] includedFiles = fileSetManager.getIncludedFiles(fileSet);
for (String include : includedFiles) {
final File includeFile = new File(fileSet.getDirectory(), include).getAbsoluteFile();
if (includeFile.exists()) {
engine.scan(includeFile, project.getName());
}
}
}
return exCol;
}
/**
* Checks if the current artifact is actually in the reactor projects that
* have not yet been built. If true a virtual dependency is created based on
* the evidence in the project.
*
* @param engine a reference to the engine being used to scan
* @param artifact the artifact being analyzed in the mojo
* @return <code>true</code> if the artifact is in the reactor; otherwise
* <code>false</code>
*/
private boolean addReactorDependency(Engine engine, Artifact artifact) {
return addVirtualDependencyFromReactor(engine, artifact, "Unable to resolve %s as it has not been built yet "
+ "- creating a virtual dependency instead.");
}
/**
* Checks if the current artifact is actually in the reactor projects. If
* true a virtual dependency is created based on the evidence in the
* project.
*
* @param engine a reference to the engine being used to scan
* @param artifact the artifact being analyzed in the mojo
* @param infoLogTemplate the template for the infoLog entry written when a
* virtual dependency is added. Needs a single %s placeholder for the
* location of the displayName in the message
* @return <code>true</code> if the artifact is in the reactor; otherwise
* <code>false</code>
*/
private boolean addVirtualDependencyFromReactor(Engine engine, Artifact artifact, String infoLogTemplate) {
getLog().debug(String.format("Checking the reactor projects (%d) for %s:%s:%s",
reactorProjects.size(),
artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()));
for (MavenProject prj : reactorProjects) {
getLog().debug(String.format("Comparing %s:%s:%s to %s:%s:%s",
artifact.getGroupId(), artifact.getArtifactId(), artifact.getBaseVersion(),
prj.getGroupId(), prj.getArtifactId(), prj.getVersion()));
if (prj.getArtifactId().equals(artifact.getArtifactId())
&& prj.getGroupId().equals(artifact.getGroupId())
&& prj.getVersion().equals(artifact.getBaseVersion())) {
final String displayName = String.format("%s:%s:%s",
prj.getGroupId(), prj.getArtifactId(), prj.getVersion());
getLog().info(String.format(infoLogTemplate,
displayName));
final File pom = new File(prj.getBasedir(), "pom.xml");
final Dependency d;
if (pom.isFile()) {
getLog().debug("Adding virtual dependency from pom.xml");
d = new Dependency(pom, true);
} else {
d = new Dependency(true);
}
final String key = String.format("%s:%s:%s", prj.getGroupId(), prj.getArtifactId(), prj.getVersion());
d.setSha1sum(Checksum.getSHA1Checksum(key));
d.setSha256sum(Checksum.getSHA256Checksum(key));
d.setMd5sum(Checksum.getMD5Checksum(key));
d.setEcosystem(JarAnalyzer.DEPENDENCY_ECOSYSTEM);
d.setDisplayFileName(displayName);
d.addEvidence(EvidenceType.PRODUCT, "project", "artifactid", prj.getArtifactId(), Confidence.HIGHEST);
d.addEvidence(EvidenceType.VENDOR, "project", "artifactid", prj.getArtifactId(), Confidence.LOW);
d.addEvidence(EvidenceType.VENDOR, "project", "groupid", prj.getGroupId(), Confidence.HIGHEST);
d.addEvidence(EvidenceType.PRODUCT, "project", "groupid", prj.getGroupId(), Confidence.LOW);
d.setEcosystem(JarAnalyzer.DEPENDENCY_ECOSYSTEM);
Identifier id;
try {
id = new PurlIdentifier(StandardTypes.MAVEN, artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion(), Confidence.HIGHEST);
} catch (MalformedPackageURLException ex) {
getLog().debug("Unable to create PackageURL object:" + key);
id = new GenericIdentifier("maven:" + key, Confidence.HIGHEST);
}
d.addSoftwareIdentifier(id);
//TODO unify the setName/version and package path - they are equivelent ideas submitted by two seperate committers
d.setName(String.format("%s:%s", prj.getGroupId(), prj.getArtifactId()));
d.setVersion(prj.getVersion());
d.setPackagePath(displayName);
if (prj.getDescription() != null) {
JarAnalyzer.addDescription(d, prj.getDescription(), "project", "description");
}
for (License l : prj.getLicenses()) {
final StringBuilder license = new StringBuilder();
if (l.getName() != null) {
license.append(l.getName());
}
if (l.getUrl() != null) {
license.append(" ").append(l.getUrl());
}
if (d.getLicense() == null) {
d.setLicense(license.toString());
} else if (!d.getLicense().contains(license)) {
d.setLicense(String.format("%s%n%s", d.getLicense(), license.toString()));
}
}
engine.addDependency(d);
return true;
}
}
return false;
}
/**
* Checks if the current artifact is actually in the reactor projects. If
* true a virtual dependency is created based on the evidence in the
* project.
*
* @param engine a reference to the engine being used to scan
* @param artifact the artifact being analyzed in the mojo
* @return <code>true</code> if the artifact is a snapshot artifact in the
* reactor; otherwise <code>false</code>
*/
private boolean addSnapshotReactorDependency(Engine engine, Artifact artifact) {
if (!artifact.isSnapshot()) {
return false;
}
return addVirtualDependencyFromReactor(engine, artifact, "Found snapshot reactor project in aggregate for %s - "
+ "creating a virtual dependency as the snapshot found in the repository may contain outdated dependencies.");
}
/**
* @param project The target project to create a building request for.
* @return Returns a new ProjectBuildingRequest populated from the current
* session and the target project remote repositories, used to resolve
* artifacts.
*/
public ProjectBuildingRequest newResolveArtifactProjectBuildingRequest(MavenProject project) {
final ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
buildingRequest.setRemoteRepositories(new ArrayList<>(project.getRemoteArtifactRepositories()));
buildingRequest.setProject(project);
return buildingRequest;
}
/**
* Executes the dependency-check scan and generates the necessary report.
*
* @throws MojoExecutionException thrown if there is an exception running
* the scan
* @throws MojoFailureException thrown if dependency-check is configured to
* fail the build
*/
protected void runCheck() throws MojoExecutionException, MojoFailureException {
muteJCS();
try (Engine engine = initializeEngine()) {
ExceptionCollection exCol = scanDependencies(engine);
try {
engine.analyzeDependencies();
} catch (ExceptionCollection ex) {
exCol = handleAnalysisExceptions(exCol, ex);
}
if (exCol == null || !exCol.isFatal()) {
File outputDir = getCorrectOutputDirectory(this.getProject());
if (outputDir == null) {
//in some regards we shouldn't be writing this, but we are anyway.
//we shouldn't write this because nothing is configured to generate this report.
outputDir = new File(this.getProject().getBuild().getDirectory());
}
try {
final MavenProject p = this.getProject();
for (String f : getFormats()) {
engine.writeReports(p.getName(), p.getGroupId(), p.getArtifactId(), p.getVersion(), outputDir, f, exCol);
}
} catch (ReportException ex) {
if (exCol == null) {
exCol = new ExceptionCollection(ex);
} else {
exCol.addException(ex);
}
if (this.isFailOnError()) {
throw new MojoExecutionException("One or more exceptions occurred during dependency-check analysis", exCol);
} else {
getLog().debug("Error writing the report", ex);
}
}
showSummary(this.getProject(), engine.getDependencies());
checkForFailure(engine.getDependencies());
if (exCol != null && this.isFailOnError()) {
throw new MojoExecutionException("One or more exceptions occurred during dependency-check analysis", exCol);
}
}
} catch (DatabaseException ex) {
if (getLog().isDebugEnabled()) {
getLog().debug("Database connection error", ex);
}
final String msg = "An exception occurred connecting to the local database. Please see the log file for more details.";
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, ex);
}
getLog().error(msg, ex);
} finally {
getSettings().cleanup();
}
}
/**
* Combines the two exception collections and if either are fatal, throw an
* MojoExecutionException
*
* @param currentEx the primary exception collection
* @param newEx the new exception collection to add
* @return the combined exception collection
* @throws MojoExecutionException thrown if dependency-check is configured
* to fail on errors
*/
private ExceptionCollection handleAnalysisExceptions(ExceptionCollection currentEx, ExceptionCollection newEx) throws MojoExecutionException {
ExceptionCollection returnEx = currentEx;
if (returnEx == null) {
returnEx = newEx;
} else {
returnEx.getExceptions().addAll(newEx.getExceptions());
if (newEx.isFatal()) {
returnEx.setFatal(true);
}
}
if (returnEx.isFatal()) {
final String msg = String.format("Fatal exception(s) analyzing %s", getProject().getName());
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, returnEx);
}
getLog().error(msg);
if (getLog().isDebugEnabled()) {
getLog().debug(returnEx);
}
} else {
final String msg = String.format("Exception(s) analyzing %s", getProject().getName());
if (getLog().isDebugEnabled()) {
getLog().debug(msg, returnEx);
}
}
return returnEx;
}
/**
* Scans the dependencies of the projects in aggregate.
*
* @param engine the engine used to perform the scanning
* @return a collection of exceptions
* @throws MojoExecutionException thrown if a fatal exception occurs
*/
protected abstract ExceptionCollection scanDependencies(Engine engine) throws MojoExecutionException;
/**
* Returns the report output directory.
*
* @return the report output directory
*/
@Override
public File getReportOutputDirectory() {
return reportOutputDirectory;
}
/**
* Sets the Reporting output directory.
*
* @param directory the output directory
*/
@Override
public void setReportOutputDirectory(File directory) {
reportOutputDirectory = directory;
}
/**
* Returns the output directory.
*
* @return the output directory
*/
public File getOutputDirectory() {
return outputDirectory;
}
/**
* Returns whether this is an external report. This method always returns
* true.
*
* @return <code>true</code>
*/
@Override
public final boolean isExternalReport() {
return true;
}
/**
* Returns the output name.
*
* @return the output name
*/
@Override
public String getOutputName() {
final Set<String> selectedFormats = getFormats();
if (selectedFormats.contains("HTML") || selectedFormats.contains("ALL") || selectedFormats.size() > 1) {
return "dependency-check-report";
} else if (selectedFormats.contains("XML")) {
return "dependency-check-report.xml";
} else if (selectedFormats.contains("JUNIT")) {
return "dependency-check-junit.xml";
} else if (selectedFormats.contains("JSON")) {
return "dependency-check-report.json";
} else if (selectedFormats.contains("CSV")) {
return "dependency-check-report.csv";
} else {
getLog().warn("Unknown report format used during site generation.");
return "dependency-check-report";
}
}
/**
* Returns the category name.
*
* @return the category name
*/
@Override
public String getCategoryName() {
return MavenReport.CATEGORY_PROJECT_REPORTS;
}
//</editor-fold>
/**
* Initializes a new <code>Engine</code> that can be used for scanning. This
* method should only be called in a try-with-resources to ensure that the
* engine is properly closed.
*
* @return a newly instantiated <code>Engine</code>
* @throws DatabaseException thrown if there is a database exception
*/
protected Engine initializeEngine() throws DatabaseException {
populateSettings();
return new Engine(settings);
}
/**
* Takes the properties supplied and updates the dependency-check settings.
* Additionally, this sets the system properties required to change the
* proxy URL, port, and connection timeout.
*/
protected void populateSettings() {
settings = new Settings();
InputStream mojoProperties = null;
try {
mojoProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
settings.mergeProperties(mojoProperties);
} catch (IOException ex) {
getLog().warn("Unable to load the dependency-check maven mojo.properties file.");
if (getLog().isDebugEnabled()) {
getLog().debug("", ex);
}
} finally {
if (mojoProperties != null) {
try {
mojoProperties.close();
} catch (IOException ex) {
if (getLog().isDebugEnabled()) {
getLog().debug("", ex);
}
}
}
}
settings.setBooleanIfNotNull(Settings.KEYS.AUTO_UPDATE, autoUpdate);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, enableExperimental);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RETIRED_ENABLED, enableRetired);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_GOLANG_DEP_ENABLED, golangDepEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_GOLANG_MOD_ENABLED, golangModEnabled);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_GOLANG_PATH, pathToGo);
final Proxy proxy = getMavenProxy();
if (proxy != null) {
settings.setString(Settings.KEYS.PROXY_SERVER, proxy.getHost());
settings.setString(Settings.KEYS.PROXY_PORT, Integer.toString(proxy.getPort()));
final String userName = proxy.getUsername();
final String password = proxy.getPassword();
settings.setStringIfNotNull(Settings.KEYS.PROXY_USERNAME, userName);
settings.setStringIfNotNull(Settings.KEYS.PROXY_PASSWORD, password);
settings.setStringIfNotNull(Settings.KEYS.PROXY_NON_PROXY_HOSTS, proxy.getNonProxyHosts());
}
final String[] suppressions = determineSuppressions();
settings.setArrayIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressions);
settings.setBooleanIfNotNull(Settings.KEYS.UPDATE_VERSION_CHECK_ENABLED, versionCheckEnabled);
settings.setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout);
settings.setStringIfNotEmpty(Settings.KEYS.HINTS_FILE, hintsFile);
settings.setFloat(Settings.KEYS.JUNIT_FAIL_ON_CVSS, junitFailOnCVSS);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_JAR_ENABLED, jarAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, nuspecAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NUGETCONF_ENABLED, nugetconfAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, centralAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CENTRAL_USE_CACHE, centralAnalyzerUseCache);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_ENABLED, artifactoryAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_ENABLED, nexusAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, assemblyAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, archiveAnalyzerEnabled);
settings.setStringIfNotEmpty(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, zipExtensions);
settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_ASSEMBLY_DOTNET_PATH, pathToCore);
settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl);
configureServerCredentials(nexusServerId, Settings.KEYS.ANALYZER_NEXUS_USER, Settings.KEYS.ANALYZER_NEXUS_PASSWORD);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY, nexusUsesProxy);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_URL, artifactoryAnalyzerUrl);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_USES_PROXY, artifactoryAnalyzerUseProxy);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_PARALLEL_ANALYSIS, artifactoryAnalyzerParallelAnalysis);
if (Boolean.TRUE.equals(artifactoryAnalyzerEnabled)) {
if (artifactoryAnalyzerServerId != null) {
configureServerCredentials(artifactoryAnalyzerServerId, Settings.KEYS.ANALYZER_ARTIFACTORY_API_USERNAME,
Settings.KEYS.ANALYZER_ARTIFACTORY_API_TOKEN);
} else {
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_API_USERNAME, artifactoryAnalyzerUsername);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_API_TOKEN, artifactoryAnalyzerApiToken);
}
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_ARTIFACTORY_BEARER_TOKEN, artifactoryAnalyzerBearerToken);
}
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, pyDistributionAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED, pyPackageAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RUBY_GEMSPEC_ENABLED, rubygemsAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_OPENSSL_ENABLED, opensslAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CMAKE_ENABLED, cmakeAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_AUTOCONF_ENABLED, autoconfAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PIP_ENABLED, pipAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PIPFILE_ENABLED, pipfileAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_COMPOSER_LOCK_ENABLED, composerAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED, nodeAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED, nodeAuditAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_AUDIT_USE_CACHE, nodeAuditAnalyzerUseCache);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_AUDIT_SKIPDEV, nodeAuditSkipDevDependencies);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RETIREJS_ENABLED, retireJsAnalyzerEnabled);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_RETIREJS_REPO_JS_URL, retireJsUrl);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RETIREJS_FORCEUPDATE, retireJsForceUpdate);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_MIX_AUDIT_ENABLED, mixAuditAnalyzerEnabled);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_MIX_AUDIT_PATH, mixAuditPath);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_ENABLED, bundleAuditAnalyzerEnabled);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, bundleAuditPath);
settings.setStringIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_WORKING_DIRECTORY, bundleAuditWorkingDirectory);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_COCOAPODS_ENABLED, cocoapodsAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_SWIFT_PACKAGE_MANAGER_ENABLED, swiftPackageManagerAnalyzerEnabled);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_OSSINDEX_ENABLED, ossindexAnalyzerEnabled);
settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_OSSINDEX_URL, ossindexAnalyzerUrl);
configureServerCredentials(ossIndexServerId, Settings.KEYS.ANALYZER_OSSINDEX_USER, Settings.KEYS.ANALYZER_OSSINDEX_PASSWORD);
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_OSSINDEX_USE_CACHE, ossindexAnalyzerUseCache);
if (retirejs != null) {
settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RETIREJS_FILTER_NON_VULNERABLE, retirejs.getFilterNonVulnerable());
settings.setArrayIfNotEmpty(Settings.KEYS.ANALYZER_RETIREJS_FILTERS, retirejs.getFilters());
}
//Database configuration
settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName);
settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath);
settings.setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
if (databaseUser == null && databasePassword == null && serverId != null) {
configureServerCredentials(serverId, Settings.KEYS.DB_USER, Settings.KEYS.DB_PASSWORD);
} else {
settings.setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser);
settings.setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword);
}
settings.setStringIfNotEmpty(Settings.KEYS.DATA_DIRECTORY, dataDirectory);
settings.setStringIfNotEmpty(Settings.KEYS.DB_FILE_NAME, dbFilename);
settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_JSON, cveUrlModified);
settings.setStringIfNotEmpty(Settings.KEYS.CVE_BASE_JSON, cveUrlBase);
settings.setIntIfNotNull(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, cveValidForHours);
settings.setBooleanIfNotNull(Settings.KEYS.PRETTY_PRINT, prettyPrint);
artifactScopeExcluded = new ArtifactScopeExcluded(skipTestScope, skipProvidedScope, skipSystemScope, skipRuntimeScope);
artifactTypeExcluded = new ArtifactTypeExcluded(skipArtifactType);
if (cveUser == null && cvePassword == null && cveServerId != null) {
configureServerCredentials(cveServerId, Settings.KEYS.CVE_USER, Settings.KEYS.CVE_PASSWORD);
} else {
settings.setStringIfNotEmpty(Settings.KEYS.CVE_USER, cveUser);
settings.setStringIfNotEmpty(Settings.KEYS.CVE_PASSWORD, cvePassword);
}
}
/**
* Retrieves the server credentials from the settings.xml, decrypts the
* password, and places the values into the settings under the given key
* names.
*
* @param serverId the server id
* @param userSettingKey the property name for the username
* @param passwordSettingKey the property name for the password
*/
private void configureServerCredentials(String serverId, String userSettingKey, String passwordSettingKey) {
if (serverId != null) {
final Server server = settingsXml.getServer(serverId);
if (server != null) {
final String username = server.getUsername();
String password = null;
try {
password = decryptServerPassword(server);
} catch (SecDispatcherException ex) {
if (ex.getCause() instanceof FileNotFoundException
|| (ex.getCause() != null && ex.getCause().getCause() instanceof FileNotFoundException)) {
//maybe its not encrypted?
final String tmp = server.getPassword();
if (tmp.startsWith("{") && tmp.endsWith("}")) {
getLog().error(String.format(
"Unable to decrypt the server password for server id '%s' in settings.xml%n\tCause: %s",
serverId, ex.getMessage()));
} else {
password = tmp;
}
} else {
getLog().error(String.format(
"Unable to decrypt the server password for server id '%s' in settings.xml%n\tCause: %s",
serverId, ex.getMessage()));
}
}
settings.setStringIfNotEmpty(userSettingKey, username);
settings.setStringIfNotEmpty(passwordSettingKey, password);
} else {
getLog().error(String.format("Server '%s' not found in the settings.xml file", serverId));
}
}
}
//CSOFF: LineLength
/**
* Obtains the configured password for the given server.
*
* @param server the configured server from the settings.xml
* @return the decrypted password from the Maven configuration
* @throws SecDispatcherException thrown if there is an error decrypting the
* password
*/
private String decryptServerPassword(Server server) throws SecDispatcherException {
//The following fix was copied from:
// https://github.com/bsorrentino/maven-confluence-plugin/blob/master/maven-confluence-reporting-plugin/src/main/java/org/bsc/maven/confluence/plugin/AbstractBaseConfluenceMojo.java
//
// FIX to resolve
// org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException:
// java.io.FileNotFoundException: ~/.settings-security.xml (No such file or directory)
//
if (securityDispatcher instanceof DefaultSecDispatcher) {
((DefaultSecDispatcher) securityDispatcher).setConfigurationFile("~/.m2/settings-security.xml");
}
return securityDispatcher.decrypt(server.getPassword());
}
//CSON: LineLength
/**
* Combines the configured suppressionFile and suppressionFiles into a
* single array.
*
* @return an array of suppression file paths
*/
private String[] determineSuppressions() {
String[] suppressions = suppressionFiles;
if (suppressionFile != null) {
if (suppressions == null) {
suppressions = new String[]{suppressionFile};
} else {
suppressions = Arrays.copyOf(suppressions, suppressions.length + 1);
suppressions[suppressions.length - 1] = suppressionFile;
}
}
return suppressions;
}
/**
* Hacky method of muting the noisy logging from JCS. Implemented using a
* solution from SO: https://stackoverflow.com/a/50723801
*/
private void muteJCS() {
final String[] noisyLoggers = {
"org.apache.commons.jcs.auxiliary.disk.AbstractDiskCache",
"org.apache.commons.jcs.engine.memory.AbstractMemoryCache",
"org.apache.commons.jcs.engine.control.CompositeCache",
"org.apache.commons.jcs.auxiliary.disk.indexed.IndexedDiskCache",
"org.apache.commons.jcs.engine.control.CompositeCache",
"org.apache.commons.jcs.engine.memory.AbstractMemoryCache",
"org.apache.commons.jcs.engine.control.event.ElementEventQueue",
"org.apache.commons.jcs.engine.memory.AbstractDoubleLinkedListMemoryCache",
"org.apache.commons.jcs.auxiliary.AuxiliaryCacheConfigurator",
"org.apache.commons.jcs.engine.control.CompositeCacheManager",
"org.apache.commons.jcs.utils.threadpool.ThreadPoolManager",
"org.apache.commons.jcs.engine.control.CompositeCacheConfigurator"};
for (String loggerName : noisyLoggers) {
try {
//This is actually a MavenSimpleLogger, but due to various classloader issues, can't work with the directly.
final Logger l = LoggerFactory.getLogger(loggerName);
final Field f = l.getClass().getSuperclass().getDeclaredField("currentLogLevel");
f.setAccessible(true);
f.set(l, LocationAwareLogger.ERROR_INT);
} catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException e) {
getLog().debug("Failed to reset the log level of " + loggerName + ", it will continue being noisy.");
}
}
}
/**
* Returns the maven proxy.
*
* @return the maven proxy
*/
private Proxy getMavenProxy() {
if (mavenSettings != null) {
final List<Proxy> proxies = mavenSettings.getProxies();
if (proxies != null && !proxies.isEmpty()) {
if (mavenSettingsProxyId != null) {
for (Proxy proxy : proxies) {
if (mavenSettingsProxyId.equalsIgnoreCase(proxy.getId())) {
return proxy;
}
}
} else {
for (Proxy aProxy : proxies) {
if (aProxy.isActive()) {
return aProxy;
}
}
}
}
}
return null;
}
/**
* Returns a reference to the current project. This method is used instead
* of auto-binding the project via component annotation in concrete
* implementations of this. If the child has a
* <code>@Component MavenProject project;</code> defined then the abstract
* class (i.e. this class) will not have access to the current project (just
* the way Maven works with the binding).
*
* @return returns a reference to the current project
*/
protected MavenProject getProject() {
return project;
}
/**
* Returns the list of Maven Projects in this build.
*
* @return the list of Maven Projects in this build
*/
protected List<MavenProject> getReactorProjects() {
return reactorProjects;
}
/**
* Combines the format and formats properties into a single collection.
*
* @return the selected report formats
*/
private Set<String> getFormats() {
final Set<String> invalid = new HashSet<>();
final Set<String> selectedFormats = formats == null || formats.length == 0 ? new HashSet<>() : new HashSet<>(Arrays.asList(formats));
selectedFormats.forEach((s) -> {
try {
ReportGenerator.Format.valueOf(s.toUpperCase());
} catch (IllegalArgumentException ex) {
invalid.add(s);
}
});
invalid.forEach((s) -> {
getLog().warn("Invalid report format specified: " + s);
});
if (selectedFormats.contains("true")) {
selectedFormats.remove("true");
}
if (format != null && selectedFormats.isEmpty()) {
selectedFormats.add(format);
}
return selectedFormats;
}
/**
* Returns the list of excluded artifacts based on either artifact id or
* group id and artifact id.
*
* @return a list of artifact to exclude
*/
public List<String> getExcludes() {
if (excludes == null) {
excludes = new ArrayList<>();
}
return excludes;
}
/**
* Returns the artifact scope excluded filter.
*
* @return the artifact scope excluded filter
*/
protected Filter<String> getArtifactScopeExcluded() {
return artifactScopeExcluded;
}
/**
* Returns the configured settings.
*
* @return the configured settings
*/
protected Settings getSettings() {
return settings;
}
//<editor-fold defaultstate="collapsed" desc="Methods to fail build or show summary">
/**
* Checks to see if a vulnerability has been identified with a CVSS score
* that is above the threshold set in the configuration.
*
* @param dependencies the list of dependency objects
* @throws MojoFailureException thrown if a CVSS score is found that is
* higher then the threshold set
*/
protected void checkForFailure(Dependency[] dependencies) throws MojoFailureException {
final StringBuilder ids = new StringBuilder();
for (Dependency d : dependencies) {
boolean addName = true;
for (Vulnerability v : d.getVulnerabilities()) {
if (failBuildOnAnyVulnerability || (v.getCvssV2() != null && v.getCvssV2().getScore() >= failBuildOnCVSS)
|| (v.getCvssV3() != null && v.getCvssV3().getBaseScore() >= failBuildOnCVSS)
|| (v.getUnscoredSeverity() != null && SeverityUtil.estimateCvssV2(v.getUnscoredSeverity()) >= failBuildOnCVSS)) {
if (addName) {
addName = false;
ids.append(NEW_LINE).append(d.getFileName()).append(": ");
ids.append(v.getName());
} else {
ids.append(", ").append(v.getName());
}
}
}
}
if (ids.length() > 0) {
final String msg;
if (showSummary) {
if (failBuildOnAnyVulnerability) {
msg = String.format("%n%nOne or more dependencies were identified with vulnerabilities: %n%s%n%n"
+ "See the dependency-check report for more details.%n%n", ids.toString());
} else {
msg = String.format("%n%nOne or more dependencies were identified with vulnerabilities that have a CVSS score greater than or "
+ "equal to '%.1f': %n%s%n%nSee the dependency-check report for more details.%n%n", failBuildOnCVSS, ids.toString());
}
} else {
msg = String.format("%n%nOne or more dependencies were identified with vulnerabilities.%n%n"
+ "See the dependency-check report for more details.%n%n");
}
throw new MojoFailureException(msg);
}
}
/**
* Generates a warning message listing a summary of dependencies and their
* associated CPE and CVE entries.
*
* @param mp the Maven project for which the summary is shown
* @param dependencies a list of dependency objects
*/
protected void showSummary(MavenProject mp, Dependency[] dependencies) {
if (showSummary) {
DependencyCheckScanAgent.showSummary(mp.getName(), dependencies);
}
}
//</editor-fold>
}
| [issue 2960] Added support for encrypted proxy passwords in Maven settings (#2966)
Also:
- Refactored handling of SecDispatcherException in class org.owasp.dependencycheck.maven.BaseDependencyCheckMojo.
- Added setting the system property "jdk.http.auth.tunneling.disabledSchemes" to an empty list already in
org.owasp.dependencycheck.maven.BaseDependencyCheckMojo (if demanded), because setting it only
in org.owasp.dependencycheck.utils.URLConnectionFactory comes too late to take effect when using DepCheck
as a Maven plugin. | maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java | [issue 2960] Added support for encrypted proxy passwords in Maven settings (#2966) | <ide><path>aven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
<ide> settings.setString(Settings.KEYS.PROXY_SERVER, proxy.getHost());
<ide> settings.setString(Settings.KEYS.PROXY_PORT, Integer.toString(proxy.getPort()));
<ide> final String userName = proxy.getUsername();
<del> final String password = proxy.getPassword();
<add> String password = proxy.getPassword();
<add> if (password != null && !password.isEmpty()) {
<add> if (settings.getBoolean(Settings.KEYS.PROXY_DISABLE_SCHEMAS, true)) {
<add> System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
<add> }
<add> try {
<add> password = decryptPasswordFromSettings(password);
<add> } catch (SecDispatcherException ex) {
<add> password = handleSecDispatcherException("proxy", proxy.getId(), password, ex);
<add> }
<add> }
<ide> settings.setStringIfNotNull(Settings.KEYS.PROXY_USERNAME, userName);
<ide> settings.setStringIfNotNull(Settings.KEYS.PROXY_PASSWORD, password);
<ide> settings.setStringIfNotNull(Settings.KEYS.PROXY_NON_PROXY_HOSTS, proxy.getNonProxyHosts());
<ide> final String username = server.getUsername();
<ide> String password = null;
<ide> try {
<del> password = decryptServerPassword(server);
<add> password = decryptPasswordFromSettings(server.getPassword());
<ide> } catch (SecDispatcherException ex) {
<del> if (ex.getCause() instanceof FileNotFoundException
<del> || (ex.getCause() != null && ex.getCause().getCause() instanceof FileNotFoundException)) {
<del> //maybe its not encrypted?
<del> final String tmp = server.getPassword();
<del> if (tmp.startsWith("{") && tmp.endsWith("}")) {
<del> getLog().error(String.format(
<del> "Unable to decrypt the server password for server id '%s' in settings.xml%n\tCause: %s",
<del> serverId, ex.getMessage()));
<del> } else {
<del> password = tmp;
<del> }
<del> } else {
<del> getLog().error(String.format(
<del> "Unable to decrypt the server password for server id '%s' in settings.xml%n\tCause: %s",
<del> serverId, ex.getMessage()));
<del> }
<add> password = handleSecDispatcherException("server", serverId, server.getPassword(), ex);
<ide> }
<ide> settings.setStringIfNotEmpty(userSettingKey, username);
<ide> settings.setStringIfNotEmpty(passwordSettingKey, password);
<ide>
<ide> //CSOFF: LineLength
<ide> /**
<del> * Obtains the configured password for the given server.
<del> *
<del> * @param server the configured server from the settings.xml
<add> * Decrypts a password from the Maven settings if it needs to be decrypted.
<add> * If it's not encrypted the input password will be returned unchanged.
<add> *
<add> * @param the original password value from the settings.xml
<ide> * @return the decrypted password from the Maven configuration
<ide> * @throws SecDispatcherException thrown if there is an error decrypting the
<ide> * password
<ide> */
<del> private String decryptServerPassword(Server server) throws SecDispatcherException {
<add> private String decryptPasswordFromSettings(String password) throws SecDispatcherException {
<ide>
<ide> //The following fix was copied from:
<ide> // https://github.com/bsorrentino/maven-confluence-plugin/blob/master/maven-confluence-reporting-plugin/src/main/java/org/bsc/maven/confluence/plugin/AbstractBaseConfluenceMojo.java
<ide> ((DefaultSecDispatcher) securityDispatcher).setConfigurationFile("~/.m2/settings-security.xml");
<ide> }
<ide>
<del> return securityDispatcher.decrypt(server.getPassword());
<del> }
<add> return securityDispatcher.decrypt(password);
<add> }
<ide> //CSON: LineLength
<add>
<add> /**
<add> * Handles a SecDispatcherException that was thrown at an attempt to decrypt an encrypted password from the Maven settings.
<add> *
<add> * @param settingsElementName - "server" or "proxy"
<add> * @param settingsElementId - value of the id attribute of the proxy resp. server element to which the password belongs
<add> * @param passwordValueFromSettings - original, undecrypted password value from the settings
<add> * @param ex - the Exception to handle
<add> * @return the password fallback value to go on with, might be a not working one.
<add> */
<add> private String handleSecDispatcherException(String settingsElementName, String settingsElementId, String passwordValueFromSettings,
<add> SecDispatcherException ex) {
<add> String password = passwordValueFromSettings;
<add> if (ex.getCause() instanceof FileNotFoundException
<add> || (ex.getCause() != null && ex.getCause().getCause() instanceof FileNotFoundException)) {
<add> //maybe its not encrypted?
<add> final String tmp = passwordValueFromSettings;
<add> if (tmp.startsWith("{") && tmp.endsWith("}")) {
<add> getLog().error(String.format(
<add> "Unable to decrypt the %s password for %s id '%s' in settings.xml%n\tCause: %s",
<add> settingsElementName, settingsElementName, settingsElementId, ex.getMessage()));
<add> } else {
<add> password = tmp;
<add> }
<add> } else {
<add> getLog().error(String.format(
<add> "Unable to decrypt the %s password for %s id '%s' in settings.xml%n\tCause: %s",
<add> settingsElementName, settingsElementName, settingsElementId, ex.getMessage()));
<add> }
<add> return password;
<add> }
<ide>
<ide> /**
<ide> * Combines the configured suppressionFile and suppressionFiles into a |
|
Java | apache-2.0 | 9c6c512f9f1f3c645939223814578ba9f09af579 | 0 | rblalock/titanium_mobile,sriks/titanium_mobile,peymanmortazavi/titanium_mobile,taoger/titanium_mobile,linearhub/titanium_mobile,mano-mykingdom/titanium_mobile,jhaynie/titanium_mobile,KoketsoMabuela92/titanium_mobile,jhaynie/titanium_mobile,linearhub/titanium_mobile,cheekiatng/titanium_mobile,falkolab/titanium_mobile,jvkops/titanium_mobile,FokkeZB/titanium_mobile,peymanmortazavi/titanium_mobile,perdona/titanium_mobile,emilyvon/titanium_mobile,csg-coder/titanium_mobile,indera/titanium_mobile,benbahrenburg/titanium_mobile,prop/titanium_mobile,openbaoz/titanium_mobile,shopmium/titanium_mobile,smit1625/titanium_mobile,openbaoz/titanium_mobile,bright-sparks/titanium_mobile,sriks/titanium_mobile,mano-mykingdom/titanium_mobile,perdona/titanium_mobile,kopiro/titanium_mobile,indera/titanium_mobile,benbahrenburg/titanium_mobile,pec1985/titanium_mobile,benbahrenburg/titanium_mobile,bhatfield/titanium_mobile,emilyvon/titanium_mobile,AngelkPetkov/titanium_mobile,bright-sparks/titanium_mobile,sriks/titanium_mobile,formalin14/titanium_mobile,FokkeZB/titanium_mobile,pinnamur/titanium_mobile,formalin14/titanium_mobile,ashcoding/titanium_mobile,cheekiatng/titanium_mobile,prop/titanium_mobile,cheekiatng/titanium_mobile,kopiro/titanium_mobile,collinprice/titanium_mobile,perdona/titanium_mobile,pinnamur/titanium_mobile,bhatfield/titanium_mobile,mano-mykingdom/titanium_mobile,FokkeZB/titanium_mobile,emilyvon/titanium_mobile,bright-sparks/titanium_mobile,peymanmortazavi/titanium_mobile,formalin14/titanium_mobile,collinprice/titanium_mobile,formalin14/titanium_mobile,peymanmortazavi/titanium_mobile,peymanmortazavi/titanium_mobile,formalin14/titanium_mobile,formalin14/titanium_mobile,bhatfield/titanium_mobile,FokkeZB/titanium_mobile,benbahrenburg/titanium_mobile,cheekiatng/titanium_mobile,linearhub/titanium_mobile,mvitr/titanium_mobile,benbahrenburg/titanium_mobile,mano-mykingdom/titanium_mobile,collinprice/titanium_mobile,prop/titanium_mobile,jhaynie/titanium_mobile,bright-sparks/titanium_mobile,bhatfield/titanium_mobile,pec1985/titanium_mobile,benbahrenburg/titanium_mobile,smit1625/titanium_mobile,indera/titanium_mobile,mano-mykingdom/titanium_mobile,bhatfield/titanium_mobile,KangaCoders/titanium_mobile,indera/titanium_mobile,FokkeZB/titanium_mobile,AngelkPetkov/titanium_mobile,sriks/titanium_mobile,kopiro/titanium_mobile,benbahrenburg/titanium_mobile,rblalock/titanium_mobile,peymanmortazavi/titanium_mobile,linearhub/titanium_mobile,csg-coder/titanium_mobile,kopiro/titanium_mobile,pec1985/titanium_mobile,jhaynie/titanium_mobile,perdona/titanium_mobile,prop/titanium_mobile,csg-coder/titanium_mobile,AngelkPetkov/titanium_mobile,benbahrenburg/titanium_mobile,openbaoz/titanium_mobile,kopiro/titanium_mobile,KangaCoders/titanium_mobile,smit1625/titanium_mobile,indera/titanium_mobile,linearhub/titanium_mobile,pinnamur/titanium_mobile,bright-sparks/titanium_mobile,csg-coder/titanium_mobile,rblalock/titanium_mobile,rblalock/titanium_mobile,taoger/titanium_mobile,openbaoz/titanium_mobile,kopiro/titanium_mobile,smit1625/titanium_mobile,jvkops/titanium_mobile,jhaynie/titanium_mobile,AngelkPetkov/titanium_mobile,mvitr/titanium_mobile,prop/titanium_mobile,mvitr/titanium_mobile,FokkeZB/titanium_mobile,prop/titanium_mobile,bright-sparks/titanium_mobile,taoger/titanium_mobile,emilyvon/titanium_mobile,rblalock/titanium_mobile,AngelkPetkov/titanium_mobile,linearhub/titanium_mobile,FokkeZB/titanium_mobile,smit1625/titanium_mobile,cheekiatng/titanium_mobile,pec1985/titanium_mobile,peymanmortazavi/titanium_mobile,ashcoding/titanium_mobile,AngelkPetkov/titanium_mobile,ashcoding/titanium_mobile,smit1625/titanium_mobile,rblalock/titanium_mobile,sriks/titanium_mobile,taoger/titanium_mobile,perdona/titanium_mobile,jvkops/titanium_mobile,bhatfield/titanium_mobile,openbaoz/titanium_mobile,falkolab/titanium_mobile,jhaynie/titanium_mobile,pec1985/titanium_mobile,csg-coder/titanium_mobile,shopmium/titanium_mobile,KoketsoMabuela92/titanium_mobile,KangaCoders/titanium_mobile,csg-coder/titanium_mobile,taoger/titanium_mobile,taoger/titanium_mobile,falkolab/titanium_mobile,FokkeZB/titanium_mobile,mvitr/titanium_mobile,perdona/titanium_mobile,shopmium/titanium_mobile,AngelkPetkov/titanium_mobile,mano-mykingdom/titanium_mobile,falkolab/titanium_mobile,indera/titanium_mobile,linearhub/titanium_mobile,prop/titanium_mobile,KangaCoders/titanium_mobile,sriks/titanium_mobile,jvkops/titanium_mobile,jvkops/titanium_mobile,indera/titanium_mobile,KoketsoMabuela92/titanium_mobile,linearhub/titanium_mobile,prop/titanium_mobile,formalin14/titanium_mobile,csg-coder/titanium_mobile,shopmium/titanium_mobile,mvitr/titanium_mobile,ashcoding/titanium_mobile,perdona/titanium_mobile,rblalock/titanium_mobile,falkolab/titanium_mobile,openbaoz/titanium_mobile,shopmium/titanium_mobile,sriks/titanium_mobile,shopmium/titanium_mobile,mano-mykingdom/titanium_mobile,cheekiatng/titanium_mobile,ashcoding/titanium_mobile,bright-sparks/titanium_mobile,cheekiatng/titanium_mobile,smit1625/titanium_mobile,collinprice/titanium_mobile,bhatfield/titanium_mobile,emilyvon/titanium_mobile,rblalock/titanium_mobile,taoger/titanium_mobile,falkolab/titanium_mobile,KangaCoders/titanium_mobile,jvkops/titanium_mobile,kopiro/titanium_mobile,cheekiatng/titanium_mobile,kopiro/titanium_mobile,emilyvon/titanium_mobile,mvitr/titanium_mobile,KangaCoders/titanium_mobile,mano-mykingdom/titanium_mobile,ashcoding/titanium_mobile,jvkops/titanium_mobile,pinnamur/titanium_mobile,shopmium/titanium_mobile,falkolab/titanium_mobile,AngelkPetkov/titanium_mobile,ashcoding/titanium_mobile,perdona/titanium_mobile,shopmium/titanium_mobile,peymanmortazavi/titanium_mobile,KoketsoMabuela92/titanium_mobile,collinprice/titanium_mobile,jvkops/titanium_mobile,pec1985/titanium_mobile,smit1625/titanium_mobile,pinnamur/titanium_mobile,ashcoding/titanium_mobile,formalin14/titanium_mobile,collinprice/titanium_mobile,collinprice/titanium_mobile,mvitr/titanium_mobile,jhaynie/titanium_mobile,KoketsoMabuela92/titanium_mobile,KangaCoders/titanium_mobile,jhaynie/titanium_mobile,openbaoz/titanium_mobile,pec1985/titanium_mobile,pinnamur/titanium_mobile,bhatfield/titanium_mobile,emilyvon/titanium_mobile,sriks/titanium_mobile,falkolab/titanium_mobile,openbaoz/titanium_mobile,emilyvon/titanium_mobile,pec1985/titanium_mobile,pinnamur/titanium_mobile,collinprice/titanium_mobile,KoketsoMabuela92/titanium_mobile,bright-sparks/titanium_mobile,pinnamur/titanium_mobile,pinnamur/titanium_mobile,mvitr/titanium_mobile,KoketsoMabuela92/titanium_mobile,KangaCoders/titanium_mobile,pec1985/titanium_mobile,csg-coder/titanium_mobile,KoketsoMabuela92/titanium_mobile,taoger/titanium_mobile,indera/titanium_mobile | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.titanium;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Stack;
import java.util.concurrent.CopyOnWriteArrayList;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollFunction;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.KrollRuntime;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiMessenger;
import org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent;
import org.appcelerator.titanium.TiLifecycle.OnWindowFocusChangedEvent;
import org.appcelerator.titanium.TiLifecycle.interceptOnBackPressedEvent;
import org.appcelerator.titanium.analytics.TiAnalyticsEventFactory;
import org.appcelerator.titanium.proxy.ActionBarProxy;
import org.appcelerator.titanium.proxy.ActivityProxy;
import org.appcelerator.titanium.proxy.IntentProxy;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.proxy.TiWindowProxy;
import org.appcelerator.titanium.util.TiActivityResultHandler;
import org.appcelerator.titanium.util.TiActivitySupport;
import org.appcelerator.titanium.util.TiActivitySupportHelper;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiMenuSupport;
import org.appcelerator.titanium.util.TiPlatformHelper;
import org.appcelerator.titanium.util.TiUIHelper;
import org.appcelerator.titanium.util.TiWeakList;
import org.appcelerator.titanium.view.TiCompositeLayout;
import org.appcelerator.titanium.view.TiCompositeLayout.LayoutArrangement;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
/**
* The base class for all non tab Titanium activities. To learn more about Activities, see the
* <a href="http://developer.android.com/reference/android/app/Activity.html">Android Activity documentation</a>.
*/
public abstract class TiBaseActivity extends ActionBarActivity
implements TiActivitySupport/*, ITiWindowHandler*/
{
private static final String TAG = "TiBaseActivity";
private static OrientationChangedListener orientationChangedListener = null;
private boolean onDestroyFired = false;
private int originalOrientationMode = -1;
private boolean inForeground = false; // Indicates whether this activity is in foreground or not.
private TiWeakList<OnLifecycleEvent> lifecycleListeners = new TiWeakList<OnLifecycleEvent>();
private TiWeakList<OnWindowFocusChangedEvent> windowFocusChangedListeners = new TiWeakList<OnWindowFocusChangedEvent>();
private TiWeakList<interceptOnBackPressedEvent> interceptOnBackPressedListeners = new TiWeakList<interceptOnBackPressedEvent>();
protected View layout;
protected TiActivitySupportHelper supportHelper;
protected int supportHelperId = -1;
protected TiWindowProxy window;
protected TiViewProxy view;
protected ActivityProxy activityProxy;
protected TiWeakList<ConfigurationChangedListener> configChangedListeners = new TiWeakList<ConfigurationChangedListener>();
protected int orientationDegrees;
protected TiMenuSupport menuHelper;
protected Messenger messenger;
protected int msgActivityCreatedId = -1;
protected int msgId = -1;
protected static int previousOrientation = -1;
//Storing the activity's dialogs and their persistence
private CopyOnWriteArrayList<DialogWrapper> dialogs = new CopyOnWriteArrayList<DialogWrapper>();
private Stack<TiWindowProxy> windowStack = new Stack<TiWindowProxy>();
public TiWindowProxy lwWindow;
public boolean isResumed = false;
public class DialogWrapper {
boolean isPersistent;
AlertDialog dialog;
WeakReference<TiBaseActivity> dialogActivity;
public DialogWrapper(AlertDialog d, boolean persistent, WeakReference<TiBaseActivity> activity) {
isPersistent = persistent;
dialog = d;
dialogActivity = activity;
}
public TiBaseActivity getActivity()
{
if (dialogActivity == null) {
return null;
} else {
return dialogActivity.get();
}
}
public void setActivity(WeakReference<TiBaseActivity> da)
{
dialogActivity = da;
}
public AlertDialog getDialog() {
return dialog;
}
public void setDialog(AlertDialog d) {
dialog = d;
}
public void release()
{
dialog = null;
dialogActivity = null;
}
public boolean getPersistent()
{
return isPersistent;
}
public void setPersistent(boolean p)
{
isPersistent = p;
}
}
public void addWindowToStack(TiWindowProxy proxy)
{
if (windowStack.contains(proxy)) {
Log.e(TAG, "Window already exists in stack", Log.DEBUG_MODE);
return;
}
boolean isEmpty = windowStack.empty();
if (!isEmpty) {
windowStack.peek().onWindowFocusChange(false);
}
windowStack.add(proxy);
if (!isEmpty) {
proxy.onWindowFocusChange(true);
}
}
public void removeWindowFromStack(TiWindowProxy proxy)
{
proxy.onWindowFocusChange(false);
boolean isTopWindow = ( (!windowStack.isEmpty()) && (windowStack.peek() == proxy) ) ? true : false;
windowStack.remove(proxy);
//Fire focus only if activity is not paused and the removed window was topWindow
if (!windowStack.empty() && isResumed && isTopWindow) {
TiWindowProxy nextWindow = windowStack.peek();
nextWindow.onWindowFocusChange(true);
}
}
/**
* Returns the window at the top of the stack.
* @return the top window or null if the stack is empty.
*/
public TiWindowProxy topWindowOnStack()
{
return (windowStack.isEmpty()) ? null : windowStack.peek();
}
// could use a normal ConfigurationChangedListener but since only orientation changes are
// forwarded, create a separate interface in order to limit scope and maintain clarity
public static interface OrientationChangedListener
{
public void onOrientationChanged (int configOrientationMode);
}
public static void registerOrientationListener (OrientationChangedListener listener)
{
orientationChangedListener = listener;
}
public static void deregisterOrientationListener()
{
orientationChangedListener = null;
}
public static interface ConfigurationChangedListener
{
public void onConfigurationChanged(TiBaseActivity activity, Configuration newConfig);
}
/**
* @return the instance of TiApplication.
*/
public TiApplication getTiApp()
{
return (TiApplication) getApplication();
}
/**
* @return the window proxy associated with this activity.
*/
public TiWindowProxy getWindowProxy()
{
return this.window;
}
/**
* Sets the window proxy.
* @param proxy
*/
public void setWindowProxy(TiWindowProxy proxy)
{
this.window = proxy;
updateTitle();
}
/**
* Sets the proxy for our layout (used for post layout event)
*
* @param proxy
*/
public void setLayoutProxy(TiViewProxy proxy)
{
if (layout instanceof TiCompositeLayout) {
((TiCompositeLayout) layout).setProxy(proxy);
}
}
/**
* Sets the view proxy.
* @param proxy
*/
public void setViewProxy(TiViewProxy proxy)
{
this.view = proxy;
}
/**
* @return activity proxy associated with this activity.
*/
public ActivityProxy getActivityProxy()
{
return activityProxy;
}
public void addDialog(DialogWrapper d)
{
if (!dialogs.contains(d)) {
dialogs.add(d);
}
}
public void removeDialog(Dialog d)
{
for (int i = 0; i < dialogs.size(); i++) {
DialogWrapper p = dialogs.get(i);
if (p.getDialog().equals(d)) {
p.release();
dialogs.remove(i);
return;
}
}
}
public void setActivityProxy(ActivityProxy proxy)
{
this.activityProxy = proxy;
}
/**
* @return the activity's current layout.
*/
public View getLayout()
{
return layout;
}
public void setLayout(View layout)
{
this.layout = layout;
}
public void addConfigurationChangedListener(ConfigurationChangedListener listener)
{
configChangedListeners.add(new WeakReference<ConfigurationChangedListener>(listener));
}
public void removeConfigurationChangedListener(ConfigurationChangedListener listener)
{
configChangedListeners.remove(listener);
}
public void registerOrientationChangedListener (OrientationChangedListener listener)
{
orientationChangedListener = listener;
}
public void deregisterOrientationChangedListener()
{
orientationChangedListener = null;
}
protected boolean getIntentBoolean(String property, boolean defaultValue)
{
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(property)) {
return intent.getBooleanExtra(property, defaultValue);
}
}
return defaultValue;
}
protected int getIntentInt(String property, int defaultValue)
{
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(property)) {
return intent.getIntExtra(property, defaultValue);
}
}
return defaultValue;
}
protected String getIntentString(String property, String defaultValue)
{
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(property)) {
return intent.getStringExtra(property);
}
}
return defaultValue;
}
protected void updateTitle()
{
if (window == null) return;
if (window.hasProperty(TiC.PROPERTY_TITLE)) {
String oldTitle = (String) getTitle();
String newTitle = TiConvert.toString(window.getProperty(TiC.PROPERTY_TITLE));
if (oldTitle == null) {
oldTitle = "";
}
if (newTitle == null) {
newTitle = "";
}
if (!newTitle.equals(oldTitle)) {
final String fnewTitle = newTitle;
runOnUiThread(new Runnable(){
public void run() {
setTitle(fnewTitle);
}
});
}
}
}
// Subclasses can override to provide a custom layout
protected View createLayout()
{
LayoutArrangement arrangement = LayoutArrangement.DEFAULT;
String layoutFromIntent = getIntentString(TiC.INTENT_PROPERTY_LAYOUT, "");
if (layoutFromIntent.equals(TiC.LAYOUT_HORIZONTAL)) {
arrangement = LayoutArrangement.HORIZONTAL;
} else if (layoutFromIntent.equals(TiC.LAYOUT_VERTICAL)) {
arrangement = LayoutArrangement.VERTICAL;
}
// set to null for now, this will get set correctly in setWindowProxy()
return new TiCompositeLayout(this, arrangement, null);
}
protected void setFullscreen(boolean fullscreen)
{
if (fullscreen) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
protected void setNavBarHidden(boolean hidden)
{
if (!hidden) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// Do not enable these features on Honeycomb or later since it will break the action bar.
this.requestWindowFeature(Window.FEATURE_LEFT_ICON);
this.requestWindowFeature(Window.FEATURE_RIGHT_ICON);
}
this.requestWindowFeature(Window.FEATURE_PROGRESS);
this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
} else {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
// Subclasses can override to handle post-creation (but pre-message fire) logic
protected void windowCreated()
{
boolean fullscreen = getIntentBoolean(TiC.PROPERTY_FULLSCREEN, false);
boolean navBarHidden = getIntentBoolean(TiC.PROPERTY_NAV_BAR_HIDDEN, false);
boolean modal = getIntentBoolean(TiC.PROPERTY_MODAL, false);
int softInputMode = getIntentInt(TiC.PROPERTY_WINDOW_SOFT_INPUT_MODE, -1);
boolean hasSoftInputMode = softInputMode != -1;
setFullscreen(fullscreen);
setNavBarHidden(navBarHidden);
if (modal) {
if (Build.VERSION.SDK_INT < TiC.API_LEVEL_ICE_CREAM_SANDWICH) {
// This flag is deprecated in API 14. On ICS, the background is not blurred but straight black.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
}
}
if (hasSoftInputMode) {
Log.d(TAG, "windowSoftInputMode: " + softInputMode, Log.DEBUG_MODE);
getWindow().setSoftInputMode(softInputMode);
}
boolean useActivityWindow = getIntentBoolean(TiC.INTENT_PROPERTY_USE_ACTIVITY_WINDOW, false);
if (useActivityWindow) {
int windowId = getIntentInt(TiC.INTENT_PROPERTY_WINDOW_ID, -1);
TiActivityWindows.windowCreated(this, windowId);
}
}
@Override
/**
* When the activity is created, this method adds it to the activity stack and
* fires a javascript 'create' event.
* @param savedInstanceState Bundle of saved data.
*/
protected void onCreate(Bundle savedInstanceState)
{
Log.d(TAG, "Activity " + this + " onCreate", Log.DEBUG_MODE);
inForeground = true;
TiApplication tiApp = getTiApp();
if (tiApp.isRestartPending()) {
super.onCreate(savedInstanceState);
if (!isFinishing()) {
finish();
}
return;
}
// If all the activities has been killed and the runtime has been disposed, we cannot recover one
// specific activity because the info of the top-most view proxy has been lost (TiActivityWindows.dispose()).
// In this case, we have to restart the app.
if (TiBaseActivity.isUnsupportedReLaunch(this, savedInstanceState)) {
Log.w(TAG, "Runtime has been disposed. Finishing.");
super.onCreate(savedInstanceState);
tiApp.scheduleRestart(250);
finish();
return;
}
TiApplication.addToActivityStack(this);
// create the activity proxy here so that it is accessible from the activity in all cases
activityProxy = new ActivityProxy(this);
// Increment the reference count so we correctly clean up when all of our activities have been destroyed
KrollRuntime.incrementActivityRefCount();
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(TiC.INTENT_PROPERTY_MESSENGER)) {
messenger = (Messenger) intent.getParcelableExtra(TiC.INTENT_PROPERTY_MESSENGER);
msgActivityCreatedId = intent.getIntExtra(TiC.INTENT_PROPERTY_MSG_ACTIVITY_CREATED_ID, -1);
msgId = intent.getIntExtra(TiC.INTENT_PROPERTY_MSG_ID, -1);
}
if (intent.hasExtra(TiC.PROPERTY_WINDOW_PIXEL_FORMAT)) {
getWindow().setFormat(intent.getIntExtra(TiC.PROPERTY_WINDOW_PIXEL_FORMAT, PixelFormat.UNKNOWN));
}
}
// Doing this on every create in case the activity is externally created.
TiPlatformHelper.intializeDisplayMetrics(this);
if (layout == null) {
layout = createLayout();
}
if (intent != null && intent.hasExtra(TiC.PROPERTY_KEEP_SCREEN_ON)) {
layout.setKeepScreenOn(intent.getBooleanExtra(TiC.PROPERTY_KEEP_SCREEN_ON, layout.getKeepScreenOn()));
}
super.onCreate(savedInstanceState);
// we only want to set the current activity for good in the resume state but we need it right now.
// save off the existing current activity, set ourselves to be the new current activity temporarily
// so we don't run into problems when we give the proxy the event
Activity tempCurrentActivity = tiApp.getCurrentActivity();
tiApp.setCurrentActivity(this, this);
windowCreated();
if (activityProxy != null) {
activityProxy.fireEvent(TiC.EVENT_CREATE, null);
}
// set the current activity back to what it was originally
tiApp.setCurrentActivity(this, tempCurrentActivity);
setContentView(layout);
sendMessage(msgActivityCreatedId);
// for backwards compatibility
sendMessage(msgId);
// store off the original orientation for the activity set in the AndroidManifest.xml
// for later use
originalOrientationMode = getRequestedOrientation();
if (window != null) {
window.onWindowActivityCreated();
}
}
public int getOriginalOrientationMode()
{
return originalOrientationMode;
}
public boolean isInForeground()
{
return inForeground;
}
protected void sendMessage(final int msgId)
{
if (messenger == null || msgId == -1) {
return;
}
// fire an async message on this thread's queue
// so we don't block onCreate() from returning
TiMessenger.postOnMain(new Runnable() {
public void run()
{
handleSendMessage(msgId);
}
});
}
protected void handleSendMessage(int messageId)
{
try {
Message message = TiMessenger.getMainMessenger().getHandler().obtainMessage(messageId, this);
messenger.send(message);
} catch (RemoteException e) {
Log.e(TAG, "Unable to message creator. finishing.", e);
finish();
} catch (RuntimeException e) {
Log.e(TAG, "Unable to message creator. finishing.", e);
finish();
}
}
protected TiActivitySupportHelper getSupportHelper()
{
if (supportHelper == null) {
this.supportHelper = new TiActivitySupportHelper(this);
// Register the supportHelper so we can get it back when the activity is recovered from force-quitting.
supportHelperId = TiActivitySupportHelpers.addSupportHelper(supportHelper);
}
return supportHelper;
}
// Activity Support
public int getUniqueResultCode()
{
return getSupportHelper().getUniqueResultCode();
}
/**
* See TiActivitySupport.launchActivityForResult for more details.
*/
public void launchActivityForResult(Intent intent, int code, TiActivityResultHandler resultHandler)
{
getSupportHelper().launchActivityForResult(intent, code, resultHandler);
}
/**
* See TiActivitySupport.launchIntentSenderForResult for more details.
*/
public void launchIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options, TiActivityResultHandler resultHandler)
{
getSupportHelper().launchIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags, options, resultHandler);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
getSupportHelper().onActivityResult(requestCode, resultCode, data);
}
@Override
public void onBackPressed()
{
synchronized (interceptOnBackPressedListeners.synchronizedList()) {
for (interceptOnBackPressedEvent listener : interceptOnBackPressedListeners.nonNull()) {
try {
if (listener.interceptOnBackPressed()) {
return;
}
} catch (Throwable t) {
Log.e(TAG, "Error dispatching interceptOnBackPressed event: " + t.getMessage(), t);
}
}
}
TiWindowProxy topWindow = topWindowOnStack();
// Prevent default Android behavior for "back" press
// if the top window has a listener to handle the event.
if (topWindow != null && topWindow.hasListeners(TiC.EVENT_ANDROID_BACK)) {
topWindow.fireEvent(TiC.EVENT_ANDROID_BACK, null);
} else {
// If event is not handled by any listeners allow default behavior.
super.onBackPressed();
}
}
@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
boolean handled = false;
TiViewProxy window;
if (this.window != null) {
window = this.window;
} else {
window = this.view;
}
if (window == null) {
return super.dispatchKeyEvent(event);
}
switch(event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK : {
if (event.getAction() == KeyEvent.ACTION_UP) {
String backEvent = "android:back";
KrollProxy proxy = null;
//android:back could be fired from a tabGroup window (activityProxy)
//or hw window (window).This event is added specifically to the activity
//proxy of a tab group in window.js
if (activityProxy.hasListeners(backEvent)) {
proxy = activityProxy;
} else if (window.hasListeners(backEvent)) {
proxy = window;
}
if (proxy != null) {
proxy.fireEvent(backEvent, null);
handled = true;
}
}
break;
}
case KeyEvent.KEYCODE_CAMERA : {
if (window.hasListeners(TiC.EVENT_ANDROID_CAMERA)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_CAMERA, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:camera")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:camera", null);
}
handled = true;
}
break;
}
case KeyEvent.KEYCODE_FOCUS : {
if (window.hasListeners(TiC.EVENT_ANDROID_FOCUS)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_FOCUS, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:focus")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:focus", null);
}
handled = true;
}
break;
}
case KeyEvent.KEYCODE_SEARCH : {
if (window.hasListeners(TiC.EVENT_ANDROID_SEARCH)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_SEARCH, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:search")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:search", null);
}
handled = true;
}
break;
}
case KeyEvent.KEYCODE_VOLUME_UP : {
if (window.hasListeners(TiC.EVENT_ANDROID_VOLUP)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_VOLUP, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:volup")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:volup", null);
}
handled = true;
}
break;
}
case KeyEvent.KEYCODE_VOLUME_DOWN : {
if (window.hasListeners(TiC.EVENT_ANDROID_VOLDOWN)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_VOLDOWN, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:voldown")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:voldown", null);
}
handled = true;
}
break;
}
}
if (!handled) {
handled = super.dispatchKeyEvent(event);
}
return handled;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// If targetSdkVersion is set to 11+, Android will invoke this function
// to initialize the menu (since it's part of the action bar). Due
// to the fix for Android bug 2373, activityProxy won't be initialized b/c the
// activity is expected to restart, so we will ignore it.
if (activityProxy == null) {
return false;
}
if (menuHelper == null) {
menuHelper = new TiMenuSupport(activityProxy);
}
return menuHelper.onCreateOptionsMenu(super.onCreateOptionsMenu(menu), menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case android.R.id.home:
if (activityProxy != null) {
ActionBarProxy actionBarProxy = activityProxy.getActionBar();
if (actionBarProxy != null) {
KrollFunction onHomeIconItemSelected = (KrollFunction) actionBarProxy
.getProperty(TiC.PROPERTY_ON_HOME_ICON_ITEM_SELECTED);
KrollDict event = new KrollDict();
event.put(TiC.EVENT_PROPERTY_SOURCE, actionBarProxy);
if (onHomeIconItemSelected != null) {
onHomeIconItemSelected.call(activityProxy.getKrollObject(), new Object[] { event });
}
}
}
return true;
default:
return menuHelper.onOptionsItemSelected(item);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
return menuHelper.onPrepareOptionsMenu(super.onPrepareOptionsMenu(menu), menu);
}
public static void callOrientationChangedListener(Configuration newConfig)
{
if (orientationChangedListener != null && previousOrientation != newConfig.orientation) {
previousOrientation = newConfig.orientation;
orientationChangedListener.onOrientationChanged (newConfig.orientation);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
for (WeakReference<ConfigurationChangedListener> listener : configChangedListeners) {
if (listener.get() != null) {
listener.get().onConfigurationChanged(this, newConfig);
}
}
callOrientationChangedListener(newConfig);
}
@Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
Log.d(TAG, "Activity " + this + " onNewIntent", Log.DEBUG_MODE);
if (activityProxy != null) {
IntentProxy ip = new IntentProxy(intent);
KrollDict data = new KrollDict();
data.put(TiC.PROPERTY_INTENT, ip);
activityProxy.fireSyncEvent(TiC.EVENT_NEW_INTENT, data);
// TODO: Deprecate old event
activityProxy.fireSyncEvent("newIntent", data);
}
}
public void addOnLifecycleEventListener(OnLifecycleEvent listener)
{
lifecycleListeners.add(new WeakReference<OnLifecycleEvent>(listener));
}
public void addOnWindowFocusChangedEventListener(OnWindowFocusChangedEvent listener)
{
windowFocusChangedListeners.add(new WeakReference<OnWindowFocusChangedEvent>(listener));
}
public void addInterceptOnBackPressedEventListener(interceptOnBackPressedEvent listener)
{
interceptOnBackPressedListeners.add(new WeakReference<interceptOnBackPressedEvent>(listener));
}
public void removeOnLifecycleEventListener(OnLifecycleEvent listener)
{
// TODO stub
}
private void releaseDialogs(boolean finish)
{
//clean up dialogs when activity is pausing or finishing
for (Iterator<DialogWrapper> iter = dialogs.iterator(); iter.hasNext(); ) {
DialogWrapper p = iter.next();
Dialog dialog = p.getDialog();
boolean persistent = p.getPersistent();
//if the activity is pausing but not finishing, clean up dialogs only if
//they are non-persistent
if (finish || !persistent) {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
dialogs.remove(p);
}
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
synchronized (windowFocusChangedListeners.synchronizedList()) {
for (OnWindowFocusChangedEvent listener : windowFocusChangedListeners.nonNull()) {
try {
listener.onWindowFocusChanged(hasFocus);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching onWindowFocusChanged event: " + t.getMessage(), t);
}
}
}
super.onWindowFocusChanged(hasFocus);
}
@Override
/**
* When this activity pauses, this method sets the current activity to null, fires a javascript 'pause' event,
* and if the activity is finishing, remove all dialogs associated with it.
*/
protected void onPause()
{
inForeground = false;
super.onPause();
isResumed = false;
Log.d(TAG, "Activity " + this + " onPause", Log.DEBUG_MODE);
TiApplication tiApp = getTiApp();
if (tiApp.isRestartPending()) {
releaseDialogs(true);
if (!isFinishing()) {
finish();
}
return;
}
if (!windowStack.empty()) {
windowStack.peek().onWindowFocusChange(false);
}
TiApplication.updateActivityTransitionState(true);
tiApp.setCurrentActivity(this, null);
TiUIHelper.showSoftKeyboard(getWindow().getDecorView(), false);
if (this.isFinishing()) {
releaseDialogs(true);
} else {
//release non-persistent dialogs when activity hides
releaseDialogs(false);
}
if (activityProxy != null) {
activityProxy.fireEvent(TiC.EVENT_PAUSE, null);
}
synchronized (lifecycleListeners.synchronizedList()) {
for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
try {
TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_PAUSE);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
}
}
}
// Checkpoint for ti.end event
if (tiApp != null) {
tiApp.postAnalyticsEvent(TiAnalyticsEventFactory.createAppEndEvent());
}
}
@Override
/**
* When the activity resumes, this method updates the current activity to this and fires a javascript
* 'resume' event.
*/
protected void onResume()
{
inForeground = true;
super.onResume();
if (isFinishing()) {
return;
}
Log.d(TAG, "Activity " + this + " onResume", Log.DEBUG_MODE);
TiApplication tiApp = getTiApp();
if (tiApp.isRestartPending()) {
if (!isFinishing()) {
finish();
}
return;
}
if (!windowStack.empty()) {
windowStack.peek().onWindowFocusChange(true);
}
tiApp.setCurrentActivity(this, this);
TiApplication.updateActivityTransitionState(false);
if (activityProxy != null) {
activityProxy.fireEvent(TiC.EVENT_RESUME, null);
}
synchronized (lifecycleListeners.synchronizedList()) {
for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
try {
TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_RESUME);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
}
}
}
isResumed = true;
// Checkpoint for ti.start event
String deployType = tiApp.getAppProperties().getString("ti.deploytype", "unknown");
tiApp.postAnalyticsEvent(TiAnalyticsEventFactory.createAppStartEvent(tiApp, deployType));
}
@Override
/**
* When this activity starts, this method updates the current activity to this if necessary and
* fire javascript 'start' and 'focus' events. Focus events will only fire if
* the activity is not a tab activity.
*/
protected void onStart()
{
inForeground = true;
super.onStart();
if (isFinishing()) {
return;
}
// Newer versions of Android appear to turn this on by default.
// Turn if off until an activity indicator is shown.
setProgressBarIndeterminateVisibility(false);
Log.d(TAG, "Activity " + this + " onStart", Log.DEBUG_MODE);
TiApplication tiApp = getTiApp();
if (tiApp.isRestartPending()) {
if (!isFinishing()) {
finish();
}
return;
}
updateTitle();
if (activityProxy != null) {
// we only want to set the current activity for good in the resume state but we need it right now.
// save off the existing current activity, set ourselves to be the new current activity temporarily
// so we don't run into problems when we give the proxy the event
Activity tempCurrentActivity = tiApp.getCurrentActivity();
tiApp.setCurrentActivity(this, this);
activityProxy.fireEvent(TiC.EVENT_START, null);
// set the current activity back to what it was originally
tiApp.setCurrentActivity(this, tempCurrentActivity);
}
synchronized (lifecycleListeners.synchronizedList()) {
for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
try {
TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_START);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
}
}
}
// store current configuration orientation
// This fixed bug with double orientation chnage firing when activity starts in landscape
previousOrientation = getResources().getConfiguration().orientation;
}
@Override
/**
* When this activity stops, this method fires the javascript 'blur' and 'stop' events. Blur events will only fire
* if the activity is not a tab activity.
*/
protected void onStop()
{
inForeground = false;
super.onStop();
Log.d(TAG, "Activity " + this + " onStop", Log.DEBUG_MODE);
if (getTiApp().isRestartPending()) {
if (!isFinishing()) {
finish();
}
return;
}
if (activityProxy != null) {
activityProxy.fireEvent(TiC.EVENT_STOP, null);
}
synchronized (lifecycleListeners.synchronizedList()) {
for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
try {
TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_STOP);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
}
}
}
KrollRuntime.suggestGC();
}
@Override
/**
* When this activity restarts, this method updates the current activity to this and fires javascript 'restart'
* event.
*/
protected void onRestart()
{
inForeground = true;
super.onRestart();
Log.d(TAG, "Activity " + this + " onRestart", Log.DEBUG_MODE);
TiApplication tiApp = getTiApp();
if (tiApp.isRestartPending()) {
if (!isFinishing()) {
finish();
}
return;
}
if (activityProxy != null) {
// we only want to set the current activity for good in the resume state but we need it right now.
// save off the existing current activity, set ourselves to be the new current activity temporarily
// so we don't run into problems when we give the proxy the event
Activity tempCurrentActivity = tiApp.getCurrentActivity();
tiApp.setCurrentActivity(this, this);
activityProxy.fireEvent(TiC.EVENT_RESTART, null);
// set the current activity back to what it was originally
tiApp.setCurrentActivity(this, tempCurrentActivity);
}
}
@Override
/**
* When the activity is about to go into the background as a result of user choice, this method fires the
* javascript 'userleavehint' event.
*/
protected void onUserLeaveHint()
{
Log.d(TAG, "Activity " + this + " onUserLeaveHint", Log.DEBUG_MODE);
if (getTiApp().isRestartPending()) {
if (!isFinishing()) {
finish();
}
return;
}
if (activityProxy != null) {
activityProxy.fireEvent(TiC.EVENT_USER_LEAVE_HINT, null);
}
super.onUserLeaveHint();
}
@Override
/**
* When this activity is destroyed, this method removes it from the activity stack, performs
* clean up, and fires javascript 'destroy' event.
*/
protected void onDestroy()
{
Log.d(TAG, "Activity " + this + " onDestroy", Log.DEBUG_MODE);
inForeground = false;
TiApplication tiApp = getTiApp();
//Clean up dialogs when activity is destroyed.
releaseDialogs(true);
if (tiApp.isRestartPending()) {
super.onDestroy();
if (!isFinishing()) {
finish();
}
return;
}
synchronized (lifecycleListeners.synchronizedList()) {
for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
try {
TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_DESTROY);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
}
}
}
super.onDestroy();
boolean isFinishing = isFinishing();
// If the activity is finishing, remove the windowId and supportHelperId so the window and supportHelper can be released.
// If the activity is forced to destroy by Android OS, keep the windowId and supportHelperId so the activity can be recovered.
if (isFinishing) {
int windowId = getIntentInt(TiC.INTENT_PROPERTY_WINDOW_ID, -1);
TiActivityWindows.removeWindow(windowId);
TiActivitySupportHelpers.removeSupportHelper(supportHelperId);
}
fireOnDestroy();
if (layout instanceof TiCompositeLayout) {
Log.d(TAG, "Layout cleanup.", Log.DEBUG_MODE);
((TiCompositeLayout) layout).removeAllViews();
}
layout = null;
//LW windows
if (window == null && view != null) {
view.releaseViews();
view = null;
}
if (window != null) {
window.closeFromActivity(isFinishing);
window = null;
}
if (menuHelper != null) {
menuHelper.destroy();
menuHelper = null;
}
if (activityProxy != null) {
activityProxy.release();
activityProxy = null;
}
// Don't dispose the runtime if the activity is forced to destroy by Android,
// so we can recover the activity later.
KrollRuntime.decrementActivityRefCount(isFinishing);
KrollRuntime.suggestGC();
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
// If the activity is forced to destroy by Android, save the supportHelperId so
// we can get it back when the activity is recovered.
if (!isFinishing() && supportHelper != null) {
outState.putInt("supportHelperId", supportHelperId);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("supportHelperId")) {
supportHelperId = savedInstanceState.getInt("supportHelperId");
supportHelper = TiActivitySupportHelpers.retrieveSupportHelper(this, supportHelperId);
if (supportHelper == null) {
Log.e(TAG, "Unable to retrieve the activity support helper.");
}
}
}
// called in order to ensure that the onDestroy call is only acted upon once.
// should be called by any subclass
protected void fireOnDestroy()
{
if (!onDestroyFired) {
if (activityProxy != null) {
activityProxy.fireEvent(TiC.EVENT_DESTROY, null);
}
onDestroyFired = true;
}
}
protected boolean shouldFinishRootActivity()
{
return getIntentBoolean(TiC.INTENT_PROPERTY_FINISH_ROOT, false);
}
@Override
public void finish()
{
super.finish();
if (shouldFinishRootActivity()) {
TiApplication app = getTiApp();
if (app != null) {
TiRootActivity rootActivity = app.getRootActivity();
if (rootActivity != null && !(rootActivity.equals(this)) && !rootActivity.isFinishing()) {
rootActivity.finish();
} else if (rootActivity == null && !app.isRestartPending()) {
// When the root activity has been killed and garbage collected and the app is not scheduled to restart,
// we need to force finish the root activity while this activity has an intent to finish root.
// This happens when the "Don't keep activities" option is enabled and the user stays in some activity
// (eg. heavyweight window, tabgroup) other than the root activity for a while and then he wants to back
// out the app.
app.setForceFinishRootActivity(true);
}
}
}
}
// These activityOnXxxx are all used by TiLaunchActivity when
// the android bug 2373 is detected and the app is being re-started.
// By calling these from inside its on onXxxx handlers, TiLaunchActivity
// can avoid calling super.onXxxx (super being TiBaseActivity), which would
// result in a bunch of Titanium-specific code running when we don't need it
// since we are restarting the app as fast as possible. Calling these methods
// allows TiLaunchActivity to fulfill the requirement that the Android built-in
// Activity's onXxxx must be called. (Think of these as something like super.super.onXxxx
// from inside TiLaunchActivity.)
protected void activityOnPause()
{
super.onPause();
}
protected void activityOnRestart()
{
super.onRestart();
}
protected void activityOnResume()
{
super.onResume();
}
protected void activityOnStop()
{
super.onStop();
}
protected void activityOnStart()
{
super.onStart();
}
protected void activityOnDestroy()
{
super.onDestroy();
}
public void activityOnCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
/**
* Called by the onCreate methods of TiBaseActivity to determine if an unsupported application
* re-launch appears to be occurring.
* @param activity The Activity getting the onCreate
* @param savedInstanceState The argument passed to the onCreate. A non-null value is a "tell"
* that the system is re-starting a killed application.
*/
public static boolean isUnsupportedReLaunch(Activity activity, Bundle savedInstanceState)
{
// If all the activities has been killed and the runtime has been disposed, we have to relaunch
// the app.
if (KrollRuntime.getInstance().getRuntimeState() == KrollRuntime.State.DISPOSED &&
savedInstanceState != null && !(activity instanceof TiLaunchActivity)) {
return true;
}
return false;
}
}
| android/titanium/src/java/org/appcelerator/titanium/TiBaseActivity.java | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.titanium;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Stack;
import java.util.concurrent.CopyOnWriteArrayList;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollFunction;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.KrollRuntime;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiMessenger;
import org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent;
import org.appcelerator.titanium.TiLifecycle.OnWindowFocusChangedEvent;
import org.appcelerator.titanium.TiLifecycle.interceptOnBackPressedEvent;
import org.appcelerator.titanium.analytics.TiAnalyticsEventFactory;
import org.appcelerator.titanium.proxy.ActionBarProxy;
import org.appcelerator.titanium.proxy.ActivityProxy;
import org.appcelerator.titanium.proxy.IntentProxy;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.proxy.TiWindowProxy;
import org.appcelerator.titanium.util.TiActivityResultHandler;
import org.appcelerator.titanium.util.TiActivitySupport;
import org.appcelerator.titanium.util.TiActivitySupportHelper;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiMenuSupport;
import org.appcelerator.titanium.util.TiPlatformHelper;
import org.appcelerator.titanium.util.TiUIHelper;
import org.appcelerator.titanium.util.TiWeakList;
import org.appcelerator.titanium.view.TiCompositeLayout;
import org.appcelerator.titanium.view.TiCompositeLayout.LayoutArrangement;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
/**
* The base class for all non tab Titanium activities. To learn more about Activities, see the
* <a href="http://developer.android.com/reference/android/app/Activity.html">Android Activity documentation</a>.
*/
public abstract class TiBaseActivity extends ActionBarActivity
implements TiActivitySupport/*, ITiWindowHandler*/
{
private static final String TAG = "TiBaseActivity";
private static OrientationChangedListener orientationChangedListener = null;
private boolean onDestroyFired = false;
private int originalOrientationMode = -1;
private boolean inForeground = false; // Indicates whether this activity is in foreground or not.
private TiWeakList<OnLifecycleEvent> lifecycleListeners = new TiWeakList<OnLifecycleEvent>();
private TiWeakList<OnWindowFocusChangedEvent> windowFocusChangedListeners = new TiWeakList<OnWindowFocusChangedEvent>();
private TiWeakList<interceptOnBackPressedEvent> interceptOnBackPressedListeners = new TiWeakList<interceptOnBackPressedEvent>();
protected View layout;
protected TiActivitySupportHelper supportHelper;
protected int supportHelperId = -1;
protected TiWindowProxy window;
protected TiViewProxy view;
protected ActivityProxy activityProxy;
protected TiWeakList<ConfigurationChangedListener> configChangedListeners = new TiWeakList<ConfigurationChangedListener>();
protected int orientationDegrees;
protected TiMenuSupport menuHelper;
protected Messenger messenger;
protected int msgActivityCreatedId = -1;
protected int msgId = -1;
protected static int previousOrientation = -1;
//Storing the activity's dialogs and their persistence
private CopyOnWriteArrayList<DialogWrapper> dialogs = new CopyOnWriteArrayList<DialogWrapper>();
private Stack<TiWindowProxy> windowStack = new Stack<TiWindowProxy>();
public TiWindowProxy lwWindow;
public boolean isResumed = false;
public class DialogWrapper {
boolean isPersistent;
AlertDialog dialog;
WeakReference<TiBaseActivity> dialogActivity;
public DialogWrapper(AlertDialog d, boolean persistent, WeakReference<TiBaseActivity> activity) {
isPersistent = persistent;
dialog = d;
dialogActivity = activity;
}
public TiBaseActivity getActivity()
{
if (dialogActivity == null) {
return null;
} else {
return dialogActivity.get();
}
}
public void setActivity(WeakReference<TiBaseActivity> da)
{
dialogActivity = da;
}
public AlertDialog getDialog() {
return dialog;
}
public void setDialog(AlertDialog d) {
dialog = d;
}
public void release()
{
dialog = null;
dialogActivity = null;
}
public boolean getPersistent()
{
return isPersistent;
}
public void setPersistent(boolean p)
{
isPersistent = p;
}
}
public void addWindowToStack(TiWindowProxy proxy)
{
if (windowStack.contains(proxy)) {
Log.e(TAG, "Window already exists in stack", Log.DEBUG_MODE);
return;
}
boolean isEmpty = windowStack.empty();
if (!isEmpty) {
windowStack.peek().onWindowFocusChange(false);
}
windowStack.add(proxy);
if (!isEmpty) {
proxy.onWindowFocusChange(true);
}
}
public void removeWindowFromStack(TiWindowProxy proxy)
{
proxy.onWindowFocusChange(false);
boolean isTopWindow = ( (!windowStack.isEmpty()) && (windowStack.peek() == proxy) ) ? true : false;
windowStack.remove(proxy);
//Fire focus only if activity is not paused and the removed window was topWindow
if (!windowStack.empty() && isResumed && isTopWindow) {
TiWindowProxy nextWindow = windowStack.peek();
nextWindow.onWindowFocusChange(true);
}
}
/**
* Returns the window at the top of the stack.
* @return the top window or null if the stack is empty.
*/
public TiWindowProxy topWindowOnStack()
{
return (windowStack.isEmpty()) ? null : windowStack.peek();
}
// could use a normal ConfigurationChangedListener but since only orientation changes are
// forwarded, create a separate interface in order to limit scope and maintain clarity
public static interface OrientationChangedListener
{
public void onOrientationChanged (int configOrientationMode);
}
public static void registerOrientationListener (OrientationChangedListener listener)
{
orientationChangedListener = listener;
}
public static void deregisterOrientationListener()
{
orientationChangedListener = null;
}
public static interface ConfigurationChangedListener
{
public void onConfigurationChanged(TiBaseActivity activity, Configuration newConfig);
}
/**
* @return the instance of TiApplication.
*/
public TiApplication getTiApp()
{
return (TiApplication) getApplication();
}
/**
* @return the window proxy associated with this activity.
*/
public TiWindowProxy getWindowProxy()
{
return this.window;
}
/**
* Sets the window proxy.
* @param proxy
*/
public void setWindowProxy(TiWindowProxy proxy)
{
this.window = proxy;
updateTitle();
}
/**
* Sets the proxy for our layout (used for post layout event)
*
* @param proxy
*/
public void setLayoutProxy(TiViewProxy proxy)
{
if (layout instanceof TiCompositeLayout) {
((TiCompositeLayout) layout).setProxy(proxy);
}
}
/**
* Sets the view proxy.
* @param proxy
*/
public void setViewProxy(TiViewProxy proxy)
{
this.view = proxy;
}
/**
* @return activity proxy associated with this activity.
*/
public ActivityProxy getActivityProxy()
{
return activityProxy;
}
public void addDialog(DialogWrapper d)
{
if (!dialogs.contains(d)) {
dialogs.add(d);
}
}
public void removeDialog(Dialog d)
{
for (int i = 0; i < dialogs.size(); i++) {
DialogWrapper p = dialogs.get(i);
if (p.getDialog().equals(d)) {
p.release();
dialogs.remove(i);
return;
}
}
}
public void setActivityProxy(ActivityProxy proxy)
{
this.activityProxy = proxy;
}
/**
* @return the activity's current layout.
*/
public View getLayout()
{
return layout;
}
public void setLayout(View layout)
{
this.layout = layout;
}
public void addConfigurationChangedListener(ConfigurationChangedListener listener)
{
configChangedListeners.add(new WeakReference<ConfigurationChangedListener>(listener));
}
public void removeConfigurationChangedListener(ConfigurationChangedListener listener)
{
configChangedListeners.remove(listener);
}
public void registerOrientationChangedListener (OrientationChangedListener listener)
{
orientationChangedListener = listener;
}
public void deregisterOrientationChangedListener()
{
orientationChangedListener = null;
}
protected boolean getIntentBoolean(String property, boolean defaultValue)
{
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(property)) {
return intent.getBooleanExtra(property, defaultValue);
}
}
return defaultValue;
}
protected int getIntentInt(String property, int defaultValue)
{
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(property)) {
return intent.getIntExtra(property, defaultValue);
}
}
return defaultValue;
}
protected String getIntentString(String property, String defaultValue)
{
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(property)) {
return intent.getStringExtra(property);
}
}
return defaultValue;
}
protected void updateTitle()
{
if (window == null) return;
if (window.hasProperty(TiC.PROPERTY_TITLE)) {
String oldTitle = (String) getTitle();
String newTitle = TiConvert.toString(window.getProperty(TiC.PROPERTY_TITLE));
if (oldTitle == null) {
oldTitle = "";
}
if (newTitle == null) {
newTitle = "";
}
if (!newTitle.equals(oldTitle)) {
final String fnewTitle = newTitle;
runOnUiThread(new Runnable(){
public void run() {
setTitle(fnewTitle);
}
});
}
}
}
// Subclasses can override to provide a custom layout
protected View createLayout()
{
LayoutArrangement arrangement = LayoutArrangement.DEFAULT;
String layoutFromIntent = getIntentString(TiC.INTENT_PROPERTY_LAYOUT, "");
if (layoutFromIntent.equals(TiC.LAYOUT_HORIZONTAL)) {
arrangement = LayoutArrangement.HORIZONTAL;
} else if (layoutFromIntent.equals(TiC.LAYOUT_VERTICAL)) {
arrangement = LayoutArrangement.VERTICAL;
}
// set to null for now, this will get set correctly in setWindowProxy()
return new TiCompositeLayout(this, arrangement, null);
}
protected void setFullscreen(boolean fullscreen)
{
if (fullscreen) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
protected void setNavBarHidden(boolean hidden)
{
if (!hidden) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// Do not enable these features on Honeycomb or later since it will break the action bar.
this.requestWindowFeature(Window.FEATURE_LEFT_ICON);
this.requestWindowFeature(Window.FEATURE_RIGHT_ICON);
}
this.requestWindowFeature(Window.FEATURE_PROGRESS);
this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
} else {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
// Subclasses can override to handle post-creation (but pre-message fire) logic
protected void windowCreated()
{
boolean fullscreen = getIntentBoolean(TiC.PROPERTY_FULLSCREEN, false);
boolean navBarHidden = getIntentBoolean(TiC.PROPERTY_NAV_BAR_HIDDEN, false);
boolean modal = getIntentBoolean(TiC.PROPERTY_MODAL, false);
int softInputMode = getIntentInt(TiC.PROPERTY_WINDOW_SOFT_INPUT_MODE, -1);
boolean hasSoftInputMode = softInputMode != -1;
setFullscreen(fullscreen);
setNavBarHidden(navBarHidden);
if (modal) {
if (Build.VERSION.SDK_INT < TiC.API_LEVEL_ICE_CREAM_SANDWICH) {
// This flag is deprecated in API 14. On ICS, the background is not blurred but straight black.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
}
}
if (hasSoftInputMode) {
Log.d(TAG, "windowSoftInputMode: " + softInputMode, Log.DEBUG_MODE);
getWindow().setSoftInputMode(softInputMode);
}
boolean useActivityWindow = getIntentBoolean(TiC.INTENT_PROPERTY_USE_ACTIVITY_WINDOW, false);
if (useActivityWindow) {
int windowId = getIntentInt(TiC.INTENT_PROPERTY_WINDOW_ID, -1);
TiActivityWindows.windowCreated(this, windowId);
}
}
@Override
/**
* When the activity is created, this method adds it to the activity stack and
* fires a javascript 'create' event.
* @param savedInstanceState Bundle of saved data.
*/
protected void onCreate(Bundle savedInstanceState)
{
Log.d(TAG, "Activity " + this + " onCreate", Log.DEBUG_MODE);
inForeground = true;
TiApplication tiApp = getTiApp();
if (tiApp.isRestartPending()) {
super.onCreate(savedInstanceState);
if (!isFinishing()) {
finish();
}
return;
}
// If all the activities has been killed and the runtime has been disposed, we cannot recover one
// specific activity because the info of the top-most view proxy has been lost (TiActivityWindows.dispose()).
// In this case, we have to restart the app.
if (TiBaseActivity.isUnsupportedReLaunch(this, savedInstanceState)) {
Log.w(TAG, "Runtime has been disposed. Finishing.");
super.onCreate(savedInstanceState);
tiApp.scheduleRestart(250);
finish();
return;
}
TiApplication.addToActivityStack(this);
// create the activity proxy here so that it is accessible from the activity in all cases
activityProxy = new ActivityProxy(this);
// Increment the reference count so we correctly clean up when all of our activities have been destroyed
KrollRuntime.incrementActivityRefCount();
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(TiC.INTENT_PROPERTY_MESSENGER)) {
messenger = (Messenger) intent.getParcelableExtra(TiC.INTENT_PROPERTY_MESSENGER);
msgActivityCreatedId = intent.getIntExtra(TiC.INTENT_PROPERTY_MSG_ACTIVITY_CREATED_ID, -1);
msgId = intent.getIntExtra(TiC.INTENT_PROPERTY_MSG_ID, -1);
}
if (intent.hasExtra(TiC.PROPERTY_WINDOW_PIXEL_FORMAT)) {
getWindow().setFormat(intent.getIntExtra(TiC.PROPERTY_WINDOW_PIXEL_FORMAT, PixelFormat.UNKNOWN));
}
}
// Doing this on every create in case the activity is externally created.
TiPlatformHelper.intializeDisplayMetrics(this);
if (layout == null) {
layout = createLayout();
}
if (intent != null && intent.hasExtra(TiC.PROPERTY_KEEP_SCREEN_ON)) {
layout.setKeepScreenOn(intent.getBooleanExtra(TiC.PROPERTY_KEEP_SCREEN_ON, layout.getKeepScreenOn()));
}
super.onCreate(savedInstanceState);
// we only want to set the current activity for good in the resume state but we need it right now.
// save off the existing current activity, set ourselves to be the new current activity temporarily
// so we don't run into problems when we give the proxy the event
Activity tempCurrentActivity = tiApp.getCurrentActivity();
tiApp.setCurrentActivity(this, this);
windowCreated();
if (activityProxy != null) {
// Fire the sync event with a timeout, so the main thread won't be blocked too long to get an ANR. (TIMOB-13253)
activityProxy.fireSyncEvent(TiC.EVENT_CREATE, null, 4000);
}
// set the current activity back to what it was originally
tiApp.setCurrentActivity(this, tempCurrentActivity);
setContentView(layout);
sendMessage(msgActivityCreatedId);
// for backwards compatibility
sendMessage(msgId);
// store off the original orientation for the activity set in the AndroidManifest.xml
// for later use
originalOrientationMode = getRequestedOrientation();
if (window != null) {
window.onWindowActivityCreated();
}
}
public int getOriginalOrientationMode()
{
return originalOrientationMode;
}
public boolean isInForeground()
{
return inForeground;
}
protected void sendMessage(final int msgId)
{
if (messenger == null || msgId == -1) {
return;
}
// fire an async message on this thread's queue
// so we don't block onCreate() from returning
TiMessenger.postOnMain(new Runnable() {
public void run()
{
handleSendMessage(msgId);
}
});
}
protected void handleSendMessage(int messageId)
{
try {
Message message = TiMessenger.getMainMessenger().getHandler().obtainMessage(messageId, this);
messenger.send(message);
} catch (RemoteException e) {
Log.e(TAG, "Unable to message creator. finishing.", e);
finish();
} catch (RuntimeException e) {
Log.e(TAG, "Unable to message creator. finishing.", e);
finish();
}
}
protected TiActivitySupportHelper getSupportHelper()
{
if (supportHelper == null) {
this.supportHelper = new TiActivitySupportHelper(this);
// Register the supportHelper so we can get it back when the activity is recovered from force-quitting.
supportHelperId = TiActivitySupportHelpers.addSupportHelper(supportHelper);
}
return supportHelper;
}
// Activity Support
public int getUniqueResultCode()
{
return getSupportHelper().getUniqueResultCode();
}
/**
* See TiActivitySupport.launchActivityForResult for more details.
*/
public void launchActivityForResult(Intent intent, int code, TiActivityResultHandler resultHandler)
{
getSupportHelper().launchActivityForResult(intent, code, resultHandler);
}
/**
* See TiActivitySupport.launchIntentSenderForResult for more details.
*/
public void launchIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options, TiActivityResultHandler resultHandler)
{
getSupportHelper().launchIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags, options, resultHandler);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
getSupportHelper().onActivityResult(requestCode, resultCode, data);
}
@Override
public void onBackPressed()
{
synchronized (interceptOnBackPressedListeners.synchronizedList()) {
for (interceptOnBackPressedEvent listener : interceptOnBackPressedListeners.nonNull()) {
try {
if (listener.interceptOnBackPressed()) {
return;
}
} catch (Throwable t) {
Log.e(TAG, "Error dispatching interceptOnBackPressed event: " + t.getMessage(), t);
}
}
}
TiWindowProxy topWindow = topWindowOnStack();
// Prevent default Android behavior for "back" press
// if the top window has a listener to handle the event.
if (topWindow != null && topWindow.hasListeners(TiC.EVENT_ANDROID_BACK)) {
topWindow.fireEvent(TiC.EVENT_ANDROID_BACK, null);
} else {
// If event is not handled by any listeners allow default behavior.
super.onBackPressed();
}
}
@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
boolean handled = false;
TiViewProxy window;
if (this.window != null) {
window = this.window;
} else {
window = this.view;
}
if (window == null) {
return super.dispatchKeyEvent(event);
}
switch(event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK : {
if (event.getAction() == KeyEvent.ACTION_UP) {
String backEvent = "android:back";
KrollProxy proxy = null;
//android:back could be fired from a tabGroup window (activityProxy)
//or hw window (window).This event is added specifically to the activity
//proxy of a tab group in window.js
if (activityProxy.hasListeners(backEvent)) {
proxy = activityProxy;
} else if (window.hasListeners(backEvent)) {
proxy = window;
}
if (proxy != null) {
proxy.fireEvent(backEvent, null);
handled = true;
}
}
break;
}
case KeyEvent.KEYCODE_CAMERA : {
if (window.hasListeners(TiC.EVENT_ANDROID_CAMERA)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_CAMERA, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:camera")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:camera", null);
}
handled = true;
}
break;
}
case KeyEvent.KEYCODE_FOCUS : {
if (window.hasListeners(TiC.EVENT_ANDROID_FOCUS)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_FOCUS, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:focus")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:focus", null);
}
handled = true;
}
break;
}
case KeyEvent.KEYCODE_SEARCH : {
if (window.hasListeners(TiC.EVENT_ANDROID_SEARCH)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_SEARCH, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:search")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:search", null);
}
handled = true;
}
break;
}
case KeyEvent.KEYCODE_VOLUME_UP : {
if (window.hasListeners(TiC.EVENT_ANDROID_VOLUP)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_VOLUP, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:volup")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:volup", null);
}
handled = true;
}
break;
}
case KeyEvent.KEYCODE_VOLUME_DOWN : {
if (window.hasListeners(TiC.EVENT_ANDROID_VOLDOWN)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent(TiC.EVENT_ANDROID_VOLDOWN, null);
}
handled = true;
}
// TODO: Deprecate old event
if (window.hasListeners("android:voldown")) {
if (event.getAction() == KeyEvent.ACTION_UP) {
window.fireEvent("android:voldown", null);
}
handled = true;
}
break;
}
}
if (!handled) {
handled = super.dispatchKeyEvent(event);
}
return handled;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// If targetSdkVersion is set to 11+, Android will invoke this function
// to initialize the menu (since it's part of the action bar). Due
// to the fix for Android bug 2373, activityProxy won't be initialized b/c the
// activity is expected to restart, so we will ignore it.
if (activityProxy == null) {
return false;
}
if (menuHelper == null) {
menuHelper = new TiMenuSupport(activityProxy);
}
return menuHelper.onCreateOptionsMenu(super.onCreateOptionsMenu(menu), menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case android.R.id.home:
if (activityProxy != null) {
ActionBarProxy actionBarProxy = activityProxy.getActionBar();
if (actionBarProxy != null) {
KrollFunction onHomeIconItemSelected = (KrollFunction) actionBarProxy
.getProperty(TiC.PROPERTY_ON_HOME_ICON_ITEM_SELECTED);
KrollDict event = new KrollDict();
event.put(TiC.EVENT_PROPERTY_SOURCE, actionBarProxy);
if (onHomeIconItemSelected != null) {
onHomeIconItemSelected.call(activityProxy.getKrollObject(), new Object[] { event });
}
}
}
return true;
default:
return menuHelper.onOptionsItemSelected(item);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
return menuHelper.onPrepareOptionsMenu(super.onPrepareOptionsMenu(menu), menu);
}
public static void callOrientationChangedListener(Configuration newConfig)
{
if (orientationChangedListener != null && previousOrientation != newConfig.orientation) {
previousOrientation = newConfig.orientation;
orientationChangedListener.onOrientationChanged (newConfig.orientation);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
for (WeakReference<ConfigurationChangedListener> listener : configChangedListeners) {
if (listener.get() != null) {
listener.get().onConfigurationChanged(this, newConfig);
}
}
callOrientationChangedListener(newConfig);
}
@Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
Log.d(TAG, "Activity " + this + " onNewIntent", Log.DEBUG_MODE);
if (activityProxy != null) {
IntentProxy ip = new IntentProxy(intent);
KrollDict data = new KrollDict();
data.put(TiC.PROPERTY_INTENT, ip);
activityProxy.fireSyncEvent(TiC.EVENT_NEW_INTENT, data);
// TODO: Deprecate old event
activityProxy.fireSyncEvent("newIntent", data);
}
}
public void addOnLifecycleEventListener(OnLifecycleEvent listener)
{
lifecycleListeners.add(new WeakReference<OnLifecycleEvent>(listener));
}
public void addOnWindowFocusChangedEventListener(OnWindowFocusChangedEvent listener)
{
windowFocusChangedListeners.add(new WeakReference<OnWindowFocusChangedEvent>(listener));
}
public void addInterceptOnBackPressedEventListener(interceptOnBackPressedEvent listener)
{
interceptOnBackPressedListeners.add(new WeakReference<interceptOnBackPressedEvent>(listener));
}
public void removeOnLifecycleEventListener(OnLifecycleEvent listener)
{
// TODO stub
}
private void releaseDialogs(boolean finish)
{
//clean up dialogs when activity is pausing or finishing
for (Iterator<DialogWrapper> iter = dialogs.iterator(); iter.hasNext(); ) {
DialogWrapper p = iter.next();
Dialog dialog = p.getDialog();
boolean persistent = p.getPersistent();
//if the activity is pausing but not finishing, clean up dialogs only if
//they are non-persistent
if (finish || !persistent) {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
dialogs.remove(p);
}
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
synchronized (windowFocusChangedListeners.synchronizedList()) {
for (OnWindowFocusChangedEvent listener : windowFocusChangedListeners.nonNull()) {
try {
listener.onWindowFocusChanged(hasFocus);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching onWindowFocusChanged event: " + t.getMessage(), t);
}
}
}
super.onWindowFocusChanged(hasFocus);
}
@Override
/**
* When this activity pauses, this method sets the current activity to null, fires a javascript 'pause' event,
* and if the activity is finishing, remove all dialogs associated with it.
*/
protected void onPause()
{
inForeground = false;
super.onPause();
isResumed = false;
Log.d(TAG, "Activity " + this + " onPause", Log.DEBUG_MODE);
TiApplication tiApp = getTiApp();
if (tiApp.isRestartPending()) {
releaseDialogs(true);
if (!isFinishing()) {
finish();
}
return;
}
if (!windowStack.empty()) {
windowStack.peek().onWindowFocusChange(false);
}
TiApplication.updateActivityTransitionState(true);
tiApp.setCurrentActivity(this, null);
TiUIHelper.showSoftKeyboard(getWindow().getDecorView(), false);
if (this.isFinishing()) {
releaseDialogs(true);
} else {
//release non-persistent dialogs when activity hides
releaseDialogs(false);
}
if (activityProxy != null) {
activityProxy.fireSyncEvent(TiC.EVENT_PAUSE, null);
}
synchronized (lifecycleListeners.synchronizedList()) {
for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
try {
TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_PAUSE);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
}
}
}
// Checkpoint for ti.end event
if (tiApp != null) {
tiApp.postAnalyticsEvent(TiAnalyticsEventFactory.createAppEndEvent());
}
}
@Override
/**
* When the activity resumes, this method updates the current activity to this and fires a javascript
* 'resume' event.
*/
protected void onResume()
{
inForeground = true;
super.onResume();
if (isFinishing()) {
return;
}
Log.d(TAG, "Activity " + this + " onResume", Log.DEBUG_MODE);
TiApplication tiApp = getTiApp();
if (tiApp.isRestartPending()) {
if (!isFinishing()) {
finish();
}
return;
}
if (!windowStack.empty()) {
windowStack.peek().onWindowFocusChange(true);
}
tiApp.setCurrentActivity(this, this);
TiApplication.updateActivityTransitionState(false);
if (activityProxy != null) {
// Fire the sync event with a timeout, so the main thread won't be blocked too long to get an ANR. (TIMOB-13253)
activityProxy.fireSyncEvent(TiC.EVENT_RESUME, null, 4000);
}
synchronized (lifecycleListeners.synchronizedList()) {
for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
try {
TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_RESUME);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
}
}
}
isResumed = true;
// Checkpoint for ti.start event
String deployType = tiApp.getAppProperties().getString("ti.deploytype", "unknown");
tiApp.postAnalyticsEvent(TiAnalyticsEventFactory.createAppStartEvent(tiApp, deployType));
}
@Override
/**
* When this activity starts, this method updates the current activity to this if necessary and
* fire javascript 'start' and 'focus' events. Focus events will only fire if
* the activity is not a tab activity.
*/
protected void onStart()
{
inForeground = true;
super.onStart();
if (isFinishing()) {
return;
}
// Newer versions of Android appear to turn this on by default.
// Turn if off until an activity indicator is shown.
setProgressBarIndeterminateVisibility(false);
Log.d(TAG, "Activity " + this + " onStart", Log.DEBUG_MODE);
TiApplication tiApp = getTiApp();
if (tiApp.isRestartPending()) {
if (!isFinishing()) {
finish();
}
return;
}
updateTitle();
if (activityProxy != null) {
// we only want to set the current activity for good in the resume state but we need it right now.
// save off the existing current activity, set ourselves to be the new current activity temporarily
// so we don't run into problems when we give the proxy the event
Activity tempCurrentActivity = tiApp.getCurrentActivity();
tiApp.setCurrentActivity(this, this);
// Fire the sync event with a timeout, so the main thread won't be blocked too long to get an ANR. (TIMOB-13253)
activityProxy.fireSyncEvent(TiC.EVENT_START, null, 4000);
// set the current activity back to what it was originally
tiApp.setCurrentActivity(this, tempCurrentActivity);
}
synchronized (lifecycleListeners.synchronizedList()) {
for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
try {
TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_START);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
}
}
}
// store current configuration orientation
// This fixed bug with double orientation chnage firing when activity starts in landscape
previousOrientation = getResources().getConfiguration().orientation;
}
@Override
/**
* When this activity stops, this method fires the javascript 'blur' and 'stop' events. Blur events will only fire
* if the activity is not a tab activity.
*/
protected void onStop()
{
inForeground = false;
super.onStop();
Log.d(TAG, "Activity " + this + " onStop", Log.DEBUG_MODE);
if (getTiApp().isRestartPending()) {
if (!isFinishing()) {
finish();
}
return;
}
if (activityProxy != null) {
activityProxy.fireSyncEvent(TiC.EVENT_STOP, null);
}
synchronized (lifecycleListeners.synchronizedList()) {
for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
try {
TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_STOP);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
}
}
}
KrollRuntime.suggestGC();
}
@Override
/**
* When this activity restarts, this method updates the current activity to this and fires javascript 'restart'
* event.
*/
protected void onRestart()
{
inForeground = true;
super.onRestart();
Log.d(TAG, "Activity " + this + " onRestart", Log.DEBUG_MODE);
TiApplication tiApp = getTiApp();
if (tiApp.isRestartPending()) {
if (!isFinishing()) {
finish();
}
return;
}
if (activityProxy != null) {
// we only want to set the current activity for good in the resume state but we need it right now.
// save off the existing current activity, set ourselves to be the new current activity temporarily
// so we don't run into problems when we give the proxy the event
Activity tempCurrentActivity = tiApp.getCurrentActivity();
tiApp.setCurrentActivity(this, this);
activityProxy.fireSyncEvent(TiC.EVENT_RESTART, null);
// set the current activity back to what it was originally
tiApp.setCurrentActivity(this, tempCurrentActivity);
}
}
@Override
/**
* When the activity is about to go into the background as a result of user choice, this method fires the
* javascript 'userleavehint' event.
*/
protected void onUserLeaveHint()
{
Log.d(TAG, "Activity " + this + " onUserLeaveHint", Log.DEBUG_MODE);
if (getTiApp().isRestartPending()) {
if (!isFinishing()) {
finish();
}
return;
}
if (activityProxy != null) {
activityProxy.fireSyncEvent(TiC.EVENT_USER_LEAVE_HINT, null);
}
super.onUserLeaveHint();
}
@Override
/**
* When this activity is destroyed, this method removes it from the activity stack, performs
* clean up, and fires javascript 'destroy' event.
*/
protected void onDestroy()
{
Log.d(TAG, "Activity " + this + " onDestroy", Log.DEBUG_MODE);
inForeground = false;
TiApplication tiApp = getTiApp();
//Clean up dialogs when activity is destroyed.
releaseDialogs(true);
if (tiApp.isRestartPending()) {
super.onDestroy();
if (!isFinishing()) {
finish();
}
return;
}
synchronized (lifecycleListeners.synchronizedList()) {
for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
try {
TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_DESTROY);
} catch (Throwable t) {
Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
}
}
}
super.onDestroy();
boolean isFinishing = isFinishing();
// If the activity is finishing, remove the windowId and supportHelperId so the window and supportHelper can be released.
// If the activity is forced to destroy by Android OS, keep the windowId and supportHelperId so the activity can be recovered.
if (isFinishing) {
int windowId = getIntentInt(TiC.INTENT_PROPERTY_WINDOW_ID, -1);
TiActivityWindows.removeWindow(windowId);
TiActivitySupportHelpers.removeSupportHelper(supportHelperId);
}
fireOnDestroy();
if (layout instanceof TiCompositeLayout) {
Log.d(TAG, "Layout cleanup.", Log.DEBUG_MODE);
((TiCompositeLayout) layout).removeAllViews();
}
layout = null;
//LW windows
if (window == null && view != null) {
view.releaseViews();
view = null;
}
if (window != null) {
window.closeFromActivity(isFinishing);
window = null;
}
if (menuHelper != null) {
menuHelper.destroy();
menuHelper = null;
}
if (activityProxy != null) {
activityProxy.release();
activityProxy = null;
}
// Don't dispose the runtime if the activity is forced to destroy by Android,
// so we can recover the activity later.
KrollRuntime.decrementActivityRefCount(isFinishing);
KrollRuntime.suggestGC();
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
// If the activity is forced to destroy by Android, save the supportHelperId so
// we can get it back when the activity is recovered.
if (!isFinishing() && supportHelper != null) {
outState.putInt("supportHelperId", supportHelperId);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("supportHelperId")) {
supportHelperId = savedInstanceState.getInt("supportHelperId");
supportHelper = TiActivitySupportHelpers.retrieveSupportHelper(this, supportHelperId);
if (supportHelper == null) {
Log.e(TAG, "Unable to retrieve the activity support helper.");
}
}
}
// called in order to ensure that the onDestroy call is only acted upon once.
// should be called by any subclass
protected void fireOnDestroy()
{
if (!onDestroyFired) {
if (activityProxy != null) {
activityProxy.fireSyncEvent(TiC.EVENT_DESTROY, null);
}
onDestroyFired = true;
}
}
protected boolean shouldFinishRootActivity()
{
return getIntentBoolean(TiC.INTENT_PROPERTY_FINISH_ROOT, false);
}
@Override
public void finish()
{
super.finish();
if (shouldFinishRootActivity()) {
TiApplication app = getTiApp();
if (app != null) {
TiRootActivity rootActivity = app.getRootActivity();
if (rootActivity != null && !(rootActivity.equals(this)) && !rootActivity.isFinishing()) {
rootActivity.finish();
} else if (rootActivity == null && !app.isRestartPending()) {
// When the root activity has been killed and garbage collected and the app is not scheduled to restart,
// we need to force finish the root activity while this activity has an intent to finish root.
// This happens when the "Don't keep activities" option is enabled and the user stays in some activity
// (eg. heavyweight window, tabgroup) other than the root activity for a while and then he wants to back
// out the app.
app.setForceFinishRootActivity(true);
}
}
}
}
// These activityOnXxxx are all used by TiLaunchActivity when
// the android bug 2373 is detected and the app is being re-started.
// By calling these from inside its on onXxxx handlers, TiLaunchActivity
// can avoid calling super.onXxxx (super being TiBaseActivity), which would
// result in a bunch of Titanium-specific code running when we don't need it
// since we are restarting the app as fast as possible. Calling these methods
// allows TiLaunchActivity to fulfill the requirement that the Android built-in
// Activity's onXxxx must be called. (Think of these as something like super.super.onXxxx
// from inside TiLaunchActivity.)
protected void activityOnPause()
{
super.onPause();
}
protected void activityOnRestart()
{
super.onRestart();
}
protected void activityOnResume()
{
super.onResume();
}
protected void activityOnStop()
{
super.onStop();
}
protected void activityOnStart()
{
super.onStart();
}
protected void activityOnDestroy()
{
super.onDestroy();
}
public void activityOnCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
/**
* Called by the onCreate methods of TiBaseActivity to determine if an unsupported application
* re-launch appears to be occurring.
* @param activity The Activity getting the onCreate
* @param savedInstanceState The argument passed to the onCreate. A non-null value is a "tell"
* that the system is re-starting a killed application.
*/
public static boolean isUnsupportedReLaunch(Activity activity, Bundle savedInstanceState)
{
// If all the activities has been killed and the runtime has been disposed, we have to relaunch
// the app.
if (KrollRuntime.getInstance().getRuntimeState() == KrollRuntime.State.DISPOSED &&
savedInstanceState != null && !(activity instanceof TiLaunchActivity)) {
return true;
}
return false;
}
}
| timob-16279: convert life cycle sync events to async
| android/titanium/src/java/org/appcelerator/titanium/TiBaseActivity.java | timob-16279: convert life cycle sync events to async | <ide><path>ndroid/titanium/src/java/org/appcelerator/titanium/TiBaseActivity.java
<ide> windowCreated();
<ide>
<ide> if (activityProxy != null) {
<del> // Fire the sync event with a timeout, so the main thread won't be blocked too long to get an ANR. (TIMOB-13253)
<del> activityProxy.fireSyncEvent(TiC.EVENT_CREATE, null, 4000);
<add> activityProxy.fireEvent(TiC.EVENT_CREATE, null);
<ide> }
<ide>
<ide> // set the current activity back to what it was originally
<ide> }
<ide>
<ide> if (activityProxy != null) {
<del> activityProxy.fireSyncEvent(TiC.EVENT_PAUSE, null);
<add> activityProxy.fireEvent(TiC.EVENT_PAUSE, null);
<ide> }
<ide>
<ide> synchronized (lifecycleListeners.synchronizedList()) {
<ide> TiApplication.updateActivityTransitionState(false);
<ide>
<ide> if (activityProxy != null) {
<del> // Fire the sync event with a timeout, so the main thread won't be blocked too long to get an ANR. (TIMOB-13253)
<del> activityProxy.fireSyncEvent(TiC.EVENT_RESUME, null, 4000);
<add> activityProxy.fireEvent(TiC.EVENT_RESUME, null);
<ide> }
<ide>
<ide> synchronized (lifecycleListeners.synchronizedList()) {
<ide> Activity tempCurrentActivity = tiApp.getCurrentActivity();
<ide> tiApp.setCurrentActivity(this, this);
<ide>
<del> // Fire the sync event with a timeout, so the main thread won't be blocked too long to get an ANR. (TIMOB-13253)
<del> activityProxy.fireSyncEvent(TiC.EVENT_START, null, 4000);
<add> activityProxy.fireEvent(TiC.EVENT_START, null);
<ide>
<ide> // set the current activity back to what it was originally
<ide> tiApp.setCurrentActivity(this, tempCurrentActivity);
<ide> }
<ide>
<ide> if (activityProxy != null) {
<del> activityProxy.fireSyncEvent(TiC.EVENT_STOP, null);
<add> activityProxy.fireEvent(TiC.EVENT_STOP, null);
<ide> }
<ide>
<ide> synchronized (lifecycleListeners.synchronizedList()) {
<ide> Activity tempCurrentActivity = tiApp.getCurrentActivity();
<ide> tiApp.setCurrentActivity(this, this);
<ide>
<del> activityProxy.fireSyncEvent(TiC.EVENT_RESTART, null);
<add> activityProxy.fireEvent(TiC.EVENT_RESTART, null);
<ide>
<ide> // set the current activity back to what it was originally
<ide> tiApp.setCurrentActivity(this, tempCurrentActivity);
<ide> }
<ide>
<ide> if (activityProxy != null) {
<del> activityProxy.fireSyncEvent(TiC.EVENT_USER_LEAVE_HINT, null);
<add> activityProxy.fireEvent(TiC.EVENT_USER_LEAVE_HINT, null);
<ide> }
<ide>
<ide> super.onUserLeaveHint();
<ide> {
<ide> if (!onDestroyFired) {
<ide> if (activityProxy != null) {
<del> activityProxy.fireSyncEvent(TiC.EVENT_DESTROY, null);
<add> activityProxy.fireEvent(TiC.EVENT_DESTROY, null);
<ide> }
<ide> onDestroyFired = true;
<ide> } |
|
Java | bsd-3-clause | c4649988d6dc2c666e04121d1801f01d0a1c146a | 0 | magicDGS/gatk,ksthesis/gatk,frank-y-liu/gatk,magicDGS/gatk,magicDGS/gatk,broadinstitute/hellbender,frank-y-liu/gatk,ksthesis/gatk,frank-y-liu/gatk,ksthesis/gatk,magicDGS/gatk,ksthesis/gatk,magicDGS/gatk,broadinstitute/hellbender,frank-y-liu/gatk,frank-y-liu/gatk,broadinstitute/hellbender,ksthesis/gatk,broadinstitute/hellbender,broadinstitute/hellbender,magicDGS/gatk,frank-y-liu/gatk,broadinstitute/hellbender,ksthesis/gatk | package org.broadinstitute.hellbender.tools.walkers.mutect;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.variantcontext.VariantContextBuilder;
import htsjdk.variant.variantcontext.writer.VariantContextWriter;
import htsjdk.variant.vcf.VCFHeader;
import htsjdk.variant.vcf.VCFHeaderLine;
import org.broadinstitute.barclay.argparser.Argument;
import org.broadinstitute.barclay.argparser.ArgumentCollection;
import org.broadinstitute.barclay.argparser.BetaFeature;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.barclay.help.DocumentedFeature;
import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions;
import org.broadinstitute.hellbender.cmdline.programgroups.VariantProgramGroup;
import org.broadinstitute.hellbender.engine.*;
import org.broadinstitute.hellbender.utils.variant.GATKVCFConstants;
import org.broadinstitute.hellbender.utils.variant.GATKVCFHeaderLines;
import org.broadinstitute.hellbender.tools.exome.FilterByOrientationBias;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
/**
* Filter SNVs and indels from a Mutect2 callset.
*
* <p>
* FilterMutectCalls encapsulates GATK3 MuTect2's filtering functionality.
* GATK4 Mutect2 retains variant calling and some prefiltering.
* Separating calling and filtering functionalities into two tools better enables an iterative filtering process
* that allows for context-specific optimizations. To filter further based on sequence context artifacts,
* additionally use {@link FilterByOrientationBias}.
* </p>
*
* <p>
* Filtering thresholds for both normal_artifact_lod (default threshold 0.0) and tumor_lod (default threshold 5.3) can be set in this tool.
* If the normal artifact log odds is larger than the threshold, then FilterMutectCalls applies the artifact-in-normal filter.
* For matched normal analyses with tumor contamination in the normal, consider increasing the normal_artifact_lod threshold.
* If the tumor log odds is smaller than the threshold, then FilterMutectCalls filters the variant.
* </p>
*
* <p>
* If given a --contaminationTable file, e.g. results from
* {@link org.broadinstitute.hellbender.tools.walkers.contamination.CalculateContamination}, the tool will additionally
* filter on contamination fractions. Alternatively, provide a numerical fraction to filter with --contamination_fraction_to_filter.
* </p>
*
* <h3>Example</h3>
*
* <pre>
* gatk-launch --javaOptions "-Xmx4g" FilterMutectCalls \
* -V tumor_matched_m2_snvs_indels.vcf.gz \
* -contaminationTable contamination.table \
* -O tumor_matched_m2_filtered.vcf.gz
* </pre>
*
*/
@CommandLineProgramProperties(
summary = "Filter somatic SNVs and indels called by Mutect2",
oneLineSummary = "Filter somatic SNVs and indels called by Mutect2",
programGroup = VariantProgramGroup.class
)
@DocumentedFeature
@BetaFeature
public final class FilterMutectCalls extends VariantWalker {
@Argument(fullName= StandardArgumentDefinitions.OUTPUT_LONG_NAME,
shortName=StandardArgumentDefinitions.OUTPUT_SHORT_NAME,
doc="The output filtered VCF file", optional=false)
private final String outputVcf = null;
@ArgumentCollection
protected M2FiltersArgumentCollection MTFAC = new M2FiltersArgumentCollection();
private VariantContextWriter vcfWriter;
private Mutect2FilteringEngine filteringEngine;
@Override
public void onTraversalStart() {
final VCFHeader inputHeader = getHeaderForVariants();
final Set<VCFHeaderLine> headerLines = inputHeader.getMetaDataInSortedOrder().stream()
.filter(line -> !line.getKey().equals(Mutect2FilteringEngine.FILTERING_STATUS_VCF_KEY)) //remove header line from Mutect2 stating that calls are unfiltered.
.collect(Collectors.toSet());
headerLines.add(new VCFHeaderLine(Mutect2FilteringEngine.FILTERING_STATUS_VCF_KEY, "These calls have been filtered by " + FilterMutectCalls.class.getSimpleName() + " to label false positives with a list of failed filters and true positives with PASS."));
GATKVCFConstants.MUTECT_FILTER_NAMES.stream().map(GATKVCFHeaderLines::getFilterLine).forEach(headerLines::add);
headerLines.addAll(getDefaultToolVCFHeaderLines());
final VCFHeader vcfHeader = new VCFHeader(headerLines, inputHeader.getGenotypeSamples());
vcfWriter = createVCFWriter(new File(outputVcf));
vcfWriter.writeHeader(vcfHeader);
final String tumorSample = getHeaderForVariants().getMetaDataLine(Mutect2Engine.TUMOR_SAMPLE_KEY_IN_VCF_HEADER).getValue();
filteringEngine = new Mutect2FilteringEngine(MTFAC, tumorSample);
}
@Override
public Object onTraversalSuccess() {
return "SUCCESS";
}
@Override
public void apply(final VariantContext vc, final ReadsContext readsContext, final ReferenceContext refContext, final FeatureContext fc) {
final VariantContextBuilder vcb = new VariantContextBuilder(vc);
vcb.filters(filteringEngine.calculateFilters(MTFAC, vc));
vcfWriter.add(vcb.make());
}
@Override
public void closeTool() {
if ( vcfWriter != null ) {
vcfWriter.close();
}
}
}
| src/main/java/org/broadinstitute/hellbender/tools/walkers/mutect/FilterMutectCalls.java | package org.broadinstitute.hellbender.tools.walkers.mutect;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.variantcontext.VariantContextBuilder;
import htsjdk.variant.variantcontext.writer.VariantContextWriter;
import htsjdk.variant.vcf.VCFHeader;
import htsjdk.variant.vcf.VCFHeaderLine;
import org.broadinstitute.barclay.argparser.Argument;
import org.broadinstitute.barclay.argparser.ArgumentCollection;
import org.broadinstitute.barclay.argparser.BetaFeature;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.barclay.help.DocumentedFeature;
import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions;
import org.broadinstitute.hellbender.cmdline.programgroups.VariantProgramGroup;
import org.broadinstitute.hellbender.engine.*;
import org.broadinstitute.hellbender.utils.variant.GATKVCFConstants;
import org.broadinstitute.hellbender.utils.variant.GATKVCFHeaderLines;
import org.broadinstitute.hellbender.tools.exome.FilterByOrientationBias;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
/**
* Filter SNVs and indels from a Mutect2 callset.
*
* <p>
* FilterMutectCalls encapsulates GATK3 MuTect2's filtering functionality.
* GATK4 Mutect2 retains variant calling and some prefiltering.
* Separating calling and filtering functionalities into two tools better enables an iterative filtering process
* that allows for context-specific optimizations. To filter further based on sequence context artifacts,
* additionally use {@link FilterByOrientationBias}.
* </p>
*
* <p>
* Filtering thresholds for both normal_artifact_lod (default threshold 0.0) and tumor_lod (default threshold 5.3) can be set in this tool.
* If the normal artifact log odds is larger than the threshold, then FilterMutectCalls applies the artifact-in-normal filter.
* For matched normal analyses with tumor contamination in the normal, consider increasing the normal_artifact_lod threshold.
* If the tumor log odds is smaller than the threshold, then FilterMutectCalls filters the variant.
* </p>
*
* <p>
* If given a --contaminationTable file, e.g. results from
* {@link org.broadinstitute.hellbender.tools.walkers.contamination.CalculateContamination}, the tool will additionally
* filter on contamination fractions. Alternatively, provide a numerical fraction to filter with --contamination_fraction_to_filter.
* </p>
*
* <h3>Example</h3>
*
* <pre>
* gatk-launch --javaOptions "-Xmx4g" FilterMutectCalls \
* -V tumor_matched_m2_snvs_indels.vcf.gz \
* -contaminationTable contamination.table \
* -O tumor_matched_m2_filtered.vcf.gz
* </pre>
*
*/
@CommandLineProgramProperties(
summary = "Filter somatic SNVs and indels called by Mutect2",
oneLineSummary = "Filter somatic SNVs and indels called by Mutect2",
programGroup = VariantProgramGroup.class
)
@DocumentedFeature
@BetaFeature
public final class FilterMutectCalls extends VariantWalker {
@Argument(fullName= StandardArgumentDefinitions.OUTPUT_LONG_NAME,
shortName=StandardArgumentDefinitions.OUTPUT_SHORT_NAME,
doc="The output filtered VCF file", optional=false)
private final String outputVcf = null;
@ArgumentCollection
protected M2FiltersArgumentCollection MTFAC = new M2FiltersArgumentCollection();
private VariantContextWriter vcfWriter;
private final List<VariantContext> unfilteredCalls = new ArrayList<>();
@Override
public void onTraversalStart() {
final VCFHeader inputHeader = getHeaderForVariants();
final Set<VCFHeaderLine> headerLines = inputHeader.getMetaDataInSortedOrder().stream()
.filter(line -> !line.getKey().equals(Mutect2FilteringEngine.FILTERING_STATUS_VCF_KEY)) //remove header line from Mutect2 stating that calls are unfiltered.
.collect(Collectors.toSet());
headerLines.add(new VCFHeaderLine(Mutect2FilteringEngine.FILTERING_STATUS_VCF_KEY, "These calls have been filtered by " + FilterMutectCalls.class.getSimpleName() + " to label false positives with a list of failed filters and true positives with PASS."));
GATKVCFConstants.MUTECT_FILTER_NAMES.stream().map(GATKVCFHeaderLines::getFilterLine).forEach(headerLines::add);
headerLines.addAll(getDefaultToolVCFHeaderLines());
final VCFHeader vcfHeader = new VCFHeader(headerLines, inputHeader.getGenotypeSamples());
vcfWriter = createVCFWriter(new File(outputVcf));
vcfWriter.writeHeader(vcfHeader);
}
@Override
public Object onTraversalSuccess() {
final String tumorSample = getHeaderForVariants().getMetaDataLine(Mutect2Engine.TUMOR_SAMPLE_KEY_IN_VCF_HEADER).getValue();
final Mutect2FilteringEngine filteringEngine = new Mutect2FilteringEngine(MTFAC, tumorSample);
// TODO: implement sophisticated filtering
for (final VariantContext vc : unfilteredCalls) {
final VariantContextBuilder vcb = new VariantContextBuilder(vc);
vcb.filters(filteringEngine.calculateFilters(MTFAC, vc));
vcfWriter.add(vcb.make());
}
return "SUCCESS";
}
@Override
public void apply(final VariantContext vc, final ReadsContext readsContext, final ReferenceContext refContext, final FeatureContext fc) {
unfilteredCalls.add(vc);
}
@Override
public void closeTool() {
if ( vcfWriter != null ) {
vcfWriter.close();
}
}
}
| FilterMutectCalls: write as we go to save memory (#3832)
| src/main/java/org/broadinstitute/hellbender/tools/walkers/mutect/FilterMutectCalls.java | FilterMutectCalls: write as we go to save memory (#3832) | <ide><path>rc/main/java/org/broadinstitute/hellbender/tools/walkers/mutect/FilterMutectCalls.java
<ide>
<ide> private VariantContextWriter vcfWriter;
<ide>
<del> private final List<VariantContext> unfilteredCalls = new ArrayList<>();
<del>
<add> private Mutect2FilteringEngine filteringEngine;
<ide>
<ide> @Override
<ide> public void onTraversalStart() {
<ide> final VCFHeader vcfHeader = new VCFHeader(headerLines, inputHeader.getGenotypeSamples());
<ide> vcfWriter = createVCFWriter(new File(outputVcf));
<ide> vcfWriter.writeHeader(vcfHeader);
<add>
<add> final String tumorSample = getHeaderForVariants().getMetaDataLine(Mutect2Engine.TUMOR_SAMPLE_KEY_IN_VCF_HEADER).getValue();
<add> filteringEngine = new Mutect2FilteringEngine(MTFAC, tumorSample);
<ide> }
<ide>
<ide> @Override
<ide> public Object onTraversalSuccess() {
<del> final String tumorSample = getHeaderForVariants().getMetaDataLine(Mutect2Engine.TUMOR_SAMPLE_KEY_IN_VCF_HEADER).getValue();
<del> final Mutect2FilteringEngine filteringEngine = new Mutect2FilteringEngine(MTFAC, tumorSample);
<del> // TODO: implement sophisticated filtering
<del> for (final VariantContext vc : unfilteredCalls) {
<del> final VariantContextBuilder vcb = new VariantContextBuilder(vc);
<del> vcb.filters(filteringEngine.calculateFilters(MTFAC, vc));
<del> vcfWriter.add(vcb.make());
<del> }
<ide> return "SUCCESS";
<ide> }
<ide>
<ide> @Override
<ide> public void apply(final VariantContext vc, final ReadsContext readsContext, final ReferenceContext refContext, final FeatureContext fc) {
<del> unfilteredCalls.add(vc);
<add> final VariantContextBuilder vcb = new VariantContextBuilder(vc);
<add> vcb.filters(filteringEngine.calculateFilters(MTFAC, vc));
<add> vcfWriter.add(vcb.make());
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | error: pathspec 'src/de/st_ddt/crazyutil/paramitrisable/PermissionedParamitriable.java' did not match any file(s) known to git
| 8a4f692d1e7ea6f9945845c21c3eff158153d391 | 1 | ST-DDT/CrazyCore | package de.st_ddt.crazyutil.paramitrisable;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.CommandSender;
import de.st_ddt.crazyplugin.exceptions.CrazyCommandPermissionException;
import de.st_ddt.crazyplugin.exceptions.CrazyException;
import de.st_ddt.crazyutil.Named;
public class PermissionedParamitriable<S> extends TypedParamitrisable<S>
{
protected final CommandSender sender;
protected final TypedParamitrisable<S> param;
public PermissionedParamitriable(final CommandSender sender, final TypedParamitrisable<S> param)
{
super(param.getValue());
this.sender = sender;
this.param = param;
}
@Override
public void setParameter(final String parameter) throws CrazyException
{
if (!hasAccessPermission(sender, parameter))
handleNoPermission(parameter);
this.param.setParameter(parameter);
setValue(param.getValue());
if (!hasAccessPermission(sender, value))
handleNoPermission(parameter);
}
@Override
public List<String> tab(final String parameter)
{
final List<String> list = param.tab(parameter);
final List<String> res = new ArrayList<String>(list.size());
for (final String string : list)
if (hasAccessPermission(sender, string))
res.add(string);
return res;
}
public boolean hasAccessPermission(final CommandSender sender, final String parameter)
{
return true;
}
public boolean hasAccessPermission(final CommandSender sender, final S value)
{
if (value instanceof Named)
return hasAccessPermission(sender, ((Named) value).getName());
else if (value instanceof Enum<?>)
return hasAccessPermission(sender, ((Enum<?>) value).name());
else
return hasAccessPermission(sender, value.toString());
}
public void handleNoPermission(final String parameter) throws CrazyException
{
throw new CrazyCommandPermissionException();
}
}
| src/de/st_ddt/crazyutil/paramitrisable/PermissionedParamitriable.java | CrazyCore: added PermissionParamitrisable
| src/de/st_ddt/crazyutil/paramitrisable/PermissionedParamitriable.java | CrazyCore: added PermissionParamitrisable | <ide><path>rc/de/st_ddt/crazyutil/paramitrisable/PermissionedParamitriable.java
<add>package de.st_ddt.crazyutil.paramitrisable;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>import org.bukkit.command.CommandSender;
<add>
<add>import de.st_ddt.crazyplugin.exceptions.CrazyCommandPermissionException;
<add>import de.st_ddt.crazyplugin.exceptions.CrazyException;
<add>import de.st_ddt.crazyutil.Named;
<add>
<add>public class PermissionedParamitriable<S> extends TypedParamitrisable<S>
<add>{
<add>
<add> protected final CommandSender sender;
<add> protected final TypedParamitrisable<S> param;
<add>
<add> public PermissionedParamitriable(final CommandSender sender, final TypedParamitrisable<S> param)
<add> {
<add> super(param.getValue());
<add> this.sender = sender;
<add> this.param = param;
<add> }
<add>
<add> @Override
<add> public void setParameter(final String parameter) throws CrazyException
<add> {
<add> if (!hasAccessPermission(sender, parameter))
<add> handleNoPermission(parameter);
<add> this.param.setParameter(parameter);
<add> setValue(param.getValue());
<add> if (!hasAccessPermission(sender, value))
<add> handleNoPermission(parameter);
<add> }
<add>
<add> @Override
<add> public List<String> tab(final String parameter)
<add> {
<add> final List<String> list = param.tab(parameter);
<add> final List<String> res = new ArrayList<String>(list.size());
<add> for (final String string : list)
<add> if (hasAccessPermission(sender, string))
<add> res.add(string);
<add> return res;
<add> }
<add>
<add> public boolean hasAccessPermission(final CommandSender sender, final String parameter)
<add> {
<add> return true;
<add> }
<add>
<add> public boolean hasAccessPermission(final CommandSender sender, final S value)
<add> {
<add> if (value instanceof Named)
<add> return hasAccessPermission(sender, ((Named) value).getName());
<add> else if (value instanceof Enum<?>)
<add> return hasAccessPermission(sender, ((Enum<?>) value).name());
<add> else
<add> return hasAccessPermission(sender, value.toString());
<add> }
<add>
<add> public void handleNoPermission(final String parameter) throws CrazyException
<add> {
<add> throw new CrazyCommandPermissionException();
<add> }
<add>} |
|
Java | agpl-3.0 | 739c52afdb3dc26a9154c76d4fc08e4df23e0448 | 0 | RapidInfoSys/Rapid,RapidInfoSys/Rapid,RapidInfoSys/Rapid,RapidInfoSys/Rapid | /*
Copyright (C) 2021 - Gareth Edwards / Rapid Information Systems
[email protected]
This file is part of the Rapid Application Platform
Rapid is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version. The terms require you
to include the original copyright, and the license notice in all redistributions.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
in a file named "COPYING". If not, see <http://www.gnu.org/licenses/>.
*/
package com.rapid.actions;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.rapid.core.Action;
import com.rapid.core.Application;
import com.rapid.core.Control;
import com.rapid.core.Page;
import com.rapid.core.Page.Variables;
import com.rapid.core.Parameter;
import com.rapid.data.ConnectionAdapter;
import com.rapid.data.DataFactory;
import com.rapid.data.DataFactory.Parameters;
import com.rapid.data.DatabaseConnection;
import com.rapid.data.SQLiteDataFactory;
import com.rapid.server.ActionCache;
import com.rapid.server.RapidHttpServlet;
import com.rapid.server.RapidRequest;
public class Database extends Action {
// details of the query (inputs, sql, outputs)
public static class Query {
private List<Parameter> _inputs, _outputs;
private String _sql;
private boolean _multiRow;
private int _databaseConnectionIndex;
public List<Parameter> getInputs() { return _inputs; }
public void setInputs(List<Parameter> inputs) { _inputs = inputs; }
public List<Parameter> getOutputs() { return _outputs; }
public void setOutputs(List<Parameter> outputs) { _outputs = outputs; }
public String getSQL() { return _sql; }
public void setSQL(String sql) { _sql = sql; }
public boolean getMultiRow() { return _multiRow; }
public void setMultiRow(boolean multiRow) { _multiRow = multiRow; }
public int getDatabaseConnectionIndex() { return _databaseConnectionIndex; }
public void setDatabaseConnectionIndex(int databaseConnectionIndex) { _databaseConnectionIndex = databaseConnectionIndex; }
public Query() {};
public Query(List<Parameter> inputs, List<Parameter> outputs, String sql, boolean multiRow, int databaseConnectionIndex) {
_inputs = inputs;
_outputs = outputs;
_sql = sql;
_multiRow = multiRow;
_databaseConnectionIndex = databaseConnectionIndex;
}
}
// static variables
private static Logger _logger = LogManager.getLogger(Database.class);
// instance variables
private Query _query;
private boolean _showLoading, _mergeChildren;
private List<Database> _childDatabaseActions;
private List<Action> _successActions, _errorActions, _childActions;
// properties
public Query getQuery() { return _query; }
public void setQuery(Query query) { _query = query; }
public boolean getShowLoading() { return _showLoading; }
public void setShowLoading(boolean showLoading) { _showLoading = showLoading; }
public List<Database> getChildDatabaseActions() { return _childDatabaseActions; }
public void setChildDatabaseActions(List<Database> childDatabaseActions) { _childDatabaseActions = childDatabaseActions; };
public boolean getMergeChildren() { return _mergeChildren; }
public void setMergeChildren(boolean mergeChildren) { _mergeChildren = mergeChildren; }
public List<Action> getSuccessActions() { return _successActions; }
public void setSuccessActions(List<Action> successActions) { _successActions = successActions; }
public List<Action> getErrorActions() { return _errorActions; }
public void setErrorActions(List<Action> errorActions) { _errorActions = errorActions; }
// constructors
// used by jaxb
public Database() {
// set the xml version, etc
super();
// default merge children to true for older applications - new ones will have it set to false by default by the designer
_mergeChildren = true;
}
// used by designer
public Database(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
// call the super parameterless constructor which sets the xml version
super();
// save all key/values from the json into the properties
for (String key : JSONObject.getNames(jsonAction)) {
// add all json properties to our properties, except for query
if (!"query".equals(key) && !"showLoading".equals(key) && !"childDatabaseActions".equals(key) && !"successActions".equals(key) && !"errorActions".equals(key) && !"childActions".equals(key)) addProperty(key, jsonAction.get(key).toString());
// if this is mergeChildren we need to update our property variable too, to deal with legacy values
if ("mergeChildren".equals(key)) _mergeChildren = jsonAction.optBoolean(key);
}
// try and build the query object
JSONObject jsonQuery = jsonAction.optJSONObject("query");
// check we got one
if (jsonQuery != null) {
// get the parameters
ArrayList<Parameter> inputs = getParameters(jsonQuery.optJSONArray("inputs"));
ArrayList<Parameter> outputs = getParameters(jsonQuery.optJSONArray("outputs"));
String sql = jsonQuery.optString("SQL");
boolean multiRow = jsonQuery.optBoolean("multiRow");
int databaseConnectionIndex = jsonQuery.optInt("databaseConnectionIndex");
// make the object
_query = new Query(inputs, outputs, sql, multiRow, databaseConnectionIndex);
}
// look for showLoading
_showLoading = jsonAction.optBoolean("showLoading");
// grab any successActions
JSONArray jsonChildDatabaseActions = jsonAction.optJSONArray("childDatabaseActions");
// if we had some
if (jsonChildDatabaseActions != null) {
// instantiate collection
_childDatabaseActions = new ArrayList<>();
// loop them
for (int i = 0; i < jsonChildDatabaseActions.length(); i++) {
// get one
JSONObject jsonChildDatabaseAction = jsonChildDatabaseActions.getJSONObject(i);
// instantiate and add to collection
_childDatabaseActions.add(new Database(rapidServlet, jsonChildDatabaseAction));
}
}
// grab any successActions
JSONArray jsonSuccessActions = jsonAction.optJSONArray("successActions");
// if we had some instantiate our collection
if (jsonSuccessActions != null) _successActions = Control.getActions(rapidServlet, jsonSuccessActions);
// grab any errorActions
JSONArray jsonErrorActions = jsonAction.optJSONArray("errorActions");
// if we had some instantiate our collection
if (jsonErrorActions != null) _errorActions = Control.getActions(rapidServlet, jsonErrorActions);
}
// this is used to get both input and output parameters
private ArrayList<Parameter> getParameters(JSONArray jsonParameters) throws JSONException {
// prepare return
ArrayList<Parameter> parameters = null;
// check
if (jsonParameters != null) {
// instantiate collection
parameters = new ArrayList<>();
// loop
for (int i = 0; i < jsonParameters.length(); i++) {
// instaniate member
Parameter parameter = new Parameter(
jsonParameters.getJSONObject(i).optString("itemId"),
jsonParameters.getJSONObject(i).optString("field")
);
// add member
parameters.add(parameter);
}
}
// return
return parameters;
}
// overrides
@Override
public List<Action> getChildActions() {
// initialise and populate on first get
if (_childActions == null) {
// our list of all child actions
_childActions = new ArrayList<>();
// add child success actions
if (_successActions != null) {
for (Action action : _successActions) _childActions.add(action);
}
// add child error actions
if (_errorActions != null) {
for (Action action : _errorActions) _childActions.add(action);
}
// add child error actions
if (_childDatabaseActions != null) {
for (Action action : _childDatabaseActions) _childActions.add(action);
}
}
return _childActions;
}
public String getLoadingJS(Page page, List<Parameter> parameters, boolean show) {
String js = "";
// check there are parameters
if (parameters != null) {
// loop the output parameters
for (int i = 0; i < parameters.size(); i++) {
// get the parameter
Parameter output = parameters.get(i);
// get the control the data is going into
Control control = page.getControl(output.getItemId());
// check the control still exists
if (control != null) {
if ("grid".equals(control.getType())) {
if (show) {
js += "$('#" + control.getId() + "').showLoading();\n";
} else {
js += "$('#" + control.getId() + "').hideLoading();\n";
}
}
}
}
}
return js;
}
// private function to get inputs into the query object, reused by child database actions
private String getInputsJavaScript(ServletContext servletContext, Application application, Page page, Query query) {
// assume it'll be an empty string
String js = "";
// if there is a query
if (query != null) {
// get the inputs from the query
List<Parameter> inputs = query.getInputs();
// if we were given some
if (inputs != null) {
// check there is at least one
if (inputs.size() > 0) {
// get the first itemId (this is the only one visible to the users)
String sourceItemId = inputs.get(0).getItemId();
js += "[";
// loop them
for (int i = 0; i < inputs.size(); i++) {
// get the parameter
Parameter parameter = inputs.get(i);
// get this item id
String itemId = parameter.getItemId();
// get this item field
String itemField = parameter.getField();
// if there was an id
if (itemId != null) {
// add the input item
js += "{";
if (query.getMultiRow() && itemId.equals(sourceItemId)) {
js += "field: '" + itemField + "'";
} else {
js += "id: '" + itemId + (itemField == null || "".equals(itemField) ? "" : "." + itemField) + "', ";
js += "value:" + Control.getDataJavaScript(servletContext, application, page, itemId, itemField);
}
js += "}";
// add comma if not last item
if (i < inputs.size() - 1) js += ", ";
} // got item
} // loop inputs
// close the array
js += "]";
// if this is a multirow query
if (query.getMultiRow()) {
// add the field-less get data for the first item the first parameter
js += ", '" + sourceItemId + "', " + Control.getDataJavaScript(servletContext, application, page, sourceItemId, null);
}
} // inputs > 0
} // got inputs
} // got query
// if we got no inputs set to null
if (!js.startsWith("[")) js = "null";
// return
return js;
}
// private function to get outputs into a string, reused by child database actions
private String getOutputsJavaScript(ServletContext servletContext, Application application, Page page, List<Parameter> outputs, String childName) {
// the outputs array we're going to make
String jsOutputs = "";
// any property outputs that must be done separately;
String jsPropertyOutputs = "";
// loop the output parameters
for (int i = 0; i < outputs.size(); i++) {
// get the parameter
Parameter output = outputs.get(i);
// get the id
String outputId = output.getItemId();
// get the id parts
String[] idParts = outputId.split("\\.");
// if there is more than 1 part we are dealing with set properties, for now just update the output id
if (idParts.length > 1) outputId = idParts[0];
// get the control the data is going into
Control outputControl = page.getControl(outputId);
// assume we found it
boolean pageControl = true;
// if not found in the page
if (outputControl == null) {
// try the application
outputControl = application.getControl(servletContext, outputId);
// set page control to false
pageControl = false;
}
// check we got one
if (outputControl == null) {
jsOutputs += " /* output not found for " + outputId + "*/ ";
} else {
// get any details we may have
String details = outputControl.getDetailsJavaScript(application, page);
// set to empty string or clean up
if (details == null) {
details = "";
} else {
// if this is a page control
if (pageControl) {
// the details will already be in the page so we can use the short form
details = outputControl.getId() + "details";
}
// add details property with json details
details = ", details: " + details;
}
// start the jsOutputs
jsOutputs += "{id: '" + outputControl.getId() + "', type: '" + outputControl.getType() + "', field: '" + output.getField() + "'" + details;
// if there are two parts this is a property
if (idParts.length > 1) {
// get the property from the second id part
String property = idParts[1];
// append the property
jsOutputs += ", property: '" + property + "'";
} // property / control check
// close the jsOutputs
jsOutputs += "},";
} // control found check
} // outputs loop
// remove the last comma from any conventional outputs
if (jsOutputs.length() > 0) jsOutputs = jsOutputs.substring(0, jsOutputs.length() - 1);
// wrap the outputs with their variable
jsOutputs = "var outputs" + childName + " = [" + jsOutputs + "]";
// if jsPropertyOutputs, add them before
if (jsPropertyOutputs.length() > 0) jsOutputs = jsPropertyOutputs.trim().replace("\n", "\n ") + "\n " + jsOutputs;
// return
return jsOutputs;
}
@Override
public String getJavaScript(RapidRequest rapidRequest, Application application, Page page, Control control, JSONObject jsonDetails) throws Exception {
String js = "";
if (_query != null) {
// get the rapid servlet
RapidHttpServlet rapidServlet = rapidRequest.getRapidServlet();
// get the sequence for this action requests so long-running early ones don't overwrite fast later ones (defined in databaseaction.xml)
js += "var sequence = getDatabaseActionSequence('" + getId() + "');\n";
// open the js function to get the input data
js += "var data = getDatabaseActionInputData(" + _query.getMultiRow() + ", ";
// get the inputs
js += getInputsJavaScript(rapidServlet.getServletContext(), application, page, _query);
// close the js function to get the input data
js += ");\n";
// drop in the query variable used to collect the inputs, and hold the sequence
js += "var query = { data: data, sequence: sequence };\n";
// assume no child queries
boolean childQueries = false;
// look for any _childDatabaseActions
if (_childDatabaseActions != null && _childDatabaseActions.size() > 0) {
// remember we have child queries
childQueries = true;
// add a collection into the parent
js += "query.childQueries = [];\n";
// count them
int i = 1;
// loop them
for (Database childDatabaseAction : _childDatabaseActions) {
// get the childQuery
Query childQuery = childDatabaseAction.getQuery();
// open function to get input data
js += "var childData" + i + " = getDatabaseActionInputData(" + childQuery.getMultiRow() + ", ";
// add inputs
js += getInputsJavaScript(rapidServlet.getServletContext(), application, page, childQuery);
// close the function
js += ");\n";
// create object
js += "var childQuery" + i + " = { data: childData" + i + ", index: " + (i - 1) + " };\n";
// add to query
js += "query.childQueries.push(childQuery" + i + ");\n";
// increment the counter
i ++;
}
}
// control can be null when the action is called from the page load
String controlParam = "";
if (control != null) controlParam = "&c=" + control.getId();
// get the outputs
List<Parameter> outputs = _query.getOutputs();
// get the js to hide the loading (if applicable)
if (_showLoading) js += getLoadingJS(page, outputs, true);
// stringify the query
js += "query = JSON.stringify(query);\n";
// open the ajax call
js += "$.ajax({ url : '~?a=" + application.getId() + "&v=" + application.getVersion() + "&p=" + page.getId() + controlParam + "&act=" + getId() + "', type: 'POST', contentType: 'application/json', dataType: 'json',\n";
js += " data: query,\n";
js += " error: function(server, status, message) {\n";
// hide the loading javascript (if applicable)
if (_showLoading) js += " " + getLoadingJS(page, outputs, false);
// add standard error actions with offline and working handling
js += getErrorActionsJavaScript(rapidRequest, application, page, control, jsonDetails, _errorActions);
// open success function
js += " success: function(data) {\n";
// hide the loading javascript (if applicable)
if (_showLoading) js += " " + getLoadingJS(page, outputs, false);
// open if data check
js += " if (data) {\n";
// check there are outputs
if (outputs != null) {
// if there are parent outputs
if (outputs.size() > 0) {
// add the parent outputs property
js += " " + getOutputsJavaScript(rapidServlet.getServletContext(), application, page, outputs, "") + ";\n";
// add indent
js += " ";
// if there are child queries, add child queries check
if (childQueries) js += "if (data.fields && data.fields.length > 0) {\n if (data.fields[0].indexOf('childAction') == 0) {\n Action_database(ev,'" + getId() + "', {sequence:data.sequence, fields:[], rows:[]}, outputs);\n } else {\n ";
// send them and the data to the database action (unless there are children and this parent has been skipped)
js += "Action_database(ev,'" + getId() + "', data, outputs);\n";
// close the extra child queries check
if (childQueries) js += " }\n }\n";
}
} // outputs null check
// if we are expecting child action results
// check for any child database actions
if (_childDatabaseActions != null) {
// loop them
for (int i = 0; i < _childDatabaseActions.size(); i++) {
// get the outputs
List<Parameter> childOutputs = _childDatabaseActions.get(i).getQuery().getOutputs();
// if it has out puts
if (childOutputs != null && childOutputs.size() > 0) {
// get the name of this child
String childName = "childAction" + (i + 1);
// get the outputs
js += " " + getOutputsJavaScript(rapidServlet.getServletContext(), application, page, childOutputs, childName) + ";\n";
// get the data
js += " Action_database(ev,'" + getId() + "', data, " + "outputs" + childName + ",'" + childName + "');\n";
} // outputs check
} // child action loop
} // child action check
// close if data check
js += " }\n";
// get the standardised JavaScript to hide any working page only if this action has no children
js += getWorkingPageHideJavaScript(jsonDetails, _successActions, " ");
// add any success actions
if (_successActions != null) {
for (Action action : _successActions) {
js += " " + action.getJavaScriptWithHeader(rapidRequest, application, page, control, jsonDetails).trim().replace("\n", "\n ") + "\n";
}
}
// close success function
js += " }\n";
// close ajax call
js += "});";
}
// return what we built
return js;
}
private String getJsonInputValue(JSONArray jsonFields, JSONArray jsonRow, String id) {
for (int j = 0; j < jsonFields.length(); j++) {
// get the id from the fields
String jsonId = jsonFields.optString(j);
// if the id we want matches this one
if (id.equalsIgnoreCase(jsonId)) {
// return the value
return jsonRow.optString(j,null);
}
}
return null;
}
public JSONObject doQuery(RapidRequest rapidRequest, JSONObject jsonAction, Application application, DataFactory df) throws Exception {
// place holder for the object we're going to return
JSONObject jsonData = null;
// get the rapidServlet
RapidHttpServlet rapidServlet = rapidRequest.getRapidServlet();
ServletContext context = rapidServlet.getServletContext();
// retrieve the sql
String sql = _query.getSQL();
// only if there is some sql is it worth going further
if (sql != null) {
// merge in any application parameters
sql = application.insertParameters(context, sql);
// get any json inputs
JSONObject jsonInputData = jsonAction.optJSONObject("data");
// initialise the parameters list
ArrayList<Parameters> parametersList = new ArrayList<>();
// populate the parameters from the inputs collection (we do this first as we use them as the cache key due to getting values from the session)
if (_query.getInputs() == null) {
// just add an empty parameters member if no inputs
parametersList.add(new Parameters());
} else {
// if there is input data
if (jsonInputData != null) {
// get any input fields
JSONArray jsonFields = jsonInputData.optJSONArray("fields");
// get any input rows
JSONArray jsonRows = jsonInputData.optJSONArray("rows");
// if we have fields and rows
if (jsonFields != null && jsonRows != null) {
// loop the input rows (only the top row if not multirow)
for (int i = 0; i < jsonRows.length() && (_query.getMultiRow() || i == 0); i ++) {
// get this jsonRow
JSONArray jsonRow = jsonRows.getJSONArray(i);
// make the parameters for this row
Parameters parameters = new Parameters();
// loop the query inputs
for (Parameter input : _query.getInputs()) {
// get the input id
String id = input.getItemId();
// get the input field
String field = input.getField();
// add field to id if present
if (field != null && !"".equals(field)) id += "." + field;
// retain the value
String value = null;
// if it looks like a control, or a system value (bit of extra safety checking)
if (id.indexOf("_C") > 0 || id.indexOf("System.") == 0) {
// check special cases
switch (id) {
case "System.device" :
// get the device from the request
value = rapidRequest.getDevice();
break;
case "System.user name" :
// get the user name from the session (don't trust the front end)
value = rapidRequest.getUserName();
break;
default :
// get the value from the json inputs
value = getJsonInputValue(jsonFields, jsonRow, id);
}
} else {
// didn't look like a control so check page parameters
if (rapidRequest.getPage() != null) {
// get page variables
Variables pageVariables = rapidRequest.getPage().getVariables();
// check for page parameters
if (pageVariables != null) {
// if this is one
if (pageVariables.contains(id)) {
// get the value
value = getJsonInputValue(jsonFields, jsonRow, id);
}
}
}
}
// if still null try the session
if (value == null) value = (String) rapidRequest.getSessionAttribute(input.getItemId());
// add the parameter
parameters.add(value);
}
// add the parameters to the list
parametersList.add(parameters);
} // row loop
} // input fields and rows check
} // input data check
} // query inputs check
// placeholder for the action cache
ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache();
// if an action cache was found
if (actionCache != null) {
// log that we found action cache
_logger.debug("Database action cache found");
// attempt to fetch data from the cache
jsonData = actionCache.get(application.getId(), getId(), parametersList.toString());
}
// unmap numbered numbered parameters
List<Parameter> originalInputs = _query.getInputs();
if (originalInputs == null) originalInputs = new ArrayList<>();
List<String> inputs = new ArrayList<>();
// populate it with nulls
for (int i = 0; i < originalInputs.size(); i++) {
Parameter input = originalInputs.get(i);
String inputName = input.getItemId();
if (!input.getField().isEmpty()) inputName += "." + input.getField();
inputs.add(inputName);
}
// if there were parameters in the list unmap and reset them
if (parametersList.size() > 0) parametersList.set(0, unmappedParameters(sql, parametersList.get(0), inputs, application, context));
sql = unspecifySqlSlots(sql);
// if there isn't a cache or no data was retrieved
if (jsonData == null) {
try {
// instantiate jsonData
jsonData = new JSONObject();
// fields collection
JSONArray jsonFields = new JSONArray();
// rows collection can start initialised
JSONArray jsonRows = new JSONArray();
// trim the sql
sql = sql.trim();
// check the verb
if (sql.toLowerCase().startsWith("select") || sql.toLowerCase().startsWith("with") || sql.toLowerCase().startsWith("exec")) {
// if select set readonly to true (makes for faster querying) - but not for SQLite as it throws an exception if done after the connection is established
if (sql.toLowerCase().startsWith("select") && !df.getConnectionAdapter().getConnectionString().toLowerCase().contains("sqlite")) df.setReadOnly(true);
// got fields indicator
boolean gotFields = false;
// loop the parameterList getting a result set for each parameters (input row)
for (Parameters parameters : parametersList) {
// get the result set!
ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);
// check we got one
if (rs != null) {
// date formatters we might need but only want to fetch / initialise once
SimpleDateFormat localDateFormatter = null;
SimpleDateFormat localDateTimeFormatter = null;
// assume results
boolean gotResults = true;
// get the statement
Statement st = rs.getStatement();
while (gotResults) {
// get this resultset's meta data for the field names
ResultSetMetaData rsmd = rs.getMetaData();
// loop the result set
while (rs.next()) {
// initialise the row
JSONArray jsonRow = new JSONArray();
// loop the columns
for (int i = 0; i < rsmd.getColumnCount(); i++) {
// add the field name to the fields collection if not done yet
if (!gotFields) jsonFields.put(rsmd.getColumnLabel(i + 1));
// get the value as a string
String value = rs.getString(i + 1);
// check for null
if (value == null) {
// put null
jsonRow.put(value);
} else {
// get the column type
int columnType = rsmd.getColumnType(i + 1);
// add the data to the row according to it's type
switch (columnType) {
case (Types.NUMERIC) :
jsonRow.put(rs.getDouble(i + 1));
break;
case (Types.INTEGER) :
jsonRow.put(rs.getInt(i + 1));
break;
case (Types.BIGINT) :
jsonRow.put(rs.getLong(i + 1));
break;
case (Types.FLOAT) :
jsonRow.put(rs.getFloat(i + 1));
break;
case (Types.DOUBLE) : case (Types.DECIMAL) :
jsonRow.put(rs.getDouble(i + 1));
break;
case (Types.DATE) :
Date date = rs.getDate(i + 1);
if (date == null) {
jsonRow.put(date);
} else {
if (localDateFormatter == null) localDateFormatter = rapidRequest.getRapidServlet().getLocalDateFormatter();
jsonRow.put(localDateFormatter.format(date));
}
break;
case (Types.TIMESTAMP) :
Timestamp timeStamp = rs.getTimestamp(i + 1);
if (timeStamp == null) {
jsonRow.put(timeStamp);
} else {
// check for 0 millseconds past midnight - a truncated date time (time zone offset is in minutes, multiplied by the number of millis in a minute modulus with number of millis in a day)
if ((timeStamp.getTime() - timeStamp.getTimezoneOffset() * 60000) % 86400000L == 0) {
// if so show just date
if (localDateFormatter == null) localDateFormatter = rapidRequest.getRapidServlet().getLocalDateFormatter();
jsonRow.put(localDateFormatter.format(timeStamp));
} else {
// show date and time
if (localDateTimeFormatter == null) localDateTimeFormatter = rapidRequest.getRapidServlet().getLocalDateTimeFormatter();
jsonRow.put(localDateTimeFormatter.format(timeStamp));
}
}
break;
default :
jsonRow.put(value);
}
}
}
// add the row to the rows collection
jsonRows.put(jsonRow);
// remember we now have our fields
gotFields = true;
}
// close the record set
rs.close();
// look for any more results
gotResults = st.getMoreResults();
// if we got some
if (gotResults) {
// move result set on
rs = st.getResultSet();
// clear fields collection
jsonFields = new JSONArray();
// clear rows collection can start initialised
jsonRows = new JSONArray();
}
} // got results loop
} // check rs
} // parameters list loop - not sure whether this ever called
} else {
// assume rows affected is 0
int rows = 0;
// sql check
if (sql.length() > 0) {
// perform update for all incoming parameters (one parameters collection for each row)
for (Parameters parameters : parametersList) {
rows += df.getPreparedUpdate(rapidRequest, sql, parameters);
}
// add a psuedo field
jsonFields.put("rows");
// create a row array
JSONArray jsonRow = new JSONArray();
// add the rows updated
jsonRow.put(rows);
// add the row we just made
jsonRows.put(jsonRow);
}
}
// add the fields to the data object
jsonData.put("fields", jsonFields);
// add the rows to the data object
jsonData.put("rows", jsonRows);
// check for any child database actions
if (_childDatabaseActions != null) {
// if there really are some
if (_childDatabaseActions.size() > 0) {
// a list of mergeChildrenFields
List<String> childFields = new ArrayList<>();
// look for any mergeChildrenFields
String childDataFields = getProperty("childDataFields");
// if we got some
if (childDataFields != null) {
// split them
String[] childDataFieldsParts = childDataFields.split(",");
// loop them
for (String childField : childDataFieldsParts) {
// trim
String childFieldTrim = childField.trim();
// add if we got something (avoid the blank)
childFields.add(childFieldTrim);
}
}
// get any child data
JSONArray jsonChildQueries = jsonAction.optJSONArray("childQueries");
// if there was some
if (jsonChildQueries != null) {
// loop
for (int i = 0; i < jsonChildQueries.length(); i++) {
// fetch the data
JSONObject jsonChildAction = jsonChildQueries.getJSONObject(i);
// read the index (the position of the child this related to
int index = jsonChildAction.getInt("index");
// get the relevant child action
Database childDatabaseAction = _childDatabaseActions.get(index);
// get the resultant child data
JSONObject jsonChildData = childDatabaseAction.doQuery(rapidRequest, jsonChildAction, application, df);
// prepare the merge child field name
String childFieldName = "childAction" + (i + 1);
// if we were given a child field name at this position, use that instead
if (childFields.size() > i) childFieldName = childFields.get(i);
// add a field for the results of this child action
jsonFields.put(childFieldName);
// if we are merging child data, which was the default before 2.4.4.1
if (_mergeChildren) {
// a map for indexes of matching fields between our parent and child
Map<Integer,Integer> fieldsMap = new HashMap<>();
// the child fields
JSONArray jsonChildFields = jsonChildData.getJSONArray("fields");
if (jsonChildFields != null) {
// loop the parent fields
for (int j = 0; j < jsonFields.length(); j++) {
// loop the child fields
for (int k = 0; k < jsonChildFields.length(); k++) {
// get parent field
String field = jsonFields.getString(j);
// get child field
String childField = jsonChildFields.getString(k);
// if both not null
if (field != null && childField != null) {
// check for match
if (field.toLowerCase().equals(childField.toLowerCase())) fieldsMap.put(j, k);
}
}
}
}
// if matching fields exists and not all columns are matched (stops simple queries like for drop down lookups merging)
if (fieldsMap.size() > 0 && fieldsMap.size() != jsonFields.length() - i - 1) {
// an object with a null value for when there is no match
Object nullObject = null;
// get the child rows
JSONArray jsonChildRows = jsonChildData.getJSONArray("rows");
// if we had some
if (jsonChildRows != null) {
// loop the parent rows
for (int j = 0; j < jsonRows.length(); j++) {
// get the parent row
JSONArray jsonRow = jsonRows.getJSONArray(j);
// make a new rows collection for the child subset
JSONArray jsonChildRowsSubset = new JSONArray();
// loop the child rows
for (int k =0; k < jsonChildRows.length(); k++) {
// get the child row
JSONArray jsonChildRow = jsonChildRows.getJSONArray(k);
// assume no matches
int matches = 0;
// loop the fields map
for (Integer l: fieldsMap.keySet()) {
// parent value
Object parentValue = null;
// get the value if there are enough
if (jsonRow.length() > l) parentValue = jsonRow.get(l);
// child value
Object childValue = null;
// get child value if present
if (jsonChildRow.length() > l) childValue= jsonChildRow.opt(fieldsMap.get(l));
// non null check
if (parentValue != null && childValue != null) {
// a string we will concert the child value to
String parentString = null;
// check the parent value type
if (parentValue.getClass() == String.class) {
parentString = (String) parentValue;
} else if (parentValue.getClass() == Integer.class) {
parentString = Integer.toString((Integer) parentValue);
} else if (parentValue.getClass() == Long.class) {
parentString = Long.toString((Long) parentValue);
} else if (parentValue.getClass() == Double.class) {
parentString = Double.toString((Double) parentValue);
} else if (parentValue.getClass() == Boolean.class) {
parentString = Boolean.toString((Boolean) parentValue);
}
// a string we will convert the child value to
String childString = null;
// check the parent value type
if (childValue.getClass() == String.class) {
childString = (String) childValue;
} else if (childValue.getClass() == Integer.class) {
childString = Integer.toString((Integer) childValue);
} else if (childValue.getClass() == Long.class) {
childString = Long.toString((Long) childValue);
} else if (childValue.getClass() == Double.class) {
childString = Double.toString((Double) childValue);
} else if (childValue.getClass() == Boolean.class) {
childString = Boolean.toString((Boolean) childValue);
}
// non null check
if (parentString != null && childString != null) {
// do the match!
if (parentString.equals(childString)) matches++;
}
} // values non null
} // field map loop
// if we got some matches for all the fields add this row to the subset
if (matches == fieldsMap.size()) jsonChildRowsSubset.put(jsonChildRow);
} // child row loop
// if our child subset has rows in it
if (jsonChildRowsSubset.length() > 0) {
// create a new childSubset object
JSONObject jsonChildDataSubset = new JSONObject();
// add the fields
jsonChildDataSubset.put("fields", jsonChildFields);
// add the subset of rows
jsonChildDataSubset.put("rows", jsonChildRowsSubset);
// add the child database action data subset
jsonRow.put(jsonChildDataSubset);
} else {
// add an empty cell
jsonRow.put(nullObject);
}
} // parent row loop
} // jsonChildRows null check
} else {
// add a top row if we need one
if (jsonRows.length() == 0) jsonRows.put(new JSONArray());
// get the top row - only this one is used when the child data is retrieved
JSONArray jsonRow = jsonRows.getJSONArray(0);
// add the child database action data
jsonRow.put(jsonChildData);
} // matching fields check
} else {
// add a top row if we need one
if (jsonRows.length() == 0) jsonRows.put(new JSONArray());
// get the top row - only this one is used when the child data is retrieved
JSONArray jsonRow = jsonRows.getJSONArray(0);
// add the child database action data
jsonRow.put(jsonChildData);
} // child merge check
} // jsonChildQueries loop
} // jsonChildQueries null check
} // _childDatabaseActions size > 0
} // _childDatabaseActions not null
// cache if in use
if (actionCache != null) actionCache.put(application.getId(), getId(), parametersList.toString(), jsonData);
} catch (Exception ex) {
// log the error
_logger.error(ex);
// close the data factory and silently fail
try { df.close(); } catch (Exception ex2) {}
// only throw if no action cache
if (actionCache == null) {
throw ex;
} else {
_logger.debug("Error not shown to user due to cache : " + ex.getMessage());
}
} // jsonData not null
} // jsonData == null
} // got sql
return jsonData;
}
// finds ? followed by a name optionally in quotes, or ? followed by a name of lower and/or upper case letters - we'll find any of these first and convert them to numbers, only limitation is names outside of quotes can't start with numbers
private static String _namedParameterSlotRegex = "(\\?\"[^\"]+\")|(\\?(?=[a-zA-Z])\\w*)";
// finds ? followed by a name in quotes, or ? followed by 0 or more numbers, or ? on their own
private static String _parameterSlotRegex = "(\\?\"[^\"]+\")|(\\?\\w\\S*)|\\?";
// finds ? followed by a number
private static String _unspecifySlotsRegex = "(\\?\\d*)";
// returns all parameters for the sql by finding any ?'s followed by numbers/names and creating a longer parameter list populated with those mapped
public static Parameters unmappedParameters(String sql, Parameters oldParameters, List<String> inputIds, Application application, ServletContext context) throws SQLException {
// we first use this to find parameters with names and convert them into numbers
Map<String, Integer> parameterIndexesByControlName = new HashMap<>();
// if there were any ?'s followed by names in the sql
if (Pattern.compile(_namedParameterSlotRegex).matcher(sql).find()) {
// loop the inputs to see which are in the sql and populate the map
for (int inputIndex = 0; inputIndex < inputIds.size(); inputIndex++) {
// the id of the control for this input
String id = inputIds.get(inputIndex);
if (id.startsWith("System.")) {
String name = "\"" + id + "\"";
parameterIndexesByControlName.put(name, inputIndex);
} else {
String[] parts = id.split("\\.");
String controlId = parts[0];
Control control = application.getControl(context, controlId);
if (control != null) {
String name = control.getName();
id = id.replaceAll(".+\\.", name + ".");
if (parts.length > 1) name += "." + parts[1].toLowerCase().replace(" ", "");
for (int idIndex = 2; idIndex < parts.length; idIndex++) name += "." + parts[idIndex];
parameterIndexesByControlName.put("\"" + name + "\"", inputIndex);
if (!name.contains(" ")) parameterIndexesByControlName.put(name, inputIndex);
}
}
}
}
// remove comment blocks
String[] stringParts = sql.split("\\/\\*|\\*\\/");
sql = "";
for (int partIndex = 0; partIndex < stringParts.length; partIndex += 2) {
sql += stringParts[partIndex];
}
// remove quote blocks
stringParts = sql.split("'");
sql = "";
for (int partIndex = 0; partIndex < stringParts.length; partIndex += 2) {
sql += stringParts[partIndex];
}
// named variables should have been replaced so use the number finding pattern
Matcher matcher = Pattern.compile(_parameterSlotRegex).matcher(sql);
// a probably longer list of parameters we'll be making using the numbers or names after the ?'s
Parameters newParameters = new Parameters();
// the old parameters we want to map out to the new ones, we use a set to remove the ones we've done until they all are
Set<Integer> oldParametersNumbers = new HashSet<>();
// loop the original inputs to populate the set
for (int number = 1; number <= oldParameters.size(); number++) {
oldParametersNumbers.add(number);
}
// a running count of ?'s without a number/name
int unspecifiedSlots = 0;
// loop the ?'s and their number/name
while (matcher.find()) {
// get what the regex found: the ? followed by either numbers or letters
String slot = matcher.group();
// replace any following commas or closing brackets which would have been included by the regex when we were looking for names
slot = slot.replace(",", "").replace(")", "");
int parameterIndex = unspecifiedSlots;
// if there is only a ? this slot is unspecified
if (slot.length() == 1) {
unspecifiedSlots++;
} else {
// get the number/name after the ?
String specifier = slot.substring(1);
// check if all numbers
if (specifier.matches("\\d+")) {
// use the number after the ? as the index to find the parameter
parameterIndex = Integer.parseInt(specifier) - 1;
} else {
//
String[] parts = specifier.split("\\.");
String name = parts[0];
if (parts.length > 1) name += "." + parts[1].toLowerCase().replace(" ", "");
for (int idIndex = 2; idIndex < parts.length; idIndex++) name += "." + parts[idIndex];
// use the letters after the ? as the key to find the parameter
parameterIndex = parameterIndexesByControlName.get(name);
}
}
// if we have an input at this index in the original inputs
if (parameterIndex < oldParameters.size()) {
//
newParameters.add(oldParameters.get(parameterIndex));
oldParametersNumbers.remove(parameterIndex + 1);
} else {
throw new SQLException("Parameter " + (parameterIndex + 1) + " not provided in inputs list");
}
} // slot loop
// if there are any parameters left that weren't used by the query
if (oldParametersNumbers.size() > 0) {
int firstUnusedInputNumber = oldParametersNumbers.iterator().next();
throw new SQLException("Input " + firstUnusedInputNumber + " not used");
}
// if not all parameters got mapped
if (oldParameters.size() > newParameters.size()) {
// send back the originals
return oldParameters;
} else {
// send the new ones!
return newParameters;
}
}
// returns sql with any numbers after the ? removed (used after the name number replacement above)
public static String unspecifySqlSlots(String sql) {
// add an extra space to the end - something to do with ensuring there are an even number of parts when we split on the ' below
sql = sql + " ";
// split on the single quote - we only want to replace parameters outside of them
String[] stringParts = sql.split("'");
// replace the first part of the sql which goes up to the first single quote
sql = stringParts[0].replaceAll(_unspecifySlotsRegex, "\\?");
// loop the remaining parts from index 1 onwards
for (int partIndex = 1; partIndex < stringParts.length; partIndex++) {
// if this is an even numbered part
if (partIndex % 2 == 0) {
// its outside of a quoted string so replace the ? numbers
sql += "'" + stringParts[partIndex].replaceAll(_unspecifySlotsRegex, "\\?");
} else {
// its within quotes so add back as it was
sql += "'" + stringParts[partIndex];
}
}
return sql;
}
@Override
public JSONObject doAction(RapidRequest rapidRequest, JSONObject jsonAction) throws Exception {
// This code could be optimised to only return required data, according to the outputs collection
_logger.trace("Database action : " + jsonAction);
// fetch the application
Application application = rapidRequest.getApplication();
// fetch the page
Page page = rapidRequest.getPage();
// fetch in the sequence
int sequence = jsonAction.optInt("sequence", 1);
// place holder for the object we're going to return
JSONObject jsonData = null;
// only if there is a query object, application, and page, and connection
if (_query != null && application != null && page != null && application.getDatabaseConnections() != null && application.getDatabaseConnections().size() > _query.getDatabaseConnectionIndex()) {
// get the relevant connection
DatabaseConnection databaseConnection = application.getDatabaseConnections().get(_query.getDatabaseConnectionIndex());
// get the connection adapter
ConnectionAdapter ca = databaseConnection.getConnectionAdapter(rapidRequest.getRapidServlet().getServletContext(), application);
// placeholder for data factory
DataFactory df = null;
// if this is sqlite
if (databaseConnection.getConnectionString().toLowerCase().contains("sqlite")) {
// instantiate a SQLite data factory with autocommit = false;
df = new SQLiteDataFactory(ca, false);
} else {
// instantiate a data factory with autocommit = false;
df = new DataFactory(ca, false);
}
// use the reusable do query function (so child database actions can use it as well)
jsonData = doQuery(rapidRequest, jsonAction, application, df);
// commit the data factory transaction
df.commit();
// close the data factory
df.close();
} // got query, app, and page
// if it's null instantiate one
if (jsonData == null) jsonData = new JSONObject();
// add it back to the data object we're returning
jsonData.put("sequence", sequence);
return jsonData;
}
@Override
public boolean isWebService() {
return true;
}
}
| src/com/rapid/actions/Database.java | /*
Copyright (C) 2021 - Gareth Edwards / Rapid Information Systems
[email protected]
This file is part of the Rapid Application Platform
Rapid is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version. The terms require you
to include the original copyright, and the license notice in all redistributions.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
in a file named "COPYING". If not, see <http://www.gnu.org/licenses/>.
*/
package com.rapid.actions;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.rapid.core.Action;
import com.rapid.core.Application;
import com.rapid.core.Control;
import com.rapid.core.Page;
import com.rapid.core.Page.Variables;
import com.rapid.core.Parameter;
import com.rapid.data.ConnectionAdapter;
import com.rapid.data.DataFactory;
import com.rapid.data.DataFactory.Parameters;
import com.rapid.data.DatabaseConnection;
import com.rapid.data.SQLiteDataFactory;
import com.rapid.server.ActionCache;
import com.rapid.server.RapidHttpServlet;
import com.rapid.server.RapidRequest;
public class Database extends Action {
// details of the query (inputs, sql, outputs)
public static class Query {
private List<Parameter> _inputs, _outputs;
private String _sql;
private boolean _multiRow;
private int _databaseConnectionIndex;
public List<Parameter> getInputs() { return _inputs; }
public void setInputs(List<Parameter> inputs) { _inputs = inputs; }
public List<Parameter> getOutputs() { return _outputs; }
public void setOutputs(List<Parameter> outputs) { _outputs = outputs; }
public String getSQL() { return _sql; }
public void setSQL(String sql) { _sql = sql; }
public boolean getMultiRow() { return _multiRow; }
public void setMultiRow(boolean multiRow) { _multiRow = multiRow; }
public int getDatabaseConnectionIndex() { return _databaseConnectionIndex; }
public void setDatabaseConnectionIndex(int databaseConnectionIndex) { _databaseConnectionIndex = databaseConnectionIndex; }
public Query() {};
public Query(List<Parameter> inputs, List<Parameter> outputs, String sql, boolean multiRow, int databaseConnectionIndex) {
_inputs = inputs;
_outputs = outputs;
_sql = sql;
_multiRow = multiRow;
_databaseConnectionIndex = databaseConnectionIndex;
}
}
// static variables
private static Logger _logger = LogManager.getLogger(Database.class);
// instance variables
private Query _query;
private boolean _showLoading, _mergeChildren;
private List<Database> _childDatabaseActions;
private List<Action> _successActions, _errorActions, _childActions;
// properties
public Query getQuery() { return _query; }
public void setQuery(Query query) { _query = query; }
public boolean getShowLoading() { return _showLoading; }
public void setShowLoading(boolean showLoading) { _showLoading = showLoading; }
public List<Database> getChildDatabaseActions() { return _childDatabaseActions; }
public void setChildDatabaseActions(List<Database> childDatabaseActions) { _childDatabaseActions = childDatabaseActions; };
public boolean getMergeChildren() { return _mergeChildren; }
public void setMergeChildren(boolean mergeChildren) { _mergeChildren = mergeChildren; }
public List<Action> getSuccessActions() { return _successActions; }
public void setSuccessActions(List<Action> successActions) { _successActions = successActions; }
public List<Action> getErrorActions() { return _errorActions; }
public void setErrorActions(List<Action> errorActions) { _errorActions = errorActions; }
// constructors
// used by jaxb
public Database() {
// set the xml version, etc
super();
// default merge children to true for older applications - new ones will have it set to false by default by the designer
_mergeChildren = true;
}
// used by designer
public Database(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
// call the super parameterless constructor which sets the xml version
super();
// save all key/values from the json into the properties
for (String key : JSONObject.getNames(jsonAction)) {
// add all json properties to our properties, except for query
if (!"query".equals(key) && !"showLoading".equals(key) && !"childDatabaseActions".equals(key) && !"successActions".equals(key) && !"errorActions".equals(key) && !"childActions".equals(key)) addProperty(key, jsonAction.get(key).toString());
// if this is mergeChildren we need to update our property variable too, to deal with legacy values
if ("mergeChildren".equals(key)) _mergeChildren = jsonAction.optBoolean(key);
}
// try and build the query object
JSONObject jsonQuery = jsonAction.optJSONObject("query");
// check we got one
if (jsonQuery != null) {
// get the parameters
ArrayList<Parameter> inputs = getParameters(jsonQuery.optJSONArray("inputs"));
ArrayList<Parameter> outputs = getParameters(jsonQuery.optJSONArray("outputs"));
String sql = jsonQuery.optString("SQL");
boolean multiRow = jsonQuery.optBoolean("multiRow");
int databaseConnectionIndex = jsonQuery.optInt("databaseConnectionIndex");
// make the object
_query = new Query(inputs, outputs, sql, multiRow, databaseConnectionIndex);
}
// look for showLoading
_showLoading = jsonAction.optBoolean("showLoading");
// grab any successActions
JSONArray jsonChildDatabaseActions = jsonAction.optJSONArray("childDatabaseActions");
// if we had some
if (jsonChildDatabaseActions != null) {
// instantiate collection
_childDatabaseActions = new ArrayList<>();
// loop them
for (int i = 0; i < jsonChildDatabaseActions.length(); i++) {
// get one
JSONObject jsonChildDatabaseAction = jsonChildDatabaseActions.getJSONObject(i);
// instantiate and add to collection
_childDatabaseActions.add(new Database(rapidServlet, jsonChildDatabaseAction));
}
}
// grab any successActions
JSONArray jsonSuccessActions = jsonAction.optJSONArray("successActions");
// if we had some instantiate our collection
if (jsonSuccessActions != null) _successActions = Control.getActions(rapidServlet, jsonSuccessActions);
// grab any errorActions
JSONArray jsonErrorActions = jsonAction.optJSONArray("errorActions");
// if we had some instantiate our collection
if (jsonErrorActions != null) _errorActions = Control.getActions(rapidServlet, jsonErrorActions);
}
// this is used to get both input and output parameters
private ArrayList<Parameter> getParameters(JSONArray jsonParameters) throws JSONException {
// prepare return
ArrayList<Parameter> parameters = null;
// check
if (jsonParameters != null) {
// instantiate collection
parameters = new ArrayList<>();
// loop
for (int i = 0; i < jsonParameters.length(); i++) {
// instaniate member
Parameter parameter = new Parameter(
jsonParameters.getJSONObject(i).optString("itemId"),
jsonParameters.getJSONObject(i).optString("field")
);
// add member
parameters.add(parameter);
}
}
// return
return parameters;
}
// overrides
@Override
public List<Action> getChildActions() {
// initialise and populate on first get
if (_childActions == null) {
// our list of all child actions
_childActions = new ArrayList<>();
// add child success actions
if (_successActions != null) {
for (Action action : _successActions) _childActions.add(action);
}
// add child error actions
if (_errorActions != null) {
for (Action action : _errorActions) _childActions.add(action);
}
// add child error actions
if (_childDatabaseActions != null) {
for (Action action : _childDatabaseActions) _childActions.add(action);
}
}
return _childActions;
}
public String getLoadingJS(Page page, List<Parameter> parameters, boolean show) {
String js = "";
// check there are parameters
if (parameters != null) {
// loop the output parameters
for (int i = 0; i < parameters.size(); i++) {
// get the parameter
Parameter output = parameters.get(i);
// get the control the data is going into
Control control = page.getControl(output.getItemId());
// check the control still exists
if (control != null) {
if ("grid".equals(control.getType())) {
if (show) {
js += "$('#" + control.getId() + "').showLoading();\n";
} else {
js += "$('#" + control.getId() + "').hideLoading();\n";
}
}
}
}
}
return js;
}
// private function to get inputs into the query object, reused by child database actions
private String getInputsJavaScript(ServletContext servletContext, Application application, Page page, Query query) {
// assume it'll be an empty string
String js = "";
// if there is a query
if (query != null) {
// get the inputs from the query
List<Parameter> inputs = query.getInputs();
// if we were given some
if (inputs != null) {
// check there is at least one
if (inputs.size() > 0) {
// get the first itemId (this is the only one visible to the users)
String sourceItemId = inputs.get(0).getItemId();
js += "[";
// loop them
for (int i = 0; i < inputs.size(); i++) {
// get the parameter
Parameter parameter = inputs.get(i);
// get this item id
String itemId = parameter.getItemId();
// get this item field
String itemField = parameter.getField();
// if there was an id
if (itemId != null) {
// add the input item
js += "{";
if (query.getMultiRow() && itemId.equals(sourceItemId)) {
js += "field: '" + itemField + "'";
} else {
js += "id: '" + itemId + (itemField == null || "".equals(itemField) ? "" : "." + itemField) + "', ";
js += "value:" + Control.getDataJavaScript(servletContext, application, page, itemId, itemField);
}
js += "}";
// add comma if not last item
if (i < inputs.size() - 1) js += ", ";
} // got item
} // loop inputs
// close the array
js += "]";
// if this is a multirow query
if (query.getMultiRow()) {
// add the field-less get data for the first item the first parameter
js += ", '" + sourceItemId + "', " + Control.getDataJavaScript(servletContext, application, page, sourceItemId, null);
}
} // inputs > 0
} // got inputs
} // got query
// if we got no inputs set to null
if (!js.startsWith("[")) js = "null";
// return
return js;
}
// private function to get outputs into a string, reused by child database actions
private String getOutputsJavaScript(ServletContext servletContext, Application application, Page page, List<Parameter> outputs, String childName) {
// the outputs array we're going to make
String jsOutputs = "";
// any property outputs that must be done separately;
String jsPropertyOutputs = "";
// loop the output parameters
for (int i = 0; i < outputs.size(); i++) {
// get the parameter
Parameter output = outputs.get(i);
// get the id
String outputId = output.getItemId();
// get the id parts
String[] idParts = outputId.split("\\.");
// if there is more than 1 part we are dealing with set properties, for now just update the output id
if (idParts.length > 1) outputId = idParts[0];
// get the control the data is going into
Control outputControl = page.getControl(outputId);
// assume we found it
boolean pageControl = true;
// if not found in the page
if (outputControl == null) {
// try the application
outputControl = application.getControl(servletContext, outputId);
// set page control to false
pageControl = false;
}
// check we got one
if (outputControl == null) {
jsOutputs += " /* output not found for " + outputId + "*/ ";
} else {
// get any details we may have
String details = outputControl.getDetailsJavaScript(application, page);
// set to empty string or clean up
if (details == null) {
details = "";
} else {
// if this is a page control
if (pageControl) {
// the details will already be in the page so we can use the short form
details = outputControl.getId() + "details";
}
// add details property with json details
details = ", details: " + details;
}
// start the jsOutputs
jsOutputs += "{id: '" + outputControl.getId() + "', type: '" + outputControl.getType() + "', field: '" + output.getField() + "'" + details;
// if there are two parts this is a property
if (idParts.length > 1) {
// get the property from the second id part
String property = idParts[1];
// append the property
jsOutputs += ", property: '" + property + "'";
} // property / control check
// close the jsOutputs
jsOutputs += "},";
} // control found check
} // outputs loop
// remove the last comma from any conventional outputs
if (jsOutputs.length() > 0) jsOutputs = jsOutputs.substring(0, jsOutputs.length() - 1);
// wrap the outputs with their variable
jsOutputs = "var outputs" + childName + " = [" + jsOutputs + "]";
// if jsPropertyOutputs, add them before
if (jsPropertyOutputs.length() > 0) jsOutputs = jsPropertyOutputs.trim().replace("\n", "\n ") + "\n " + jsOutputs;
// return
return jsOutputs;
}
@Override
public String getJavaScript(RapidRequest rapidRequest, Application application, Page page, Control control, JSONObject jsonDetails) throws Exception {
String js = "";
if (_query != null) {
// get the rapid servlet
RapidHttpServlet rapidServlet = rapidRequest.getRapidServlet();
// get the sequence for this action requests so long-running early ones don't overwrite fast later ones (defined in databaseaction.xml)
js += "var sequence = getDatabaseActionSequence('" + getId() + "');\n";
// open the js function to get the input data
js += "var data = getDatabaseActionInputData(" + _query.getMultiRow() + ", ";
// get the inputs
js += getInputsJavaScript(rapidServlet.getServletContext(), application, page, _query);
// close the js function to get the input data
js += ");\n";
// drop in the query variable used to collect the inputs, and hold the sequence
js += "var query = { data: data, sequence: sequence };\n";
// assume no child queries
boolean childQueries = false;
// look for any _childDatabaseActions
if (_childDatabaseActions != null && _childDatabaseActions.size() > 0) {
// remember we have child queries
childQueries = true;
// add a collection into the parent
js += "query.childQueries = [];\n";
// count them
int i = 1;
// loop them
for (Database childDatabaseAction : _childDatabaseActions) {
// get the childQuery
Query childQuery = childDatabaseAction.getQuery();
// open function to get input data
js += "var childData" + i + " = getDatabaseActionInputData(" + childQuery.getMultiRow() + ", ";
// add inputs
js += getInputsJavaScript(rapidServlet.getServletContext(), application, page, childQuery);
// close the function
js += ");\n";
// create object
js += "var childQuery" + i + " = { data: childData" + i + ", index: " + (i - 1) + " };\n";
// add to query
js += "query.childQueries.push(childQuery" + i + ");\n";
// increment the counter
i ++;
}
}
// control can be null when the action is called from the page load
String controlParam = "";
if (control != null) controlParam = "&c=" + control.getId();
// get the outputs
List<Parameter> outputs = _query.getOutputs();
// get the js to hide the loading (if applicable)
if (_showLoading) js += getLoadingJS(page, outputs, true);
// stringify the query
js += "query = JSON.stringify(query);\n";
// open the ajax call
js += "$.ajax({ url : '~?a=" + application.getId() + "&v=" + application.getVersion() + "&p=" + page.getId() + controlParam + "&act=" + getId() + "', type: 'POST', contentType: 'application/json', dataType: 'json',\n";
js += " data: query,\n";
js += " error: function(server, status, message) {\n";
// hide the loading javascript (if applicable)
if (_showLoading) js += " " + getLoadingJS(page, outputs, false);
// add standard error actions with offline and working handling
js += getErrorActionsJavaScript(rapidRequest, application, page, control, jsonDetails, _errorActions);
// open success function
js += " success: function(data) {\n";
// hide the loading javascript (if applicable)
if (_showLoading) js += " " + getLoadingJS(page, outputs, false);
// open if data check
js += " if (data) {\n";
// check there are outputs
if (outputs != null) {
// if there are parent outputs
if (outputs.size() > 0) {
// add the parent outputs property
js += " " + getOutputsJavaScript(rapidServlet.getServletContext(), application, page, outputs, "") + ";\n";
// add indent
js += " ";
// if there are child queries, add child queries check
if (childQueries) js += "if (data.fields && data.fields.length > 0) {\n if (data.fields[0].indexOf('childAction') == 0) {\n Action_database(ev,'" + getId() + "', {sequence:data.sequence, fields:[], rows:[]}, outputs);\n } else {\n ";
// send them and the data to the database action (unless there are children and this parent has been skipped)
js += "Action_database(ev,'" + getId() + "', data, outputs);\n";
// close the extra child queries check
if (childQueries) js += " }\n }\n";
}
} // outputs null check
// if we are expecting child action results
// check for any child database actions
if (_childDatabaseActions != null) {
// loop them
for (int i = 0; i < _childDatabaseActions.size(); i++) {
// get the outputs
List<Parameter> childOutputs = _childDatabaseActions.get(i).getQuery().getOutputs();
// if it has out puts
if (childOutputs != null && childOutputs.size() > 0) {
// get the name of this child
String childName = "childAction" + (i + 1);
// get the outputs
js += " " + getOutputsJavaScript(rapidServlet.getServletContext(), application, page, childOutputs, childName) + ";\n";
// get the data
js += " Action_database(ev,'" + getId() + "', data, " + "outputs" + childName + ",'" + childName + "');\n";
} // outputs check
} // child action loop
} // child action check
// close if data check
js += " }\n";
// get the standardised JavaScript to hide any working page only if this action has no children
js += getWorkingPageHideJavaScript(jsonDetails, _successActions, " ");
// add any success actions
if (_successActions != null) {
for (Action action : _successActions) {
js += " " + action.getJavaScriptWithHeader(rapidRequest, application, page, control, jsonDetails).trim().replace("\n", "\n ") + "\n";
}
}
// close success function
js += " }\n";
// close ajax call
js += "});";
}
// return what we built
return js;
}
private String getJsonInputValue(JSONArray jsonFields, JSONArray jsonRow, String id) {
for (int j = 0; j < jsonFields.length(); j++) {
// get the id from the fields
String jsonId = jsonFields.optString(j);
// if the id we want matches this one
if (id.equalsIgnoreCase(jsonId)) {
// return the value
return jsonRow.optString(j,null);
}
}
return null;
}
public JSONObject doQuery(RapidRequest rapidRequest, JSONObject jsonAction, Application application, DataFactory df) throws Exception {
// place holder for the object we're going to return
JSONObject jsonData = null;
// get the rapidServlet
RapidHttpServlet rapidServlet = rapidRequest.getRapidServlet();
ServletContext context = rapidServlet.getServletContext();
// retrieve the sql
String sql = _query.getSQL();
// only if there is some sql is it worth going further
if (sql != null) {
// merge in any application parameters
sql = application.insertParameters(context, sql);
// get any json inputs
JSONObject jsonInputData = jsonAction.optJSONObject("data");
// initialise the parameters list
ArrayList<Parameters> parametersList = new ArrayList<>();
// populate the parameters from the inputs collection (we do this first as we use them as the cache key due to getting values from the session)
if (_query.getInputs() == null) {
// just add an empty parameters member if no inputs
parametersList.add(new Parameters());
} else {
// if there is input data
if (jsonInputData != null) {
// get any input fields
JSONArray jsonFields = jsonInputData.optJSONArray("fields");
// get any input rows
JSONArray jsonRows = jsonInputData.optJSONArray("rows");
// if we have fields and rows
if (jsonFields != null && jsonRows != null) {
// loop the input rows (only the top row if not multirow)
for (int i = 0; i < jsonRows.length() && (_query.getMultiRow() || i == 0); i ++) {
// get this jsonRow
JSONArray jsonRow = jsonRows.getJSONArray(i);
// make the parameters for this row
Parameters parameters = new Parameters();
// loop the query inputs
for (Parameter input : _query.getInputs()) {
// get the input id
String id = input.getItemId();
// get the input field
String field = input.getField();
// add field to id if present
if (field != null && !"".equals(field)) id += "." + field;
// retain the value
String value = null;
// if it looks like a control, or a system value (bit of extra safety checking)
if (id.indexOf("_C") > 0 || id.indexOf("System.") == 0) {
// check special cases
switch (id) {
case "System.device" :
// get the device from the request
value = rapidRequest.getDevice();
break;
case "System.user name" :
// get the user name from the session (don't trust the front end)
value = rapidRequest.getUserName();
break;
default :
// get the value from the json inputs
value = getJsonInputValue(jsonFields, jsonRow, id);
}
} else {
// didn't look like a control so check page parameters
if (rapidRequest.getPage() != null) {
// get page variables
Variables pageVariables = rapidRequest.getPage().getVariables();
// check for page parameters
if (pageVariables != null) {
// if this is one
if (pageVariables.contains(id)) {
// get the value
value = getJsonInputValue(jsonFields, jsonRow, id);
}
}
}
}
// if still null try the session
if (value == null) value = (String) rapidRequest.getSessionAttribute(input.getItemId());
// add the parameter
parameters.add(value);
}
// add the parameters to the list
parametersList.add(parameters);
} // row loop
} // input fields and rows check
} // input data check
} // query inputs check
// placeholder for the action cache
ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache();
// if an action cache was found
if (actionCache != null) {
// log that we found action cache
_logger.debug("Database action cache found");
// attempt to fetch data from the cache
jsonData = actionCache.get(application.getId(), getId(), parametersList.toString());
}
// unmap numbered numbered parameters
List<Parameter> originalInputs = _query.getInputs();
if (originalInputs == null) originalInputs = new ArrayList<>();
List<String> inputs = new ArrayList<>();
// populate it with nulls
for (int i = 0; i < originalInputs.size(); i++) {
Parameter input = originalInputs.get(i);
String inputName = input.getItemId();
if (!input.getField().isEmpty()) inputName += "." + input.getField();
inputs.add(inputName);
}
// if there were parameters in the list unmap and reset them
if (parametersList.size() > 0) parametersList.set(0, unmappedParameters(sql, parametersList.get(0), inputs, application, context));
sql = unspecifySqlSlots(sql);
// if there isn't a cache or no data was retrieved
if (jsonData == null) {
try {
// instantiate jsonData
jsonData = new JSONObject();
// fields collection
JSONArray jsonFields = new JSONArray();
// rows collection can start initialised
JSONArray jsonRows = new JSONArray();
// trim the sql
sql = sql.trim();
// check the verb
if (sql.toLowerCase().startsWith("select") || sql.toLowerCase().startsWith("with") || sql.toLowerCase().startsWith("exec")) {
// if select set readonly to true (makes for faster querying) - but not for SQLite as it throws an exception if done after the connection is established
if (sql.toLowerCase().startsWith("select") && !df.getConnectionAdapter().getConnectionString().toLowerCase().contains("sqlite")) df.setReadOnly(true);
// got fields indicator
boolean gotFields = false;
// loop the parameterList getting a result set for each parameters (input row)
for (Parameters parameters : parametersList) {
// get the result set!
ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);
// check we got one
if (rs != null) {
// date formatters we might need but only want to fetch / initialise once
SimpleDateFormat localDateFormatter = null;
SimpleDateFormat localDateTimeFormatter = null;
// assume results
boolean gotResults = true;
// get the statement
Statement st = rs.getStatement();
while (gotResults) {
// get this resultset's meta data for the field names
ResultSetMetaData rsmd = rs.getMetaData();
// loop the result set
while (rs.next()) {
// initialise the row
JSONArray jsonRow = new JSONArray();
// loop the columns
for (int i = 0; i < rsmd.getColumnCount(); i++) {
// add the field name to the fields collection if not done yet
if (!gotFields) jsonFields.put(rsmd.getColumnLabel(i + 1));
// get the value as a string
String value = rs.getString(i + 1);
// check for null
if (value == null) {
// put null
jsonRow.put(value);
} else {
// get the column type
int columnType = rsmd.getColumnType(i + 1);
// add the data to the row according to it's type
switch (columnType) {
case (Types.NUMERIC) :
jsonRow.put(rs.getDouble(i + 1));
break;
case (Types.INTEGER) :
jsonRow.put(rs.getInt(i + 1));
break;
case (Types.BIGINT) :
jsonRow.put(rs.getLong(i + 1));
break;
case (Types.FLOAT) :
jsonRow.put(rs.getFloat(i + 1));
break;
case (Types.DOUBLE) : case (Types.DECIMAL) :
jsonRow.put(rs.getDouble(i + 1));
break;
case (Types.DATE) :
Date date = rs.getDate(i + 1);
if (date == null) {
jsonRow.put(date);
} else {
if (localDateFormatter == null) localDateFormatter = rapidRequest.getRapidServlet().getLocalDateFormatter();
jsonRow.put(localDateFormatter.format(date));
}
break;
case (Types.TIMESTAMP) :
Timestamp timeStamp = rs.getTimestamp(i + 1);
if (timeStamp == null) {
jsonRow.put(timeStamp);
} else {
// check for 0 millseconds past midnight - a truncated date time (time zone offset is in minutes, multiplied by the number of millis in a minute modulus with number of millis in a day)
if ((timeStamp.getTime() - timeStamp.getTimezoneOffset() * 60000) % 86400000L == 0) {
// if so show just date
if (localDateFormatter == null) localDateFormatter = rapidRequest.getRapidServlet().getLocalDateFormatter();
jsonRow.put(localDateFormatter.format(timeStamp));
} else {
// show date and time
if (localDateTimeFormatter == null) localDateTimeFormatter = rapidRequest.getRapidServlet().getLocalDateTimeFormatter();
jsonRow.put(localDateTimeFormatter.format(timeStamp));
}
}
break;
default :
jsonRow.put(value);
}
}
}
// add the row to the rows collection
jsonRows.put(jsonRow);
// remember we now have our fields
gotFields = true;
}
// close the record set
rs.close();
// look for any more results
gotResults = st.getMoreResults();
// if we got some
if (gotResults) {
// move result set on
rs = st.getResultSet();
// clear fields collection
jsonFields = new JSONArray();
// clear rows collection can start initialised
jsonRows = new JSONArray();
}
} // got results loop
} // check rs
} // parameters list loop - not sure whether this ever called
} else {
// assume rows affected is 0
int rows = 0;
// sql check
if (sql.length() > 0) {
// perform update for all incoming parameters (one parameters collection for each row)
for (Parameters parameters : parametersList) {
rows += df.getPreparedUpdate(rapidRequest, sql, parameters);
}
// add a psuedo field
jsonFields.put("rows");
// create a row array
JSONArray jsonRow = new JSONArray();
// add the rows updated
jsonRow.put(rows);
// add the row we just made
jsonRows.put(jsonRow);
}
}
// add the fields to the data object
jsonData.put("fields", jsonFields);
// add the rows to the data object
jsonData.put("rows", jsonRows);
// check for any child database actions
if (_childDatabaseActions != null) {
// if there really are some
if (_childDatabaseActions.size() > 0) {
// a list of mergeChildrenFields
List<String> childFields = new ArrayList<>();
// look for any mergeChildrenFields
String childDataFields = getProperty("childDataFields");
// if we got some
if (childDataFields != null) {
// split them
String[] childDataFieldsParts = childDataFields.split(",");
// loop them
for (String childField : childDataFieldsParts) {
// trim
String childFieldTrim = childField.trim();
// add if we got something (avoid the blank)
childFields.add(childFieldTrim);
}
}
// get any child data
JSONArray jsonChildQueries = jsonAction.optJSONArray("childQueries");
// if there was some
if (jsonChildQueries != null) {
// loop
for (int i = 0; i < jsonChildQueries.length(); i++) {
// fetch the data
JSONObject jsonChildAction = jsonChildQueries.getJSONObject(i);
// read the index (the position of the child this related to
int index = jsonChildAction.getInt("index");
// get the relevant child action
Database childDatabaseAction = _childDatabaseActions.get(index);
// get the resultant child data
JSONObject jsonChildData = childDatabaseAction.doQuery(rapidRequest, jsonChildAction, application, df);
// prepare the merge child field name
String childFieldName = "childAction" + (i + 1);
// if we were given a child field name at this position, use that instead
if (childFields.size() > i) childFieldName = childFields.get(i);
// add a field for the results of this child action
jsonFields.put(childFieldName);
// if we are merging child data, which was the default before 2.4.4.1
if (_mergeChildren) {
// a map for indexes of matching fields between our parent and child
Map<Integer,Integer> fieldsMap = new HashMap<>();
// the child fields
JSONArray jsonChildFields = jsonChildData.getJSONArray("fields");
if (jsonChildFields != null) {
// loop the parent fields
for (int j = 0; j < jsonFields.length(); j++) {
// loop the child fields
for (int k = 0; k < jsonChildFields.length(); k++) {
// get parent field
String field = jsonFields.getString(j);
// get child field
String childField = jsonChildFields.getString(k);
// if both not null
if (field != null && childField != null) {
// check for match
if (field.toLowerCase().equals(childField.toLowerCase())) fieldsMap.put(j, k);
}
}
}
}
// if matching fields exists and not all columns are matched (stops simple queries like for drop down lookups merging)
if (fieldsMap.size() > 0 && fieldsMap.size() != jsonFields.length() - i - 1) {
// an object with a null value for when there is no match
Object nullObject = null;
// get the child rows
JSONArray jsonChildRows = jsonChildData.getJSONArray("rows");
// if we had some
if (jsonChildRows != null) {
// loop the parent rows
for (int j = 0; j < jsonRows.length(); j++) {
// get the parent row
JSONArray jsonRow = jsonRows.getJSONArray(j);
// make a new rows collection for the child subset
JSONArray jsonChildRowsSubset = new JSONArray();
// loop the child rows
for (int k =0; k < jsonChildRows.length(); k++) {
// get the child row
JSONArray jsonChildRow = jsonChildRows.getJSONArray(k);
// assume no matches
int matches = 0;
// loop the fields map
for (Integer l: fieldsMap.keySet()) {
// parent value
Object parentValue = null;
// get the value if there are enough
if (jsonRow.length() > l) parentValue = jsonRow.get(l);
// child value
Object childValue = null;
// get child value if present
if (jsonChildRow.length() > l) childValue= jsonChildRow.opt(fieldsMap.get(l));
// non null check
if (parentValue != null && childValue != null) {
// a string we will concert the child value to
String parentString = null;
// check the parent value type
if (parentValue.getClass() == String.class) {
parentString = (String) parentValue;
} else if (parentValue.getClass() == Integer.class) {
parentString = Integer.toString((Integer) parentValue);
} else if (parentValue.getClass() == Long.class) {
parentString = Long.toString((Long) parentValue);
} else if (parentValue.getClass() == Double.class) {
parentString = Double.toString((Double) parentValue);
} else if (parentValue.getClass() == Boolean.class) {
parentString = Boolean.toString((Boolean) parentValue);
}
// a string we will convert the child value to
String childString = null;
// check the parent value type
if (childValue.getClass() == String.class) {
childString = (String) childValue;
} else if (childValue.getClass() == Integer.class) {
childString = Integer.toString((Integer) childValue);
} else if (childValue.getClass() == Long.class) {
childString = Long.toString((Long) childValue);
} else if (childValue.getClass() == Double.class) {
childString = Double.toString((Double) childValue);
} else if (childValue.getClass() == Boolean.class) {
childString = Boolean.toString((Boolean) childValue);
}
// non null check
if (parentString != null && childString != null) {
// do the match!
if (parentString.equals(childString)) matches++;
}
} // values non null
} // field map loop
// if we got some matches for all the fields add this row to the subset
if (matches == fieldsMap.size()) jsonChildRowsSubset.put(jsonChildRow);
} // child row loop
// if our child subset has rows in it
if (jsonChildRowsSubset.length() > 0) {
// create a new childSubset object
JSONObject jsonChildDataSubset = new JSONObject();
// add the fields
jsonChildDataSubset.put("fields", jsonChildFields);
// add the subset of rows
jsonChildDataSubset.put("rows", jsonChildRowsSubset);
// add the child database action data subset
jsonRow.put(jsonChildDataSubset);
} else {
// add an empty cell
jsonRow.put(nullObject);
}
} // parent row loop
} // jsonChildRows null check
} else {
// add a top row if we need one
if (jsonRows.length() == 0) jsonRows.put(new JSONArray());
// get the top row - only this one is used when the child data is retrieved
JSONArray jsonRow = jsonRows.getJSONArray(0);
// add the child database action data
jsonRow.put(jsonChildData);
} // matching fields check
} else {
// add a top row if we need one
if (jsonRows.length() == 0) jsonRows.put(new JSONArray());
// get the top row - only this one is used when the child data is retrieved
JSONArray jsonRow = jsonRows.getJSONArray(0);
// add the child database action data
jsonRow.put(jsonChildData);
} // child merge check
} // jsonChildQueries loop
} // jsonChildQueries null check
} // _childDatabaseActions size > 0
} // _childDatabaseActions not null
// cache if in use
if (actionCache != null) actionCache.put(application.getId(), getId(), parametersList.toString(), jsonData);
} catch (Exception ex) {
// log the error
_logger.error(ex);
// close the data factory and silently fail
try { df.close(); } catch (Exception ex2) {}
// only throw if no action cache
if (actionCache == null) {
throw ex;
} else {
_logger.debug("Error not shown to user due to cache : " + ex.getMessage());
}
} // jsonData not null
} // jsonData == null
} // got sql
return jsonData;
}
// finds ? followed by a name optionally in quotes, or ? followed by a name of lower and/or upper case letters - we'll find any of these first and convert them to numbers, only limitation is names outside of quotes can't start with numbers
private static String _namedParameterSlotRegex = "(\\?\"[^\"]+\")|(\\?(?=[a-zA-Z])\\w*)";
// finds ? followed by a name in quotes, or ? followed by 0 or more numbers, or ? on their own
private static String _parameterSlotRegex = "(\\?\"[^\"]+\")|(\\?\\w\\S*)|\\?";
// returns all parameters for the sql by finding any ?'s followed by numbers/names and creating a longer parameter list populated with those mapped
public static Parameters unmappedParameters(String sql, Parameters oldParameters, List<String> inputIds, Application application, ServletContext context) throws SQLException {
// we first use this to find parameters with names and convert them into numbers
Map<String, Integer> parameterIndexesByControlName = new HashMap<>();
// if there were any ?'s followed by names in the sql
if (Pattern.compile(_namedParameterSlotRegex).matcher(sql).find()) {
// loop the inputs to see which are in the sql and populate the map
for (int inputIndex = 0; inputIndex < inputIds.size(); inputIndex++) {
// the id of the control for this input
String id = inputIds.get(inputIndex);
if (id.startsWith("System.")) {
String name = "\"" + id + "\"";
parameterIndexesByControlName.put(name, inputIndex);
} else {
String[] parts = id.split("\\.");
String controlId = parts[0];
Control control = application.getControl(context, controlId);
if (control != null) {
String name = control.getName();
id = id.replaceAll(".+\\.", name + ".");
if (parts.length > 1) name += "." + parts[1].toLowerCase().replace(" ", "");
for (int idIndex = 2; idIndex < parts.length; idIndex++) name += "." + parts[idIndex];
parameterIndexesByControlName.put("\"" + name + "\"", inputIndex);
if (!name.contains(" ")) parameterIndexesByControlName.put(name, inputIndex);
}
}
}
}
// remove comment blocks
String[] stringParts = sql.split("\\/\\*|\\*\\/");
sql = "";
for (int partIndex = 0; partIndex < stringParts.length; partIndex += 2) {
sql += stringParts[partIndex];
}
// remove quote blocks
stringParts = sql.split("'");
sql = "";
for (int partIndex = 0; partIndex < stringParts.length; partIndex += 2) {
sql += stringParts[partIndex];
}
// named variables should have been replaced so use the number finding pattern
Matcher matcher = Pattern.compile(_parameterSlotRegex).matcher(sql);
// a probably longer list of parameters we'll be making using the numbers or names after the ?'s
Parameters newParameters = new Parameters();
// the old parameters we want to map out to the new ones, we use a set to remove the ones we've done until they all are
Set<Integer> oldParametersNumbers = new HashSet<>();
// loop the original inputs to populate the set
for (int number = 1; number <= oldParameters.size(); number++) {
oldParametersNumbers.add(number);
}
// a running count of ?'s without a number/name
int unspecifiedSlots = 0;
// loop the ?'s and their number/name
while (matcher.find()) {
// get what the regex found: the ? followed by either numbers or letters
String slot = matcher.group();
// replace any following commas or closing brackets which would have been included by the regex when we were looking for names
slot = slot.replace(",", "").replace(")", "");
int parameterIndex = unspecifiedSlots;
// if there is only a ? this slot is unspecified
if (slot.length() == 1) {
unspecifiedSlots++;
} else {
// get the number/name after the ?
String specifier = slot.substring(1);
// check if all numbers
if (specifier.matches("\\d+")) {
// use the number after the ? as the index to find the parameter
parameterIndex = Integer.parseInt(specifier) - 1;
} else {
//
String[] parts = specifier.split("\\.");
String name = parts[0];
if (parts.length > 1) name += "." + parts[1].toLowerCase().replace(" ", "");
for (int idIndex = 2; idIndex < parts.length; idIndex++) name += "." + parts[idIndex];
// use the letters after the ? as the key to find the parameter
parameterIndex = parameterIndexesByControlName.get(name);
}
}
// if we have an input at this index in the original inputs
if (parameterIndex < oldParameters.size()) {
//
newParameters.add(oldParameters.get(parameterIndex));
oldParametersNumbers.remove(parameterIndex + 1);
} else {
throw new SQLException("Parameter " + (parameterIndex + 1) + " not provided in inputs list");
}
} // slot loop
// if there are any parameters left that weren't used by the query
if (oldParametersNumbers.size() > 0) {
int firstUnusedInputNumber = oldParametersNumbers.iterator().next();
throw new SQLException("Input " + firstUnusedInputNumber + " not used");
}
// if not all parameters got mapped
if (oldParameters.size() > newParameters.size()) {
// send back the originals
return oldParameters;
} else {
// send the new ones!
return newParameters;
}
}
// returns sql with the numbers/names after the ? removed
public static String unspecifySqlSlots(String sql) {
sql = sql + " ";
String[] stringParts = sql.split("'");
sql = stringParts[0].replaceAll(_parameterSlotRegex, "\\?");
for (int partIndex = 1; partIndex < stringParts.length; partIndex++) {
if (partIndex % 2 == 0) {
sql += "'" + stringParts[partIndex].replaceAll(_parameterSlotRegex, "\\?");
} else {
sql += "'" + stringParts[partIndex];
}
}
return sql;
}
@Override
public JSONObject doAction(RapidRequest rapidRequest, JSONObject jsonAction) throws Exception {
// This code could be optimised to only return required data, according to the outputs collection
_logger.trace("Database action : " + jsonAction);
// fetch the application
Application application = rapidRequest.getApplication();
// fetch the page
Page page = rapidRequest.getPage();
// fetch in the sequence
int sequence = jsonAction.optInt("sequence", 1);
// place holder for the object we're going to return
JSONObject jsonData = null;
// only if there is a query object, application, and page, and connection
if (_query != null && application != null && page != null && application.getDatabaseConnections() != null && application.getDatabaseConnections().size() > _query.getDatabaseConnectionIndex()) {
// get the relevant connection
DatabaseConnection databaseConnection = application.getDatabaseConnections().get(_query.getDatabaseConnectionIndex());
// get the connection adapter
ConnectionAdapter ca = databaseConnection.getConnectionAdapter(rapidRequest.getRapidServlet().getServletContext(), application);
// placeholder for data factory
DataFactory df = null;
// if this is sqlite
if (databaseConnection.getConnectionString().toLowerCase().contains("sqlite")) {
// instantiate a SQLite data factory with autocommit = false;
df = new SQLiteDataFactory(ca, false);
} else {
// instantiate a data factory with autocommit = false;
df = new DataFactory(ca, false);
}
// use the reusable do query function (so child database actions can use it as well)
jsonData = doQuery(rapidRequest, jsonAction, application, df);
// commit the data factory transaction
df.commit();
// close the data factory
df.close();
} // got query, app, and page
// if it's null instantiate one
if (jsonData == null) jsonData = new JSONObject();
// add it back to the data object we're returning
jsonData.put("sequence", sequence);
return jsonData;
}
@Override
public boolean isWebService() {
return true;
}
}
| Fixed to database action unspecify numbered parameter method | src/com/rapid/actions/Database.java | Fixed to database action unspecify numbered parameter method | <ide><path>rc/com/rapid/actions/Database.java
<ide> private static String _namedParameterSlotRegex = "(\\?\"[^\"]+\")|(\\?(?=[a-zA-Z])\\w*)";
<ide> // finds ? followed by a name in quotes, or ? followed by 0 or more numbers, or ? on their own
<ide> private static String _parameterSlotRegex = "(\\?\"[^\"]+\")|(\\?\\w\\S*)|\\?";
<add> // finds ? followed by a number
<add> private static String _unspecifySlotsRegex = "(\\?\\d*)";
<ide>
<ide> // returns all parameters for the sql by finding any ?'s followed by numbers/names and creating a longer parameter list populated with those mapped
<ide> public static Parameters unmappedParameters(String sql, Parameters oldParameters, List<String> inputIds, Application application, ServletContext context) throws SQLException {
<ide> }
<ide> }
<ide>
<del> // returns sql with the numbers/names after the ? removed
<add> // returns sql with any numbers after the ? removed (used after the name number replacement above)
<ide> public static String unspecifySqlSlots(String sql) {
<add> // add an extra space to the end - something to do with ensuring there are an even number of parts when we split on the ' below
<ide> sql = sql + " ";
<add> // split on the single quote - we only want to replace parameters outside of them
<ide> String[] stringParts = sql.split("'");
<del> sql = stringParts[0].replaceAll(_parameterSlotRegex, "\\?");
<add> // replace the first part of the sql which goes up to the first single quote
<add> sql = stringParts[0].replaceAll(_unspecifySlotsRegex, "\\?");
<add> // loop the remaining parts from index 1 onwards
<ide> for (int partIndex = 1; partIndex < stringParts.length; partIndex++) {
<add> // if this is an even numbered part
<ide> if (partIndex % 2 == 0) {
<del> sql += "'" + stringParts[partIndex].replaceAll(_parameterSlotRegex, "\\?");
<add> // its outside of a quoted string so replace the ? numbers
<add> sql += "'" + stringParts[partIndex].replaceAll(_unspecifySlotsRegex, "\\?");
<ide> } else {
<add> // its within quotes so add back as it was
<ide> sql += "'" + stringParts[partIndex];
<ide> }
<ide> } |
|
Java | mit | 7f40753fcd2eea03221272829272dabd4f286f58 | 0 | CS2103JAN2017-F14-B2/main,CS2103JAN2017-F14-B2/main,CS2103JAN2017-F14-B2/main | package seedu.task.logic.commandlibrary;
import static seedu.task.commons.core.Messages.MESSAGE_COMMAND_DOES_NOT_EXIST;
import static seedu.task.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.HashMap;
import seedu.task.commons.core.EventsCenter;
import seedu.task.commons.events.ui.QueryUnknownCommandEvent;
import seedu.task.logic.commands.AddCommand;
import seedu.task.logic.commands.ClearCommand;
import seedu.task.logic.commands.Command;
import seedu.task.logic.commands.DeleteCommand;
import seedu.task.logic.commands.DoneCommand;
import seedu.task.logic.commands.EditCommand;
import seedu.task.logic.commands.ExitCommand;
import seedu.task.logic.commands.FindCommand;
//import seedu.task.logic.commands.FindDateCommand;
import seedu.task.logic.commands.FindExactCommand;
import seedu.task.logic.commands.GetGoogleCalendarCommand;
import seedu.task.logic.commands.HelpCommand;
import seedu.task.logic.commands.HelpFormatCommand;
import seedu.task.logic.commands.IncorrectCommand;
//import seedu.task.logic.commands.ListByDoneCommand;
//import seedu.task.logic.commands.ListByNotDoneCommand;
import seedu.task.logic.commands.ListByTagCommand;
import seedu.task.logic.commands.ListCommand;
import seedu.task.logic.commands.LoadCommand;
import seedu.task.logic.commands.PostGoogleCalendarCommand;
import seedu.task.logic.commands.QuickAddCommand;
import seedu.task.logic.commands.RedoCommand;
import seedu.task.logic.commands.SaveCommand;
import seedu.task.logic.commands.SelectCommand;
import seedu.task.logic.commands.ThemeChangeCommand;
import seedu.task.logic.commands.UndoCommand;
import seedu.task.logic.commands.UndoneCommand;
import seedu.task.logic.parser.AddCommandParser;
import seedu.task.logic.parser.ClearCommandParser;
import seedu.task.logic.parser.CommandParser;
import seedu.task.logic.parser.DeleteCommandParser;
import seedu.task.logic.parser.DoneCommandParser;
import seedu.task.logic.parser.EditCommandParser;
import seedu.task.logic.parser.ExitCommandParser;
import seedu.task.logic.parser.FindCommandParser;
//import seedu.task.logic.parser.FindDateCommandParser;
import seedu.task.logic.parser.FindExactCommandParser;
import seedu.task.logic.parser.GetGoogleCalendarCommandParser;
import seedu.task.logic.parser.HelpCommandParser;
import seedu.task.logic.parser.HelpFormatCommandParser;
//import seedu.task.logic.parser.ListByDoneCommandParser;
//import seedu.task.logic.parser.ListByNotDoneCommandParser;
import seedu.task.logic.parser.ListByTagCommandParser;
import seedu.task.logic.parser.ListCommandParser;
import seedu.task.logic.parser.LoadCommandParser;
import seedu.task.logic.parser.PostGoogleCalendarCommandParser;
import seedu.task.logic.parser.QuickAddCommandParser;
import seedu.task.logic.parser.RedoCommandParser;
import seedu.task.logic.parser.SaveCommandParser;
import seedu.task.logic.parser.SelectCommandParser;
import seedu.task.logic.parser.ThemeChangeCommandParser;
import seedu.task.logic.parser.UndoCommandParser;
import seedu.task.logic.parser.UndoneCommandParser;
//@@author A0142487Y
public class CommandLibrary {
private static CommandLibrary instance = null;
private static HashMap<String, CommandInstance> commandTable;
protected CommandLibrary() {
init();
}
public static CommandLibrary getInstance() {
if (instance == null) {
instance = new CommandLibrary();
}
return instance;
}
/**
* To initialize the hashmap and necessary variables
*/
private static void init() {
commandTable = new HashMap<>();
commandTable.put(AddCommand.COMMAND_WORD_1, new CommandInstance(AddCommand.COMMAND_WORD_1,
new AddCommandParser() , AddCommand.MESSAGE_USAGE));
commandTable.put(ClearCommand.COMMAND_WORD_1, new CommandInstance(ClearCommand.COMMAND_WORD_1,
new ClearCommandParser() , ClearCommand.MESSAGE_USAGE));
commandTable.put(DeleteCommand.COMMAND_WORD_1, new CommandInstance(DeleteCommand.COMMAND_WORD_1,
new DeleteCommandParser() , DeleteCommand.MESSAGE_USAGE));
commandTable.put(DoneCommand.COMMAND_WORD_1, new CommandInstance(DoneCommand.COMMAND_WORD_1,
new DoneCommandParser() , DoneCommand.MESSAGE_USAGE));
commandTable.put(DoneCommand.COMMAND_WORD_2, new CommandInstance(DoneCommand.COMMAND_WORD_1,
new DoneCommandParser() , DoneCommand.MESSAGE_USAGE));
commandTable.put(EditCommand.COMMAND_WORD_1, new CommandInstance(EditCommand.COMMAND_WORD_1,
new EditCommandParser() , EditCommand.MESSAGE_USAGE));
commandTable.put(ExitCommand.COMMAND_WORD_1, new CommandInstance(ExitCommand.COMMAND_WORD_1,
new ExitCommandParser() , ExitCommand.MESSAGE_USAGE));
commandTable.put(FindCommand.COMMAND_WORD_1, new CommandInstance(FindCommand.COMMAND_WORD_1,
new FindCommandParser() , FindCommand.MESSAGE_USAGE));
commandTable.put(FindCommand.COMMAND_WORD_2, new CommandInstance(FindCommand.COMMAND_WORD_1,
new FindCommandParser() , FindCommand.MESSAGE_USAGE));
commandTable.put(FindExactCommand.COMMAND_WORD_1, new CommandInstance(FindExactCommand.COMMAND_WORD_1,
new FindExactCommandParser(), FindExactCommand.MESSAGE_USAGE));
commandTable.put(FindExactCommand.COMMAND_WORD_2, new CommandInstance(FindExactCommand.COMMAND_WORD_1,
new FindExactCommandParser(), FindExactCommand.MESSAGE_USAGE));
commandTable.put(FindExactCommand.COMMAND_WORD_3, new CommandInstance(FindExactCommand.COMMAND_WORD_1,
new FindExactCommandParser(), FindExactCommand.MESSAGE_USAGE));
commandTable.put(FindExactCommand.COMMAND_WORD_4, new CommandInstance(FindExactCommand.COMMAND_WORD_1,
new FindExactCommandParser(), FindExactCommand.MESSAGE_USAGE));
commandTable.put(GetGoogleCalendarCommand.COMMAND_WORD_1,
new CommandInstance(GetGoogleCalendarCommand.COMMAND_WORD_1,
new GetGoogleCalendarCommandParser(), GetGoogleCalendarCommand.MESSAGE_USAGE));
commandTable.put(GetGoogleCalendarCommand.COMMAND_WORD_2,
new CommandInstance(GetGoogleCalendarCommand.COMMAND_WORD_1,
new GetGoogleCalendarCommandParser(), GetGoogleCalendarCommand.MESSAGE_USAGE));
commandTable.put(HelpCommand.COMMAND_WORD_1, new CommandInstance(HelpCommand.COMMAND_WORD_1,
new HelpCommandParser(), HelpCommand.MESSAGE_USAGE));
commandTable.put(HelpCommand.COMMAND_WORD_2, new CommandInstance(HelpCommand.COMMAND_WORD_1,
new HelpCommandParser(), HelpCommand.MESSAGE_USAGE));
commandTable.put(HelpCommand.COMMAND_WORD_3, new CommandInstance(HelpCommand.COMMAND_WORD_1,
new HelpCommandParser(), HelpCommand.MESSAGE_USAGE));
commandTable.put(HelpCommand.COMMAND_WORD_4, new CommandInstance(HelpCommand.COMMAND_WORD_1,
new HelpCommandParser(), HelpCommand.MESSAGE_USAGE));
commandTable.put(HelpFormatCommand.COMMAND_WORD_1, new CommandInstance(HelpFormatCommand.COMMAND_WORD_1,
new HelpFormatCommandParser(), HelpFormatCommand.MESSAGE_USAGE));
commandTable.put(HelpFormatCommand.COMMAND_WORD_2, new CommandInstance(HelpFormatCommand.COMMAND_WORD_1,
new HelpFormatCommandParser(), HelpFormatCommand.MESSAGE_USAGE));
commandTable.put(HelpFormatCommand.COMMAND_WORD_3, new CommandInstance(HelpFormatCommand.COMMAND_WORD_1,
new HelpFormatCommandParser(), HelpFormatCommand.MESSAGE_USAGE));
commandTable.put(HelpFormatCommand.COMMAND_WORD_4, new CommandInstance(HelpFormatCommand.COMMAND_WORD_1,
new HelpFormatCommandParser(), HelpFormatCommand.MESSAGE_USAGE));
// commandTable.put(ListByDoneCommand.COMMAND_WORD_1, new CommandInstance(ListByDoneCommand.COMMAND_WORD_1,
// new ListByDoneCommandParser(), ListByDoneCommand.MESSAGE_USAGE));
// commandTable.put(ListByDoneCommand.COMMAND_WORD_2, new CommandInstance(ListByDoneCommand.COMMAND_WORD_1,
// new ListByDoneCommandParser(), ListByDoneCommand.MESSAGE_USAGE));
//
// commandTable.put(ListByNotDoneCommand.COMMAND_WORD_1, new CommandInstance(ListByNotDoneCommand.COMMAND_WORD_1,
// new ListByNotDoneCommandParser(), ListByNotDoneCommand.MESSAGE_USAGE));
// commandTable.put(ListByNotDoneCommand.COMMAND_WORD_2, new CommandInstance(ListByNotDoneCommand.COMMAND_WORD_1,
// new ListByNotDoneCommandParser(), ListByNotDoneCommand.MESSAGE_USAGE));
// commandTable.put(ListByNotDoneCommand.COMMAND_WORD_3, new CommandInstance(ListByNotDoneCommand.COMMAND_WORD_1,
// new ListByNotDoneCommandParser(), ListByNotDoneCommand.MESSAGE_USAGE));
commandTable.put(ListByTagCommand.COMMAND_WORD_1, new CommandInstance(ListByTagCommand.COMMAND_WORD_1,
new ListByTagCommandParser(), ListByTagCommand.MESSAGE_USAGE));
commandTable.put(ListByTagCommand.COMMAND_WORD_2, new CommandInstance(ListByTagCommand.COMMAND_WORD_1,
new ListByTagCommandParser(), ListByTagCommand.MESSAGE_USAGE));
commandTable.put(ListByTagCommand.COMMAND_WORD_3, new CommandInstance(ListByTagCommand.COMMAND_WORD_1,
new ListByTagCommandParser(), ListByTagCommand.MESSAGE_USAGE));
commandTable.put(ListByTagCommand.COMMAND_WORD_4, new CommandInstance(ListByTagCommand.COMMAND_WORD_1,
new ListByTagCommandParser(), ListByTagCommand.MESSAGE_USAGE));
commandTable.put(ListCommand.COMMAND_WORD_1, new CommandInstance(ListCommand.COMMAND_WORD_1,
new ListCommandParser(), ListCommand.MESSAGE_USAGE));
commandTable.put(ListCommand.COMMAND_WORD_2, new CommandInstance(ListCommand.COMMAND_WORD_1,
new ListCommandParser(), ListCommand.MESSAGE_USAGE));
commandTable.put(ListCommand.COMMAND_WORD_3, new CommandInstance(ListCommand.COMMAND_WORD_1,
new ListCommandParser(), ListCommand.MESSAGE_USAGE));
commandTable.put(LoadCommand.COMMAND_WORD_1, new CommandInstance(LoadCommand.COMMAND_WORD_1,
new LoadCommandParser(), LoadCommand.MESSAGE_USAGE));
commandTable.put(PostGoogleCalendarCommand.COMMAND_WORD_1,
new CommandInstance(PostGoogleCalendarCommand.COMMAND_WORD_1,
new PostGoogleCalendarCommandParser(), PostGoogleCalendarCommand.MESSAGE_USAGE));
commandTable.put(PostGoogleCalendarCommand.COMMAND_WORD_2,
new CommandInstance(PostGoogleCalendarCommand.COMMAND_WORD_1,
new PostGoogleCalendarCommandParser(), PostGoogleCalendarCommand.MESSAGE_USAGE));
commandTable.put(QuickAddCommand.COMMAND_WORD_1, new CommandInstance(QuickAddCommand.COMMAND_WORD_1,
new QuickAddCommandParser() , QuickAddCommand.MESSAGE_USAGE));
commandTable.put(RedoCommand.COMMAND_WORD_1, new CommandInstance(RedoCommand.COMMAND_WORD_1,
new RedoCommandParser(), RedoCommand.MESSAGE_USAGE));
commandTable.put(SaveCommand.COMMAND_WORD_1, new CommandInstance(SaveCommand.COMMAND_WORD_1,
new SaveCommandParser(), SaveCommand.MESSAGE_USAGE));
commandTable.put(SelectCommand.COMMAND_WORD_1, new CommandInstance(SelectCommand.COMMAND_WORD_1,
new SelectCommandParser(), SelectCommand.MESSAGE_USAGE));
commandTable.put(SelectCommand.COMMAND_WORD_2, new CommandInstance(SelectCommand.COMMAND_WORD_1,
new SelectCommandParser(), SelectCommand.MESSAGE_USAGE));
commandTable.put(ThemeChangeCommand.COMMAND_WORD_1, new CommandInstance(ThemeChangeCommand.COMMAND_WORD_1,
new ThemeChangeCommandParser(), ThemeChangeCommand.MESSAGE_USAGE));
commandTable.put(UndoCommand.COMMAND_WORD_1, new CommandInstance(UndoCommand.COMMAND_WORD_1,
new UndoCommandParser(), UndoCommand.MESSAGE_USAGE));
commandTable.put(UndoCommand.COMMAND_WORD_2, new CommandInstance(UndoCommand.COMMAND_WORD_1,
new UndoCommandParser(), UndoCommand.MESSAGE_USAGE));
commandTable.put(UndoneCommand.COMMAND_WORD_1, new CommandInstance(UndoneCommand.COMMAND_WORD_1,
new UndoneCommandParser(), UndoneCommand.MESSAGE_USAGE));
commandTable.put(UndoneCommand.COMMAND_WORD_2, new CommandInstance(UndoneCommand.COMMAND_WORD_1,
new UndoneCommandParser(), UndoneCommand.MESSAGE_USAGE));
}
/**
*
* @param commandWord
* @param arguments
* @return Returns the correct command with the correct arguments
*/
public Command getCorrectCommand(String commandWord, String arguments) {
if (!commandTable.containsKey(commandWord)) {
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
return commandTable.get(commandWord).commandParser.parse(arguments.trim());
}
public String getCommandUsage(String commandWord) {
if (!commandTable.containsKey(commandWord)) {
EventsCenter.getInstance().post(new QueryUnknownCommandEvent());
return String.format(MESSAGE_COMMAND_DOES_NOT_EXIST, commandWord);
}
return commandTable.get(commandWord).getCommandUsage();
}
protected static class CommandInstance {
private String commandKey;
private String commandUsage;
private CommandParser commandParser;
protected CommandInstance(String commandKey, CommandParser commandParser, String commandUsage) {
this.commandKey = commandKey;
this.commandParser = commandParser;
this.commandUsage = commandUsage;
}
public String getCommandKey() {
return this.commandKey;
}
public CommandParser getCommandParser() {
return this.commandParser;
}
public String getCommandUsage() {
return this.commandUsage;
}
}
public static HashMap<String, CommandInstance> getCommandTable() {
return commandTable;
}
}
| src/main/java/seedu/task/logic/commandlibrary/CommandLibrary.java | package seedu.task.logic.commandlibrary;
import static seedu.task.commons.core.Messages.MESSAGE_COMMAND_DOES_NOT_EXIST;
import static seedu.task.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.HashMap;
import seedu.task.commons.core.EventsCenter;
import seedu.task.commons.events.ui.QueryUnknownCommandEvent;
import seedu.task.logic.commands.AddCommand;
import seedu.task.logic.commands.ClearCommand;
import seedu.task.logic.commands.Command;
import seedu.task.logic.commands.DeleteCommand;
import seedu.task.logic.commands.DoneCommand;
import seedu.task.logic.commands.EditCommand;
import seedu.task.logic.commands.ExitCommand;
import seedu.task.logic.commands.FindCommand;
//import seedu.task.logic.commands.FindDateCommand;
import seedu.task.logic.commands.FindExactCommand;
import seedu.task.logic.commands.GetGoogleCalendarCommand;
import seedu.task.logic.commands.HelpCommand;
import seedu.task.logic.commands.HelpFormatCommand;
import seedu.task.logic.commands.IncorrectCommand;
//import seedu.task.logic.commands.ListByDoneCommand;
//import seedu.task.logic.commands.ListByNotDoneCommand;
import seedu.task.logic.commands.ListByTagCommand;
import seedu.task.logic.commands.ListCommand;
import seedu.task.logic.commands.LoadCommand;
import seedu.task.logic.commands.PostGoogleCalendarCommand;
import seedu.task.logic.commands.QuickAddCommand;
import seedu.task.logic.commands.RedoCommand;
import seedu.task.logic.commands.SaveCommand;
import seedu.task.logic.commands.SelectCommand;
import seedu.task.logic.commands.ThemeChangeCommand;
import seedu.task.logic.commands.UndoCommand;
import seedu.task.logic.commands.UndoneCommand;
import seedu.task.logic.parser.AddCommandParser;
import seedu.task.logic.parser.ClearCommandParser;
import seedu.task.logic.parser.CommandParser;
import seedu.task.logic.parser.DeleteCommandParser;
import seedu.task.logic.parser.DoneCommandParser;
import seedu.task.logic.parser.EditCommandParser;
import seedu.task.logic.parser.ExitCommandParser;
import seedu.task.logic.parser.FindCommandParser;
//import seedu.task.logic.parser.FindDateCommandParser;
import seedu.task.logic.parser.FindExactCommandParser;
import seedu.task.logic.parser.GetGoogleCalendarCommandParser;
import seedu.task.logic.parser.HelpCommandParser;
import seedu.task.logic.parser.HelpFormatCommandParser;
//import seedu.task.logic.parser.ListByDoneCommandParser;
//import seedu.task.logic.parser.ListByNotDoneCommandParser;
import seedu.task.logic.parser.ListByTagCommandParser;
import seedu.task.logic.parser.ListCommandParser;
import seedu.task.logic.parser.LoadCommandParser;
import seedu.task.logic.parser.PostGoogleCalendarCommandParser;
import seedu.task.logic.parser.QuickAddCommandParser;
import seedu.task.logic.parser.RedoCommandParser;
import seedu.task.logic.parser.SaveCommandParser;
import seedu.task.logic.parser.SelectCommandParser;
import seedu.task.logic.parser.ThemeChangeCommandParser;
import seedu.task.logic.parser.UndoCommandParser;
import seedu.task.logic.parser.UndoneCommandParser;
//@@author A0142487Y
public class CommandLibrary {
private static CommandLibrary instance = null;
private static HashMap<String, CommandInstance> commandTable;
protected CommandLibrary() {
init();
}
public static CommandLibrary getInstance() {
if (instance == null) {
instance = new CommandLibrary();
}
return instance;
}
/**
* To initialize the hashmap and necessary variables
*/
private static void init() {
commandTable = new HashMap<>();
commandTable.put(AddCommand.COMMAND_WORD_1, new CommandInstance(AddCommand.COMMAND_WORD_1,
new AddCommandParser() , AddCommand.MESSAGE_USAGE));
commandTable.put(ClearCommand.COMMAND_WORD_1, new CommandInstance(ClearCommand.COMMAND_WORD_1,
new ClearCommandParser() , ClearCommand.MESSAGE_USAGE));
commandTable.put(DeleteCommand.COMMAND_WORD_1, new CommandInstance(DeleteCommand.COMMAND_WORD_1,
new DeleteCommandParser() , DeleteCommand.MESSAGE_USAGE));
commandTable.put(DoneCommand.COMMAND_WORD_1, new CommandInstance(DoneCommand.COMMAND_WORD_1,
new DoneCommandParser() , DoneCommand.MESSAGE_USAGE));
commandTable.put(DoneCommand.COMMAND_WORD_2, new CommandInstance(DoneCommand.COMMAND_WORD_1,
new DoneCommandParser() , DoneCommand.MESSAGE_USAGE));
commandTable.put(EditCommand.COMMAND_WORD_1, new CommandInstance(EditCommand.COMMAND_WORD_1,
new EditCommandParser() , EditCommand.MESSAGE_USAGE));
commandTable.put(ExitCommand.COMMAND_WORD_1, new CommandInstance(ExitCommand.COMMAND_WORD_1,
new ExitCommandParser() , ExitCommand.MESSAGE_USAGE));
commandTable.put(FindCommand.COMMAND_WORD_1, new CommandInstance(FindCommand.COMMAND_WORD_1,
new FindCommandParser() , FindCommand.MESSAGE_USAGE));
commandTable.put(FindCommand.COMMAND_WORD_2, new CommandInstance(FindCommand.COMMAND_WORD_1,
new FindCommandParser() , FindCommand.MESSAGE_USAGE));
commandTable.put(FindExactCommand.COMMAND_WORD_1, new CommandInstance(FindExactCommand.COMMAND_WORD_1,
new FindExactCommandParser(), FindExactCommand.MESSAGE_USAGE));
commandTable.put(FindExactCommand.COMMAND_WORD_2, new CommandInstance(FindExactCommand.COMMAND_WORD_1,
new FindExactCommandParser(), FindExactCommand.MESSAGE_USAGE));
commandTable.put(FindExactCommand.COMMAND_WORD_3, new CommandInstance(FindExactCommand.COMMAND_WORD_1,
new FindExactCommandParser(), FindExactCommand.MESSAGE_USAGE));
commandTable.put(FindExactCommand.COMMAND_WORD_4, new CommandInstance(FindExactCommand.COMMAND_WORD_1,
new FindExactCommandParser(), FindExactCommand.MESSAGE_USAGE));
commandTable.put(GetGoogleCalendarCommand.COMMAND_WORD_1,
new CommandInstance(GetGoogleCalendarCommand.COMMAND_WORD_1,
new GetGoogleCalendarCommandParser(), GetGoogleCalendarCommand.MESSAGE_USAGE));
commandTable.put(GetGoogleCalendarCommand.COMMAND_WORD_2,
new CommandInstance(GetGoogleCalendarCommand.COMMAND_WORD_1,
new GetGoogleCalendarCommandParser(), GetGoogleCalendarCommand.MESSAGE_USAGE));
commandTable.put(HelpCommand.COMMAND_WORD_1, new CommandInstance(HelpCommand.COMMAND_WORD_1,
new HelpCommandParser(), HelpCommand.MESSAGE_USAGE));
commandTable.put(HelpCommand.COMMAND_WORD_2, new CommandInstance(HelpCommand.COMMAND_WORD_1,
new HelpCommandParser(), HelpCommand.MESSAGE_USAGE));
commandTable.put(HelpCommand.COMMAND_WORD_3, new CommandInstance(HelpCommand.COMMAND_WORD_1,
new HelpCommandParser(), HelpCommand.MESSAGE_USAGE));
commandTable.put(HelpCommand.COMMAND_WORD_4, new CommandInstance(HelpCommand.COMMAND_WORD_1,
new HelpCommandParser(), HelpCommand.MESSAGE_USAGE));
commandTable.put(HelpFormatCommand.COMMAND_WORD_1, new CommandInstance(HelpFormatCommand.COMMAND_WORD_1,
new HelpFormatCommandParser(), HelpFormatCommand.MESSAGE_USAGE));
commandTable.put(HelpFormatCommand.COMMAND_WORD_2, new CommandInstance(HelpFormatCommand.COMMAND_WORD_1,
new HelpFormatCommandParser(), HelpFormatCommand.MESSAGE_USAGE));
commandTable.put(HelpFormatCommand.COMMAND_WORD_3, new CommandInstance(HelpFormatCommand.COMMAND_WORD_1,
new HelpFormatCommandParser(), HelpFormatCommand.MESSAGE_USAGE));
commandTable.put(HelpFormatCommand.COMMAND_WORD_4, new CommandInstance(HelpFormatCommand.COMMAND_WORD_1,
new HelpFormatCommandParser(), HelpFormatCommand.MESSAGE_USAGE));
// commandTable.put(ListByDoneCommand.COMMAND_WORD_1, new CommandInstance(ListByDoneCommand.COMMAND_WORD_1,
// new ListByDoneCommandParser(), ListByDoneCommand.MESSAGE_USAGE));
// commandTable.put(ListByDoneCommand.COMMAND_WORD_2, new CommandInstance(ListByDoneCommand.COMMAND_WORD_1,
// new ListByDoneCommandParser(), ListByDoneCommand.MESSAGE_USAGE));
//
// commandTable.put(ListByNotDoneCommand.COMMAND_WORD_1, new CommandInstance(ListByNotDoneCommand.COMMAND_WORD_1,
// new ListByNotDoneCommandParser(), ListByNotDoneCommand.MESSAGE_USAGE));
// commandTable.put(ListByNotDoneCommand.COMMAND_WORD_2, new CommandInstance(ListByNotDoneCommand.COMMAND_WORD_1,
// new ListByNotDoneCommandParser(), ListByNotDoneCommand.MESSAGE_USAGE));
// commandTable.put(ListByNotDoneCommand.COMMAND_WORD_3, new CommandInstance(ListByNotDoneCommand.COMMAND_WORD_1,
// new ListByNotDoneCommandParser(), ListByNotDoneCommand.MESSAGE_USAGE));
commandTable.put(ListByTagCommand.COMMAND_WORD_1, new CommandInstance(ListByTagCommand.COMMAND_WORD_1,
new ListByTagCommandParser(), ListByTagCommand.MESSAGE_USAGE));
commandTable.put(ListByTagCommand.COMMAND_WORD_2, new CommandInstance(ListByTagCommand.COMMAND_WORD_1,
new ListByTagCommandParser(), ListByTagCommand.MESSAGE_USAGE));
commandTable.put(ListByTagCommand.COMMAND_WORD_3, new CommandInstance(ListByTagCommand.COMMAND_WORD_1,
new ListByTagCommandParser(), ListByTagCommand.MESSAGE_USAGE));
commandTable.put(ListByTagCommand.COMMAND_WORD_4, new CommandInstance(ListByTagCommand.COMMAND_WORD_1,
new ListByTagCommandParser(), ListByTagCommand.MESSAGE_USAGE));
commandTable.put(ListCommand.COMMAND_WORD_1, new CommandInstance(ListCommand.COMMAND_WORD_1,
new ListCommandParser(), ListCommand.MESSAGE_USAGE));
commandTable.put(ListCommand.COMMAND_WORD_2, new CommandInstance(ListCommand.COMMAND_WORD_1,
new ListCommandParser(), ListCommand.MESSAGE_USAGE));
commandTable.put(ListCommand.COMMAND_WORD_3, new CommandInstance(ListCommand.COMMAND_WORD_1,
new ListCommandParser(), ListCommand.MESSAGE_USAGE));
commandTable.put(ListCommand.NOT_DONE, new CommandInstance(ListCommand.NOT_DONE,
new ListCommandParser(), ListCommand.MESSAGE_USAGE));
commandTable.put(LoadCommand.COMMAND_WORD_1, new CommandInstance(LoadCommand.COMMAND_WORD_1,
new LoadCommandParser(), LoadCommand.MESSAGE_USAGE));
commandTable.put(PostGoogleCalendarCommand.COMMAND_WORD_1,
new CommandInstance(PostGoogleCalendarCommand.COMMAND_WORD_1,
new PostGoogleCalendarCommandParser(), PostGoogleCalendarCommand.MESSAGE_USAGE));
commandTable.put(PostGoogleCalendarCommand.COMMAND_WORD_2,
new CommandInstance(PostGoogleCalendarCommand.COMMAND_WORD_1,
new PostGoogleCalendarCommandParser(), PostGoogleCalendarCommand.MESSAGE_USAGE));
commandTable.put(QuickAddCommand.COMMAND_WORD_1, new CommandInstance(QuickAddCommand.COMMAND_WORD_1,
new QuickAddCommandParser() , QuickAddCommand.MESSAGE_USAGE));
commandTable.put(RedoCommand.COMMAND_WORD_1, new CommandInstance(RedoCommand.COMMAND_WORD_1,
new RedoCommandParser(), RedoCommand.MESSAGE_USAGE));
commandTable.put(SaveCommand.COMMAND_WORD_1, new CommandInstance(SaveCommand.COMMAND_WORD_1,
new SaveCommandParser(), SaveCommand.MESSAGE_USAGE));
commandTable.put(SelectCommand.COMMAND_WORD_1, new CommandInstance(SelectCommand.COMMAND_WORD_1,
new SelectCommandParser(), SelectCommand.MESSAGE_USAGE));
commandTable.put(SelectCommand.COMMAND_WORD_2, new CommandInstance(SelectCommand.COMMAND_WORD_1,
new SelectCommandParser(), SelectCommand.MESSAGE_USAGE));
commandTable.put(ThemeChangeCommand.COMMAND_WORD_1, new CommandInstance(ThemeChangeCommand.COMMAND_WORD_1,
new ThemeChangeCommandParser(), ThemeChangeCommand.MESSAGE_USAGE));
commandTable.put(UndoCommand.COMMAND_WORD_1, new CommandInstance(UndoCommand.COMMAND_WORD_1,
new UndoCommandParser(), UndoCommand.MESSAGE_USAGE));
commandTable.put(UndoCommand.COMMAND_WORD_2, new CommandInstance(UndoCommand.COMMAND_WORD_1,
new UndoCommandParser(), UndoCommand.MESSAGE_USAGE));
commandTable.put(UndoneCommand.COMMAND_WORD_1, new CommandInstance(UndoneCommand.COMMAND_WORD_1,
new UndoneCommandParser(), UndoneCommand.MESSAGE_USAGE));
commandTable.put(UndoneCommand.COMMAND_WORD_2, new CommandInstance(UndoneCommand.COMMAND_WORD_1,
new UndoneCommandParser(), UndoneCommand.MESSAGE_USAGE));
}
/**
*
* @param commandWord
* @param arguments
* @return Returns the correct command with the correct arguments
*/
public Command getCorrectCommand(String commandWord, String arguments) {
if (!commandTable.containsKey(commandWord)) {
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
return commandTable.get(commandWord).commandParser.parse(arguments.trim());
}
public String getCommandUsage(String commandWord) {
if (!commandTable.containsKey(commandWord)) {
EventsCenter.getInstance().post(new QueryUnknownCommandEvent());
return String.format(MESSAGE_COMMAND_DOES_NOT_EXIST, commandWord);
}
return commandTable.get(commandWord).getCommandUsage();
}
protected static class CommandInstance {
private String commandKey;
private String commandUsage;
private CommandParser commandParser;
protected CommandInstance(String commandKey, CommandParser commandParser, String commandUsage) {
this.commandKey = commandKey;
this.commandParser = commandParser;
this.commandUsage = commandUsage;
}
public String getCommandKey() {
return this.commandKey;
}
public CommandParser getCommandParser() {
return this.commandParser;
}
public String getCommandUsage() {
return this.commandUsage;
}
}
public static HashMap<String, CommandInstance> getCommandTable() {
return commandTable;
}
}
| edit code
| src/main/java/seedu/task/logic/commandlibrary/CommandLibrary.java | edit code | <ide><path>rc/main/java/seedu/task/logic/commandlibrary/CommandLibrary.java
<ide> new ListCommandParser(), ListCommand.MESSAGE_USAGE));
<ide> commandTable.put(ListCommand.COMMAND_WORD_3, new CommandInstance(ListCommand.COMMAND_WORD_1,
<ide> new ListCommandParser(), ListCommand.MESSAGE_USAGE));
<del> commandTable.put(ListCommand.NOT_DONE, new CommandInstance(ListCommand.NOT_DONE,
<del> new ListCommandParser(), ListCommand.MESSAGE_USAGE));
<ide>
<ide> commandTable.put(LoadCommand.COMMAND_WORD_1, new CommandInstance(LoadCommand.COMMAND_WORD_1,
<ide> new LoadCommandParser(), LoadCommand.MESSAGE_USAGE)); |
|
Java | apache-2.0 | a29dead3670eec47eb155f1433285e151b08ecc7 | 0 | HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j | /**
* Copyright (c) 2002-2014 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.impl.api;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.test.TestGraphDatabaseFactory;
import static org.junit.Assert.*;
public class PropertyTransactionStateTest
{
private GraphDatabaseService db;
@Before
public void setUp() throws Exception
{
db = new TestGraphDatabaseFactory().newImpermanentDatabase();
}
@After
public void shutDown()
{
db.shutdown();
}
@Test
public void testUpdateDoubleArrayProperty() throws Exception
{
Node node;
try ( Transaction tx = db.beginTx() )
{
node = db.createNode();
node.setProperty( "foo", new double[] { 0, 0, 0, 0 } );
tx.success();
}
try ( Transaction ignore = db.beginTx() )
{
for ( int i = 0; i < 100; i++ )
{
double[] data = (double[]) node.getProperty( "foo" );
data[2] = i;
data[3] = i;
node.setProperty( "foo", data );
assertArrayEquals( new double[] { 0, 0, i, i }, (double[]) node.getProperty( "foo" ), 0.1D );
}
}
}
@Test
public void testStringPropertyUpdate() throws Exception
{
String key = "foo";
Node node;
try ( Transaction tx = db.beginTx() )
{
node = db.createNode();
node.setProperty( key, "one" );
tx.success();
}
try ( Transaction ignore = db.beginTx() )
{
node.setProperty( key, "one" );
node.setProperty( key, "two" );
assertEquals( "two", node.getProperty( key ) );
}
}
@Test
public void testSetDoubleArrayProperty() throws Exception
{
try ( Transaction ignore = db.beginTx() )
{
Node node = db.createNode();
for ( int i = 0; i < 100; i++ )
{
node.setProperty( "foo", new double[] { 0, 0, i, i } );
assertArrayEquals( new double[] { 0, 0, i, i }, (double[]) node.getProperty( "foo" ), 0.1D );
}
}
}
}
| community/kernel/src/test/java/org/neo4j/kernel/impl/api/PropertyTransactionStateTest.java | /**
* Copyright (c) 2002-2014 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.impl.api;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.test.TestGraphDatabaseFactory;
import static org.junit.Assert.*;
public class PropertyTransactionStateTest
{
private GraphDatabaseService db;
@Before
public void setUp() throws Exception
{
db = new TestGraphDatabaseFactory().newImpermanentDatabase();
}
@After
public void shutDown()
{
db.shutdown();
}
@Test
public void testUpdateDoubleArrayProperty() throws Exception
{
Node node;
try ( Transaction tx = db.beginTx() )
{
node = db.createNode();
node.setProperty( "foo", new double[] { 0, 0, 0, 0 } );
tx.success();
}
try ( Transaction tx = db.beginTx() )
{
for ( int i = 0; i < 100; i++ )
{
double[] data = (double[]) node.getProperty( "foo" );
data[2] = i;
data[3] = i;
node.setProperty( "foo", data );
assertArrayEquals( new double[] { 0, 0, i, i }, (double[]) node.getProperty( "foo" ), 0.1D );
}
}
}
@Test
public void testStringPropertyUpdate() throws Exception
{
String key = "foo";
Node node;
try ( Transaction tx = db.beginTx() )
{
node = db.createNode();
node.setProperty( key, "one" );
tx.success();
}
try ( Transaction tx = db.beginTx() )
{
node.setProperty( key, "one" );
node.setProperty( key, "two" );
assertEquals( "two", node.getProperty( key ) );
}
}
@Test
public void testSetDoubleArrayProperty() throws Exception
{
db.beginTx();
Node node = db.createNode();
for ( int i = 0; i < 100; i++ )
{
node.setProperty( "foo", new double[] { 0, 0, i, i } );
assertArrayEquals( new double[] { 0, 0, i, i }, (double[]) node.getProperty( "foo" ), 0.1D );
}
}
}
| Speed up PropertyTransactionStateTest
| community/kernel/src/test/java/org/neo4j/kernel/impl/api/PropertyTransactionStateTest.java | Speed up PropertyTransactionStateTest | <ide><path>ommunity/kernel/src/test/java/org/neo4j/kernel/impl/api/PropertyTransactionStateTest.java
<ide> tx.success();
<ide> }
<ide>
<del> try ( Transaction tx = db.beginTx() )
<add> try ( Transaction ignore = db.beginTx() )
<ide> {
<ide> for ( int i = 0; i < 100; i++ )
<ide> {
<ide> tx.success();
<ide> }
<ide>
<del> try ( Transaction tx = db.beginTx() )
<add> try ( Transaction ignore = db.beginTx() )
<ide> {
<ide> node.setProperty( key, "one" );
<ide> node.setProperty( key, "two" );
<ide> @Test
<ide> public void testSetDoubleArrayProperty() throws Exception
<ide> {
<del> db.beginTx();
<del> Node node = db.createNode();
<del> for ( int i = 0; i < 100; i++ )
<add> try ( Transaction ignore = db.beginTx() )
<ide> {
<del> node.setProperty( "foo", new double[] { 0, 0, i, i } );
<del> assertArrayEquals( new double[] { 0, 0, i, i }, (double[]) node.getProperty( "foo" ), 0.1D );
<add> Node node = db.createNode();
<add> for ( int i = 0; i < 100; i++ )
<add> {
<add> node.setProperty( "foo", new double[] { 0, 0, i, i } );
<add> assertArrayEquals( new double[] { 0, 0, i, i }, (double[]) node.getProperty( "foo" ), 0.1D );
<add> }
<ide> }
<ide> }
<ide> } |
|
Java | mit | 2a301bfc9bce74945f3cd01e8462d204c3b0c946 | 0 | tndatacommons/android-grow-app,Revenaunt/android-app,tndatacommons/android-app,izzyalonso/android-app | package org.tndata.android.compass.fragment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import org.tndata.android.compass.CompassApplication;
import org.tndata.android.compass.R;
import org.tndata.android.compass.activity.ChooseGoalsActivity;
import org.tndata.android.compass.activity.GoalTryActivity;
import org.tndata.android.compass.adapter.CategoryFragmentAdapter;
import org.tndata.android.compass.model.Category;
import org.tndata.android.compass.model.Goal;
import org.tndata.android.compass.task.DeleteGoalTask;
import org.tndata.android.compass.ui.SpacingItemDecoration;
import org.tndata.android.compass.ui.button.FloatingActionButton;
import org.tndata.android.compass.util.Constants;
import java.util.ArrayList;
public class CategoryFragment extends Fragment implements
CategoryFragmentAdapter.CategoryFragmentAdapterInterface,
DeleteGoalTask.DeleteGoalTaskListener{
private Category mCategory;
private FloatingActionButton mFloatingActionButton;
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private CategoryFragmentAdapter mAdapter;
private ArrayList<Goal> mItems = new ArrayList<Goal>();
private boolean mBroadcastIsRegistered = false;
private CategoryFragmentListener mCallback;
private static final String TAG = "Category Fragment";
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "receive broadcast");
categoryGoalsUpdated();
}
};
public interface CategoryFragmentListener {
public void assignGoalsToCategories(boolean shouldSendBroadcast);
}
public static CategoryFragment newInstance(Category category) {
CategoryFragment fragment = new CategoryFragment();
Bundle args = new Bundle();
args.putSerializable("category", category);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCategory = getArguments() != null ? ((Category) getArguments().get(
"category")) : new Category();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = getActivity().getLayoutInflater().inflate(
R.layout.fragment_category, container, false);
mFloatingActionButton = (FloatingActionButton) v.findViewById(R.id.category_fab_button);
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addGoals();
}
});
return v;
}
@Override
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView = (RecyclerView) v
.findViewById(R.id.category_recyclerview);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.addItemDecoration(new SpacingItemDecoration(30));
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CategoryFragmentAdapter(getActivity().getApplicationContext(),
mItems, mCategory, this);
mRecyclerView.setAdapter(mAdapter);
registerReceivers();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setGoals();
mAdapter = new CategoryFragmentAdapter(getActivity(), mItems, mCategory, this);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void onDestroy() {
unRegisterReceivers();
super.onDestroy();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity); // This makes sure that the container activity
// has implemented the callback interface. If not, it throws an
// exception
try {
mCallback = (CategoryFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement CategoryFragmentListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mCallback = null;
}
private void registerReceivers() {
if (mBroadcastIsRegistered == false) {
getActivity().getApplicationContext().registerReceiver(broadcastReceiver,
new IntentFilter(Constants.GOAL_UPDATED_BROADCAST_ACTION));
mBroadcastIsRegistered = true;
Log.d(TAG, "Broadcast registered");
}
}
private void unRegisterReceivers() {
if (mBroadcastIsRegistered == true) {
try {
getActivity().getApplicationContext().unregisterReceiver(broadcastReceiver);
mBroadcastIsRegistered = false;
} catch (Exception e) {
}
}
}
private void addGoals() {
Intent intent = new Intent(getActivity().getApplicationContext(),
ChooseGoalsActivity.class);
intent.putExtra("category", mCategory);
startActivityForResult(intent, Constants.CHOOSE_GOALS_REQUEST_CODE);
mAdapter.notifyDataSetChanged();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult");
if (requestCode == Constants.CHOOSE_GOALS_REQUEST_CODE ||
requestCode == Constants.BEHAVIOR_CHANGED_RESULT_CODE ||
requestCode == Constants.GOALS_CHANGED_RESULT_CODE) {
mCallback.assignGoalsToCategories(true);
}
}
public void categoryGoalsUpdated() {
Log.d(TAG, "categoryGoalsUpdated");
for (Category category : ((CompassApplication) getActivity()
.getApplication()).getCategories()) {
if (category.getId() == mCategory.getId()) {
mCategory.setGoals(category.getGoals());
break;
}
}
setGoals();
mAdapter.notifyDataSetChanged();
}
private void setGoals() {
Log.d(TAG, "setGoals");
ArrayList<Goal> goals = mCategory.getGoals();
mItems.clear();
if (goals != null && !goals.isEmpty()) {
mItems.addAll(goals);
}
mAdapter.notifyDataSetChanged();
}
private void removeGoal(Goal goal) {
// NOTE: this is similar to code in GoalDetailsActivity.deleteGoal(); refactor?
// Delete the goal from the backend api.
ArrayList<String> goals = new ArrayList<String>();
goals.add(String.valueOf(goal.getMappingId()));
new DeleteGoalTask(getActivity(), this, goals).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// Remove the goal from the category's collection
mCategory.removeGoal(goal);
// Delete the goal from the Compass Application's collection
((CompassApplication) getActivity().getApplication()).removeGoal(goal);
setGoals(); // reset the goals collection for this fragment.
mAdapter.notifyDataSetChanged();
}
@Override
public void goalsDeleted() {
Toast.makeText(getActivity(), getText(R.string.goal_deleted), Toast.LENGTH_SHORT).show();
mAdapter.notifyDataSetChanged();
}
@Override
public void chooseBehaviors(Goal goal) {
Intent intent = new Intent(getActivity()
.getApplicationContext(), GoalTryActivity.class);
intent.putExtra("goal", goal);
intent.putExtra("category", mCategory);
startActivityForResult(intent, Constants.CHOOSE_BEHAVIORS_REQUEST_CODE);
}
@Override
public void viewGoal(Goal goal) {
Intent intent = new Intent(getActivity()
.getApplicationContext(), GoalTryActivity.class);
intent.putExtra("goal", goal);
intent.putExtra("category", mCategory);
startActivityForResult(intent, Constants.CHOOSE_BEHAVIORS_REQUEST_CODE);
}
@Override
public void deleteGoal(final Goal goal) {
Log.d(TAG, "Deleting Goal: " + goal.getTitle());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getText(R.string.goal_dialog_delete_message))
.setTitle(getText(R.string.goal_dialog_delete_title))
.setNegativeButton(R.string.picker_cancel, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
})
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
removeGoal(goal);
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
| src/main/java/org/tndata/android/compass/fragment/CategoryFragment.java | package org.tndata.android.compass.fragment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import org.tndata.android.compass.CompassApplication;
import org.tndata.android.compass.R;
import org.tndata.android.compass.activity.ChooseGoalsActivity;
import org.tndata.android.compass.activity.GoalDetailsActivity;
import org.tndata.android.compass.activity.GoalTryActivity;
import org.tndata.android.compass.adapter.CategoryFragmentAdapter;
import org.tndata.android.compass.model.Category;
import org.tndata.android.compass.model.Goal;
import org.tndata.android.compass.task.DeleteGoalTask;
import org.tndata.android.compass.ui.SpacingItemDecoration;
import org.tndata.android.compass.ui.button.FloatingActionButton;
import org.tndata.android.compass.util.Constants;
import java.util.ArrayList;
public class CategoryFragment extends Fragment implements
CategoryFragmentAdapter.CategoryFragmentAdapterInterface,
DeleteGoalTask.DeleteGoalTaskListener{
private Category mCategory;
private FloatingActionButton mFloatingActionButton;
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private CategoryFragmentAdapter mAdapter;
private ArrayList<Goal> mItems = new ArrayList<Goal>();
private boolean mBroadcastIsRegistered = false;
private CategoryFragmentListener mCallback;
private static final String TAG = "Category Fragment";
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "receive broadcast");
categoryGoalsUpdated();
}
};
public interface CategoryFragmentListener {
public void assignGoalsToCategories(boolean shouldSendBroadcast);
}
public static CategoryFragment newInstance(Category category) {
CategoryFragment fragment = new CategoryFragment();
Bundle args = new Bundle();
args.putSerializable("category", category);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCategory = getArguments() != null ? ((Category) getArguments().get(
"category")) : new Category();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = getActivity().getLayoutInflater().inflate(
R.layout.fragment_category, container, false);
mFloatingActionButton = (FloatingActionButton) v.findViewById(R.id.category_fab_button);
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addGoals();
}
});
return v;
}
@Override
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView = (RecyclerView) v
.findViewById(R.id.category_recyclerview);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.addItemDecoration(new SpacingItemDecoration(30));
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CategoryFragmentAdapter(getActivity().getApplicationContext(),
mItems, mCategory, this);
mRecyclerView.setAdapter(mAdapter);
registerReceivers();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setGoals();
mAdapter = new CategoryFragmentAdapter(getActivity(), mItems, mCategory, this);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void onDestroy() {
unRegisterReceivers();
super.onDestroy();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity); // This makes sure that the container activity
// has implemented the callback interface. If not, it throws an
// exception
try {
mCallback = (CategoryFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement CategoryFragmentListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mCallback = null;
}
private void registerReceivers() {
if (mBroadcastIsRegistered == false) {
getActivity().getApplicationContext().registerReceiver(broadcastReceiver,
new IntentFilter(Constants.GOAL_UPDATED_BROADCAST_ACTION));
mBroadcastIsRegistered = true;
Log.d(TAG, "Broadcast registered");
}
}
private void unRegisterReceivers() {
if (mBroadcastIsRegistered == true) {
try {
getActivity().getApplicationContext().unregisterReceiver(broadcastReceiver);
mBroadcastIsRegistered = false;
} catch (Exception e) {
}
}
}
private void addGoals() {
Intent intent = new Intent(getActivity().getApplicationContext(),
ChooseGoalsActivity.class);
intent.putExtra("category", mCategory);
startActivityForResult(intent, Constants.CHOOSE_GOALS_REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult");
if (requestCode == Constants.CHOOSE_GOALS_REQUEST_CODE ||
requestCode == Constants.BEHAVIOR_CHANGED_RESULT_CODE ||
requestCode == Constants.GOALS_CHANGED_RESULT_CODE) {
mCallback.assignGoalsToCategories(true);
}
}
public void categoryGoalsUpdated() {
Log.d(TAG, "categoryGoalsUpdated");
for (Category category : ((CompassApplication) getActivity()
.getApplication()).getCategories()) {
if (category.getId() == mCategory.getId()) {
mCategory.setGoals(category.getGoals());
break;
}
}
setGoals();
mAdapter.notifyDataSetChanged();
}
private void setGoals() {
Log.d(TAG, "setGoals");
ArrayList<Goal> goals = mCategory.getGoals();
mItems.clear();
if (goals != null && !goals.isEmpty()) {
mItems.addAll(goals);
}
}
private void removeGoal(Goal goal) {
// NOTE: this is similar to code in GoalDetailsActivity.deleteGoal(); refactor?
// Delete the goal from the backend api.
ArrayList<String> goals = new ArrayList<String>();
goals.add(String.valueOf(goal.getMappingId()));
new DeleteGoalTask(getActivity(), this, goals).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// Remove the goal from the category's collection
mCategory.removeGoal(goal);
// Delete the goal from the Compass Application's collection
((CompassApplication) getActivity().getApplication()).removeGoal(goal);
setGoals(); // reset the goals collection for this fragment.
mAdapter.notifyDataSetChanged();
}
@Override
public void goalsDeleted() {
Toast.makeText(getActivity(), getText(R.string.goal_deleted), Toast.LENGTH_SHORT).show();
}
@Override
public void chooseBehaviors(Goal goal) {
Intent intent = new Intent(getActivity()
.getApplicationContext(), GoalTryActivity.class);
intent.putExtra("goal", goal);
intent.putExtra("category", mCategory);
startActivityForResult(intent, Constants.CHOOSE_BEHAVIORS_REQUEST_CODE);
}
@Override
public void viewGoal(Goal goal) {
Intent intent = new Intent(getActivity().getApplicationContext(),
GoalDetailsActivity.class);
intent.putExtra("goal", goal);
intent.putExtra("category", mCategory);
startActivityForResult(intent, Constants.GOALS_CHANGED_RESULT_CODE);
}
@Override
public void deleteGoal(final Goal goal) {
Log.d(TAG, "Deleting Goal: " + goal.getTitle());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getText(R.string.goal_dialog_delete_message))
.setTitle(getText(R.string.goal_dialog_delete_title))
.setNegativeButton(R.string.picker_cancel, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
})
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
removeGoal(goal);
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
| launching the GoalTryActivity instead of the GoalDetailsActivity even when the user has selected goals
| src/main/java/org/tndata/android/compass/fragment/CategoryFragment.java | launching the GoalTryActivity instead of the GoalDetailsActivity even when the user has selected goals | <ide><path>rc/main/java/org/tndata/android/compass/fragment/CategoryFragment.java
<ide> import org.tndata.android.compass.CompassApplication;
<ide> import org.tndata.android.compass.R;
<ide> import org.tndata.android.compass.activity.ChooseGoalsActivity;
<del>import org.tndata.android.compass.activity.GoalDetailsActivity;
<ide> import org.tndata.android.compass.activity.GoalTryActivity;
<ide> import org.tndata.android.compass.adapter.CategoryFragmentAdapter;
<ide> import org.tndata.android.compass.model.Category;
<ide> ChooseGoalsActivity.class);
<ide> intent.putExtra("category", mCategory);
<ide> startActivityForResult(intent, Constants.CHOOSE_GOALS_REQUEST_CODE);
<add> mAdapter.notifyDataSetChanged();
<ide> }
<ide>
<ide> @Override
<ide> if (goals != null && !goals.isEmpty()) {
<ide> mItems.addAll(goals);
<ide> }
<add> mAdapter.notifyDataSetChanged();
<ide> }
<ide>
<ide> private void removeGoal(Goal goal) {
<ide> @Override
<ide> public void goalsDeleted() {
<ide> Toast.makeText(getActivity(), getText(R.string.goal_deleted), Toast.LENGTH_SHORT).show();
<add> mAdapter.notifyDataSetChanged();
<ide> }
<ide>
<ide> @Override
<ide>
<ide> @Override
<ide> public void viewGoal(Goal goal) {
<del> Intent intent = new Intent(getActivity().getApplicationContext(),
<del> GoalDetailsActivity.class);
<add> Intent intent = new Intent(getActivity()
<add> .getApplicationContext(), GoalTryActivity.class);
<ide> intent.putExtra("goal", goal);
<ide> intent.putExtra("category", mCategory);
<del> startActivityForResult(intent, Constants.GOALS_CHANGED_RESULT_CODE);
<add> startActivityForResult(intent, Constants.CHOOSE_BEHAVIORS_REQUEST_CODE);
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | f794dfb3858fe2473841e9ca4051f921b90f39a1 | 0 | JohnReedLOL/Nineteen_Characters | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package src.controller;
import java.util.ArrayList;
import src.model.MapEntity_Relation;
/**
*
* @author JohnReedLOL
*/
abstract public class Entity extends DrawableThing {
// Converts an entity's name [which must be unique] into a unique base 35 number
private static final long serialVersionUID = Long.parseLong("Entity", 35);
// map_relationship_ is used in place of a map_referance_
private final MapEntity_Relation map_relationship_;
/**
* Use this to call functions contained within the MapEntity relationship
* @return map_relationship_
* @author Reed, John
*/
@Override
public MapEntity_Relation getMapRelation() {
return map_relationship_;
}
public Entity(String name, char representation,
int x_respawn_point, int y_respawn_point) {
super(name, representation);
map_relationship_ = new MapEntity_Relation( this, x_respawn_point, y_respawn_point );
inventory_ = new ArrayList<Item>();
}
private Occupation occupation_ = null;
ArrayList<Item> inventory_;
// Only 1 equipped item in iteration 1
Item equipped_item_;
//private final int max_level_;
private StatsPack my_stats_after_powerups_;
/**
* Adds default stats to item stats and updates my_stats_after_powerups
* @author Jessan
*/
private void recalculateStats() {
//my_stats_after_powerups_.equals(my_stats_after_powerups_.add(equipped_item_.get_stats_pack_()));
my_stats_after_powerups_ = get_default_stats_pack_().add(equipped_item_.get_default_stats_pack_());
}
/**
* this function levels up an entity
* @author Jessan
*/
public void levelUp() {
if(occupation_ == null){
//levelup normally
StatsPack new_stats = new StatsPack(0,1,1,1,1,1,1,1,1);
set_default_stats_pack(get_default_stats_pack_().add(new_stats));
}
//if occupation is not null/have an occupation
else {
set_default_stats_pack(occupation_.change_stats(get_default_stats_pack_()));
}
}
public void setOccupation(Occupation occupation) {
occupation_ = occupation;
}
public Occupation getOccupation(){
return occupation_;
}
public void addItemToInventory(Item item) {
inventory_.add(item);
}
}
| src/src/controller/Entity.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package src.controller;
import java.util.ArrayList;
import src.model.MapEntity_Relation;
/**
*
* @author JohnReedLOL
*/
abstract public class Entity extends DrawableThing {
// Converts an entity's name [which must be unique] into a unique base 35 number
private static final long serialVersionUID = Long.parseLong("Entity", 35);
// map_relationship_ is used in place of a map_referance_
private final MapEntity_Relation map_relationship_;
/**
* Use this to call functions contained within the MapEntity relationship
* @return map_relationship_
* @author Reed, John
*/
@Override
public MapEntity_Relation getMapRelation() {
return map_relationship_;
}
public Entity(String name, char representation,
int x_respawn_point, int y_respawn_point) {
super(name, representation);
map_relationship_ = new MapEntity_Relation( this, x_respawn_point, y_respawn_point );
inventory_ = new ArrayList<Item>();
}
private Occupation occupation_ = null;
ArrayList<Item> inventory_;
// Only 1 equipped item in iteration 1
Item equipped_item_;
//private final int max_level_;
private StatsPack my_stats_after_powerups_;
private void recalculateStats() {
//my_stats_after_powerups_.equals(my_stats_after_powerups_.add(equipped_item_.get_stats_pack_()));
}
/**
* this function levels up an entity
* @author Jessan
*/
public void levelUp() {
if(occupation_ == null){
//levelup normally
StatsPack new_stats = new StatsPack(0,1,1,1,1,1,1,1,1);
set_default_stats_pack(get_default_stats_pack_().add(new_stats));
}
//if occupation is not null/have an occupation
else {
set_default_stats_pack(occupation_.change_stats(get_default_stats_pack_()));
}
}
public void setOccupation(Occupation occupation) {
occupation_ = occupation;
}
public Occupation getOccupation(){
return occupation_;
}
public void addItemToInventory(Item item) {
inventory_.add(item);
}
}
| updated recalculateStats()
| src/src/controller/Entity.java | updated recalculateStats() | <ide><path>rc/src/controller/Entity.java
<ide>
<ide> private StatsPack my_stats_after_powerups_;
<ide>
<add> /**
<add> * Adds default stats to item stats and updates my_stats_after_powerups
<add> * @author Jessan
<add> */
<ide> private void recalculateStats() {
<ide> //my_stats_after_powerups_.equals(my_stats_after_powerups_.add(equipped_item_.get_stats_pack_()));
<add> my_stats_after_powerups_ = get_default_stats_pack_().add(equipped_item_.get_default_stats_pack_());
<ide> }
<ide>
<ide> /** |
|
Java | bsd-3-clause | d2f6ff477d473ea40541d622af795bfd84e8be6f | 0 | mdeanda/ajaxproxy,mdeanda/ajaxproxy,mdeanda/ajaxproxy | package com.thedeanda.ajaxproxy.ui;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SpringLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.ListenerSupportedSimpleLoggerFactory;
import org.slf4j.impl.LogListener;
import com.thedeanda.ajaxproxy.AjaxProxy;
import com.thedeanda.ajaxproxy.ProxyListener;
import com.thedeanda.ajaxproxy.ui.proxy.ProxyPanel;
import com.thedeanda.ajaxproxy.ui.proxy.ProxyTableModel;
import com.thedeanda.javajson.JsonException;
import com.thedeanda.javajson.JsonObject;
public class MainPanel extends JPanel implements ProxyListener, LogListener,
SettingsChangedListener {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(MainPanel.class);
private JButton btn;
private boolean started = false;
private AjaxProxy proxy = null;
private ProxyTableModel proxyModel;
private MergeTableModel mergeModel;
private VariableTableModel variableModel;
private File configFile;
private JsonObject config;
private JTextArea logBox;
private OptionsPanel optionsPanel;
private FileTrackerPanel trackerPanel;
private JTabbedPane tabs;
private JScrollPane logBoxScrollPane;
private GeneralPanel generalPanel;
private static final String START = "Start";
private static final String STOP = "Stop";
private List<ProxyListener> listeners = new ArrayList<ProxyListener>();
private ResourceViewerPanel resourceViewerPanel;
private JTextArea logTextArea;
private JButton restartButton;
public MainPanel() {
SpringLayout layout = new SpringLayout();
setLayout(layout);
ListenerSupportedSimpleLoggerFactory.addListener(this);
btn = new JButton(START);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (started)
stop();
else
start();
}
});
this.tabs = new JTabbedPane();
add(tabs);
generalPanel = new GeneralPanel(this);
tabs.add("General", generalPanel);
proxyModel = new ProxyTableModel();
tabs.add("Proxy", new ProxyPanel(this, proxyModel));
mergeModel = new MergeTableModel();
tabs.add("Merge", new MergePanel(this, mergeModel));
// TODO: move proxy to its own panel so code is easier to maintain
variableModel = new VariableTableModel();
tabs.add("Variables", new VariablesPanel(this, variableModel));
optionsPanel = new OptionsPanel();
tabs.add("Options", optionsPanel);
trackerPanel = new FileTrackerPanel();
tabs.add("Tracker", trackerPanel);
resourceViewerPanel = new ResourceViewerPanel();
tabs.add("Resource Viewer", resourceViewerPanel);
logTextArea = new JTextArea();
logTextArea.setWrapStyleWord(true);
logTextArea.setLineWrap(true);
this.logBox = logTextArea;
Font font = logTextArea.getFont();
logTextArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, font
.getSize()));
// ta.setEditable(false);
this.logBoxScrollPane = new JScrollPane(logTextArea);
tabs.add("Log", logBoxScrollPane);
// LF5SwingUtils.makeVerticalScrollBarTrack(logBoxScrollPane);
add(btn);
restartButton = new JButton("Restart Required");
add(restartButton);
restartButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (started) {
stop();
start();
}
}
});
layout.putConstraint(SpringLayout.SOUTH, btn, -10, SpringLayout.SOUTH,
this);
layout.putConstraint(SpringLayout.EAST, btn, -10, SpringLayout.EAST,
this);
layout.putConstraint(SpringLayout.NORTH, tabs, 15, SpringLayout.NORTH,
this);
layout.putConstraint(SpringLayout.WEST, tabs, 10, SpringLayout.WEST,
this);
layout.putConstraint(SpringLayout.EAST, tabs, -10, SpringLayout.EAST,
this);
layout.putConstraint(SpringLayout.SOUTH, tabs, -10, SpringLayout.NORTH,
btn);
layout.putConstraint(SpringLayout.SOUTH, restartButton, 0,
SpringLayout.SOUTH, btn);
layout.putConstraint(SpringLayout.EAST, restartButton, -10,
SpringLayout.WEST, btn);
clearAll();
}
public void addProxyListener(ProxyListener listener) {
listeners.add(listener);
if (started)
listener.started();
else
listener.stopped();
}
private void fireProxyStarted() {
for (ProxyListener l : listeners) {
l.started();
}
}
private void fireProxyStopped() {
for (ProxyListener l : listeners) {
l.stopped();
}
}
/**
* updates the config from the ui data
*
* @return the json object representing the config
*/
public JsonObject getConfig() {
JsonObject json = config;
json.put("port", generalPanel.getPort());
json.put("resourceBase", generalPanel.getResourceBase());
json.put(AjaxProxy.SHOW_INDEX, generalPanel.isShowIndex());
json.put("proxy", proxyModel.getConfig());
json.put("merge", mergeModel.getConfig());
json.put("variables", variableModel.getConfig());
json.put("tracker", trackerPanel.getConfig());
json.put("resource", resourceViewerPanel.getConfig());
json.put("options", optionsPanel.getConfig());
log.info(json.toString(2));
return json;
}
/**
* ui settings not stored in the current config file
*
* @return
*/
public JsonObject getSettings() {
JsonObject ret = new JsonObject();
ret.put("currentTab", tabs.getSelectedIndex());
return ret;
}
/**
* load ui settings
*
* @param json
*/
public void setSettings(JsonObject json) {
if (json == null)
return;
tabs.setSelectedIndex(json.getInt("currentTab"));
}
public void start() {
if (started)
return;
logBox.setText("");
try {
btn.setText(STOP);
JsonObject json = JsonObject.parse(getConfig().toString());
File workingDir = configFile.getParentFile();
if (workingDir == null)
workingDir = new File(".");
proxy = new AjaxProxy(json, workingDir);
proxy.addProxyListener(this);
new Thread(proxy).start();
optionsPanel.setProxy(proxy);
trackerPanel.setProxy(proxy);
resourceViewerPanel.setProxy(proxy);
started = true;
fireProxyStarted();
} catch (Exception e) {
log.error(e.getMessage(), e);
failed();
this.tabs.setSelectedComponent(logBoxScrollPane);
}
}
public void clearAll() {
stop();
configFile = new File("");
config = new JsonObject();
generalPanel.setPort(0);
generalPanel.setResourceBase("");
generalPanel.setShowIndex(false);
proxyModel.clear();
mergeModel.clear();
variableModel.clear();
}
public void stop() {
restartButton.setVisible(false);
try {
if (proxy != null) {
log.info("stopping server");
AjaxProxy p = proxy;
proxy = null;
p.stop();
optionsPanel.setProxy(null);
trackerPanel.setProxy(null);
resourceViewerPanel.setProxy(null);
}
} finally {
proxy = null;
started = false;
btn.setText(START);
fireProxyStopped();
}
}
public File getConfigFile() {
return configFile;
}
public void setConfigFile(final File configFile) {
this.configFile = configFile;
InputStream is = null;
try {
is = new FileInputStream(configFile);
setConfig(JsonObject.parse(is));
} catch (IOException e) {
log.error(e.getMessage(), e);
JOptionPane.showMessageDialog(MainPanel.this, "Error reading file");
clearAll();
} catch (JsonException e) {
log.error(e.getMessage(), e);
JOptionPane.showMessageDialog(MainPanel.this, "Error parsing file");
clearAll();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
public void setConfig(JsonObject json) {
this.config = json;
proxyModel.setConfig(config.getJsonArray("proxy"));
mergeModel.setConfig(config.getJsonArray("merge"));
variableModel.setConfig(config.getJsonObject("variables"));
generalPanel.setPort(config.getInt("port"));
generalPanel.setResourceBase(config.getString("resourceBase"));
generalPanel.setShowIndex(config.getBoolean(AjaxProxy.SHOW_INDEX));
trackerPanel.setConfig(json.getJsonObject("tracker"));
resourceViewerPanel.setConfig(json.getJsonObject("resource"));
optionsPanel.setConfig(json.getJsonObject("options"));
}
@Override
public void started() {
}
@Override
public void stopped() {
this.stop();
}
@Override
public void failed() {
log.error("failed, so calling stop");
this.stop();
}
@Override
public void write(String msg) {
logTextArea.append(msg);
}
@Override
public void restartRequired() {
if (started) {
restartButton.setVisible(true);
}
}
@Override
public void settingsChanged() {
log.debug("settings changed, possible track to warn of unsaved changes during close");
}
public void addVariables(Map<String, String> vars) {
if (vars != null) {
for (String key : vars.keySet()) {
String value = vars.get(key);
variableModel.set(key, value);
}
}
}
}
| src/main/java/com/thedeanda/ajaxproxy/ui/MainPanel.java | package com.thedeanda.ajaxproxy.ui;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SpringLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.ListenerSupportedSimpleLoggerFactory;
import org.slf4j.impl.LogListener;
import com.thedeanda.ajaxproxy.AjaxProxy;
import com.thedeanda.ajaxproxy.ProxyListener;
import com.thedeanda.ajaxproxy.ui.proxy.ProxyPanel;
import com.thedeanda.ajaxproxy.ui.proxy.ProxyTableModel;
import com.thedeanda.javajson.JsonException;
import com.thedeanda.javajson.JsonObject;
public class MainPanel extends JPanel implements ProxyListener, LogListener,
SettingsChangedListener {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(MainPanel.class);
private JButton btn;
private boolean started = false;
private AjaxProxy proxy = null;
private ProxyTableModel proxyModel;
private MergeTableModel mergeModel;
private VariableTableModel variableModel;
private File configFile;
private JsonObject config;
private JTextArea logBox;
private OptionsPanel optionsPanel;
private FileTrackerPanel trackerPanel;
private JTabbedPane tabs;
private JScrollPane logBoxScrollPane;
private GeneralPanel generalPanel;
private static final String START = "Start";
private static final String STOP = "Stop";
private List<ProxyListener> listeners = new ArrayList<ProxyListener>();
private ResourceViewerPanel resourceViewerPanel;
private JTextArea logTextArea;
private JButton restartButton;
public MainPanel() {
SpringLayout layout = new SpringLayout();
setLayout(layout);
ListenerSupportedSimpleLoggerFactory.addListener(this);
btn = new JButton(START);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (started)
stop();
else
start();
}
});
this.tabs = new JTabbedPane();
add(tabs);
generalPanel = new GeneralPanel(this);
tabs.add("General", generalPanel);
proxyModel = new ProxyTableModel();
tabs.add("Proxy", new ProxyPanel(this, proxyModel));
mergeModel = new MergeTableModel();
tabs.add("Merge", new MergePanel(this, mergeModel));
// TODO: move proxy to its own panel so code is easier to maintain
variableModel = new VariableTableModel();
tabs.add("Variables", new VariablesPanel(this, variableModel));
optionsPanel = new OptionsPanel();
tabs.add("Options", optionsPanel);
trackerPanel = new FileTrackerPanel();
tabs.add("Tracker", trackerPanel);
resourceViewerPanel = new ResourceViewerPanel();
tabs.add("Resource Viewer", resourceViewerPanel);
logTextArea = new JTextArea();
logTextArea.setWrapStyleWord(true);
logTextArea.setLineWrap(true);
this.logBox = logTextArea;
Font font = logTextArea.getFont();
logTextArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, font
.getSize()));
// ta.setEditable(false);
this.logBoxScrollPane = new JScrollPane(logTextArea);
tabs.add("Log", logBoxScrollPane);
// LF5SwingUtils.makeVerticalScrollBarTrack(logBoxScrollPane);
add(btn);
restartButton = new JButton("Restart Required");
add(restartButton);
restartButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (started) {
stop();
start();
}
}
});
layout.putConstraint(SpringLayout.SOUTH, btn, -10, SpringLayout.SOUTH,
this);
layout.putConstraint(SpringLayout.EAST, btn, -10, SpringLayout.EAST,
this);
layout.putConstraint(SpringLayout.NORTH, tabs, 15, SpringLayout.NORTH,
this);
layout.putConstraint(SpringLayout.WEST, tabs, 10, SpringLayout.WEST,
this);
layout.putConstraint(SpringLayout.EAST, tabs, -10, SpringLayout.EAST,
this);
layout.putConstraint(SpringLayout.SOUTH, tabs, -10, SpringLayout.NORTH,
btn);
layout.putConstraint(SpringLayout.SOUTH, restartButton, 0,
SpringLayout.SOUTH, btn);
layout.putConstraint(SpringLayout.EAST, restartButton, -10,
SpringLayout.WEST, btn);
clearAll();
}
public void addProxyListener(ProxyListener listener) {
listeners.add(listener);
if (started)
listener.started();
else
listener.stopped();
}
private void fireProxyStarted() {
for (ProxyListener l : listeners) {
l.started();
}
}
private void fireProxyStopped() {
for (ProxyListener l : listeners) {
l.stopped();
}
}
/**
* updates the config from the ui data
*
* @return the json object representing the config
*/
public JsonObject getConfig() {
JsonObject json = config;
json.put("port", generalPanel.getPort());
json.put("resourceBase", generalPanel.getResourceBase());
json.put(AjaxProxy.SHOW_INDEX, generalPanel.isShowIndex());
json.put("proxy", proxyModel.getConfig());
json.put("merge", mergeModel.getConfig());
json.put("variables", variableModel.getConfig());
json.put("tracker", trackerPanel.getConfig());
json.put("resource", resourceViewerPanel.getConfig());
json.put("options", optionsPanel.getConfig());
log.info(json.toString(2));
return json;
}
// TODO: figure out why this returns nothing
public JsonObject getSettings() {
JsonObject ret = new JsonObject();
// ret.put("port", port.getText());
return ret;
}
// TODO: figure out why this does nothing
public void setSettings(JsonObject json) {
if (json == null)
return;
// port.setText(json.getString("port"));
}
public void start() {
if (started)
return;
logBox.setText("");
try {
btn.setText(STOP);
JsonObject json = JsonObject.parse(getConfig().toString());
File workingDir = configFile.getParentFile();
if (workingDir == null)
workingDir = new File(".");
proxy = new AjaxProxy(json, workingDir);
proxy.addProxyListener(this);
new Thread(proxy).start();
optionsPanel.setProxy(proxy);
trackerPanel.setProxy(proxy);
resourceViewerPanel.setProxy(proxy);
started = true;
fireProxyStarted();
} catch (Exception e) {
log.error(e.getMessage(), e);
failed();
this.tabs.setSelectedComponent(logBoxScrollPane);
}
}
public void clearAll() {
stop();
configFile = new File("");
config = new JsonObject();
generalPanel.setPort(0);
generalPanel.setResourceBase("");
generalPanel.setShowIndex(false);
proxyModel.clear();
mergeModel.clear();
variableModel.clear();
}
public void stop() {
restartButton.setVisible(false);
try {
if (proxy != null) {
log.info("stopping server");
AjaxProxy p = proxy;
proxy = null;
p.stop();
optionsPanel.setProxy(null);
trackerPanel.setProxy(null);
resourceViewerPanel.setProxy(null);
}
} finally {
proxy = null;
started = false;
btn.setText(START);
fireProxyStopped();
}
}
public File getConfigFile() {
return configFile;
}
public void setConfigFile(final File configFile) {
this.configFile = configFile;
InputStream is = null;
try {
is = new FileInputStream(configFile);
setConfig(JsonObject.parse(is));
} catch (IOException e) {
log.error(e.getMessage(), e);
JOptionPane.showMessageDialog(MainPanel.this, "Error reading file");
clearAll();
} catch (JsonException e) {
log.error(e.getMessage(), e);
JOptionPane.showMessageDialog(MainPanel.this, "Error parsing file");
clearAll();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
public void setConfig(JsonObject json) {
this.config = json;
proxyModel.setConfig(config.getJsonArray("proxy"));
mergeModel.setConfig(config.getJsonArray("merge"));
variableModel.setConfig(config.getJsonObject("variables"));
generalPanel.setPort(config.getInt("port"));
generalPanel.setResourceBase(config.getString("resourceBase"));
generalPanel.setShowIndex(config.getBoolean(AjaxProxy.SHOW_INDEX));
trackerPanel.setConfig(json.getJsonObject("tracker"));
resourceViewerPanel.setConfig(json.getJsonObject("resource"));
optionsPanel.setConfig(json.getJsonObject("options"));
}
@Override
public void started() {
}
@Override
public void stopped() {
this.stop();
}
@Override
public void failed() {
log.error("failed, so calling stop");
this.stop();
}
@Override
public void write(String msg) {
logTextArea.append(msg);
}
@Override
public void restartRequired() {
if (started) {
restartButton.setVisible(true);
}
}
@Override
public void settingsChanged() {
log.debug("settings changed, possible track to warn of unsaved changes during close");
}
public void addVariables(Map<String, String> vars) {
if (vars != null) {
for (String key : vars.keySet()) {
String value = vars.get(key);
variableModel.set(key, value);
}
}
}
}
| remember last tab
| src/main/java/com/thedeanda/ajaxproxy/ui/MainPanel.java | remember last tab | <ide><path>rc/main/java/com/thedeanda/ajaxproxy/ui/MainPanel.java
<ide> return json;
<ide> }
<ide>
<del> // TODO: figure out why this returns nothing
<add> /**
<add> * ui settings not stored in the current config file
<add> *
<add> * @return
<add> */
<ide> public JsonObject getSettings() {
<ide> JsonObject ret = new JsonObject();
<del> // ret.put("port", port.getText());
<add> ret.put("currentTab", tabs.getSelectedIndex());
<ide> return ret;
<ide> }
<ide>
<del> // TODO: figure out why this does nothing
<add> /**
<add> * load ui settings
<add> *
<add> * @param json
<add> */
<ide> public void setSettings(JsonObject json) {
<ide> if (json == null)
<ide> return;
<ide>
<del> // port.setText(json.getString("port"));
<add> tabs.setSelectedIndex(json.getInt("currentTab"));
<ide> }
<ide>
<ide> public void start() { |
|
JavaScript | cc0-1.0 | 4d9e44ca352cb1a3ee8b8324ad4953ab26af59f9 | 0 | department-of-veterans-affairs/vets-website,department-of-veterans-affairs/vets-website | import { apiRequest } from 'platform/utilities/api';
import { COE_ELIGIBILITY_STATUS } from '../constants';
export const GENERATE_AUTOMATIC_COE_STARTED = 'GENERATE_AUTOMATIC_COE_STARTED';
export const GENERATE_AUTOMATIC_COE_SUCCEEDED =
'GENERATE_AUTOMATIC_COE_SUCCEEDED';
export const GENERATE_AUTOMATIC_COE_FAILED = 'GENERATE_AUTOMATIC_COE_FAILED';
export const SKIP_AUTOMATIC_COE_CHECK = 'SKIP_AUTOMATIC_COE_CHECK';
export const GET_COE_URL_SUCCEEDED = 'GET_COE_URL_SUCCEEDED';
export const GET_COE_URL_FAILED = 'GET_COE_URL_FAILED';
const COE_DOWNLOAD_URI = '/coe/download_coe';
const COE_STATUS_URI = '/coe/status';
export const getCoeStatus = async () => {
try {
const response = await apiRequest(COE_STATUS_URI);
return response.data.attributes;
} catch (error) {
return error;
}
};
export const getCoeURL = async () => {
try {
const response = await apiRequest(COE_DOWNLOAD_URI);
return response.data.attributes;
} catch (error) {
return error;
}
};
export const generateCoe = (skip = '') => async dispatch => {
const shouldSkip = !!skip;
if (!shouldSkip) {
dispatch({ type: GENERATE_AUTOMATIC_COE_STARTED });
const response = await getCoeStatus();
if (response.errors) {
dispatch({ type: GENERATE_AUTOMATIC_COE_FAILED, response });
} else {
dispatch({ type: GENERATE_AUTOMATIC_COE_SUCCEEDED, response });
const { status } = response;
if (
status === COE_ELIGIBILITY_STATUS.available ||
status === COE_ELIGIBILITY_STATUS.eligible
) {
const res = await getCoeURL();
if (res.errors?.length) {
dispatch({ type: GET_COE_URL_FAILED, response: res });
} else {
dispatch({ type: GET_COE_URL_SUCCEEDED, response: res });
}
}
}
return response;
}
dispatch({ type: SKIP_AUTOMATIC_COE_CHECK });
return null;
};
| src/applications/lgy/coe/shared/actions/index.js | import { apiRequest } from 'platform/utilities/api';
import { COE_ELIGIBILITY_STATUS } from '../constants';
export const GENERATE_AUTOMATIC_COE_STARTED = 'GENERATE_AUTOMATIC_COE_STARTED';
export const GENERATE_AUTOMATIC_COE_SUCCEEDED =
'GENERATE_AUTOMATIC_COE_SUCCEEDED';
export const GENERATE_AUTOMATIC_COE_FAILED = 'GENERATE_AUTOMATIC_COE_FAILED';
export const SKIP_AUTOMATIC_COE_CHECK = 'SKIP_AUTOMATIC_COE_CHECK';
export const GET_COE_URL_SUCCEEDED = 'GET_COE_URL_SUCCEEDED';
export const GET_COE_URL_FAILED = 'GET_COE_URL_FAILED';
const COE_DOWNLOAD_URI = '/coe/download_coe';
const COE_STATUS_URI = '/coe/status';
export const getCoeStatus = async () => {
try {
const response = await apiRequest(COE_STATUS_URI);
return response.data.attributes;
} catch (error) {
return error;
}
};
export const getCoeURL = async () => {
try {
const response = await apiRequest(COE_DOWNLOAD_URI);
return response.data.attributes;
} catch (error) {
return error;
}
};
export const generateCoe = (skip = '') => async dispatch => {
const shouldSkip = !!skip;
if (!shouldSkip) {
dispatch({ type: GENERATE_AUTOMATIC_COE_STARTED });
const response = await getCoeStatus();
if (response.errors) {
dispatch({ type: GENERATE_AUTOMATIC_COE_FAILED, response });
} else {
dispatch({ type: GENERATE_AUTOMATIC_COE_SUCCEEDED, response });
const { status } = response;
if (
status === COE_ELIGIBILITY_STATUS.available ||
status === COE_ELIGIBILITY_STATUS.eligible
) {
const res = await getCoeURL();
if (res.errors.length) {
dispatch({ type: GET_COE_URL_FAILED, response: res });
} else {
dispatch({ type: GET_COE_URL_SUCCEEDED, response: res });
}
}
}
return response;
}
dispatch({ type: SKIP_AUTOMATIC_COE_CHECK });
return null;
};
| Fixes issue with COE download url not working (#21868)
| src/applications/lgy/coe/shared/actions/index.js | Fixes issue with COE download url not working (#21868) | <ide><path>rc/applications/lgy/coe/shared/actions/index.js
<ide> status === COE_ELIGIBILITY_STATUS.eligible
<ide> ) {
<ide> const res = await getCoeURL();
<del> if (res.errors.length) {
<add> if (res.errors?.length) {
<ide> dispatch({ type: GET_COE_URL_FAILED, response: res });
<ide> } else {
<ide> dispatch({ type: GET_COE_URL_SUCCEEDED, response: res }); |
|
Java | apache-2.0 | 046b2f8e4bdc682c285d6852ebe4495201ae01ab | 0 | akosyakov/intellij-community,caot/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,youdonghai/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,consulo/consulo,fitermay/intellij-community,ibinti/intellij-community,ryano144/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,jagguli/intellij-community,jagguli/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,asedunov/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,caot/intellij-community,diorcety/intellij-community,robovm/robovm-studio,ryano144/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,diorcety/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,holmes/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,consulo/consulo,signed/intellij-community,dslomov/intellij-community,slisson/intellij-community,slisson/intellij-community,jexp/idea2,TangHao1987/intellij-community,adedayo/intellij-community,allotria/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,kool79/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,jagguli/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,amith01994/intellij-community,ernestp/consulo,jagguli/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,adedayo/intellij-community,consulo/consulo,amith01994/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,clumsy/intellij-community,holmes/intellij-community,clumsy/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,kool79/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,dslomov/intellij-community,signed/intellij-community,xfournet/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,robovm/robovm-studio,caot/intellij-community,allotria/intellij-community,da1z/intellij-community,slisson/intellij-community,supersven/intellij-community,samthor/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,adedayo/intellij-community,petteyg/intellij-community,slisson/intellij-community,clumsy/intellij-community,jexp/idea2,clumsy/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,FHannes/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,dslomov/intellij-community,supersven/intellij-community,allotria/intellij-community,xfournet/intellij-community,clumsy/intellij-community,supersven/intellij-community,dslomov/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,jexp/idea2,dslomov/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,izonder/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,petteyg/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,samthor/intellij-community,caot/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,semonte/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,supersven/intellij-community,hurricup/intellij-community,semonte/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,fitermay/intellij-community,da1z/intellij-community,holmes/intellij-community,kdwink/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,apixandru/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,izonder/intellij-community,semonte/intellij-community,fitermay/intellij-community,fnouama/intellij-community,vladmm/intellij-community,ibinti/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,petteyg/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,diorcety/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,izonder/intellij-community,izonder/intellij-community,caot/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,vladmm/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,allotria/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,ernestp/consulo,consulo/consulo,wreckJ/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,fnouama/intellij-community,diorcety/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,apixandru/intellij-community,izonder/intellij-community,dslomov/intellij-community,da1z/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,jagguli/intellij-community,da1z/intellij-community,supersven/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,amith01994/intellij-community,ibinti/intellij-community,blademainer/intellij-community,xfournet/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,signed/intellij-community,jexp/idea2,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,robovm/robovm-studio,asedunov/intellij-community,allotria/intellij-community,fitermay/intellij-community,consulo/consulo,kdwink/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,retomerz/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,holmes/intellij-community,petteyg/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,supersven/intellij-community,kool79/intellij-community,jexp/idea2,allotria/intellij-community,ernestp/consulo,fnouama/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,jagguli/intellij-community,da1z/intellij-community,da1z/intellij-community,wreckJ/intellij-community,samthor/intellij-community,samthor/intellij-community,samthor/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,allotria/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,kdwink/intellij-community,kool79/intellij-community,allotria/intellij-community,ernestp/consulo,lucafavatella/intellij-community,ibinti/intellij-community,samthor/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,joewalnes/idea-community,izonder/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,jexp/idea2,salguarnieri/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,caot/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,diorcety/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,hurricup/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,ibinti/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,caot/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,vvv1559/intellij-community,holmes/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,kool79/intellij-community,Distrotech/intellij-community,jexp/idea2,petteyg/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,ernestp/consulo,asedunov/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,adedayo/intellij-community,ibinti/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,fnouama/intellij-community,kool79/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,fnouama/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,semonte/intellij-community,dslomov/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,fitermay/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,caot/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,signed/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,caot/intellij-community,semonte/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,hurricup/intellij-community,amith01994/intellij-community,diorcety/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,adedayo/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,holmes/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,vladmm/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,petteyg/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,allotria/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,adedayo/intellij-community,retomerz/intellij-community,adedayo/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,jexp/idea2,ibinti/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,clumsy/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,signed/intellij-community,vvv1559/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,signed/intellij-community,signed/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,vladmm/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,ryano144/intellij-community,holmes/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,izonder/intellij-community,samthor/intellij-community,vladmm/intellij-community,supersven/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,FHannes/intellij-community,ernestp/consulo,jagguli/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,kool79/intellij-community,tmpgit/intellij-community,samthor/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,retomerz/intellij-community,jagguli/intellij-community,consulo/consulo,youdonghai/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,apixandru/intellij-community,slisson/intellij-community,allotria/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,signed/intellij-community,petteyg/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,apixandru/intellij-community | /*
* Created by IntelliJ IDEA.
* User: max
* Date: Mar 24, 2002
* Time: 6:08:14 PM
* To change template for new class use
* Code Style | Class Templates options (Tools | IDE Options).
*/
package com.intellij.codeInspection.redundantCast;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RedundantCastUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.redundantCast.RedundantCastUtil");
public static List<PsiTypeCastExpression> getRedundantCastsInside(PsiElement where) {
final ArrayList<PsiTypeCastExpression> result = new ArrayList<PsiTypeCastExpression>();
PsiElementProcessor<PsiTypeCastExpression> processor = new PsiElementProcessor<PsiTypeCastExpression>() {
public boolean execute(PsiTypeCastExpression element) {
result.add(element);
return true;
}
};
where.acceptChildren(new MyCollectingVisitor(processor));
return result;
}
public static boolean isCastRedundant (PsiTypeCastExpression typeCast) {
PsiElement parent = typeCast.getParent();
while(parent instanceof PsiParenthesizedExpression) parent = parent.getParent();
if (parent instanceof PsiExpressionList) parent = parent.getParent();
if (parent instanceof PsiReferenceExpression) parent = parent.getParent();
MyIsRedundantVisitor visitor = new MyIsRedundantVisitor();
parent.accept(visitor);
return visitor.isRedundant();
}
@Nullable
private static PsiExpression deparenthesizeExpression(PsiExpression arg) {
while (arg instanceof PsiParenthesizedExpression) arg = ((PsiParenthesizedExpression) arg).getExpression();
return arg;
}
private static class MyCollectingVisitor extends MyIsRedundantVisitor {
private final PsiElementProcessor<PsiTypeCastExpression> myProcessor;
private Set<PsiTypeCastExpression> myFoundCasts = new HashSet<PsiTypeCastExpression>();
public MyCollectingVisitor(PsiElementProcessor<PsiTypeCastExpression> processor) {
myProcessor = processor;
}
public void visitElement(PsiElement element) {
element.acceptChildren(this);
}
public void visitReferenceExpression(PsiReferenceExpression expression) {
expression.acceptChildren(this);
}
public void visitClass(PsiClass aClass) {
// avoid multiple visit
}
public void visitMethod(PsiMethod method) {
// avoid multiple visit
}
public void visitField(PsiField field) {
// avoid multiple visit
}
protected void addToResults(PsiTypeCastExpression typeCast){
if (!isTypeCastSemantical(typeCast) && myFoundCasts.add(typeCast)) {
myProcessor.execute(typeCast);
}
}
}
private static class MyIsRedundantVisitor extends PsiElementVisitor {
public boolean isRedundant() {
return myIsRedundant;
}
boolean myIsRedundant = false;
protected void addToResults(PsiTypeCastExpression typeCast){
if (!isTypeCastSemantical(typeCast)) {
myIsRedundant = true;
}
}
public void visitAssignmentExpression(PsiAssignmentExpression expression) {
processPossibleTypeCast(expression.getRExpression(), expression.getLExpression().getType());
super.visitAssignmentExpression(expression);
}
public void visitVariable(PsiVariable variable) {
processPossibleTypeCast(variable.getInitializer(), variable.getType());
super.visitVariable(variable);
}
public void visitReturnStatement(PsiReturnStatement statement) {
final PsiMethod method = PsiTreeUtil.getParentOfType(statement, PsiMethod.class);
if (method != null) {
final PsiType returnType = method.getReturnType();
final PsiExpression returnValue = statement.getReturnValue();
if (returnValue != null) {
processPossibleTypeCast(returnValue, returnType);
}
}
super.visitReturnStatement(statement);
}
public void visitBinaryExpression(PsiBinaryExpression expression) {
PsiExpression rExpr = deparenthesizeExpression(expression.getLOperand());
PsiExpression lExpr = deparenthesizeExpression(expression.getROperand());
if (rExpr != null && lExpr != null) {
final IElementType binaryToken = expression.getOperationSign().getTokenType();
processBinaryExpressionOperand(lExpr, rExpr, binaryToken);
processBinaryExpressionOperand(rExpr, lExpr, binaryToken);
}
super.visitBinaryExpression(expression);
}
private void processBinaryExpressionOperand(final PsiExpression operand,
final PsiExpression otherOperand,
final IElementType binaryToken) {
if (operand instanceof PsiTypeCastExpression) {
PsiTypeCastExpression typeCast = (PsiTypeCastExpression)operand;
PsiExpression castOperand = typeCast.getOperand();
if (castOperand != null) {
if (TypeConversionUtil.isBinaryOperatorApplicable(binaryToken, castOperand, otherOperand, false)) {
addToResults(typeCast);
}
}
}
}
private void processPossibleTypeCast(PsiExpression rExpr, @Nullable PsiType lType) {
rExpr = deparenthesizeExpression(rExpr);
if (rExpr instanceof PsiTypeCastExpression) {
PsiExpression castOperand = ((PsiTypeCastExpression)rExpr).getOperand();
if (castOperand != null) {
PsiType operandType = castOperand.getType();
if (operandType != null) {
if (lType != null && TypeConversionUtil.isAssignable(lType, operandType, false)) {
addToResults((PsiTypeCastExpression)rExpr);
}
}
}
}
}
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
processCall(expression);
checkForVirtual(expression);
super.visitMethodCallExpression(expression);
}
private void checkForVirtual(PsiMethodCallExpression methodCall) {
PsiReferenceExpression methodExpr = methodCall.getMethodExpression();
PsiExpression qualifier = methodExpr.getQualifierExpression();
if (!(qualifier instanceof PsiParenthesizedExpression)) return;
PsiExpression operand = ((PsiParenthesizedExpression)qualifier).getExpression();
if (!(operand instanceof PsiTypeCastExpression)) return;
PsiTypeCastExpression typeCast = (PsiTypeCastExpression)operand;
PsiExpression castOperand = typeCast.getOperand();
if (castOperand == null) return;
PsiType type = castOperand.getType();
if (type == null) return;
if (type instanceof PsiPrimitiveType) return;
final JavaResolveResult resolveResult = methodExpr.advancedResolve(false);
PsiMethod targetMethod = (PsiMethod)resolveResult.getElement();
if (targetMethod == null) return;
if (targetMethod.hasModifierProperty(PsiModifier.STATIC)) return;
try {
PsiManager manager = methodExpr.getManager();
PsiElementFactory factory = manager.getElementFactory();
PsiMethodCallExpression newCall = (PsiMethodCallExpression)factory.createExpressionFromText(methodCall.getText(), methodCall);
PsiExpression newQualifier = newCall.getMethodExpression().getQualifierExpression();
PsiExpression newOperand = ((PsiTypeCastExpression)((PsiParenthesizedExpression)newQualifier).getExpression()).getOperand();
newQualifier.replace(newOperand);
final JavaResolveResult newResult = newCall.getMethodExpression().advancedResolve(false);
if (!newResult.isValidResult()) return;
final PsiMethod newTargetMethod = (PsiMethod)newResult.getElement();
final PsiType newReturnType = newResult.getSubstitutor().substitute(newTargetMethod.getReturnType());
final PsiType oldReturnType = resolveResult.getSubstitutor().substitute(targetMethod.getReturnType());
if (newReturnType.equals(oldReturnType)) {
if (newTargetMethod.equals(targetMethod)) {
addToResults(typeCast);
}
else if (
newTargetMethod.getSignature(newResult.getSubstitutor()).equals(targetMethod.getSignature(resolveResult.getSubstitutor())) &&
!(newTargetMethod.isDeprecated() && !targetMethod.isDeprecated()) && // see SCR11555, SCR14559
areThrownExceptionsCompatible(targetMethod, newTargetMethod)) { //see IDEADEV-15170
addToResults(typeCast);
}
}
qualifier = ((PsiTypeCastExpression)((PsiParenthesizedExpression)qualifier).getExpression()).getOperand();
}
catch (IncorrectOperationException e) {
}
}
private static boolean areThrownExceptionsCompatible(final PsiMethod targetMethod, final PsiMethod newTargetMethod) {
final PsiClassType[] oldThrowsTypes = targetMethod.getThrowsList().getReferencedTypes();
final PsiClassType[] newThrowsTypes = newTargetMethod.getThrowsList().getReferencedTypes();
for (final PsiClassType throwsType : newThrowsTypes) {
if (!isExceptionThrown(throwsType, oldThrowsTypes)) return false;
}
return true;
}
private static boolean isExceptionThrown(PsiClassType exceptionType, PsiClassType[] thrownTypes) {
for (final PsiClassType type : thrownTypes) {
if (type.equals(exceptionType)) return true;
}
return false;
}
public void visitNewExpression(PsiNewExpression expression) {
processCall(expression);
super.visitNewExpression(expression);
}
public void visitReferenceExpression(PsiReferenceExpression expression) {
//expression.acceptChildren(this);
}
private void processCall(PsiCallExpression expression){
PsiExpressionList argumentList = expression.getArgumentList();
if (argumentList == null) return;
PsiExpression[] args = argumentList.getExpressions();
PsiMethod oldMethod = expression.resolveMethod();
if (oldMethod == null) return;
PsiParameter[] parameters = oldMethod.getParameterList().getParameters();
try {
for (int i = 0; i < args.length; i++) {
final PsiExpression arg = deparenthesizeExpression(args[i]);
if (arg instanceof PsiTypeCastExpression) {
PsiTypeCastExpression cast = ((PsiTypeCastExpression) arg);
if (i == args.length - 1 && args.length == parameters.length && parameters[i].isVarArgs()) {
//do not mark cast to resolve ambiguity for calling varargs method with inexact argument
continue;
}
PsiCallExpression newCall = (PsiCallExpression) expression.copy();
final PsiExpressionList argList = newCall.getArgumentList();
LOG.assertTrue(argList != null);
PsiExpression[] newArgs = argList.getExpressions();
PsiTypeCastExpression castExpression = (PsiTypeCastExpression) deparenthesizeExpression(newArgs[i]);
PsiExpression castOperand = castExpression.getOperand();
if (castOperand == null) return;
castExpression.replace(castOperand);
final JavaResolveResult newResult = newCall.resolveMethodGenerics();
if (oldMethod.equals(newResult.getElement()) && newResult.isValidResult() &&
Comparing.equal(newCall.getType(), expression.getType())) {
addToResults(cast);
}
}
}
}
catch (IncorrectOperationException e) {
return;
}
for (PsiExpression arg : args) {
if (arg instanceof PsiTypeCastExpression) {
PsiExpression castOperand = ((PsiTypeCastExpression)arg).getOperand();
castOperand.accept(this);
}
else {
arg.accept(this);
}
}
}
public void visitTypeCastExpression(PsiTypeCastExpression typeCast) {
PsiExpression operand = typeCast.getOperand();
if (operand == null) return;
PsiElement expr = deparenthesizeExpression(operand);
if (expr instanceof PsiTypeCastExpression) {
PsiTypeElement typeElement = ((PsiTypeCastExpression)expr).getCastType();
if (typeElement == null) return;
PsiType castType = typeElement.getType();
if (!(castType instanceof PsiPrimitiveType)) {
addToResults((PsiTypeCastExpression)expr);
}
}
else {
PsiElement parent = typeCast.getParent();
if (parent instanceof PsiConditionalExpression) {
if (PsiUtil.getLanguageLevel(typeCast).compareTo(LanguageLevel.JDK_1_5) < 0) {
//branches need to be of the same type
if (!Comparing.equal(operand.getType(),((PsiConditionalExpression)parent).getType())) return;
}
}
processAlreadyHasTypeCast(typeCast);
}
}
private void processAlreadyHasTypeCast(PsiTypeCastExpression typeCast){
PsiElement parent = typeCast.getParent();
while(parent instanceof PsiParenthesizedExpression) parent = parent.getParent();
if (parent instanceof PsiExpressionList) return; // do not replace in arg lists - should be handled by parent
if (isTypeCastSemantical(typeCast)) return;
PsiTypeElement typeElement = typeCast.getCastType();
if (typeElement == null) return;
PsiType toType = typeElement.getType();
PsiType fromType = typeCast.getOperand().getType();
if (fromType == null) return;
if (parent instanceof PsiReferenceExpression) {
if (toType instanceof PsiClassType && fromType instanceof PsiPrimitiveType) return; //explicit boxing
//Check accessibility
if (fromType instanceof PsiClassType) {
final PsiReferenceExpression refExpression = (PsiReferenceExpression)parent;
PsiElement element = refExpression.resolve();
if (!(element instanceof PsiMember)) return;
PsiClass accessClass = ((PsiClassType)fromType).resolve();
if (accessClass == null) return;
if (!parent.getManager().getResolveHelper().isAccessible((PsiMember)element, typeCast, accessClass)) return;
if (!isCastRedundantInRefExpression(refExpression, typeCast.getOperand())) return;
}
}
if (TypeConversionUtil.isAssignable(toType, fromType, false)) {
addToResults(typeCast);
}
}
}
private static boolean isCastRedundantInRefExpression (final PsiReferenceExpression refExpression, final PsiExpression castOperand) {
final PsiElement resolved = refExpression.resolve();
final Ref<Boolean> result = new Ref<Boolean>(Boolean.FALSE);
refExpression.getManager().performActionWithFormatterDisabled(new Runnable() {
public void run() {
try {
final PsiElementFactory elementFactory = refExpression.getManager().getElementFactory();
final PsiExpression copyExpression = elementFactory.createExpressionFromText(refExpression.getText(), refExpression);
if (copyExpression instanceof PsiReferenceExpression) {
final PsiReferenceExpression copy = (PsiReferenceExpression)copyExpression;
final PsiExpression qualifier = copy.getQualifierExpression();
if (qualifier != null) {
qualifier.replace(castOperand);
result.set(Boolean.valueOf(copy.resolve() == resolved));
}
}
}
catch (IncorrectOperationException e) {
}
}
});
return result.get().booleanValue();
}
public static boolean isTypeCastSemantical(PsiTypeCastExpression typeCast) {
PsiExpression operand = typeCast.getOperand();
if (operand != null) {
PsiType opType = operand.getType();
PsiTypeElement typeElement = typeCast.getCastType();
if (typeElement == null) return false;
PsiType castType = typeElement.getType();
if (castType instanceof PsiPrimitiveType) {
if (opType instanceof PsiPrimitiveType) {
return !opType.equals(castType); // let's suppose all not equal primitive casts are necessary
}
}
else if (castType instanceof PsiClassType && ((PsiClassType)castType).hasParameters()) {
if (opType instanceof PsiClassType && ((PsiClassType)opType).isRaw()) return true;
}
}
return false;
}
} | inspections/impl/com/intellij/codeInspection/redundantCast/RedundantCastUtil.java | /*
* Created by IntelliJ IDEA.
* User: max
* Date: Mar 24, 2002
* Time: 6:08:14 PM
* To change template for new class use
* Code Style | Class Templates options (Tools | IDE Options).
*/
package com.intellij.codeInspection.redundantCast;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RedundantCastUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.redundantCast.RedundantCastUtil");
public static List<PsiTypeCastExpression> getRedundantCastsInside(PsiElement where) {
final ArrayList<PsiTypeCastExpression> result = new ArrayList<PsiTypeCastExpression>();
PsiElementProcessor<PsiTypeCastExpression> processor = new PsiElementProcessor<PsiTypeCastExpression>() {
public boolean execute(PsiTypeCastExpression element) {
result.add(element);
return true;
}
};
where.acceptChildren(new MyCollectingVisitor(processor));
return result;
}
public static boolean isCastRedundant (PsiTypeCastExpression typeCast) {
PsiElement parent = typeCast.getParent();
while(parent instanceof PsiParenthesizedExpression) parent = parent.getParent();
if (parent instanceof PsiExpressionList) parent = parent.getParent();
if (parent instanceof PsiReferenceExpression) parent = parent.getParent();
MyIsRedundantVisitor visitor = new MyIsRedundantVisitor();
parent.accept(visitor);
return visitor.isRedundant();
}
@Nullable
private static PsiExpression deparenthesizeExpression(PsiExpression arg) {
while (arg instanceof PsiParenthesizedExpression) arg = ((PsiParenthesizedExpression) arg).getExpression();
return arg;
}
private static class MyCollectingVisitor extends MyIsRedundantVisitor {
private final PsiElementProcessor<PsiTypeCastExpression> myProcessor;
private Set<PsiTypeCastExpression> myFoundCasts = new HashSet<PsiTypeCastExpression>();
public MyCollectingVisitor(PsiElementProcessor<PsiTypeCastExpression> processor) {
myProcessor = processor;
}
public void visitElement(PsiElement element) {
element.acceptChildren(this);
}
public void visitReferenceExpression(PsiReferenceExpression expression) {
expression.acceptChildren(this);
}
public void visitClass(PsiClass aClass) {
// avoid multiple visit
}
public void visitMethod(PsiMethod method) {
// avoid multiple visit
}
public void visitField(PsiField field) {
// avoid multiple visit
}
protected void addToResults(PsiTypeCastExpression typeCast){
if (!isTypeCastSemantical(typeCast) && myFoundCasts.add(typeCast)) {
myProcessor.execute(typeCast);
}
}
}
private static class MyIsRedundantVisitor extends PsiElementVisitor {
public boolean isRedundant() {
return myIsRedundant;
}
boolean myIsRedundant = false;
protected void addToResults(PsiTypeCastExpression typeCast){
if (!isTypeCastSemantical(typeCast)) {
myIsRedundant = true;
}
}
public void visitAssignmentExpression(PsiAssignmentExpression expression) {
processPossibleTypeCast(expression.getRExpression(), expression.getLExpression().getType());
super.visitAssignmentExpression(expression);
}
public void visitVariable(PsiVariable variable) {
processPossibleTypeCast(variable.getInitializer(), variable.getType());
super.visitVariable(variable);
}
public void visitReturnStatement(PsiReturnStatement statement) {
final PsiMethod method = PsiTreeUtil.getParentOfType(statement, PsiMethod.class);
if (method != null) {
final PsiType returnType = method.getReturnType();
final PsiExpression returnValue = statement.getReturnValue();
if (returnValue != null) {
processPossibleTypeCast(returnValue, returnType);
}
}
super.visitReturnStatement(statement);
}
public void visitBinaryExpression(PsiBinaryExpression expression) {
PsiExpression rExpr = deparenthesizeExpression(expression.getLOperand());
PsiExpression lExpr = deparenthesizeExpression(expression.getROperand());
if (rExpr != null && lExpr != null) {
final IElementType binaryToken = expression.getOperationSign().getTokenType();
processBinaryExpressionOperand(lExpr, rExpr, binaryToken);
processBinaryExpressionOperand(rExpr, lExpr, binaryToken);
}
super.visitBinaryExpression(expression);
}
private void processBinaryExpressionOperand(final PsiExpression operand,
final PsiExpression otherOperand,
final IElementType binaryToken) {
if (operand instanceof PsiTypeCastExpression) {
PsiTypeCastExpression typeCast = (PsiTypeCastExpression)operand;
PsiExpression castOperand = typeCast.getOperand();
if (castOperand != null) {
if (TypeConversionUtil.isBinaryOperatorApplicable(binaryToken, castOperand, otherOperand, false)) {
addToResults(typeCast);
}
}
}
}
private void processPossibleTypeCast(PsiExpression rExpr, @Nullable PsiType lType) {
rExpr = deparenthesizeExpression(rExpr);
if (rExpr instanceof PsiTypeCastExpression) {
PsiExpression castOperand = ((PsiTypeCastExpression)rExpr).getOperand();
if (castOperand != null) {
PsiType operandType = castOperand.getType();
if (operandType != null) {
if (lType != null && TypeConversionUtil.isAssignable(lType, operandType, false)) {
addToResults((PsiTypeCastExpression)rExpr);
}
}
}
}
}
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
processCall(expression);
checkForVirtual(expression);
super.visitMethodCallExpression(expression);
}
private void checkForVirtual(PsiMethodCallExpression methodCall) {
PsiReferenceExpression methodExpr = methodCall.getMethodExpression();
PsiExpression qualifier = methodExpr.getQualifierExpression();
if (!(qualifier instanceof PsiParenthesizedExpression)) return;
PsiExpression operand = ((PsiParenthesizedExpression)qualifier).getExpression();
if (!(operand instanceof PsiTypeCastExpression)) return;
PsiTypeCastExpression typeCast = (PsiTypeCastExpression)operand;
PsiExpression castOperand = typeCast.getOperand();
if (castOperand == null) return;
PsiType type = castOperand.getType();
if (type == null) return;
if (type instanceof PsiPrimitiveType) return;
final JavaResolveResult resolveResult = methodExpr.advancedResolve(false);
PsiMethod targetMethod = (PsiMethod)resolveResult.getElement();
if (targetMethod == null) return;
if (targetMethod.hasModifierProperty(PsiModifier.STATIC)) return;
try {
PsiManager manager = methodExpr.getManager();
PsiElementFactory factory = manager.getElementFactory();
PsiMethodCallExpression newCall = (PsiMethodCallExpression)factory.createExpressionFromText(methodCall.getText(), methodCall);
PsiExpression newQualifier = newCall.getMethodExpression().getQualifierExpression();
PsiExpression newOperand = ((PsiTypeCastExpression)((PsiParenthesizedExpression)newQualifier).getExpression()).getOperand();
newQualifier.replace(newOperand);
final JavaResolveResult newResult = newCall.getMethodExpression().advancedResolve(false);
if (!newResult.isValidResult()) return;
final PsiMethod newTargetMethod = (PsiMethod)newResult.getElement();
final PsiType newReturnType = newResult.getSubstitutor().substitute(newTargetMethod.getReturnType());
final PsiType oldReturnType = resolveResult.getSubstitutor().substitute(targetMethod.getReturnType());
if (newReturnType.equals(oldReturnType)) {
if (newTargetMethod.equals(targetMethod)) {
addToResults(typeCast);
}
else if (
newTargetMethod.getSignature(newResult.getSubstitutor()).equals(targetMethod.getSignature(resolveResult.getSubstitutor())) &&
!(newTargetMethod.isDeprecated() && !targetMethod.isDeprecated())) { // see SCR11555, SCR14559
addToResults(typeCast);
}
}
qualifier = ((PsiTypeCastExpression)((PsiParenthesizedExpression)qualifier).getExpression()).getOperand();
}
catch (IncorrectOperationException e) {
}
}
public void visitNewExpression(PsiNewExpression expression) {
processCall(expression);
super.visitNewExpression(expression);
}
public void visitReferenceExpression(PsiReferenceExpression expression) {
//expression.acceptChildren(this);
}
private void processCall(PsiCallExpression expression){
PsiExpressionList argumentList = expression.getArgumentList();
if (argumentList == null) return;
PsiExpression[] args = argumentList.getExpressions();
PsiMethod oldMethod = expression.resolveMethod();
if (oldMethod == null) return;
PsiParameter[] parameters = oldMethod.getParameterList().getParameters();
try {
for (int i = 0; i < args.length; i++) {
final PsiExpression arg = deparenthesizeExpression(args[i]);
if (arg instanceof PsiTypeCastExpression) {
PsiTypeCastExpression cast = ((PsiTypeCastExpression) arg);
if (i == args.length - 1 && args.length == parameters.length && parameters[i].isVarArgs()) {
//do not mark cast to resolve ambiguity for calling varargs method with inexact argument
continue;
}
PsiCallExpression newCall = (PsiCallExpression) expression.copy();
final PsiExpressionList argList = newCall.getArgumentList();
LOG.assertTrue(argList != null);
PsiExpression[] newArgs = argList.getExpressions();
PsiTypeCastExpression castExpression = (PsiTypeCastExpression) deparenthesizeExpression(newArgs[i]);
PsiExpression castOperand = castExpression.getOperand();
if (castOperand == null) return;
castExpression.replace(castOperand);
final JavaResolveResult newResult = newCall.resolveMethodGenerics();
if (oldMethod.equals(newResult.getElement()) && newResult.isValidResult() &&
Comparing.equal(newCall.getType(), expression.getType())) {
addToResults(cast);
}
}
}
}
catch (IncorrectOperationException e) {
return;
}
for (PsiExpression arg : args) {
if (arg instanceof PsiTypeCastExpression) {
PsiExpression castOperand = ((PsiTypeCastExpression)arg).getOperand();
castOperand.accept(this);
}
else {
arg.accept(this);
}
}
}
public void visitTypeCastExpression(PsiTypeCastExpression typeCast) {
PsiExpression operand = typeCast.getOperand();
if (operand == null) return;
PsiElement expr = deparenthesizeExpression(operand);
if (expr instanceof PsiTypeCastExpression) {
PsiTypeElement typeElement = ((PsiTypeCastExpression)expr).getCastType();
if (typeElement == null) return;
PsiType castType = typeElement.getType();
if (!(castType instanceof PsiPrimitiveType)) {
addToResults((PsiTypeCastExpression)expr);
}
}
else {
PsiElement parent = typeCast.getParent();
if (parent instanceof PsiConditionalExpression) {
if (PsiUtil.getLanguageLevel(typeCast).compareTo(LanguageLevel.JDK_1_5) < 0) {
//branches need to be of the same type
if (!Comparing.equal(operand.getType(),((PsiConditionalExpression)parent).getType())) return;
}
}
processAlreadyHasTypeCast(typeCast);
}
}
private void processAlreadyHasTypeCast(PsiTypeCastExpression typeCast){
PsiElement parent = typeCast.getParent();
while(parent instanceof PsiParenthesizedExpression) parent = parent.getParent();
if (parent instanceof PsiExpressionList) return; // do not replace in arg lists - should be handled by parent
if (isTypeCastSemantical(typeCast)) return;
PsiTypeElement typeElement = typeCast.getCastType();
if (typeElement == null) return;
PsiType toType = typeElement.getType();
PsiType fromType = typeCast.getOperand().getType();
if (fromType == null) return;
if (parent instanceof PsiReferenceExpression) {
if (toType instanceof PsiClassType && fromType instanceof PsiPrimitiveType) return; //explicit boxing
//Check accessibility
if (fromType instanceof PsiClassType) {
final PsiReferenceExpression refExpression = (PsiReferenceExpression)parent;
PsiElement element = refExpression.resolve();
if (!(element instanceof PsiMember)) return;
PsiClass accessClass = ((PsiClassType)fromType).resolve();
if (accessClass == null) return;
if (!parent.getManager().getResolveHelper().isAccessible((PsiMember)element, typeCast, accessClass)) return;
if (!isCastRedundantInRefExpression(refExpression, typeCast.getOperand())) return;
}
}
if (TypeConversionUtil.isAssignable(toType, fromType, false)) {
addToResults(typeCast);
}
}
}
private static boolean isCastRedundantInRefExpression (final PsiReferenceExpression refExpression, final PsiExpression castOperand) {
final PsiElement resolved = refExpression.resolve();
final Ref<Boolean> result = new Ref<Boolean>(Boolean.FALSE);
refExpression.getManager().performActionWithFormatterDisabled(new Runnable() {
public void run() {
try {
final PsiElementFactory elementFactory = refExpression.getManager().getElementFactory();
final PsiExpression copyExpression = elementFactory.createExpressionFromText(refExpression.getText(), refExpression);
if (copyExpression instanceof PsiReferenceExpression) {
final PsiReferenceExpression copy = (PsiReferenceExpression)copyExpression;
final PsiExpression qualifier = copy.getQualifierExpression();
if (qualifier != null) {
qualifier.replace(castOperand);
result.set(Boolean.valueOf(copy.resolve() == resolved));
}
}
}
catch (IncorrectOperationException e) {
}
}
});
return result.get().booleanValue();
}
public static boolean isTypeCastSemantical(PsiTypeCastExpression typeCast) {
PsiExpression operand = typeCast.getOperand();
if (operand != null) {
PsiType opType = operand.getType();
PsiTypeElement typeElement = typeCast.getCastType();
if (typeElement == null) return false;
PsiType castType = typeElement.getType();
if (castType instanceof PsiPrimitiveType) {
if (opType instanceof PsiPrimitiveType) {
return !opType.equals(castType); // let's suppose all not equal primitive casts are necessary
}
}
else if (castType instanceof PsiClassType && ((PsiClassType)castType).hasParameters()) {
if (opType instanceof PsiClassType && ((PsiClassType)opType).isRaw()) return true;
}
}
return false;
}
} | IDEADEV-15170
| inspections/impl/com/intellij/codeInspection/redundantCast/RedundantCastUtil.java | IDEADEV-15170 | <ide><path>nspections/impl/com/intellij/codeInspection/redundantCast/RedundantCastUtil.java
<ide> }
<ide> else if (
<ide> newTargetMethod.getSignature(newResult.getSubstitutor()).equals(targetMethod.getSignature(resolveResult.getSubstitutor())) &&
<del> !(newTargetMethod.isDeprecated() && !targetMethod.isDeprecated())) { // see SCR11555, SCR14559
<add> !(newTargetMethod.isDeprecated() && !targetMethod.isDeprecated()) && // see SCR11555, SCR14559
<add> areThrownExceptionsCompatible(targetMethod, newTargetMethod)) { //see IDEADEV-15170
<ide> addToResults(typeCast);
<ide> }
<ide> }
<ide> }
<ide> catch (IncorrectOperationException e) {
<ide> }
<add> }
<add>
<add> private static boolean areThrownExceptionsCompatible(final PsiMethod targetMethod, final PsiMethod newTargetMethod) {
<add> final PsiClassType[] oldThrowsTypes = targetMethod.getThrowsList().getReferencedTypes();
<add> final PsiClassType[] newThrowsTypes = newTargetMethod.getThrowsList().getReferencedTypes();
<add> for (final PsiClassType throwsType : newThrowsTypes) {
<add> if (!isExceptionThrown(throwsType, oldThrowsTypes)) return false;
<add> }
<add> return true;
<add> }
<add>
<add> private static boolean isExceptionThrown(PsiClassType exceptionType, PsiClassType[] thrownTypes) {
<add> for (final PsiClassType type : thrownTypes) {
<add> if (type.equals(exceptionType)) return true;
<add> }
<add> return false;
<ide> }
<ide>
<ide> public void visitNewExpression(PsiNewExpression expression) { |
|
Java | lgpl-2.1 | 8c1690ad6122d1683d0e6578dae076c2d2d5add1 | 0 | benb/beast-mcmc,benb/beast-mcmc,benb/beast-mcmc,benb/beast-mcmc,benb/beast-mcmc | /*
* TreeMetricStatistic.java
*
* Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.tree;
import dr.evolution.tree.BranchScoreMetric;
import dr.evolution.tree.CladeMetric;
import dr.evolution.tree.Tree;
import dr.inference.model.Statistic;
import dr.xml.*;
import jebl.evolution.treemetrics.BilleraMetric;
import jebl.evolution.treemetrics.CladeHeightMetric;
import jebl.evolution.treemetrics.RobinsonsFouldMetric;
import jebl.evolution.treemetrics.RootedTreeMetric;
import jebl.evolution.trees.SimpleRootedTree;
/**
* A statistic that returns the distance between two trees.
* <p/>
* Currently supports the following metrics,
* 1. compare - returns a 0 for identity of topology, 1 otherwise.
* 2. Billera tree distance.
* 3. ROBINSONS FOULD
* 4. Clade height
* 5. Branch Score
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @author Joseph Heled
* @author Sebastian Hoehna
* @version $Id: TreeMetricStatistic.java,v 1.14 2005/07/11 14:06:25 rambaut Exp $
*/
public class TreeMetricStatistic extends Statistic.Abstract implements TreeStatistic {
public static final String TREE_METRIC_STATISTIC = "treeMetricStatistic";
public static final String TARGET = "target";
public static final String REFERENCE = "reference";
public static final String METHOD = "method";
enum Method {
TOPOLOGY, BILLERA, ROBINSONSFOULD, CLADEHEIGHTM, BRANCHSCORE, CLADEMETRIC
}
public TreeMetricStatistic(String name, Tree target, Tree reference, Method method) {
super(name);
this.target = target;
this.method = method;
switch (method) {
case TOPOLOGY: {
this.referenceNewick = Tree.Utils.uniqueNewick(reference, reference.getRoot());
break;
}
default: {
jreference = Tree.Utils.asJeblTree(reference);
break;
}
}
switch (method) {
case BILLERA:
metric = new BilleraMetric();
break;
case ROBINSONSFOULD:
metric = new RobinsonsFouldMetric();
break;
case CLADEHEIGHTM:
metric = new CladeHeightMetric();
break;
case BRANCHSCORE:
metric = new BranchScoreMetric();
break;
case CLADEMETRIC:
metric = new CladeMetric();
break;
}
}
public void setTree(Tree tree) {
this.target = tree;
}
public Tree getTree() {
return target;
}
public int getDimension() {
return 1;
}
/**
* @return value.
*/
public double getStatisticValue(int dim) {
if (method == Method.TOPOLOGY) {
return compareTreesByTopology();
}
return metric.getMetric(jreference, Tree.Utils.asJeblTree(target));
}
private double compareTreesByTopology() {
final String tar = Tree.Utils.uniqueNewick(target, target.getRoot());
return tar.equals(referenceNewick) ? 0.0 : 1.0;
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return TREE_METRIC_STATISTIC;
}
public Object parseXMLObject(
XMLObject xo)
throws XMLParseException {
String name;
if (xo.hasAttribute(NAME)) {
name = xo.getStringAttribute(NAME);
} else {
name = xo.getId();
}
Tree target = (Tree) xo.getElementFirstChild(TARGET);
Tree reference = (Tree) xo.getElementFirstChild(REFERENCE);
Method m = Method.TOPOLOGY;
if (xo.hasAttribute(METHOD)) {
final String s = xo.getStringAttribute(METHOD);
m = Method.valueOf(s.toUpperCase());
}
return new TreeMetricStatistic(name, target, reference, m);
}
// ************************************************************************
// AbstractXMLObjectParser
// implementation
// ************************************************************************
public String getParserDescription() {
return "A statistic that returns the distance between two trees. "
+ " with method=\"topology\", return a 0 for identity and a 1 for difference. "
+ "With other methods return the distance metric associated with that method.";
}
public Class getReturnType() {
return TreeMetricStatistic.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
new StringAttributeRule(
NAME,
"A name for this statistic primarily for the purposes of logging",
true),
new StringAttributeRule(METHOD, "comparision method ("
+ methodNames(",") + ")", true),
new ElementRule(TARGET, new XMLSyntaxRule[]{new ElementRule(
Tree.class)}),
new ElementRule(REFERENCE, new XMLSyntaxRule[]{new ElementRule(
Tree.class)}),};
};
private static String methodNames(String s) {
String r = "";
for (Method m : Method.values()) {
if (r.length() > 0)
r = r + s;
r = r + m.name();
}
return r;
}
private Method method;
private Tree target = null;
private String referenceNewick = null;
private SimpleRootedTree jreference = null;
RootedTreeMetric metric = null;
}
| src/dr/evomodel/tree/TreeMetricStatistic.java | /*
* TreeMetricStatistic.java
*
* Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.tree;
import dr.evolution.tree.BranchScoreMetric;
import dr.evolution.tree.CladeMetric;
import dr.evolution.tree.Tree;
import dr.inference.model.Statistic;
import dr.xml.*;
import jebl.evolution.treemetrics.BilleraMetric;
import jebl.evolution.treemetrics.CladeHeightMetric;
import jebl.evolution.treemetrics.RobinsonsFouldMetric;
import jebl.evolution.treemetrics.RootedTreeMetric;
import jebl.evolution.trees.SimpleRootedTree;
/**
* A statistic that returns the distance between two trees.
*
* Currently supports the following metrics,
* 1. compare - returns a 0 for identity of topology, 1 otherwise.
* 2. Billera tree distance.
* 3. ROBINSONS FOULD
* 4. Clade height
* 5. Branch Score
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @author Joseph Heled
* @author Sebastian Hoehna
*
* @version $Id: TreeMetricStatistic.java,v 1.14 2005/07/11 14:06:25 rambaut Exp $
*/
public class TreeMetricStatistic extends Statistic.Abstract implements
TreeStatistic {
public static final String TREE_METRIC_STATISTIC = "treeMetricStatistic";
public static final String TARGET = "target";
public static final String REFERENCE = "reference";
public static final String METHOD = "method";
enum Method {
TOPOLOGY, BILLERA, ROBINSONSFOULD, CLADEHEIGHTM, BRANCHSCORE, CLADEMETRIC
}
public TreeMetricStatistic(String name, Tree target, Tree reference,
Method method) {
super(name);
this.target = target;
this.method = method;
switch (method) {
case TOPOLOGY: {
this.referenceNewick = Tree.Utils.uniqueNewick(reference, reference
.getRoot());
break;
}
default: {
jreference = Tree.Utils.asJeblTree(reference);
break;
}
}
switch (method) {
case BILLERA:
metric = new BilleraMetric();
break;
case ROBINSONSFOULD:
metric = new RobinsonsFouldMetric();
break;
case CLADEHEIGHTM:
metric = new CladeHeightMetric();
break;
case BRANCHSCORE:
metric = new BranchScoreMetric();
break;
case CLADEMETRIC:
metric = new CladeMetric();
break;
}
}
public void setTree(Tree tree) {
this.target = tree;
}
public Tree getTree() {
return target;
}
public int getDimension() {
return 1;
}
/** @return value. */
public double getStatisticValue(int dim) {
if (method == Method.TOPOLOGY) {
return compareTreesByTopology();
}
return metric.getMetric(jreference, Tree.Utils.asJeblTree(target));
}
private double compareTreesByTopology() {
return Tree.Utils.uniqueNewick(target, target.getRoot()).equals(
referenceNewick) ? 0.0 : 1.0;
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return TREE_METRIC_STATISTIC;
}
public Object parseXMLObject(
XMLObject xo)
throws XMLParseException {
String name;
if (xo.hasAttribute(NAME)) {
name = xo
.getStringAttribute(NAME);
} else {
name = xo.getId();
}
Tree target = (Tree) xo
.getElementFirstChild(TARGET);
Tree reference = (Tree) xo
.getElementFirstChild(REFERENCE);
Method m = Method.TOPOLOGY;
if (xo.hasAttribute(METHOD)) {
final String s = xo
.getStringAttribute(METHOD);
m = Method.valueOf(s
.toUpperCase());
}
return new TreeMetricStatistic(
name, target, reference, m);
}
// ************************************************************************
// AbstractXMLObjectParser
// implementation
// ************************************************************************
public String getParserDescription() {
return "A statistic that returns the distance between two trees. "
+ " with method=\"topology\", return a 0 for identity and a 1 for difference. "
+ "With other methods return the distance metric associated with that method.";
}
public Class getReturnType() {
return TreeMetricStatistic.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private XMLSyntaxRule[] rules = new XMLSyntaxRule[] {
new StringAttributeRule(
NAME,
"A name for this statistic primarily for the purposes of logging",
true),
new StringAttributeRule(METHOD, "comparision method ("
+ methodNames(",") + ")", true),
new ElementRule(TARGET, new XMLSyntaxRule[] { new ElementRule(
TreeModel.class) }),
new ElementRule(REFERENCE, new XMLSyntaxRule[] { new ElementRule(
Tree.class) }), };
};
private static String methodNames(String s) {
String r = "";
for (Method m : Method.values()) {
if (r.length() > 0)
r = r + s;
r = r + m.name();
}
return r;
}
private Method method;
private Tree target = null;
private String referenceNewick = null;
private SimpleRootedTree jreference = null;
RootedTreeMetric metric = null;
}
| Allow any tree in target, not just tree models
| src/dr/evomodel/tree/TreeMetricStatistic.java | Allow any tree in target, not just tree models | <ide><path>rc/dr/evomodel/tree/TreeMetricStatistic.java
<ide>
<ide> /**
<ide> * A statistic that returns the distance between two trees.
<del> *
<del> * Currently supports the following metrics,
<del> * 1. compare - returns a 0 for identity of topology, 1 otherwise.
<del> * 2. Billera tree distance.
<del> * 3. ROBINSONS FOULD
<del> * 4. Clade height
<add> * <p/>
<add> * Currently supports the following metrics,
<add> * 1. compare - returns a 0 for identity of topology, 1 otherwise.
<add> * 2. Billera tree distance.
<add> * 3. ROBINSONS FOULD
<add> * 4. Clade height
<ide> * 5. Branch Score
<del> *
<add> *
<ide> * @author Alexei Drummond
<ide> * @author Andrew Rambaut
<ide> * @author Joseph Heled
<ide> * @author Sebastian Hoehna
<del> *
<ide> * @version $Id: TreeMetricStatistic.java,v 1.14 2005/07/11 14:06:25 rambaut Exp $
<ide> */
<del>public class TreeMetricStatistic extends Statistic.Abstract implements
<del> TreeStatistic {
<del>
<del> public static final String TREE_METRIC_STATISTIC = "treeMetricStatistic";
<del>
<del> public static final String TARGET = "target";
<del>
<del> public static final String REFERENCE = "reference";
<del>
<del> public static final String METHOD = "method";
<del>
<del> enum Method {
<del> TOPOLOGY, BILLERA, ROBINSONSFOULD, CLADEHEIGHTM, BRANCHSCORE, CLADEMETRIC
<del> }
<del>
<del> public TreeMetricStatistic(String name, Tree target, Tree reference,
<del> Method method) {
<del> super(name);
<del>
<del> this.target = target;
<del> this.method = method;
<del>
<del> switch (method) {
<del> case TOPOLOGY: {
<del> this.referenceNewick = Tree.Utils.uniqueNewick(reference, reference
<del> .getRoot());
<del> break;
<del> }
<del> default: {
<del> jreference = Tree.Utils.asJeblTree(reference);
<del> break;
<del> }
<del> }
<del>
<del> switch (method) {
<del> case BILLERA:
<del> metric = new BilleraMetric();
<del> break;
<del> case ROBINSONSFOULD:
<del> metric = new RobinsonsFouldMetric();
<del> break;
<del> case CLADEHEIGHTM:
<del> metric = new CladeHeightMetric();
<del> break;
<del> case BRANCHSCORE:
<del> metric = new BranchScoreMetric();
<del> break;
<del> case CLADEMETRIC:
<del> metric = new CladeMetric();
<del> break;
<del> }
<del> }
<del>
<del> public void setTree(Tree tree) {
<del> this.target = tree;
<del> }
<del>
<del> public Tree getTree() {
<del> return target;
<del> }
<del>
<del> public int getDimension() {
<del> return 1;
<del> }
<del>
<del> /** @return value. */
<del> public double getStatisticValue(int dim) {
<del>
<del> if (method == Method.TOPOLOGY) {
<del> return compareTreesByTopology();
<del> }
<del>
<del> return metric.getMetric(jreference, Tree.Utils.asJeblTree(target));
<del> }
<del>
<del> private double compareTreesByTopology() {
<del> return Tree.Utils.uniqueNewick(target, target.getRoot()).equals(
<del> referenceNewick) ? 0.0 : 1.0;
<del> }
<del>
<del> public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
<del>
<del> public String getParserName() {
<del> return TREE_METRIC_STATISTIC;
<del> }
<del>
<del> public Object parseXMLObject(
<del> XMLObject xo)
<del> throws XMLParseException {
<del>
<del> String name;
<del> if (xo.hasAttribute(NAME)) {
<del> name = xo
<del> .getStringAttribute(NAME);
<del> } else {
<del> name = xo.getId();
<del> }
<del> Tree target = (Tree) xo
<del> .getElementFirstChild(TARGET);
<del> Tree reference = (Tree) xo
<del> .getElementFirstChild(REFERENCE);
<del>
<del> Method m = Method.TOPOLOGY;
<del> if (xo.hasAttribute(METHOD)) {
<del> final String s = xo
<del> .getStringAttribute(METHOD);
<del> m = Method.valueOf(s
<del> .toUpperCase());
<del> }
<del> return new TreeMetricStatistic(
<del> name, target, reference, m);
<del> }
<del>
<del> // ************************************************************************
<del> // AbstractXMLObjectParser
<del> // implementation
<del> // ************************************************************************
<del>
<del> public String getParserDescription() {
<del> return "A statistic that returns the distance between two trees. "
<del> + " with method=\"topology\", return a 0 for identity and a 1 for difference. "
<del> + "With other methods return the distance metric associated with that method.";
<del> }
<del>
<del> public Class getReturnType() {
<del> return TreeMetricStatistic.class;
<del> }
<del>
<del> public XMLSyntaxRule[] getSyntaxRules() {
<del> return rules;
<del> }
<del>
<del> private XMLSyntaxRule[] rules = new XMLSyntaxRule[] {
<del> new StringAttributeRule(
<del> NAME,
<del> "A name for this statistic primarily for the purposes of logging",
<del> true),
<del> new StringAttributeRule(METHOD, "comparision method ("
<del> + methodNames(",") + ")", true),
<del> new ElementRule(TARGET, new XMLSyntaxRule[] { new ElementRule(
<del> TreeModel.class) }),
<del> new ElementRule(REFERENCE, new XMLSyntaxRule[] { new ElementRule(
<del> Tree.class) }), };
<del>
<del> };
<del>
<del> private static String methodNames(String s) {
<del> String r = "";
<del> for (Method m : Method.values()) {
<del> if (r.length() > 0)
<del> r = r + s;
<del> r = r + m.name();
<del> }
<del> return r;
<del> }
<del>
<del> private Method method;
<del>
<del> private Tree target = null;
<del>
<del> private String referenceNewick = null;
<del>
<del> private SimpleRootedTree jreference = null;
<del>
<del> RootedTreeMetric metric = null;
<add>public class TreeMetricStatistic extends Statistic.Abstract implements TreeStatistic {
<add>
<add> public static final String TREE_METRIC_STATISTIC = "treeMetricStatistic";
<add>
<add> public static final String TARGET = "target";
<add>
<add> public static final String REFERENCE = "reference";
<add>
<add> public static final String METHOD = "method";
<add>
<add> enum Method {
<add> TOPOLOGY, BILLERA, ROBINSONSFOULD, CLADEHEIGHTM, BRANCHSCORE, CLADEMETRIC
<add> }
<add>
<add> public TreeMetricStatistic(String name, Tree target, Tree reference, Method method) {
<add> super(name);
<add>
<add> this.target = target;
<add> this.method = method;
<add>
<add> switch (method) {
<add> case TOPOLOGY: {
<add> this.referenceNewick = Tree.Utils.uniqueNewick(reference, reference.getRoot());
<add> break;
<add> }
<add> default: {
<add> jreference = Tree.Utils.asJeblTree(reference);
<add> break;
<add> }
<add> }
<add>
<add> switch (method) {
<add> case BILLERA:
<add> metric = new BilleraMetric();
<add> break;
<add> case ROBINSONSFOULD:
<add> metric = new RobinsonsFouldMetric();
<add> break;
<add> case CLADEHEIGHTM:
<add> metric = new CladeHeightMetric();
<add> break;
<add> case BRANCHSCORE:
<add> metric = new BranchScoreMetric();
<add> break;
<add> case CLADEMETRIC:
<add> metric = new CladeMetric();
<add> break;
<add> }
<add> }
<add>
<add> public void setTree(Tree tree) {
<add> this.target = tree;
<add> }
<add>
<add> public Tree getTree() {
<add> return target;
<add> }
<add>
<add> public int getDimension() {
<add> return 1;
<add> }
<add>
<add> /**
<add> * @return value.
<add> */
<add> public double getStatisticValue(int dim) {
<add>
<add> if (method == Method.TOPOLOGY) {
<add> return compareTreesByTopology();
<add> }
<add>
<add> return metric.getMetric(jreference, Tree.Utils.asJeblTree(target));
<add> }
<add>
<add> private double compareTreesByTopology() {
<add> final String tar = Tree.Utils.uniqueNewick(target, target.getRoot());
<add> return tar.equals(referenceNewick) ? 0.0 : 1.0;
<add> }
<add>
<add> public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
<add>
<add> public String getParserName() {
<add> return TREE_METRIC_STATISTIC;
<add> }
<add>
<add> public Object parseXMLObject(
<add> XMLObject xo)
<add> throws XMLParseException {
<add>
<add> String name;
<add> if (xo.hasAttribute(NAME)) {
<add> name = xo.getStringAttribute(NAME);
<add> } else {
<add> name = xo.getId();
<add> }
<add> Tree target = (Tree) xo.getElementFirstChild(TARGET);
<add> Tree reference = (Tree) xo.getElementFirstChild(REFERENCE);
<add>
<add> Method m = Method.TOPOLOGY;
<add> if (xo.hasAttribute(METHOD)) {
<add> final String s = xo.getStringAttribute(METHOD);
<add> m = Method.valueOf(s.toUpperCase());
<add> }
<add> return new TreeMetricStatistic(name, target, reference, m);
<add> }
<add>
<add> // ************************************************************************
<add> // AbstractXMLObjectParser
<add> // implementation
<add> // ************************************************************************
<add>
<add> public String getParserDescription() {
<add> return "A statistic that returns the distance between two trees. "
<add> + " with method=\"topology\", return a 0 for identity and a 1 for difference. "
<add> + "With other methods return the distance metric associated with that method.";
<add> }
<add>
<add> public Class getReturnType() {
<add> return TreeMetricStatistic.class;
<add> }
<add>
<add> public XMLSyntaxRule[] getSyntaxRules() {
<add> return rules;
<add> }
<add>
<add> private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
<add> new StringAttributeRule(
<add> NAME,
<add> "A name for this statistic primarily for the purposes of logging",
<add> true),
<add> new StringAttributeRule(METHOD, "comparision method ("
<add> + methodNames(",") + ")", true),
<add> new ElementRule(TARGET, new XMLSyntaxRule[]{new ElementRule(
<add> Tree.class)}),
<add> new ElementRule(REFERENCE, new XMLSyntaxRule[]{new ElementRule(
<add> Tree.class)}),};
<add>
<add> };
<add>
<add> private static String methodNames(String s) {
<add> String r = "";
<add> for (Method m : Method.values()) {
<add> if (r.length() > 0)
<add> r = r + s;
<add> r = r + m.name();
<add> }
<add> return r;
<add> }
<add>
<add> private Method method;
<add>
<add> private Tree target = null;
<add>
<add> private String referenceNewick = null;
<add>
<add> private SimpleRootedTree jreference = null;
<add>
<add> RootedTreeMetric metric = null;
<ide> } |
|
Java | apache-2.0 | f72561320e6d16656443d1746f97b9f3f3b038e3 | 0 | bmitc/vaadin,asashour/framework,carrchang/vaadin,bmitc/vaadin,udayinfy/vaadin,Legioth/vaadin,sitexa/vaadin,magi42/vaadin,sitexa/vaadin,cbmeeks/vaadin,asashour/framework,cbmeeks/vaadin,asashour/framework,Darsstar/framework,mstahv/framework,travisfw/vaadin,peterl1084/framework,jdahlstrom/vaadin.react,Darsstar/framework,mittop/vaadin,bmitc/vaadin,sitexa/vaadin,mittop/vaadin,asashour/framework,travisfw/vaadin,synes/vaadin,peterl1084/framework,mstahv/framework,carrchang/vaadin,magi42/vaadin,cbmeeks/vaadin,Peppe/vaadin,mstahv/framework,asashour/framework,shahrzadmn/vaadin,udayinfy/vaadin,synes/vaadin,peterl1084/framework,Flamenco/vaadin,synes/vaadin,Darsstar/framework,jdahlstrom/vaadin.react,magi42/vaadin,oalles/vaadin,mittop/vaadin,kironapublic/vaadin,Peppe/vaadin,travisfw/vaadin,peterl1084/framework,Legioth/vaadin,fireflyc/vaadin,mstahv/framework,shahrzadmn/vaadin,sitexa/vaadin,Legioth/vaadin,Scarlethue/vaadin,fireflyc/vaadin,udayinfy/vaadin,shahrzadmn/vaadin,bmitc/vaadin,carrchang/vaadin,travisfw/vaadin,synes/vaadin,kironapublic/vaadin,Scarlethue/vaadin,jdahlstrom/vaadin.react,jdahlstrom/vaadin.react,oalles/vaadin,Legioth/vaadin,kironapublic/vaadin,Scarlethue/vaadin,Scarlethue/vaadin,synes/vaadin,Peppe/vaadin,Scarlethue/vaadin,Flamenco/vaadin,Darsstar/framework,fireflyc/vaadin,sitexa/vaadin,travisfw/vaadin,carrchang/vaadin,shahrzadmn/vaadin,oalles/vaadin,Peppe/vaadin,mstahv/framework,oalles/vaadin,Flamenco/vaadin,fireflyc/vaadin,kironapublic/vaadin,shahrzadmn/vaadin,Peppe/vaadin,magi42/vaadin,mittop/vaadin,Flamenco/vaadin,magi42/vaadin,oalles/vaadin,udayinfy/vaadin,Legioth/vaadin,kironapublic/vaadin,udayinfy/vaadin,peterl1084/framework,Darsstar/framework,cbmeeks/vaadin,jdahlstrom/vaadin.react,fireflyc/vaadin | /*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.dom.client.TableRowElement;
import com.google.gwt.dom.client.TableSectionElement;
import com.google.gwt.dom.client.Touch;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.event.dom.client.TouchStartEvent;
import com.google.gwt.event.dom.client.TouchStartHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Focusable;
import com.vaadin.terminal.gwt.client.MouseEventDetails;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.VConsole;
import com.vaadin.terminal.gwt.client.ui.VScrollTable.VScrollTableBody.VScrollTableRow;
import com.vaadin.terminal.gwt.client.ui.dd.DDUtil;
import com.vaadin.terminal.gwt.client.ui.dd.VAbstractDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VAcceptCallback;
import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager;
import com.vaadin.terminal.gwt.client.ui.dd.VDragEvent;
import com.vaadin.terminal.gwt.client.ui.dd.VHasDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VTransferable;
import com.vaadin.terminal.gwt.client.ui.dd.VerticalDropLocation;
/**
* VScrollTable
*
* VScrollTable is a FlowPanel having two widgets in it: * TableHead component *
* ScrollPanel
*
* TableHead contains table's header and widgets + logic for resizing,
* reordering and hiding columns.
*
* ScrollPanel contains VScrollTableBody object which handles content. To save
* some bandwidth and to improve clients responsiveness with loads of data, in
* VScrollTableBody all rows are not necessary rendered. There are "spacers" in
* VScrollTableBody to use the exact same space as non-rendered rows would use.
* This way we can use seamlessly traditional scrollbars and scrolling to fetch
* more rows instead of "paging".
*
* In VScrollTable we listen to scroll events. On horizontal scrolling we also
* update TableHeads scroll position which has its scrollbars hidden. On
* vertical scroll events we will check if we are reaching the end of area where
* we have rows rendered and
*
* TODO implement unregistering for child components in Cells
*/
public class VScrollTable extends FlowPanel implements Table, ScrollHandler,
VHasDropHandler, FocusHandler, BlurHandler, Focusable, ActionOwner {
private static final String ROW_HEADER_COLUMN_KEY = "0";
public static final String CLASSNAME = "v-table";
public static final String CLASSNAME_SELECTION_FOCUS = CLASSNAME + "-focus";
public static final String ITEM_CLICK_EVENT_ID = "itemClick";
public static final String HEADER_CLICK_EVENT_ID = "handleHeaderClick";
public static final String FOOTER_CLICK_EVENT_ID = "handleFooterClick";
public static final String COLUMN_RESIZE_EVENT_ID = "columnResize";
public static final String COLUMN_REORDER_EVENT_ID = "columnReorder";
private static final double CACHE_RATE_DEFAULT = 2;
/**
* The default multi select mode where simple left clicks only selects one
* item, CTRL+left click selects multiple items and SHIFT-left click selects
* a range of items.
*/
private static final int MULTISELECT_MODE_DEFAULT = 0;
/**
* The simple multiselect mode is what the table used to have before
* ctrl/shift selections were added. That is that when this is set clicking
* on an item selects/deselects the item and no ctrl/shift selections are
* available.
*/
private static final int MULTISELECT_MODE_SIMPLE = 1;
/**
* multiple of pagelength which component will cache when requesting more
* rows
*/
private double cache_rate = CACHE_RATE_DEFAULT;
/**
* fraction of pageLenght which can be scrolled without making new request
*/
private double cache_react_rate = 0.75 * cache_rate;
public static final char ALIGN_CENTER = 'c';
public static final char ALIGN_LEFT = 'b';
public static final char ALIGN_RIGHT = 'e';
private static final int CHARCODE_SPACE = 32;
private int firstRowInViewPort = 0;
private int pageLength = 15;
private int lastRequestedFirstvisible = 0; // to detect "serverside scroll"
protected boolean showRowHeaders = false;
private String[] columnOrder;
protected ApplicationConnection client;
protected String paintableId;
private boolean immediate;
private boolean nullSelectionAllowed = true;
private int selectMode = Table.SELECT_MODE_NONE;
private final HashSet<String> selectedRowKeys = new HashSet<String>();
/*
* When scrolling and selecting at the same time, the selections are not in
* sync with the server while retrieving new rows (until key is released).
*/
private HashSet<Object> unSyncedselectionsBeforeRowFetch;
/*
* These are used when jumping between pages when pressing Home and End
*/
private boolean selectLastItemInNextRender = false;
private boolean selectFirstItemInNextRender = false;
private boolean focusFirstItemInNextRender = false;
private boolean focusLastItemInNextRender = false;
/*
* The currently focused row
*/
private VScrollTableRow focusedRow;
/*
* Helper to store selection range start in when using the keyboard
*/
private VScrollTableRow selectionRangeStart;
/*
* Flag for notifying when the selection has changed and should be sent to
* the server
*/
private boolean selectionChanged = false;
/*
* The speed (in pixels) which the scrolling scrolls vertically/horizontally
*/
private int scrollingVelocity = 10;
private Timer scrollingVelocityTimer = null;
private String[] bodyActionKeys;
/**
* Represents a select range of rows
*/
private class SelectionRange {
private VScrollTableRow startRow;
private final int length;
/**
* Constuctor.
*/
public SelectionRange(VScrollTableRow row1, VScrollTableRow row2) {
VScrollTableRow endRow;
if (row2.isBefore(row1)) {
startRow = row2;
endRow = row1;
} else {
startRow = row1;
endRow = row2;
}
length = endRow.getIndex() - startRow.getIndex() + 1;
}
public SelectionRange(VScrollTableRow row, int length) {
startRow = row;
this.length = length;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return startRow.getKey() + "-" + length;
}
private boolean inRange(VScrollTableRow row) {
return row.getIndex() >= startRow.getIndex()
&& row.getIndex() < startRow.getIndex() + length;
}
public Collection<SelectionRange> split(VScrollTableRow row) {
assert row.isAttached();
ArrayList<SelectionRange> ranges = new ArrayList<SelectionRange>(2);
int endOfFirstRange = row.getIndex() - 1;
if (!(endOfFirstRange - startRow.getIndex() < 0)) {
// create range of first part unless its length is < 1
VScrollTableRow endOfRange = scrollBody
.getRowByRowIndex(endOfFirstRange);
ranges.add(new SelectionRange(startRow, endOfRange));
}
int startOfSecondRange = row.getIndex() + 1;
if (!(getEndIndex() - startOfSecondRange < 0)) {
// create range of second part unless its length is < 1
VScrollTableRow startOfRange = scrollBody
.getRowByRowIndex(startOfSecondRange);
ranges.add(new SelectionRange(startOfRange, getEndIndex()
- startOfSecondRange + 1));
}
return ranges;
}
private int getEndIndex() {
return startRow.getIndex() + length - 1;
}
};
private final HashSet<SelectionRange> selectedRowRanges = new HashSet<SelectionRange>();
private boolean initializedAndAttached = false;
/**
* Flag to indicate if a column width recalculation is needed due update.
*/
private boolean headerChangedDuringUpdate = false;
private final TableHead tHead = new TableHead();
private final TableFooter tFoot = new TableFooter();
private final FocusableScrollPanel scrollBodyPanel = new FocusableScrollPanel(
true);
private KeyPressHandler navKeyPressHandler = new KeyPressHandler() {
public void onKeyPress(KeyPressEvent keyPressEvent) {
// This is used for Firefox only, since Firefox auto-repeat
// works correctly only if we use a key press handler, other
// browsers handle it correctly when using a key down handler
if (!BrowserInfo.get().isGecko()) {
return;
}
NativeEvent event = keyPressEvent.getNativeEvent();
if (!enabled) {
// Cancel default keyboard events on a disabled Table
// (prevents scrolling)
event.preventDefault();
} else if (hasFocus) {
// Key code in Firefox/onKeyPress is present only for
// special keys, otherwise 0 is returned
int keyCode = event.getKeyCode();
if (keyCode == 0 && event.getCharCode() == ' ') {
// Provide a keyCode for space to be compatible with
// FireFox keypress event
keyCode = CHARCODE_SPACE;
}
if (handleNavigation(keyCode,
event.getCtrlKey() || event.getMetaKey(),
event.getShiftKey())) {
event.preventDefault();
}
startScrollingVelocityTimer();
}
}
};
private KeyUpHandler navKeyUpHandler = new KeyUpHandler() {
public void onKeyUp(KeyUpEvent keyUpEvent) {
NativeEvent event = keyUpEvent.getNativeEvent();
int keyCode = event.getKeyCode();
if (!isFocusable()) {
cancelScrollingVelocityTimer();
} else if (isNavigationKey(keyCode)) {
if (keyCode == getNavigationDownKey()
|| keyCode == getNavigationUpKey()) {
/*
* in multiselect mode the server may still have value from
* previous page. Clear it unless doing multiselection or
* just moving focus.
*/
if (!event.getShiftKey() && !event.getCtrlKey()) {
instructServerToForgetPreviousSelections();
}
sendSelectedRows();
}
cancelScrollingVelocityTimer();
navKeyDown = false;
}
}
};
private KeyDownHandler navKeyDownHandler = new KeyDownHandler() {
public void onKeyDown(KeyDownEvent keyDownEvent) {
NativeEvent event = keyDownEvent.getNativeEvent();
// This is not used for Firefox
if (BrowserInfo.get().isGecko()) {
return;
}
if (!enabled) {
// Cancel default keyboard events on a disabled Table
// (prevents scrolling)
event.preventDefault();
} else if (hasFocus) {
if (handleNavigation(event.getKeyCode(), event.getCtrlKey()
|| event.getMetaKey(), event.getShiftKey())) {
navKeyDown = true;
event.preventDefault();
}
startScrollingVelocityTimer();
}
}
};
private int totalRows;
private Set<String> collapsedColumns;
private final RowRequestHandler rowRequestHandler;
private VScrollTableBody scrollBody;
private int firstvisible = 0;
private boolean sortAscending;
private String sortColumn;
private boolean columnReordering;
/**
* This map contains captions and icon urls for actions like: * "33_c" ->
* "Edit" * "33_i" -> "http://dom.com/edit.png"
*/
private final HashMap<Object, String> actionMap = new HashMap<Object, String>();
private String[] visibleColOrder;
private boolean initialContentReceived = false;
private Element scrollPositionElement;
private boolean enabled;
private boolean showColHeaders;
private boolean showColFooters;
/** flag to indicate that table body has changed */
private boolean isNewBody = true;
/*
* Read from the "recalcWidths" -attribute. When it is true, the table will
* recalculate the widths for columns - desirable in some cases. For #1983,
* marked experimental.
*/
boolean recalcWidths = false;
private final ArrayList<Panel> lazyUnregistryBag = new ArrayList<Panel>();
private String height;
private String width = "";
private boolean rendering = false;
private boolean hasFocus = false;
private int dragmode;
private int multiselectmode = BrowserInfo.get().isTouchDevice() ? MULTISELECT_MODE_SIMPLE
: MULTISELECT_MODE_DEFAULT;;
private int tabIndex;
private TouchScrollDelegate touchScrollDelegate;
public VScrollTable() {
scrollBodyPanel.setStyleName(CLASSNAME + "-body-wrapper");
scrollBodyPanel.addFocusHandler(this);
scrollBodyPanel.addBlurHandler(this);
scrollBodyPanel.addScrollHandler(this);
scrollBodyPanel.setStyleName(CLASSNAME + "-body");
/*
* Firefox auto-repeat works correctly only if we use a key press
* handler, other browsers handle it correctly when using a key down
* handler
*/
if (BrowserInfo.get().isGecko()) {
scrollBodyPanel.addKeyPressHandler(navKeyPressHandler);
} else {
scrollBodyPanel.addKeyDownHandler(navKeyDownHandler);
}
scrollBodyPanel.addKeyUpHandler(navKeyUpHandler);
scrollBodyPanel.sinkEvents(Event.TOUCHEVENTS);
scrollBodyPanel.addDomHandler(new TouchStartHandler() {
public void onTouchStart(TouchStartEvent event) {
getTouchScrollDelegate().onTouchStart(event);
}
}, TouchStartEvent.getType());
scrollBodyPanel.sinkEvents(Event.ONCONTEXTMENU);
scrollBodyPanel.addDomHandler(new ContextMenuHandler() {
public void onContextMenu(ContextMenuEvent event) {
handleBodyContextMenu(event);
}
}, ContextMenuEvent.getType());
setStyleName(CLASSNAME);
add(tHead);
add(scrollBodyPanel);
add(tFoot);
rowRequestHandler = new RowRequestHandler();
}
protected TouchScrollDelegate getTouchScrollDelegate() {
if (touchScrollDelegate == null) {
touchScrollDelegate = new TouchScrollDelegate(
scrollBodyPanel.getElement());
}
return touchScrollDelegate;
}
private void handleBodyContextMenu(ContextMenuEvent event) {
if (enabled && bodyActionKeys != null) {
int left = Util.getTouchOrMouseClientX(event.getNativeEvent());
int top = Util.getTouchOrMouseClientY(event.getNativeEvent());
top += Window.getScrollTop();
left += Window.getScrollLeft();
client.getContextMenu().showAt(this, left, top);
}
event.stopPropagation();
event.preventDefault();
}
/**
* Fires a column resize event which sends the resize information to the
* server.
*
* @param columnId
* The columnId of the column which was resized
* @param originalWidth
* The width in pixels of the column before the resize event
* @param newWidth
* The width in pixels of the column after the resize event
*/
private void fireColumnResizeEvent(String columnId, int originalWidth,
int newWidth) {
client.updateVariable(paintableId, "columnResizeEventColumn", columnId,
false);
client.updateVariable(paintableId, "columnResizeEventPrev",
originalWidth, false);
client.updateVariable(paintableId, "columnResizeEventCurr", newWidth,
immediate);
}
/**
* Non-immediate variable update of column widths for a collection of
* columns.
*
* @param columns
* the columns to trigger the events for.
*/
private void sendColumnWidthUpdates(Collection<HeaderCell> columns) {
String[] newSizes = new String[columns.size()];
int ix = 0;
for (HeaderCell cell : columns) {
newSizes[ix++] = cell.getColKey() + ":" + cell.getWidth();
}
client.updateVariable(paintableId, "columnWidthUpdates", newSizes,
false);
}
/**
* Moves the focus one step down
*
* @return Returns true if succeeded
*/
private boolean moveFocusDown() {
return moveFocusDown(0);
}
/**
* Moves the focus down by 1+offset rows
*
* @return Returns true if succeeded, else false if the selection could not
* be move downwards
*/
private boolean moveFocusDown(int offset) {
if (isSelectable()) {
if (focusedRow == null && scrollBody.iterator().hasNext()) {
// FIXME should focus first visible from top, not first rendered
// ??
return setRowFocus((VScrollTableRow) scrollBody.iterator()
.next());
} else {
VScrollTableRow next = getNextRow(focusedRow, offset);
if (next != null) {
return setRowFocus(next);
}
}
}
return false;
}
/**
* Moves the selection one step up
*
* @return Returns true if succeeded
*/
private boolean moveFocusUp() {
return moveFocusUp(0);
}
/**
* Moves the focus row upwards
*
* @return Returns true if succeeded, else false if the selection could not
* be move upwards
*
*/
private boolean moveFocusUp(int offset) {
if (isSelectable()) {
if (focusedRow == null && scrollBody.iterator().hasNext()) {
// FIXME logic is exactly the same as in moveFocusDown, should
// be the opposite??
return setRowFocus((VScrollTableRow) scrollBody.iterator()
.next());
} else {
VScrollTableRow prev = getPreviousRow(focusedRow, offset);
if (prev != null) {
return setRowFocus(prev);
} else {
VConsole.log("no previous available");
}
}
}
return false;
}
/**
* Selects a row where the current selection head is
*
* @param ctrlSelect
* Is the selection a ctrl+selection
* @param shiftSelect
* Is the selection a shift+selection
* @return Returns truw
*/
private void selectFocusedRow(boolean ctrlSelect, boolean shiftSelect) {
if (focusedRow != null) {
// Arrows moves the selection and clears previous selections
if (isSelectable() && !ctrlSelect && !shiftSelect) {
deselectAll();
focusedRow.toggleSelection();
selectionRangeStart = focusedRow;
}
// Ctrl+arrows moves selection head
else if (isSelectable() && ctrlSelect && !shiftSelect) {
selectionRangeStart = focusedRow;
// No selection, only selection head is moved
}
// Shift+arrows selection selects a range
else if (selectMode == SELECT_MODE_MULTI && !ctrlSelect
&& shiftSelect) {
focusedRow.toggleShiftSelection(shiftSelect);
}
}
}
/**
* Sends the selection to the server if changed since the last update/visit.
*/
protected void sendSelectedRows() {
// Don't send anything if selection has not changed
if (!selectionChanged) {
return;
}
// Reset selection changed flag
selectionChanged = false;
// Note: changing the immediateness of this might require changes to
// "clickEvent" immediateness also.
if (multiselectmode == MULTISELECT_MODE_DEFAULT) {
// Convert ranges to a set of strings
Set<String> ranges = new HashSet<String>();
for (SelectionRange range : selectedRowRanges) {
ranges.add(range.toString());
}
// Send the selected row ranges
client.updateVariable(paintableId, "selectedRanges",
ranges.toArray(new String[selectedRowRanges.size()]), false);
// clean selectedRowKeys so that they don't contain excess values
for (Iterator<String> iterator = selectedRowKeys.iterator(); iterator
.hasNext();) {
String key = iterator.next();
VScrollTableRow renderedRowByKey = getRenderedRowByKey(key);
if (renderedRowByKey != null) {
for (SelectionRange range : selectedRowRanges) {
if (range.inRange(renderedRowByKey)) {
iterator.remove();
}
}
} else {
// orphaned selected key, must be in a range, ignore
iterator.remove();
}
}
}
// Send the selected rows
client.updateVariable(paintableId, "selected",
selectedRowKeys.toArray(new String[selectedRowKeys.size()]),
immediate);
}
/**
* Get the key that moves the selection head upwards. By default it is the
* up arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationUpKey() {
return KeyCodes.KEY_UP;
}
/**
* Get the key that moves the selection head downwards. By default it is the
* down arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationDownKey() {
return KeyCodes.KEY_DOWN;
}
/**
* Get the key that scrolls to the left in the table. By default it is the
* left arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationLeftKey() {
return KeyCodes.KEY_LEFT;
}
/**
* Get the key that scroll to the right on the table. By default it is the
* right arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationRightKey() {
return KeyCodes.KEY_RIGHT;
}
/**
* Get the key that selects an item in the table. By default it is the space
* bar key but by overriding this you can change the key to whatever you
* want.
*
* @return
*/
protected int getNavigationSelectKey() {
return CHARCODE_SPACE;
}
/**
* Get the key the moves the selection one page up in the table. By default
* this is the Page Up key but by overriding this you can change the key to
* whatever you want.
*
* @return
*/
protected int getNavigationPageUpKey() {
return KeyCodes.KEY_PAGEUP;
}
/**
* Get the key the moves the selection one page down in the table. By
* default this is the Page Down key but by overriding this you can change
* the key to whatever you want.
*
* @return
*/
protected int getNavigationPageDownKey() {
return KeyCodes.KEY_PAGEDOWN;
}
/**
* Get the key the moves the selection to the beginning of the table. By
* default this is the Home key but by overriding this you can change the
* key to whatever you want.
*
* @return
*/
protected int getNavigationStartKey() {
return KeyCodes.KEY_HOME;
}
/**
* Get the key the moves the selection to the end of the table. By default
* this is the End key but by overriding this you can change the key to
* whatever you want.
*
* @return
*/
protected int getNavigationEndKey() {
return KeyCodes.KEY_END;
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.terminal.gwt.client.Paintable#updateFromUIDL(com.vaadin.terminal
* .gwt.client.UIDL, com.vaadin.terminal.gwt.client.ApplicationConnection)
*/
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
rendering = true;
/*
* We need to do this before updateComponent since updateComponent calls
* this.setHeight() which will calculate a new body height depending on
* the space available.
*/
if (uidl.hasAttribute("colfooters")) {
showColFooters = uidl.getBooleanAttribute("colfooters");
}
tFoot.setVisible(showColFooters);
if (client.updateComponent(this, uidl, true)) {
rendering = false;
return;
}
// we may have pending cache row fetch, cancel it. See #2136
rowRequestHandler.cancel();
enabled = !uidl.hasAttribute("disabled");
if (BrowserInfo.get().isIE8() && !enabled) {
/*
* The disabled shim will not cover the table body if it is
* relative in IE8. See #7324
*/
scrollBodyPanel.getElement().getStyle()
.setPosition(Position.STATIC);
} else if (BrowserInfo.get().isIE8()) {
scrollBodyPanel.getElement().getStyle()
.setPosition(Position.RELATIVE);
}
this.client = client;
paintableId = uidl.getStringAttribute("id");
immediate = uidl.getBooleanAttribute("immediate");
final int newTotalRows = uidl.getIntAttribute("totalrows");
if (newTotalRows != totalRows) {
if (scrollBody != null) {
if (totalRows == 0) {
tHead.clear();
tFoot.clear();
}
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
totalRows = newTotalRows;
}
dragmode = uidl.hasAttribute("dragmode") ? uidl
.getIntAttribute("dragmode") : 0;
if (BrowserInfo.get().isIE()) {
if (dragmode > 0) {
getElement().setPropertyJSO("onselectstart",
getPreventTextSelectionIEHack());
} else {
getElement().setPropertyJSO("onselectstart", null);
}
}
tabIndex = uidl.hasAttribute("tabindex") ? uidl
.getIntAttribute("tabindex") : 0;
if (!BrowserInfo.get().isTouchDevice()) {
multiselectmode = uidl.hasAttribute("multiselectmode") ? uidl
.getIntAttribute("multiselectmode")
: MULTISELECT_MODE_DEFAULT;
}
if (uidl.hasAttribute("alb")) {
bodyActionKeys = uidl.getStringArrayAttribute("alb");
} else {
// Need to clear the actions if the action handlers have been
// removed
bodyActionKeys = null;
}
setCacheRate(uidl.hasAttribute("cr") ? uidl.getDoubleAttribute("cr")
: CACHE_RATE_DEFAULT);
recalcWidths = uidl.hasAttribute("recalcWidths");
if (recalcWidths) {
tHead.clear();
tFoot.clear();
}
int oldPageLength = pageLength;
if (uidl.hasAttribute("pagelength")) {
pageLength = uidl.getIntAttribute("pagelength");
} else {
// pagelenght is "0" meaning scrolling is turned off
pageLength = totalRows;
}
if (oldPageLength != pageLength && initializedAndAttached) {
// page length changed, need to update size
sizeInit();
}
firstvisible = uidl.hasVariable("firstvisible") ? uidl
.getIntVariable("firstvisible") : 0;
if (firstvisible != lastRequestedFirstvisible && scrollBody != null) {
// received 'surprising' firstvisible from server: scroll there
firstRowInViewPort = firstvisible;
scrollBodyPanel.setScrollPosition((int) (firstvisible * scrollBody
.getRowHeight()));
}
showRowHeaders = uidl.getBooleanAttribute("rowheaders");
showColHeaders = uidl.getBooleanAttribute("colheaders");
nullSelectionAllowed = uidl.hasAttribute("nsa") ? uidl
.getBooleanAttribute("nsa") : true;
String oldSortColumn = sortColumn;
if (uidl.hasVariable("sortascending")) {
sortAscending = uidl.getBooleanVariable("sortascending");
sortColumn = uidl.getStringVariable("sortcolumn");
}
boolean keyboardSelectionOverRowFetchInProgress = false;
if (uidl.hasVariable("selected")) {
final Set<String> selectedKeys = uidl
.getStringArrayVariableAsSet("selected");
if (scrollBody != null) {
Iterator<Widget> iterator = scrollBody.iterator();
while (iterator.hasNext()) {
/*
* Make the focus reflect to the server side state unless we
* are currently selecting multiple rows with keyboard.
*/
VScrollTableRow row = (VScrollTableRow) iterator.next();
boolean selected = selectedKeys.contains(row.getKey());
if (!selected
&& unSyncedselectionsBeforeRowFetch != null
&& unSyncedselectionsBeforeRowFetch.contains(row
.getKey())) {
selected = true;
keyboardSelectionOverRowFetchInProgress = true;
}
if (selected != row.isSelected()) {
row.toggleSelection();
}
}
}
}
unSyncedselectionsBeforeRowFetch = null;
if (uidl.hasAttribute("selectmode")) {
if (uidl.getBooleanAttribute("readonly")) {
selectMode = Table.SELECT_MODE_NONE;
} else if (uidl.getStringAttribute("selectmode").equals("multi")) {
selectMode = Table.SELECT_MODE_MULTI;
} else if (uidl.getStringAttribute("selectmode").equals("single")) {
selectMode = Table.SELECT_MODE_SINGLE;
} else {
selectMode = Table.SELECT_MODE_NONE;
}
}
if (uidl.hasVariable("columnorder")) {
columnReordering = true;
columnOrder = uidl.getStringArrayVariable("columnorder");
} else {
columnReordering = false;
columnOrder = null;
}
if (uidl.hasVariable("collapsedcolumns")) {
tHead.setColumnCollapsingAllowed(true);
collapsedColumns = uidl
.getStringArrayVariableAsSet("collapsedcolumns");
} else {
tHead.setColumnCollapsingAllowed(false);
}
UIDL rowData = null;
UIDL ac = null;
for (final Iterator<Object> it = uidl.getChildIterator(); it.hasNext();) {
final UIDL c = (UIDL) it.next();
if (c.getTag().equals("rows")) {
rowData = c;
} else if (c.getTag().equals("actions")) {
updateActionMap(c);
} else if (c.getTag().equals("visiblecolumns")) {
tHead.updateCellsFromUIDL(c);
tFoot.updateCellsFromUIDL(c);
} else if (c.getTag().equals("-ac")) {
ac = c;
}
}
if (ac == null) {
if (dropHandler != null) {
// remove dropHandler if not present anymore
dropHandler = null;
}
} else {
if (dropHandler == null) {
dropHandler = new VScrollTableDropHandler();
}
dropHandler.updateAcceptRules(ac);
}
updateHeader(uidl.getStringArrayAttribute("vcolorder"));
updateFooter(uidl.getStringArrayAttribute("vcolorder"));
if (!recalcWidths && initializedAndAttached) {
updateBody(rowData, uidl.getIntAttribute("firstrow"),
uidl.getIntAttribute("rows"));
if (headerChangedDuringUpdate) {
lazyAdjustColumnWidths.schedule(1);
} else {
// webkits may still bug with their disturbing scrollbar bug,
// See #3457
// run overflow fix for scrollable area
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel
.getElement());
}
});
}
} else {
if (scrollBody != null) {
scrollBody.removeFromParent();
lazyUnregistryBag.add(scrollBody);
}
scrollBody = createScrollBody();
scrollBody.renderInitialRows(rowData,
uidl.getIntAttribute("firstrow"),
uidl.getIntAttribute("rows"));
scrollBodyPanel.add(scrollBody);
initialContentReceived = true;
if (isAttached()) {
sizeInit();
}
scrollBody.restoreRowVisibility();
}
if (selectMode == Table.SELECT_MODE_NONE) {
scrollBody.addStyleName(CLASSNAME + "-body-noselection");
} else {
scrollBody.removeStyleName(CLASSNAME + "-body-noselection");
}
hideScrollPositionAnnotation();
purgeUnregistryBag();
// selection is no in sync with server, avoid excessive server visits by
// clearing to flag used during the normal operation
if (!keyboardSelectionOverRowFetchInProgress) {
selectionChanged = false;
}
/*
* This is called when the Home or page up button has been pressed in
* selectable mode and the next selected row was not yet rendered in the
* client
*/
if (selectFirstItemInNextRender || focusFirstItemInNextRender) {
selectFirstRenderedRowInViewPort(focusFirstItemInNextRender);
selectFirstItemInNextRender = focusFirstItemInNextRender = false;
}
/*
* This is called when the page down or end button has been pressed in
* selectable mode and the next selected row was not yet rendered in the
* client
*/
if (selectLastItemInNextRender || focusLastItemInNextRender) {
selectLastRenderedRowInViewPort(focusLastItemInNextRender);
selectLastItemInNextRender = focusLastItemInNextRender = false;
}
multiselectPending = false;
if (focusedRow != null) {
if (!focusedRow.isAttached()) {
// focused row has been orphaned, can't focus
focusRowFromBody();
}
}
setProperTabIndex();
// Force recalculation of the captionContainer element inside the header
// cell to accomodate for the size of the sort arrow.
HeaderCell sortedHeader = tHead.getHeaderCell(sortColumn);
if (sortedHeader != null) {
sortedHeader.resizeCaptionContainer();
}
// Also recalculate the width of the captionContainer element in the
// previously sorted header, since this now has more room.
HeaderCell oldSortedHeader = tHead.getHeaderCell(oldSortColumn);
if (oldSortedHeader != null) {
oldSortedHeader.resizeCaptionContainer();
}
rendering = false;
headerChangedDuringUpdate = false;
}
private void focusRowFromBody() {
if (selectedRowKeys.size() == 1) {
// try to focus a row currently selected and in viewport
String selectedRowKey = selectedRowKeys.iterator().next();
if (selectedRowKey != null) {
VScrollTableRow renderedRow = getRenderedRowByKey(selectedRowKey);
if (renderedRow == null || !renderedRow.isInViewPort()) {
setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
} else {
setRowFocus(renderedRow);
}
}
} else {
// multiselect mode
setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
}
}
protected VScrollTableBody createScrollBody() {
return new VScrollTableBody();
}
/**
* Selects the last row visible in the table
*
* @param focusOnly
* Should the focus only be moved to the last row
*/
private void selectLastRenderedRowInViewPort(boolean focusOnly) {
int index = firstRowInViewPort + getFullyVisibleRowCount();
VScrollTableRow lastRowInViewport = scrollBody.getRowByRowIndex(index);
if (lastRowInViewport == null) {
// this should not happen in normal situations (white space at the
// end of viewport). Select the last rendered as a fallback.
lastRowInViewport = scrollBody.getRowByRowIndex(scrollBody
.getLastRendered());
if (lastRowInViewport == null) {
return; // empty table
}
}
setRowFocus(lastRowInViewport);
if (!focusOnly) {
selectFocusedRow(false, multiselectPending);
sendSelectedRows();
}
}
/**
* Selects the first row visible in the table
*
* @param focusOnly
* Should the focus only be moved to the first row
*/
private void selectFirstRenderedRowInViewPort(boolean focusOnly) {
int index = firstRowInViewPort;
VScrollTableRow firstInViewport = scrollBody.getRowByRowIndex(index);
if (firstInViewport == null) {
// this should not happen in normal situations
return;
}
setRowFocus(firstInViewport);
if (!focusOnly) {
selectFocusedRow(false, multiselectPending);
sendSelectedRows();
}
}
private void setCacheRate(double d) {
if (cache_rate != d) {
cache_rate = d;
cache_react_rate = 0.75 * d;
}
}
/**
* Unregisters Paintables in "trashed" HasWidgets (IScrollTableBodys or
* IScrollTableRows). This is done lazily as Table must survive from
* "subtreecaching" logic.
*/
private void purgeUnregistryBag() {
for (Iterator<Panel> iterator = lazyUnregistryBag.iterator(); iterator
.hasNext();) {
client.unregisterChildPaintables(iterator.next());
}
lazyUnregistryBag.clear();
}
private void updateActionMap(UIDL c) {
final Iterator<?> it = c.getChildIterator();
while (it.hasNext()) {
final UIDL action = (UIDL) it.next();
final String key = action.getStringAttribute("key");
final String caption = action.getStringAttribute("caption");
actionMap.put(key + "_c", caption);
if (action.hasAttribute("icon")) {
// TODO need some uri handling ??
actionMap.put(key + "_i", client.translateVaadinUri(action
.getStringAttribute("icon")));
} else {
actionMap.remove(key + "_i");
}
}
}
public String getActionCaption(String actionKey) {
return actionMap.get(actionKey + "_c");
}
public String getActionIcon(String actionKey) {
return actionMap.get(actionKey + "_i");
}
private void updateHeader(String[] strings) {
if (strings == null) {
return;
}
int visibleCols = strings.length;
int colIndex = 0;
if (showRowHeaders) {
tHead.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
visibleCols++;
visibleColOrder = new String[visibleCols];
visibleColOrder[colIndex] = ROW_HEADER_COLUMN_KEY;
colIndex++;
} else {
visibleColOrder = new String[visibleCols];
tHead.removeCell(ROW_HEADER_COLUMN_KEY);
}
int i;
for (i = 0; i < strings.length; i++) {
final String cid = strings[i];
visibleColOrder[colIndex] = cid;
tHead.enableColumn(cid, colIndex);
colIndex++;
}
tHead.setVisible(showColHeaders);
setContainerHeight();
}
/**
* Updates footers.
* <p>
* Update headers whould be called before this method is called!
* </p>
*
* @param strings
*/
private void updateFooter(String[] strings) {
if (strings == null) {
return;
}
// Add dummy column if row headers are present
int colIndex = 0;
if (showRowHeaders) {
tFoot.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
colIndex++;
} else {
tFoot.removeCell(ROW_HEADER_COLUMN_KEY);
}
int i;
for (i = 0; i < strings.length; i++) {
final String cid = strings[i];
tFoot.enableColumn(cid, colIndex);
colIndex++;
}
tFoot.setVisible(showColFooters);
}
/**
* @param uidl
* which contains row data
* @param firstRow
* first row in data set
* @param reqRows
* amount of rows in data set
*/
private void updateBody(UIDL uidl, int firstRow, int reqRows) {
if (uidl == null || reqRows < 1) {
// container is empty, remove possibly existing rows
if (firstRow < 0) {
while (scrollBody.getLastRendered() > scrollBody.firstRendered) {
scrollBody.unlinkRow(false);
}
scrollBody.unlinkRow(false);
}
return;
}
scrollBody.renderRows(uidl, firstRow, reqRows);
final int optimalFirstRow = (int) (firstRowInViewPort - pageLength
* cache_rate);
boolean cont = true;
while (cont && scrollBody.getLastRendered() > optimalFirstRow
&& scrollBody.getFirstRendered() < optimalFirstRow) {
// removing row from start
cont = scrollBody.unlinkRow(true);
}
final int optimalLastRow = (int) (firstRowInViewPort + pageLength + pageLength
* cache_rate);
cont = true;
while (cont && scrollBody.getLastRendered() > optimalLastRow) {
// removing row from the end
cont = scrollBody.unlinkRow(false);
}
scrollBody.fixSpacers();
scrollBody.restoreRowVisibility();
}
/**
* Gives correct column index for given column key ("cid" in UIDL).
*
* @param colKey
* @return column index of visible columns, -1 if column not visible
*/
private int getColIndexByKey(String colKey) {
// return 0 if asked for rowHeaders
if (ROW_HEADER_COLUMN_KEY.equals(colKey)) {
return 0;
}
for (int i = 0; i < visibleColOrder.length; i++) {
if (visibleColOrder[i].equals(colKey)) {
return i;
}
}
return -1;
}
protected boolean isSelectable() {
return selectMode > Table.SELECT_MODE_NONE;
}
private boolean isCollapsedColumn(String colKey) {
if (collapsedColumns == null) {
return false;
}
if (collapsedColumns.contains(colKey)) {
return true;
}
return false;
}
private String getColKeyByIndex(int index) {
return tHead.getHeaderCell(index).getColKey();
}
private void setColWidth(int colIndex, int w, boolean isDefinedWidth) {
final HeaderCell hcell = tHead.getHeaderCell(colIndex);
// Make sure that the column grows to accommodate the sort indicator if
// necessary.
if (w < hcell.getMinWidth()) {
w = hcell.getMinWidth();
}
// Set header column width
hcell.setWidth(w, isDefinedWidth);
// Set body column width
scrollBody.setColWidth(colIndex, w);
// Set footer column width
FooterCell fcell = tFoot.getFooterCell(colIndex);
fcell.setWidth(w, isDefinedWidth);
}
private int getColWidth(String colKey) {
return tHead.getHeaderCell(colKey).getWidth();
}
/**
* Get a rendered row by its key
*
* @param key
* The key to search with
* @return
*/
private VScrollTableRow getRenderedRowByKey(String key) {
if (scrollBody != null) {
final Iterator<Widget> it = scrollBody.iterator();
VScrollTableRow r = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (r.getKey().equals(key)) {
return r;
}
}
}
return null;
}
/**
* Returns the next row to the given row
*
* @param row
* The row to calculate from
*
* @return The next row or null if no row exists
*/
private VScrollTableRow getNextRow(VScrollTableRow row, int offset) {
final Iterator<Widget> it = scrollBody.iterator();
VScrollTableRow r = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (r == row) {
r = null;
while (offset >= 0 && it.hasNext()) {
r = (VScrollTableRow) it.next();
offset--;
}
return r;
}
}
return null;
}
/**
* Returns the previous row from the given row
*
* @param row
* The row to calculate from
* @return The previous row or null if no row exists
*/
private VScrollTableRow getPreviousRow(VScrollTableRow row, int offset) {
final Iterator<Widget> it = scrollBody.iterator();
final Iterator<Widget> offsetIt = scrollBody.iterator();
VScrollTableRow r = null;
VScrollTableRow prev = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (offset < 0) {
prev = (VScrollTableRow) offsetIt.next();
}
if (r == row) {
return prev;
}
offset--;
}
return null;
}
protected void reOrderColumn(String columnKey, int newIndex) {
final int oldIndex = getColIndexByKey(columnKey);
// Change header order
tHead.moveCell(oldIndex, newIndex);
// Change body order
scrollBody.moveCol(oldIndex, newIndex);
// Change footer order
tFoot.moveCell(oldIndex, newIndex);
/*
* Build new columnOrder and update it to server Note that columnOrder
* also contains collapsed columns so we cannot directly build it from
* cells vector Loop the old columnOrder and append in order to new
* array unless on moved columnKey. On new index also put the moved key
* i == index on columnOrder, j == index on newOrder
*/
final String oldKeyOnNewIndex = visibleColOrder[newIndex];
if (showRowHeaders) {
newIndex--; // columnOrder don't have rowHeader
}
// add back hidden rows,
for (int i = 0; i < columnOrder.length; i++) {
if (columnOrder[i].equals(oldKeyOnNewIndex)) {
break; // break loop at target
}
if (isCollapsedColumn(columnOrder[i])) {
newIndex++;
}
}
// finally we can build the new columnOrder for server
final String[] newOrder = new String[columnOrder.length];
for (int i = 0, j = 0; j < newOrder.length; i++) {
if (j == newIndex) {
newOrder[j] = columnKey;
j++;
}
if (i == columnOrder.length) {
break;
}
if (columnOrder[i].equals(columnKey)) {
continue;
}
newOrder[j] = columnOrder[i];
j++;
}
columnOrder = newOrder;
// also update visibleColumnOrder
int i = showRowHeaders ? 1 : 0;
for (int j = 0; j < newOrder.length; j++) {
final String cid = newOrder[j];
if (!isCollapsedColumn(cid)) {
visibleColOrder[i++] = cid;
}
}
client.updateVariable(paintableId, "columnorder", columnOrder, false);
if (client.hasEventListeners(this, COLUMN_REORDER_EVENT_ID)) {
client.sendPendingVariableChanges();
}
}
@Override
protected void onAttach() {
super.onAttach();
if (initialContentReceived) {
sizeInit();
}
}
@Override
protected void onDetach() {
rowRequestHandler.cancel();
super.onDetach();
// ensure that scrollPosElement will be detached
if (scrollPositionElement != null) {
final Element parent = DOM.getParent(scrollPositionElement);
if (parent != null) {
DOM.removeChild(parent, scrollPositionElement);
}
}
}
/**
* Run only once when component is attached and received its initial
* content. This function : * Syncs headers and bodys "natural widths and
* saves the values. * Sets proper width and height * Makes deferred request
* to get some cache rows
*/
private void sizeInit() {
/*
* We will use browsers table rendering algorithm to find proper column
* widths. If content and header take less space than available, we will
* divide extra space relatively to each column which has not width set.
*
* Overflow pixels are added to last column.
*/
Iterator<Widget> headCells = tHead.iterator();
Iterator<Widget> footCells = tFoot.iterator();
int i = 0;
int totalExplicitColumnsWidths = 0;
int total = 0;
float expandRatioDivider = 0;
final int[] widths = new int[tHead.visibleCells.size()];
tHead.enableBrowserIntelligence();
tFoot.enableBrowserIntelligence();
// first loop: collect natural widths
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
final FooterCell fCell = (FooterCell) footCells.next();
int w = hCell.getWidth();
if (hCell.isDefinedWidth()) {
// server has defined column width explicitly
totalExplicitColumnsWidths += w;
} else {
if (hCell.getExpandRatio() > 0) {
expandRatioDivider += hCell.getExpandRatio();
w = 0;
} else {
// get and store greater of header width and column width,
// and
// store it as a minimumn natural col width
int headerWidth = hCell.getNaturalColumnWidth(i);
int footerWidth = fCell.getNaturalColumnWidth(i);
w = headerWidth > footerWidth ? headerWidth : footerWidth;
}
hCell.setNaturalMinimumColumnWidth(w);
fCell.setNaturalMinimumColumnWidth(w);
}
widths[i] = w;
total += w;
i++;
}
tHead.disableBrowserIntelligence();
tFoot.disableBrowserIntelligence();
boolean willHaveScrollbarz = willHaveScrollbars();
// fix "natural" width if width not set
if (width == null || "".equals(width)) {
int w = total;
w += scrollBody.getCellExtraWidth() * visibleColOrder.length;
if (willHaveScrollbarz) {
w += Util.getNativeScrollbarSize();
}
setContentWidth(w);
}
int availW = scrollBody.getAvailableWidth();
if (BrowserInfo.get().isIE()) {
// Hey IE, are you really sure about this?
availW = scrollBody.getAvailableWidth();
}
availW -= scrollBody.getCellExtraWidth() * visibleColOrder.length;
if (willHaveScrollbarz) {
availW -= Util.getNativeScrollbarSize();
}
// TODO refactor this code to be the same as in resize timer
boolean needsReLayout = false;
if (availW > total) {
// natural size is smaller than available space
final int extraSpace = availW - total;
final int totalWidthR = total - totalExplicitColumnsWidths;
needsReLayout = true;
if (expandRatioDivider > 0) {
// visible columns have some active expand ratios, excess
// space is divided according to them
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hCell = (HeaderCell) headCells.next();
if (hCell.getExpandRatio() > 0) {
int w = widths[i];
final int newSpace = (int) (extraSpace * (hCell
.getExpandRatio() / expandRatioDivider));
w += newSpace;
widths[i] = w;
}
i++;
}
} else if (totalWidthR > 0) {
// no expand ratios defined, we will share extra space
// relatively to "natural widths" among those without
// explicit width
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hCell = (HeaderCell) headCells.next();
if (!hCell.isDefinedWidth()) {
int w = widths[i];
final int newSpace = extraSpace * w / totalWidthR;
w += newSpace;
widths[i] = w;
}
i++;
}
}
} else {
// bodys size will be more than available and scrollbar will appear
}
// last loop: set possibly modified values or reset if new tBody
i = 0;
headCells = tHead.iterator();
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
if (isNewBody || hCell.getWidth() == -1) {
final int w = widths[i];
setColWidth(i, w, false);
}
i++;
}
initializedAndAttached = true;
if (needsReLayout) {
scrollBody.reLayoutComponents();
}
updatePageLength();
/*
* Fix "natural" height if height is not set. This must be after width
* fixing so the components' widths have been adjusted.
*/
if (height == null || "".equals(height)) {
/*
* We must force an update of the row height as this point as it
* might have been (incorrectly) calculated earlier
*/
int bodyHeight;
if (pageLength == totalRows) {
/*
* A hack to support variable height rows when paging is off.
* Generally this is not supported by scrolltable. We want to
* show all rows so the bodyHeight should be equal to the table
* height.
*/
// int bodyHeight = scrollBody.getOffsetHeight();
bodyHeight = scrollBody.getRequiredHeight();
} else {
bodyHeight = (int) Math.round(scrollBody.getRowHeight(true)
* pageLength);
}
boolean needsSpaceForHorizontalSrollbar = (total > availW);
if (needsSpaceForHorizontalSrollbar) {
bodyHeight += Util.getNativeScrollbarSize();
}
scrollBodyPanel.setHeight(bodyHeight + "px");
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
isNewBody = false;
if (firstvisible > 0) {
// Deferred due some Firefox oddities. IE & Safari could survive
// without
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
scrollBodyPanel
.setScrollPosition((int) (firstvisible * scrollBody
.getRowHeight()));
firstRowInViewPort = firstvisible;
}
});
}
if (enabled) {
// Do we need cache rows
if (scrollBody.getLastRendered() + 1 < firstRowInViewPort
+ pageLength + (int) cache_react_rate * pageLength) {
if (totalRows - 1 > scrollBody.getLastRendered()) {
// fetch cache rows
int firstInNewSet = scrollBody.getLastRendered() + 1;
rowRequestHandler.setReqFirstRow(firstInNewSet);
int lastInNewSet = (int) (firstRowInViewPort + pageLength + cache_rate
* pageLength);
if (lastInNewSet > totalRows - 1) {
lastInNewSet = totalRows - 1;
}
rowRequestHandler.setReqRows(lastInNewSet - firstInNewSet
+ 1);
rowRequestHandler.deferRowFetch(1);
}
}
}
/*
* Ensures the column alignments are correct at initial loading. <br/>
* (child components widths are correct)
*/
scrollBody.reLayoutComponents();
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
});
}
/**
* Note, this method is not official api although declared as protected.
* Extend at you own risk.
*
* @return true if content area will have scrollbars visible.
*/
protected boolean willHaveScrollbars() {
if (!(height != null && !height.equals(""))) {
if (pageLength < totalRows) {
return true;
}
} else {
int fakeheight = (int) Math.round(scrollBody.getRowHeight()
* totalRows);
int availableHeight = scrollBodyPanel.getElement().getPropertyInt(
"clientHeight");
if (fakeheight > availableHeight) {
return true;
}
}
return false;
}
private void announceScrollPosition() {
if (scrollPositionElement == null) {
scrollPositionElement = DOM.createDiv();
scrollPositionElement.setClassName(CLASSNAME + "-scrollposition");
scrollPositionElement.getStyle().setPosition(Position.ABSOLUTE);
scrollPositionElement.getStyle().setDisplay(Display.NONE);
getElement().appendChild(scrollPositionElement);
}
Style style = scrollPositionElement.getStyle();
style.setMarginLeft(getElement().getOffsetWidth() / 2 - 80, Unit.PX);
style.setMarginTop(-scrollBodyPanel.getOffsetHeight(), Unit.PX);
// indexes go from 1-totalRows, as rowheaders in index-mode indicate
int last = (firstRowInViewPort + pageLength);
if (last > totalRows) {
last = totalRows;
}
scrollPositionElement.setInnerHTML("<span>" + (firstRowInViewPort + 1)
+ " – " + (last) + "..." + "</span>");
style.setDisplay(Display.BLOCK);
}
private void hideScrollPositionAnnotation() {
if (scrollPositionElement != null) {
DOM.setStyleAttribute(scrollPositionElement, "display", "none");
}
}
private class RowRequestHandler extends Timer {
private int reqFirstRow = 0;
private int reqRows = 0;
public void deferRowFetch() {
deferRowFetch(250);
}
public void deferRowFetch(int msec) {
if (reqRows > 0 && reqFirstRow < totalRows) {
schedule(msec);
// tell scroll position to user if currently "visible" rows are
// not rendered
if (totalRows > pageLength
&& ((firstRowInViewPort + pageLength > scrollBody
.getLastRendered()) || (firstRowInViewPort < scrollBody
.getFirstRendered()))) {
announceScrollPosition();
} else {
hideScrollPositionAnnotation();
}
}
}
public void setReqFirstRow(int reqFirstRow) {
if (reqFirstRow < 0) {
reqFirstRow = 0;
} else if (reqFirstRow >= totalRows) {
reqFirstRow = totalRows - 1;
}
this.reqFirstRow = reqFirstRow;
}
public void setReqRows(int reqRows) {
this.reqRows = reqRows;
}
@Override
public void run() {
if (client.hasActiveRequest() || navKeyDown) {
// if client connection is busy, don't bother loading it more
VConsole.log("Postponed rowfetch");
schedule(250);
} else {
int firstToBeRendered = scrollBody.firstRendered;
if (reqFirstRow < firstToBeRendered) {
firstToBeRendered = reqFirstRow;
} else if (firstRowInViewPort - (int) (cache_rate * pageLength) > firstToBeRendered) {
firstToBeRendered = firstRowInViewPort
- (int) (cache_rate * pageLength);
if (firstToBeRendered < 0) {
firstToBeRendered = 0;
}
}
int lastToBeRendered = scrollBody.lastRendered;
if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
lastToBeRendered = reqFirstRow + reqRows - 1;
} else if (firstRowInViewPort + pageLength + pageLength
* cache_rate < lastToBeRendered) {
lastToBeRendered = (firstRowInViewPort + pageLength + (int) (pageLength * cache_rate));
if (lastToBeRendered >= totalRows) {
lastToBeRendered = totalRows - 1;
}
// due Safari 3.1 bug (see #2607), verify reqrows, original
// problem unknown, but this should catch the issue
if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
reqRows = lastToBeRendered - reqFirstRow;
}
}
client.updateVariable(paintableId, "firstToBeRendered",
firstToBeRendered, false);
client.updateVariable(paintableId, "lastToBeRendered",
lastToBeRendered, false);
// remember which firstvisible we requested, in case the server
// has
// a differing opinion
lastRequestedFirstvisible = firstRowInViewPort;
client.updateVariable(paintableId, "firstvisible",
firstRowInViewPort, false);
client.updateVariable(paintableId, "reqfirstrow", reqFirstRow,
false);
client.updateVariable(paintableId, "reqrows", reqRows, true);
if (selectionChanged) {
unSyncedselectionsBeforeRowFetch = new HashSet<Object>(
selectedRowKeys);
}
}
}
public int getReqFirstRow() {
return reqFirstRow;
}
/**
* Sends request to refresh content at this position.
*/
public void refreshContent() {
int first = (int) (firstRowInViewPort - pageLength * cache_rate);
int reqRows = (int) (2 * pageLength * cache_rate + pageLength);
if (first < 0) {
reqRows = reqRows + first;
first = 0;
}
setReqFirstRow(first);
setReqRows(reqRows);
run();
}
}
public class HeaderCell extends Widget {
Element td = DOM.createTD();
Element captionContainer = DOM.createDiv();
Element sortIndicator = DOM.createDiv();
Element colResizeWidget = DOM.createDiv();
Element floatingCopyOfHeaderCell;
private boolean sortable = false;
private final String cid;
private boolean dragging;
private int dragStartX;
private int colIndex;
private int originalWidth;
private boolean isResizing;
private int headerX;
private boolean moved;
private int closestSlot;
private int width = -1;
private int naturalWidth = -1;
private char align = ALIGN_LEFT;
boolean definedWidth = false;
private float expandRatio = 0;
private boolean sorted;
public void setSortable(boolean b) {
sortable = b;
}
/**
* Makes room for the sorting indicator in case the column that the
* header cell belongs to is sorted. This is done by resizing the width
* of the caption container element by the correct amount
*/
public void resizeCaptionContainer() {
if (BrowserInfo.get().isIE6() || td.getClassName().contains("-asc")
|| td.getClassName().contains("-desc")) {
/*
* Room for the sort indicator is made by subtracting the styled
* margin and width of the resizer from the width of the caption
* container.
*/
int captionContainerWidth = width
- sortIndicator.getOffsetWidth()
- colResizeWidget.getOffsetWidth();
captionContainer.getStyle().setPropertyPx("width",
captionContainerWidth);
} else {
/*
* Set the caption container element as wide as possible when
* the sorting indicator is not visible.
*/
captionContainer.getStyle().setPropertyPx("width", width);
}
}
public void setNaturalMinimumColumnWidth(int w) {
naturalWidth = w;
}
public HeaderCell(String colId, String headerText) {
cid = colId;
DOM.setElementProperty(colResizeWidget, "className", CLASSNAME
+ "-resizer");
setText(headerText);
DOM.appendChild(td, colResizeWidget);
DOM.setElementProperty(sortIndicator, "className", CLASSNAME
+ "-sort-indicator");
DOM.appendChild(td, sortIndicator);
DOM.setElementProperty(captionContainer, "className", CLASSNAME
+ "-caption-container");
// ensure no clipping initially (problem on column additions)
DOM.setStyleAttribute(captionContainer, "overflow", "visible");
DOM.appendChild(td, captionContainer);
DOM.sinkEvents(td, Event.MOUSEEVENTS | Event.TOUCHEVENTS);
setElement(td);
setAlign(ALIGN_LEFT);
}
public void disableAutoWidthCalculation() {
definedWidth = true;
expandRatio = 0;
}
public void setWidth(int w, boolean ensureDefinedWidth) {
if (ensureDefinedWidth) {
definedWidth = true;
// on column resize expand ratio becomes zero
expandRatio = 0;
}
if (width == -1) {
// go to default mode, clip content if necessary
DOM.setStyleAttribute(captionContainer, "overflow", "");
}
width = w;
if (w == -1) {
DOM.setStyleAttribute(captionContainer, "width", "");
setWidth("");
} else {
resizeCaptionContainer();
/*
* if we already have tBody, set the header width properly, if
* not defer it. IE will fail with complex float in table header
* unless TD width is not explicitly set.
*/
if (scrollBody != null) {
int tdWidth = width + scrollBody.getCellExtraWidth();
setWidth(tdWidth + "px");
} else {
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
int tdWidth = width
+ scrollBody.getCellExtraWidth();
setWidth(tdWidth + "px");
}
});
}
}
}
public void setUndefinedWidth() {
definedWidth = false;
setWidth(-1, false);
}
/**
* Detects if width is fixed by developer on server side or resized to
* current width by user.
*
* @return true if defined, false if "natural" width
*/
public boolean isDefinedWidth() {
return definedWidth;
}
public int getWidth() {
return width;
}
public void setText(String headerText) {
DOM.setInnerHTML(captionContainer, headerText);
}
public String getColKey() {
return cid;
}
private void setSorted(boolean sorted) {
this.sorted = sorted;
if (sorted) {
if (sortAscending) {
this.setStyleName(CLASSNAME + "-header-cell-asc");
} else {
this.setStyleName(CLASSNAME + "-header-cell-desc");
}
} else {
this.setStyleName(CLASSNAME + "-header-cell");
}
}
/**
* Handle column reordering.
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled && event != null) {
if (isResizing
|| event.getEventTarget().cast() == colResizeWidget) {
if (dragging
&& (event.getTypeInt() == Event.ONMOUSEUP || event
.getTypeInt() == Event.ONTOUCHEND)) {
// Handle releasing column header on spacer #5318
handleCaptionEvent(event);
} else {
onResizeEvent(event);
}
} else {
/*
* Ensure focus before handling caption event. Otherwise
* variables changed from caption event may be before
* variables from other components that fire variables when
* they lose focus.
*/
if (event.getTypeInt() == Event.ONMOUSEDOWN
|| event.getTypeInt() == Event.ONTOUCHSTART) {
scrollBodyPanel.setFocus(true);
}
handleCaptionEvent(event);
event.stopPropagation();
event.preventDefault();
}
}
}
private void createFloatingCopy() {
floatingCopyOfHeaderCell = DOM.createDiv();
DOM.setInnerHTML(floatingCopyOfHeaderCell, DOM.getInnerHTML(td));
floatingCopyOfHeaderCell = DOM
.getChild(floatingCopyOfHeaderCell, 1);
DOM.setElementProperty(floatingCopyOfHeaderCell, "className",
CLASSNAME + "-header-drag");
updateFloatingCopysPosition(DOM.getAbsoluteLeft(td),
DOM.getAbsoluteTop(td));
DOM.appendChild(RootPanel.get().getElement(),
floatingCopyOfHeaderCell);
}
private void updateFloatingCopysPosition(int x, int y) {
x -= DOM.getElementPropertyInt(floatingCopyOfHeaderCell,
"offsetWidth") / 2;
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "left", x + "px");
if (y > 0) {
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "top", (y + 7)
+ "px");
}
}
private void hideFloatingCopy() {
DOM.removeChild(RootPanel.get().getElement(),
floatingCopyOfHeaderCell);
floatingCopyOfHeaderCell = null;
}
/**
* Fires a header click event after the user has clicked a column header
* cell
*
* @param event
* The click event
*/
private void fireHeaderClickedEvent(Event event) {
if (client.hasEventListeners(VScrollTable.this,
HEADER_CLICK_EVENT_ID)) {
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "headerClickEvent",
details.toString(), false);
client.updateVariable(paintableId, "headerClickCID", cid, true);
}
}
protected void handleCaptionEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONTOUCHSTART:
case Event.ONMOUSEDOWN:
if (columnReordering) {
if (event.getTypeInt() == Event.ONTOUCHSTART) {
/*
* prevent using this event in e.g. scrolling
*/
event.stopPropagation();
}
dragging = true;
moved = false;
colIndex = getColIndexByKey(cid);
DOM.setCapture(getElement());
headerX = tHead.getAbsoluteLeft();
event.preventDefault(); // prevent selecting text &&
// generated touch events
}
break;
case Event.ONMOUSEUP:
case Event.ONTOUCHEND:
case Event.ONTOUCHCANCEL:
if (columnReordering) {
dragging = false;
DOM.releaseCapture(getElement());
if (moved) {
hideFloatingCopy();
tHead.removeSlotFocus();
if (closestSlot != colIndex
&& closestSlot != (colIndex + 1)) {
if (closestSlot > colIndex) {
reOrderColumn(cid, closestSlot - 1);
} else {
reOrderColumn(cid, closestSlot);
}
}
}
if (Util.isTouchEvent(event)) {
/*
* Prevent using in e.g. scrolling and prevent generated
* events.
*/
event.preventDefault();
event.stopPropagation();
}
}
if (!moved) {
// mouse event was a click to header -> sort column
if (sortable) {
if (sortColumn.equals(cid)) {
// just toggle order
client.updateVariable(paintableId, "sortascending",
!sortAscending, false);
} else {
// set table sorted by this column
client.updateVariable(paintableId, "sortcolumn",
cid, false);
}
// get also cache columns at the same request
scrollBodyPanel.setScrollPosition(0);
firstvisible = 0;
rowRequestHandler.setReqFirstRow(0);
rowRequestHandler.setReqRows((int) (2 * pageLength
* cache_rate + pageLength));
rowRequestHandler.deferRowFetch(); // some validation +
// defer 250ms
rowRequestHandler.cancel(); // instead of waiting
rowRequestHandler.run(); // run immediately
}
fireHeaderClickedEvent(event);
if (Util.isTouchEvent(event)) {
/*
* Prevent using in e.g. scrolling and prevent generated
* events.
*/
event.preventDefault();
event.stopPropagation();
}
break;
}
break;
case Event.ONTOUCHMOVE:
case Event.ONMOUSEMOVE:
if (dragging) {
if (event.getTypeInt() == Event.ONTOUCHMOVE) {
/*
* prevent using this event in e.g. scrolling
*/
event.stopPropagation();
}
if (!moved) {
createFloatingCopy();
moved = true;
}
final int clientX = Util.getTouchOrMouseClientX(event);
final int x = clientX + tHead.hTableWrapper.getScrollLeft();
int slotX = headerX;
closestSlot = colIndex;
int closestDistance = -1;
int start = 0;
if (showRowHeaders) {
start++;
}
final int visibleCellCount = tHead.getVisibleCellCount();
for (int i = start; i <= visibleCellCount; i++) {
if (i > 0) {
final String colKey = getColKeyByIndex(i - 1);
slotX += getColWidth(colKey);
}
final int dist = Math.abs(x - slotX);
if (closestDistance == -1 || dist < closestDistance) {
closestDistance = dist;
closestSlot = i;
}
}
tHead.focusSlot(closestSlot);
updateFloatingCopysPosition(clientX, -1);
}
break;
default:
break;
}
}
private void onResizeEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
isResizing = true;
DOM.setCapture(getElement());
dragStartX = DOM.eventGetClientX(event);
colIndex = getColIndexByKey(cid);
originalWidth = getWidth();
DOM.eventPreventDefault(event);
break;
case Event.ONMOUSEUP:
isResizing = false;
DOM.releaseCapture(getElement());
tHead.disableAutoColumnWidthCalculation(this);
fireColumnResizeEvent(cid, originalWidth, getColWidth(cid));
break;
case Event.ONMOUSEMOVE:
if (isResizing) {
final int deltaX = DOM.eventGetClientX(event) - dragStartX;
if (deltaX == 0) {
return;
}
int newWidth = originalWidth + deltaX;
if (newWidth < getMinWidth()) {
newWidth = getMinWidth();
}
setColWidth(colIndex, newWidth, true);
forceRealignColumnHeaders();
}
break;
default:
break;
}
}
public int getMinWidth() {
int cellExtraWidth = 0;
if (scrollBody != null) {
cellExtraWidth += scrollBody.getCellExtraWidth();
}
return cellExtraWidth + sortIndicator.getOffsetWidth();
}
public String getCaption() {
return DOM.getInnerText(captionContainer);
}
public boolean isEnabled() {
return getParent() != null;
}
public void setAlign(char c) {
final String ALIGN_PREFIX = CLASSNAME + "-caption-container-align-";
if (align != c) {
captionContainer.removeClassName(ALIGN_PREFIX + "center");
captionContainer.removeClassName(ALIGN_PREFIX + "right");
captionContainer.removeClassName(ALIGN_PREFIX + "left");
switch (c) {
case ALIGN_CENTER:
captionContainer.addClassName(ALIGN_PREFIX + "center");
break;
case ALIGN_RIGHT:
captionContainer.addClassName(ALIGN_PREFIX + "right");
break;
default:
captionContainer.addClassName(ALIGN_PREFIX + "left");
break;
}
}
align = c;
}
public char getAlign() {
return align;
}
/**
* Detects the natural minimum width for the column of this header cell.
* If column is resized by user or the width is defined by server the
* actual width is returned. Else the natural min width is returned.
*
* @param columnIndex
* column index hint, if -1 (unknown) it will be detected
*
* @return
*/
public int getNaturalColumnWidth(int columnIndex) {
if (isDefinedWidth()) {
return width;
} else {
if (naturalWidth < 0) {
// This is recently revealed column. Try to detect a proper
// value (greater of header and data
// cols)
int hw = captionContainer.getOffsetWidth()
+ scrollBody.getCellExtraWidth();
if (BrowserInfo.get().isGecko()
|| BrowserInfo.get().isIE7()) {
hw += sortIndicator.getOffsetWidth();
}
if (columnIndex < 0) {
columnIndex = 0;
for (Iterator<Widget> it = tHead.iterator(); it
.hasNext(); columnIndex++) {
if (it.next() == this) {
break;
}
}
}
final int cw = scrollBody.getColWidth(columnIndex);
naturalWidth = (hw > cw ? hw : cw);
}
return naturalWidth;
}
}
public void setExpandRatio(float floatAttribute) {
expandRatio = floatAttribute;
}
public float getExpandRatio() {
return expandRatio;
}
public boolean isSorted() {
return sorted;
}
}
/**
* HeaderCell that is header cell for row headers.
*
* Reordering disabled and clicking on it resets sorting.
*/
public class RowHeadersHeaderCell extends HeaderCell {
RowHeadersHeaderCell() {
super(ROW_HEADER_COLUMN_KEY, "");
this.setStyleName(CLASSNAME + "-header-cell-rowheader");
}
@Override
protected void handleCaptionEvent(Event event) {
// NOP: RowHeaders cannot be reordered
// TODO It'd be nice to reset sorting here
}
}
public class TableHead extends Panel implements ActionOwner {
private static final int WRAPPER_WIDTH = 900000;
ArrayList<Widget> visibleCells = new ArrayList<Widget>();
HashMap<String, HeaderCell> availableCells = new HashMap<String, HeaderCell>();
Element div = DOM.createDiv();
Element hTableWrapper = DOM.createDiv();
Element hTableContainer = DOM.createDiv();
Element table = DOM.createTable();
Element headerTableBody = DOM.createTBody();
Element tr = DOM.createTR();
private final Element columnSelector = DOM.createDiv();
private int focusedSlot = -1;
public TableHead() {
if (BrowserInfo.get().isIE()) {
table.setPropertyInt("cellSpacing", 0);
}
DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
+ "-header");
// TODO move styles to CSS
DOM.setElementProperty(columnSelector, "className", CLASSNAME
+ "-column-selector");
DOM.setStyleAttribute(columnSelector, "display", "none");
DOM.appendChild(table, headerTableBody);
DOM.appendChild(headerTableBody, tr);
DOM.appendChild(hTableContainer, table);
DOM.appendChild(hTableWrapper, hTableContainer);
DOM.appendChild(div, hTableWrapper);
DOM.appendChild(div, columnSelector);
setElement(div);
setStyleName(CLASSNAME + "-header-wrap");
DOM.sinkEvents(columnSelector, Event.ONCLICK);
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersHeaderCell());
}
@Override
public void clear() {
for (String cid : availableCells.keySet()) {
removeCell(cid);
}
availableCells.clear();
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersHeaderCell());
}
public void updateCellsFromUIDL(UIDL uidl) {
Iterator<?> it = uidl.getChildIterator();
HashSet<String> updated = new HashSet<String>();
while (it.hasNext()) {
final UIDL col = (UIDL) it.next();
final String cid = col.getStringAttribute("cid");
updated.add(cid);
String caption = buildCaptionHtmlSnippet(col);
HeaderCell c = getHeaderCell(cid);
if (c == null) {
c = new HeaderCell(cid, caption);
availableCells.put(cid, c);
if (initializedAndAttached) {
// we will need a column width recalculation
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
} else {
c.setText(caption);
}
if (col.hasAttribute("sortable")) {
c.setSortable(true);
if (cid.equals(sortColumn)) {
c.setSorted(true);
} else {
c.setSorted(false);
}
} else {
c.setSortable(false);
}
if (col.hasAttribute("align")) {
c.setAlign(col.getStringAttribute("align").charAt(0));
}
if (col.hasAttribute("width")) {
final String widthStr = col.getStringAttribute("width");
// Make sure to accomodate for the sort indicator if
// necessary.
int width = Integer.parseInt(widthStr);
if (width < c.getMinWidth()) {
width = c.getMinWidth();
}
c.setWidth(width, true);
} else if (recalcWidths) {
c.setUndefinedWidth();
}
if (col.hasAttribute("er")) {
c.setExpandRatio(col.getFloatAttribute("er"));
}
if (col.hasAttribute("collapsed")) {
// ensure header is properly removed from parent (case when
// collapsing happens via servers side api)
if (c.isAttached()) {
c.removeFromParent();
headerChangedDuringUpdate = true;
}
}
}
// check for orphaned header cells
for (Iterator<String> cit = availableCells.keySet().iterator(); cit
.hasNext();) {
String cid = cit.next();
if (!updated.contains(cid)) {
removeCell(cid);
cit.remove();
}
}
}
public void enableColumn(String cid, int index) {
final HeaderCell c = getHeaderCell(cid);
if (!c.isEnabled() || getHeaderCell(index) != c) {
setHeaderCell(index, c);
if (initializedAndAttached) {
headerChangedDuringUpdate = true;
}
}
}
public int getVisibleCellCount() {
return visibleCells.size();
}
public void setHorizontalScrollPosition(int scrollLeft) {
if (BrowserInfo.get().isIE6()) {
hTableWrapper.getStyle().setPosition(Position.RELATIVE);
hTableWrapper.getStyle().setLeft(-scrollLeft, Unit.PX);
} else {
hTableWrapper.setScrollLeft(scrollLeft);
}
}
public void setColumnCollapsingAllowed(boolean cc) {
if (cc) {
columnSelector.getStyle().setDisplay(Display.BLOCK);
} else {
columnSelector.getStyle().setDisplay(Display.NONE);
}
}
public void disableBrowserIntelligence() {
hTableContainer.getStyle().setWidth(WRAPPER_WIDTH, Unit.PX);
}
public void enableBrowserIntelligence() {
hTableContainer.getStyle().clearWidth();
}
public void setHeaderCell(int index, HeaderCell cell) {
if (cell.isEnabled()) {
// we're moving the cell
DOM.removeChild(tr, cell.getElement());
orphan(cell);
visibleCells.remove(cell);
}
if (index < visibleCells.size()) {
// insert to right slot
DOM.insertChild(tr, cell.getElement(), index);
adopt(cell);
visibleCells.add(index, cell);
} else if (index == visibleCells.size()) {
// simply append
DOM.appendChild(tr, cell.getElement());
adopt(cell);
visibleCells.add(cell);
} else {
throw new RuntimeException(
"Header cells must be appended in order");
}
}
public HeaderCell getHeaderCell(int index) {
if (index < visibleCells.size()) {
return (HeaderCell) visibleCells.get(index);
} else {
return null;
}
}
/**
* Get's HeaderCell by it's column Key.
*
* Note that this returns HeaderCell even if it is currently collapsed.
*
* @param cid
* Column key of accessed HeaderCell
* @return HeaderCell
*/
public HeaderCell getHeaderCell(String cid) {
return availableCells.get(cid);
}
public void moveCell(int oldIndex, int newIndex) {
final HeaderCell hCell = getHeaderCell(oldIndex);
final Element cell = hCell.getElement();
visibleCells.remove(oldIndex);
DOM.removeChild(tr, cell);
DOM.insertChild(tr, cell, newIndex);
visibleCells.add(newIndex, hCell);
}
public Iterator<Widget> iterator() {
return visibleCells.iterator();
}
@Override
public boolean remove(Widget w) {
if (visibleCells.contains(w)) {
visibleCells.remove(w);
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
return true;
}
return false;
}
public void removeCell(String colKey) {
final HeaderCell c = getHeaderCell(colKey);
remove(c);
}
private void focusSlot(int index) {
removeSlotFocus();
if (index > 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, index - 1)),
"className", CLASSNAME + "-resizer " + CLASSNAME
+ "-focus-slot-right");
} else {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, index)),
"className", CLASSNAME + "-resizer " + CLASSNAME
+ "-focus-slot-left");
}
focusedSlot = index;
}
private void removeSlotFocus() {
if (focusedSlot < 0) {
return;
}
if (focusedSlot == 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, focusedSlot)),
"className", CLASSNAME + "-resizer");
} else if (focusedSlot > 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, focusedSlot - 1)),
"className", CLASSNAME + "-resizer");
}
focusedSlot = -1;
}
@Override
public void onBrowserEvent(Event event) {
if (enabled) {
if (event.getEventTarget().cast() == columnSelector) {
final int left = DOM.getAbsoluteLeft(columnSelector);
final int top = DOM.getAbsoluteTop(columnSelector)
+ DOM.getElementPropertyInt(columnSelector,
"offsetHeight");
client.getContextMenu().showAt(this, left, top);
}
}
}
@Override
protected void onDetach() {
super.onDetach();
if (client != null) {
client.getContextMenu().ensureHidden(this);
}
}
class VisibleColumnAction extends Action {
String colKey;
private boolean collapsed;
private VScrollTableRow currentlyFocusedRow;
public VisibleColumnAction(String colKey) {
super(VScrollTable.TableHead.this);
this.colKey = colKey;
caption = tHead.getHeaderCell(colKey).getCaption();
currentlyFocusedRow = focusedRow;
}
@Override
public void execute() {
client.getContextMenu().hide();
// toggle selected column
if (collapsedColumns.contains(colKey)) {
collapsedColumns.remove(colKey);
} else {
tHead.removeCell(colKey);
collapsedColumns.add(colKey);
lazyAdjustColumnWidths.schedule(1);
}
// update variable to server
client.updateVariable(paintableId, "collapsedcolumns",
collapsedColumns.toArray(new String[collapsedColumns
.size()]), false);
// let rowRequestHandler determine proper rows
rowRequestHandler.refreshContent();
lazyRevertFocusToRow(currentlyFocusedRow);
}
public void setCollapsed(boolean b) {
collapsed = b;
}
/**
* Override default method to distinguish on/off columns
*/
@Override
public String getHTML() {
final StringBuffer buf = new StringBuffer();
if (collapsed) {
buf.append("<span class=\"v-off\">");
} else {
buf.append("<span class=\"v-on\">");
}
buf.append(super.getHTML());
buf.append("</span>");
return buf.toString();
}
}
/*
* Returns columns as Action array for column select popup
*/
public Action[] getActions() {
Object[] cols;
if (columnReordering && columnOrder != null) {
cols = columnOrder;
} else {
// if columnReordering is disabled, we need different way to get
// all available columns
cols = visibleColOrder;
cols = new Object[visibleColOrder.length
+ collapsedColumns.size()];
int i;
for (i = 0; i < visibleColOrder.length; i++) {
cols[i] = visibleColOrder[i];
}
for (final Iterator<String> it = collapsedColumns.iterator(); it
.hasNext();) {
cols[i++] = it.next();
}
}
final Action[] actions = new Action[cols.length];
for (int i = 0; i < cols.length; i++) {
final String cid = (String) cols[i];
final HeaderCell c = getHeaderCell(cid);
final VisibleColumnAction a = new VisibleColumnAction(
c.getColKey());
a.setCaption(c.getCaption());
if (!c.isEnabled()) {
a.setCollapsed(true);
}
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
/**
* Returns column alignments for visible columns
*/
public char[] getColumnAlignments() {
final Iterator<Widget> it = visibleCells.iterator();
final char[] aligns = new char[visibleCells.size()];
int colIndex = 0;
while (it.hasNext()) {
aligns[colIndex++] = ((HeaderCell) it.next()).getAlign();
}
return aligns;
}
/**
* Disables the automatic calculation of all column widths by forcing
* the widths to be "defined" thus turning off expand ratios and such.
*/
public void disableAutoColumnWidthCalculation(HeaderCell source) {
for (HeaderCell cell : availableCells.values()) {
cell.disableAutoWidthCalculation();
}
// fire column resize events for all columns but the source of the
// resize action, since an event will fire separately for this.
ArrayList<HeaderCell> columns = new ArrayList<HeaderCell>(
availableCells.values());
columns.remove(source);
sendColumnWidthUpdates(columns);
forceRealignColumnHeaders();
}
}
/**
* A cell in the footer
*/
public class FooterCell extends Widget {
private final Element td = DOM.createTD();
private final Element captionContainer = DOM.createDiv();
private char align = ALIGN_LEFT;
private int width = -1;
private float expandRatio = 0;
private final String cid;
boolean definedWidth = false;
private int naturalWidth = -1;
public FooterCell(String colId, String headerText) {
cid = colId;
setText(headerText);
DOM.setElementProperty(captionContainer, "className", CLASSNAME
+ "-footer-container");
// ensure no clipping initially (problem on column additions)
DOM.setStyleAttribute(captionContainer, "overflow", "visible");
DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS);
DOM.appendChild(td, captionContainer);
DOM.sinkEvents(td, Event.MOUSEEVENTS);
setElement(td);
}
/**
* Sets the text of the footer
*
* @param footerText
* The text in the footer
*/
public void setText(String footerText) {
DOM.setInnerHTML(captionContainer, footerText);
}
/**
* Set alignment of the text in the cell
*
* @param c
* The alignment which can be ALIGN_CENTER, ALIGN_LEFT,
* ALIGN_RIGHT
*/
public void setAlign(char c) {
if (align != c) {
switch (c) {
case ALIGN_CENTER:
DOM.setStyleAttribute(captionContainer, "textAlign",
"center");
break;
case ALIGN_RIGHT:
DOM.setStyleAttribute(captionContainer, "textAlign",
"right");
break;
default:
DOM.setStyleAttribute(captionContainer, "textAlign", "");
break;
}
}
align = c;
}
/**
* Get the alignment of the text int the cell
*
* @return Returns either ALIGN_CENTER, ALIGN_LEFT or ALIGN_RIGHT
*/
public char getAlign() {
return align;
}
/**
* Sets the width of the cell
*
* @param w
* The width of the cell
* @param ensureDefinedWidth
* Ensures the the given width is not recalculated
*/
public void setWidth(int w, boolean ensureDefinedWidth) {
if (ensureDefinedWidth) {
definedWidth = true;
// on column resize expand ratio becomes zero
expandRatio = 0;
}
if (width == w) {
return;
}
if (width == -1) {
// go to default mode, clip content if necessary
DOM.setStyleAttribute(captionContainer, "overflow", "");
}
width = w;
if (w == -1) {
DOM.setStyleAttribute(captionContainer, "width", "");
setWidth("");
} else {
/*
* Reduce width with one pixel for the right border since the
* footers does not have any spacers between them.
*/
int borderWidths = 1;
// Set the container width (check for negative value)
if (w - borderWidths >= 0) {
captionContainer.getStyle().setPropertyPx("width",
w - borderWidths);
} else {
captionContainer.getStyle().setPropertyPx("width", 0);
}
/*
* if we already have tBody, set the header width properly, if
* not defer it. IE will fail with complex float in table header
* unless TD width is not explicitly set.
*/
if (scrollBody != null) {
/*
* Reduce with one since footer does not have any spacers,
* instead a 1 pixel border.
*/
int tdWidth = width + scrollBody.getCellExtraWidth()
- borderWidths;
setWidth(tdWidth + "px");
} else {
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
int borderWidths = 1;
int tdWidth = width
+ scrollBody.getCellExtraWidth()
- borderWidths;
setWidth(tdWidth + "px");
}
});
}
}
}
/**
* Sets the width to undefined
*/
public void setUndefinedWidth() {
setWidth(-1, false);
}
/**
* Detects if width is fixed by developer on server side or resized to
* current width by user.
*
* @return true if defined, false if "natural" width
*/
public boolean isDefinedWidth() {
return definedWidth;
}
/**
* Returns the pixels width of the footer cell
*
* @return The width in pixels
*/
public int getWidth() {
return width;
}
/**
* Sets the expand ratio of the cell
*
* @param floatAttribute
* The expand ratio
*/
public void setExpandRatio(float floatAttribute) {
expandRatio = floatAttribute;
}
/**
* Returns the expand ration of the cell
*
* @return The expand ratio
*/
public float getExpandRatio() {
return expandRatio;
}
/**
* Is the cell enabled?
*
* @return True if enabled else False
*/
public boolean isEnabled() {
return getParent() != null;
}
/**
* Handle column clicking
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled && event != null) {
handleCaptionEvent(event);
if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
scrollBodyPanel.setFocus(true);
}
event.stopPropagation();
event.preventDefault();
}
}
/**
* Handles a event on the captions
*
* @param event
* The event to handle
*/
protected void handleCaptionEvent(Event event) {
if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
fireFooterClickedEvent(event);
}
}
/**
* Fires a footer click event after the user has clicked a column footer
* cell
*
* @param event
* The click event
*/
private void fireFooterClickedEvent(Event event) {
if (client.hasEventListeners(VScrollTable.this,
FOOTER_CLICK_EVENT_ID)) {
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "footerClickEvent",
details.toString(), false);
client.updateVariable(paintableId, "footerClickCID", cid, true);
}
}
/**
* Returns the column key of the column
*
* @return The column key
*/
public String getColKey() {
return cid;
}
/**
* Detects the natural minimum width for the column of this header cell.
* If column is resized by user or the width is defined by server the
* actual width is returned. Else the natural min width is returned.
*
* @param columnIndex
* column index hint, if -1 (unknown) it will be detected
*
* @return
*/
public int getNaturalColumnWidth(int columnIndex) {
if (isDefinedWidth()) {
return width;
} else {
if (naturalWidth < 0) {
// This is recently revealed column. Try to detect a proper
// value (greater of header and data
// cols)
final int hw = ((Element) getElement().getLastChild())
.getOffsetWidth() + scrollBody.getCellExtraWidth();
if (columnIndex < 0) {
columnIndex = 0;
for (Iterator<Widget> it = tHead.iterator(); it
.hasNext(); columnIndex++) {
if (it.next() == this) {
break;
}
}
}
final int cw = scrollBody.getColWidth(columnIndex);
naturalWidth = (hw > cw ? hw : cw);
}
return naturalWidth;
}
}
public void setNaturalMinimumColumnWidth(int w) {
naturalWidth = w;
}
}
/**
* HeaderCell that is header cell for row headers.
*
* Reordering disabled and clicking on it resets sorting.
*/
public class RowHeadersFooterCell extends FooterCell {
RowHeadersFooterCell() {
super(ROW_HEADER_COLUMN_KEY, "");
}
@Override
protected void handleCaptionEvent(Event event) {
// NOP: RowHeaders cannot be reordered
// TODO It'd be nice to reset sorting here
}
}
/**
* The footer of the table which can be seen in the bottom of the Table.
*/
public class TableFooter extends Panel {
private static final int WRAPPER_WIDTH = 900000;
ArrayList<Widget> visibleCells = new ArrayList<Widget>();
HashMap<String, FooterCell> availableCells = new HashMap<String, FooterCell>();
Element div = DOM.createDiv();
Element hTableWrapper = DOM.createDiv();
Element hTableContainer = DOM.createDiv();
Element table = DOM.createTable();
Element headerTableBody = DOM.createTBody();
Element tr = DOM.createTR();
public TableFooter() {
DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
+ "-footer");
DOM.appendChild(table, headerTableBody);
DOM.appendChild(headerTableBody, tr);
DOM.appendChild(hTableContainer, table);
DOM.appendChild(hTableWrapper, hTableContainer);
DOM.appendChild(div, hTableWrapper);
setElement(div);
setStyleName(CLASSNAME + "-footer-wrap");
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersFooterCell());
}
@Override
public void clear() {
for (String cid : availableCells.keySet()) {
removeCell(cid);
}
availableCells.clear();
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersFooterCell());
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.user.client.ui.Panel#remove(com.google.gwt.user.client
* .ui.Widget)
*/
@Override
public boolean remove(Widget w) {
if (visibleCells.contains(w)) {
visibleCells.remove(w);
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.HasWidgets#iterator()
*/
public Iterator<Widget> iterator() {
return visibleCells.iterator();
}
/**
* Gets a footer cell which represents the given columnId
*
* @param cid
* The columnId
*
* @return The cell
*/
public FooterCell getFooterCell(String cid) {
return availableCells.get(cid);
}
/**
* Gets a footer cell by using a column index
*
* @param index
* The index of the column
* @return The Cell
*/
public FooterCell getFooterCell(int index) {
if (index < visibleCells.size()) {
return (FooterCell) visibleCells.get(index);
} else {
return null;
}
}
/**
* Updates the cells contents when updateUIDL request is received
*
* @param uidl
* The UIDL
*/
public void updateCellsFromUIDL(UIDL uidl) {
Iterator<?> columnIterator = uidl.getChildIterator();
HashSet<String> updated = new HashSet<String>();
while (columnIterator.hasNext()) {
final UIDL col = (UIDL) columnIterator.next();
final String cid = col.getStringAttribute("cid");
updated.add(cid);
String caption = col.hasAttribute("fcaption") ? col
.getStringAttribute("fcaption") : "";
FooterCell c = getFooterCell(cid);
if (c == null) {
c = new FooterCell(cid, caption);
availableCells.put(cid, c);
if (initializedAndAttached) {
// we will need a column width recalculation
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
} else {
c.setText(caption);
}
if (col.hasAttribute("align")) {
c.setAlign(col.getStringAttribute("align").charAt(0));
}
if (col.hasAttribute("width")) {
final String width = col.getStringAttribute("width");
c.setWidth(Integer.parseInt(width), true);
} else if (recalcWidths) {
c.setUndefinedWidth();
}
if (col.hasAttribute("er")) {
c.setExpandRatio(col.getFloatAttribute("er"));
}
if (col.hasAttribute("collapsed")) {
// ensure header is properly removed from parent (case when
// collapsing happens via servers side api)
if (c.isAttached()) {
c.removeFromParent();
headerChangedDuringUpdate = true;
}
}
}
// check for orphaned header cells
for (Iterator<String> cit = availableCells.keySet().iterator(); cit
.hasNext();) {
String cid = cit.next();
if (!updated.contains(cid)) {
removeCell(cid);
cit.remove();
}
}
}
/**
* Set a footer cell for a specified column index
*
* @param index
* The index
* @param cell
* The footer cell
*/
public void setFooterCell(int index, FooterCell cell) {
if (cell.isEnabled()) {
// we're moving the cell
DOM.removeChild(tr, cell.getElement());
orphan(cell);
visibleCells.remove(cell);
}
if (index < visibleCells.size()) {
// insert to right slot
DOM.insertChild(tr, cell.getElement(), index);
adopt(cell);
visibleCells.add(index, cell);
} else if (index == visibleCells.size()) {
// simply append
DOM.appendChild(tr, cell.getElement());
adopt(cell);
visibleCells.add(cell);
} else {
throw new RuntimeException(
"Header cells must be appended in order");
}
}
/**
* Remove a cell by using the columnId
*
* @param colKey
* The columnId to remove
*/
public void removeCell(String colKey) {
final FooterCell c = getFooterCell(colKey);
remove(c);
}
/**
* Enable a column (Sets the footer cell)
*
* @param cid
* The columnId
* @param index
* The index of the column
*/
public void enableColumn(String cid, int index) {
final FooterCell c = getFooterCell(cid);
if (!c.isEnabled() || getFooterCell(index) != c) {
setFooterCell(index, c);
if (initializedAndAttached) {
headerChangedDuringUpdate = true;
}
}
}
/**
* Disable browser measurement of the table width
*/
public void disableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH
+ "px");
}
/**
* Enable browser measurement of the table width
*/
public void enableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", "");
}
/**
* Set the horizontal position in the cell in the footer. This is done
* when a horizontal scrollbar is present.
*
* @param scrollLeft
* The value of the leftScroll
*/
public void setHorizontalScrollPosition(int scrollLeft) {
if (BrowserInfo.get().isIE6()) {
hTableWrapper.getStyle().setProperty("position", "relative");
hTableWrapper.getStyle().setPropertyPx("left", -scrollLeft);
} else {
hTableWrapper.setScrollLeft(scrollLeft);
}
}
/**
* Swap cells when the column are dragged
*
* @param oldIndex
* The old index of the cell
* @param newIndex
* The new index of the cell
*/
public void moveCell(int oldIndex, int newIndex) {
final FooterCell hCell = getFooterCell(oldIndex);
final Element cell = hCell.getElement();
visibleCells.remove(oldIndex);
DOM.removeChild(tr, cell);
DOM.insertChild(tr, cell, newIndex);
visibleCells.add(newIndex, hCell);
}
}
/**
* This Panel can only contain VScrollTableRow type of widgets. This
* "simulates" very large table, keeping spacers which take room of
* unrendered rows.
*
*/
public class VScrollTableBody extends Panel {
public static final int DEFAULT_ROW_HEIGHT = 24;
private double rowHeight = -1;
private final List<Widget> renderedRows = new ArrayList<Widget>();
/**
* Due some optimizations row height measuring is deferred and initial
* set of rows is rendered detached. Flag set on when table body has
* been attached in dom and rowheight has been measured.
*/
private boolean tBodyMeasurementsDone = false;
Element preSpacer = DOM.createDiv();
Element postSpacer = DOM.createDiv();
Element container = DOM.createDiv();
TableSectionElement tBodyElement = Document.get().createTBodyElement();
Element table = DOM.createTable();
private int firstRendered;
private int lastRendered;
private char[] aligns;
protected VScrollTableBody() {
constructDOM();
setElement(container);
}
public VScrollTableRow getRowByRowIndex(int indexInTable) {
int internalIndex = indexInTable - firstRendered;
if (internalIndex >= 0 && internalIndex < renderedRows.size()) {
return (VScrollTableRow) renderedRows.get(internalIndex);
} else {
return null;
}
}
/**
* @return the height of scrollable body, subpixels ceiled.
*/
public int getRequiredHeight() {
return preSpacer.getOffsetHeight() + postSpacer.getOffsetHeight()
+ Util.getRequiredHeight(table);
}
private void constructDOM() {
DOM.setElementProperty(table, "className", CLASSNAME + "-table");
if (BrowserInfo.get().isIE()) {
table.setPropertyInt("cellSpacing", 0);
}
DOM.setElementProperty(preSpacer, "className", CLASSNAME
+ "-row-spacer");
DOM.setElementProperty(postSpacer, "className", CLASSNAME
+ "-row-spacer");
table.appendChild(tBodyElement);
DOM.appendChild(container, preSpacer);
DOM.appendChild(container, table);
DOM.appendChild(container, postSpacer);
}
public int getAvailableWidth() {
int availW = scrollBodyPanel.getOffsetWidth() - getBorderWidth();
return availW;
}
public void renderInitialRows(UIDL rowData, int firstIndex, int rows) {
firstRendered = firstIndex;
lastRendered = firstIndex + rows - 1;
final Iterator<?> it = rowData.getChildIterator();
aligns = tHead.getColumnAlignments();
while (it.hasNext()) {
final VScrollTableRow row = createRow((UIDL) it.next(), aligns);
addRow(row);
}
if (isAttached()) {
fixSpacers();
}
}
public void renderRows(UIDL rowData, int firstIndex, int rows) {
// FIXME REVIEW
aligns = tHead.getColumnAlignments();
final Iterator<?> it = rowData.getChildIterator();
if (firstIndex == lastRendered + 1) {
while (it.hasNext()) {
final VScrollTableRow row = prepareRow((UIDL) it.next());
addRow(row);
lastRendered++;
}
fixSpacers();
} else if (firstIndex + rows == firstRendered) {
final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
int i = rows;
while (it.hasNext()) {
i--;
rowArray[i] = prepareRow((UIDL) it.next());
}
for (i = 0; i < rows; i++) {
addRowBeforeFirstRendered(rowArray[i]);
firstRendered--;
}
} else {
// completely new set of rows
while (lastRendered + 1 > firstRendered) {
unlinkRow(false);
}
final VScrollTableRow row = prepareRow((UIDL) it.next());
firstRendered = firstIndex;
lastRendered = firstIndex - 1;
addRow(row);
lastRendered++;
setContainerHeight();
fixSpacers();
while (it.hasNext()) {
addRow(prepareRow((UIDL) it.next()));
lastRendered++;
}
fixSpacers();
}
// this may be a new set of rows due content change,
// ensure we have proper cache rows
int reactFirstRow = (int) (firstRowInViewPort - pageLength
* cache_react_rate);
int reactLastRow = (int) (firstRowInViewPort + pageLength + pageLength
* cache_react_rate);
if (reactFirstRow < 0) {
reactFirstRow = 0;
}
if (reactLastRow >= totalRows) {
reactLastRow = totalRows - 1;
}
if (lastRendered < reactLastRow) {
// get some cache rows below visible area
rowRequestHandler.setReqFirstRow(lastRendered + 1);
rowRequestHandler.setReqRows(reactLastRow - lastRendered);
rowRequestHandler.deferRowFetch(1);
} else if (scrollBody.getFirstRendered() > reactFirstRow) {
/*
* Branch for fetching cache above visible area.
*
* If cache needed for both before and after visible area, this
* will be rendered after-cache is reveived and rendered. So in
* some rare situations table may take two cache visits to
* server.
*/
rowRequestHandler.setReqFirstRow(reactFirstRow);
rowRequestHandler.setReqRows(firstRendered - reactFirstRow);
rowRequestHandler.deferRowFetch(1);
}
}
/**
* This method is used to instantiate new rows for this table. It
* automatically sets correct widths to rows cells and assigns correct
* client reference for child widgets.
*
* This method can be called only after table has been initialized
*
* @param uidl
*/
private VScrollTableRow prepareRow(UIDL uidl) {
final VScrollTableRow row = createRow(uidl, aligns);
final int cells = DOM.getChildCount(row.getElement());
for (int i = 0; i < cells; i++) {
final Element cell = DOM.getChild(row.getElement(), i);
int w = VScrollTable.this.getColWidth(getColKeyByIndex(i));
if (w < 0) {
w = 0;
}
cell.getFirstChildElement().getStyle()
.setPropertyPx("width", w);
cell.getStyle().setPropertyPx("width", w);
}
return row;
}
protected VScrollTableRow createRow(UIDL uidl, char[] aligns2) {
return new VScrollTableRow(uidl, aligns);
}
private void addRowBeforeFirstRendered(VScrollTableRow row) {
row.setIndex(firstRendered - 1);
if (row.isSelected()) {
row.addStyleName("v-selected");
}
tBodyElement.insertBefore(row.getElement(),
tBodyElement.getFirstChild());
adopt(row);
renderedRows.add(0, row);
}
private void addRow(VScrollTableRow row) {
row.setIndex(firstRendered + renderedRows.size());
if (row.isSelected()) {
row.addStyleName("v-selected");
}
tBodyElement.appendChild(row.getElement());
adopt(row);
renderedRows.add(row);
}
public Iterator<Widget> iterator() {
return renderedRows.iterator();
}
/**
* @return false if couldn't remove row
*/
public boolean unlinkRow(boolean fromBeginning) {
if (lastRendered - firstRendered < 0) {
return false;
}
int index;
if (fromBeginning) {
index = 0;
firstRendered++;
} else {
index = renderedRows.size() - 1;
lastRendered--;
}
if (index >= 0) {
final VScrollTableRow toBeRemoved = (VScrollTableRow) renderedRows
.get(index);
lazyUnregistryBag.add(toBeRemoved);
tBodyElement.removeChild(toBeRemoved.getElement());
orphan(toBeRemoved);
renderedRows.remove(index);
fixSpacers();
return true;
} else {
return false;
}
}
@Override
public boolean remove(Widget w) {
throw new UnsupportedOperationException();
}
@Override
protected void onAttach() {
super.onAttach();
setContainerHeight();
}
/**
* Fix container blocks height according to totalRows to avoid
* "bouncing" when scrolling
*/
private void setContainerHeight() {
fixSpacers();
DOM.setStyleAttribute(container, "height", totalRows
* getRowHeight() + "px");
}
private void fixSpacers() {
int prepx = (int) Math.round(getRowHeight() * firstRendered);
if (prepx < 0) {
prepx = 0;
}
preSpacer.getStyle().setPropertyPx("height", prepx);
int postpx = (int) (getRowHeight() * (totalRows - 1 - lastRendered));
if (postpx < 0) {
postpx = 0;
}
postSpacer.getStyle().setPropertyPx("height", postpx);
}
public double getRowHeight() {
return getRowHeight(false);
}
public double getRowHeight(boolean forceUpdate) {
if (tBodyMeasurementsDone && !forceUpdate) {
return rowHeight;
} else {
if (tBodyElement.getRows().getLength() > 0) {
int tableHeight = getTableHeight();
int rowCount = tBodyElement.getRows().getLength();
rowHeight = tableHeight / (double) rowCount;
} else {
if (isAttached()) {
// measure row height by adding a dummy row
VScrollTableRow scrollTableRow = new VScrollTableRow();
tBodyElement.appendChild(scrollTableRow.getElement());
getRowHeight(forceUpdate);
tBodyElement.removeChild(scrollTableRow.getElement());
} else {
// TODO investigate if this can never happen anymore
return DEFAULT_ROW_HEIGHT;
}
}
tBodyMeasurementsDone = true;
return rowHeight;
}
}
public int getTableHeight() {
return table.getOffsetHeight();
}
/**
* Returns the width available for column content.
*
* @param columnIndex
* @return
*/
public int getColWidth(int columnIndex) {
if (tBodyMeasurementsDone) {
NodeList<TableRowElement> rows = tBodyElement.getRows();
if (rows.getLength() == 0) {
// no rows yet rendered
return 0;
} else {
com.google.gwt.dom.client.Element wrapperdiv = rows
.getItem(0).getCells().getItem(columnIndex)
.getFirstChildElement();
return wrapperdiv.getOffsetWidth();
}
} else {
return 0;
}
}
/**
* Sets the content width of a column.
*
* Due IE limitation, we must set the width to a wrapper elements inside
* table cells (with overflow hidden, which does not work on td
* elements).
*
* To get this work properly crossplatform, we will also set the width
* of td.
*
* @param colIndex
* @param w
*/
public void setColWidth(int colIndex, int w) {
NodeList<TableRowElement> rows2 = tBodyElement.getRows();
final int rows = rows2.getLength();
for (int i = 0; i < rows; i++) {
TableRowElement row = rows2.getItem(i);
TableCellElement cell = row.getCells().getItem(colIndex);
cell.getFirstChildElement().getStyle()
.setPropertyPx("width", w);
cell.getStyle().setPropertyPx("width", w);
}
}
private int cellExtraWidth = -1;
/**
* Method to return the space used for cell paddings + border.
*/
private int getCellExtraWidth() {
if (cellExtraWidth < 0) {
detectExtrawidth();
}
return cellExtraWidth;
}
private void detectExtrawidth() {
NodeList<TableRowElement> rows = tBodyElement.getRows();
if (rows.getLength() == 0) {
/* need to temporary add empty row and detect */
VScrollTableRow scrollTableRow = new VScrollTableRow();
tBodyElement.appendChild(scrollTableRow.getElement());
detectExtrawidth();
tBodyElement.removeChild(scrollTableRow.getElement());
} else {
boolean noCells = false;
TableRowElement item = rows.getItem(0);
TableCellElement firstTD = item.getCells().getItem(0);
if (firstTD == null) {
// content is currently empty, we need to add a fake cell
// for measuring
noCells = true;
VScrollTableRow next = (VScrollTableRow) iterator().next();
next.addCell(null, "", ALIGN_LEFT, "", true, tHead
.getHeaderCell(0).isSorted());
firstTD = item.getCells().getItem(0);
}
com.google.gwt.dom.client.Element wrapper = firstTD
.getFirstChildElement();
cellExtraWidth = firstTD.getOffsetWidth()
- wrapper.getOffsetWidth();
if (noCells) {
firstTD.getParentElement().removeChild(firstTD);
}
}
}
private void reLayoutComponents() {
for (Widget w : this) {
VScrollTableRow r = (VScrollTableRow) w;
for (Widget widget : r) {
client.handleComponentRelativeSize(widget);
}
}
}
public int getLastRendered() {
return lastRendered;
}
public int getFirstRendered() {
return firstRendered;
}
public void moveCol(int oldIndex, int newIndex) {
// loop all rows and move given index to its new place
final Iterator<?> rows = iterator();
while (rows.hasNext()) {
final VScrollTableRow row = (VScrollTableRow) rows.next();
final Element td = DOM.getChild(row.getElement(), oldIndex);
DOM.removeChild(row.getElement(), td);
DOM.insertChild(row.getElement(), td, newIndex);
}
}
/**
* Restore row visibility which is set to "none" when the row is
* rendered (due a performance optimization).
*/
private void restoreRowVisibility() {
for (Widget row : renderedRows) {
row.getElement().getStyle().setProperty("visibility", "");
}
}
public class VScrollTableRow extends Panel implements ActionOwner,
Container {
private static final int TOUCHSCROLL_TIMEOUT = 70;
private static final int DRAGMODE_MULTIROW = 2;
protected ArrayList<Widget> childWidgets = new ArrayList<Widget>();
private boolean selected = false;
protected final int rowKey;
private List<UIDL> pendingComponentPaints;
private String[] actionKeys = null;
private final TableRowElement rowElement;
private boolean mDown;
private int index;
private Event touchStart;
private static final String ROW_CLASSNAME_EVEN = CLASSNAME + "-row";
private static final String ROW_CLASSNAME_ODD = CLASSNAME
+ "-row-odd";
private static final int TOUCH_CONTEXT_MENU_TIMEOUT = 500;
private Timer contextTouchTimeout;
private int touchStartY;
private int touchStartX;
private VScrollTableRow(int rowKey) {
this.rowKey = rowKey;
rowElement = Document.get().createTRElement();
setElement(rowElement);
DOM.sinkEvents(getElement(), Event.MOUSEEVENTS
| Event.TOUCHEVENTS | Event.ONDBLCLICK
| Event.ONCONTEXTMENU);
}
/**
* Detects whether row is visible in tables viewport.
*
* @return
*/
public boolean isInViewPort() {
int absoluteTop = getAbsoluteTop();
int scrollPosition = scrollBodyPanel.getScrollPosition();
if (absoluteTop < scrollPosition) {
return false;
}
int maxVisible = scrollPosition
+ scrollBodyPanel.getOffsetHeight() - getOffsetHeight();
if (absoluteTop > maxVisible) {
return false;
}
return true;
}
/**
* Makes a check based on indexes whether the row is before the
* compared row.
*
* @param row1
* @return true if this rows index is smaller than in the row1
*/
public boolean isBefore(VScrollTableRow row1) {
return getIndex() < row1.getIndex();
}
/**
* Sets the index of the row in the whole table. Currently used just
* to set even/odd classname
*
* @param indexInWholeTable
*/
private void setIndex(int indexInWholeTable) {
index = indexInWholeTable;
boolean isOdd = indexInWholeTable % 2 == 0;
// Inverted logic to be backwards compatible with earlier 6.4.
// It is very strange because rows 1,3,5 are considered "even"
// and 2,4,6 "odd".
if (!isOdd) {
addStyleName(ROW_CLASSNAME_ODD);
} else {
addStyleName(ROW_CLASSNAME_EVEN);
}
}
public int getIndex() {
return index;
}
private void paintComponent(Paintable p, UIDL uidl) {
if (isAttached()) {
p.updateFromUIDL(uidl, client);
} else {
if (pendingComponentPaints == null) {
pendingComponentPaints = new LinkedList<UIDL>();
}
pendingComponentPaints.add(uidl);
}
}
@Override
protected void onAttach() {
super.onAttach();
if (pendingComponentPaints != null) {
for (UIDL uidl : pendingComponentPaints) {
Paintable paintable = client.getPaintable(uidl);
paintable.updateFromUIDL(uidl, client);
}
}
}
@Override
protected void onDetach() {
super.onDetach();
client.getContextMenu().ensureHidden(this);
}
public String getKey() {
return String.valueOf(rowKey);
}
public VScrollTableRow(UIDL uidl, char[] aligns) {
this(uidl.getIntAttribute("key"));
/*
* Rendering the rows as hidden improves Firefox and Safari
* performance drastically.
*/
getElement().getStyle().setProperty("visibility", "hidden");
String rowStyle = uidl.getStringAttribute("rowstyle");
if (rowStyle != null) {
addStyleName(CLASSNAME + "-row-" + rowStyle);
}
tHead.getColumnAlignments();
int col = 0;
int visibleColumnIndex = -1;
// row header
if (showRowHeaders) {
boolean sorted = tHead.getHeaderCell(col).isSorted();
addCell(uidl, buildCaptionHtmlSnippet(uidl), aligns[col++],
"rowheader", true, sorted);
visibleColumnIndex++;
}
if (uidl.hasAttribute("al")) {
actionKeys = uidl.getStringArrayAttribute("al");
}
final Iterator<?> cells = uidl.getChildIterator();
while (cells.hasNext()) {
final Object cell = cells.next();
visibleColumnIndex++;
String columnId = visibleColOrder[visibleColumnIndex];
String style = "";
if (uidl.hasAttribute("style-" + columnId)) {
style = uidl.getStringAttribute("style-" + columnId);
}
boolean sorted = tHead.getHeaderCell(col).isSorted();
if (cell instanceof String) {
addCell(uidl, cell.toString(), aligns[col++], style,
false, sorted);
} else {
final Paintable cellContent = client
.getPaintable((UIDL) cell);
addCell(uidl, (Widget) cellContent, aligns[col++],
style, sorted);
paintComponent(cellContent, (UIDL) cell);
}
}
if (uidl.hasAttribute("selected") && !isSelected()) {
toggleSelection();
}
}
/**
* Add a dummy row, used for measurements if Table is empty.
*/
public VScrollTableRow() {
this(0);
addStyleName(CLASSNAME + "-row");
addCell(null, "_", 'b', "", true, false);
}
public void addCell(UIDL rowUidl, String text, char align,
String style, boolean textIsHTML, boolean sorted) {
// String only content is optimized by not using Label widget
final Element td = DOM.createTD();
final Element container = DOM.createDiv();
String className = CLASSNAME + "-cell-content";
if (style != null && !style.equals("")) {
className += " " + CLASSNAME + "-cell-content-" + style;
}
if (sorted) {
className += " " + CLASSNAME + "-cell-content-sorted";
}
td.setClassName(className);
container.setClassName(CLASSNAME + "-cell-wrapper");
if (textIsHTML) {
container.setInnerHTML(text);
} else {
container.setInnerText(text);
}
if (align != ALIGN_LEFT) {
switch (align) {
case ALIGN_CENTER:
container.getStyle().setProperty("textAlign", "center");
break;
case ALIGN_RIGHT:
default:
container.getStyle().setProperty("textAlign", "right");
break;
}
}
td.appendChild(container);
getElement().appendChild(td);
}
public void addCell(UIDL rowUidl, Widget w, char align,
String style, boolean sorted) {
final Element td = DOM.createTD();
final Element container = DOM.createDiv();
String className = CLASSNAME + "-cell-content";
if (style != null && !style.equals("")) {
className += " " + CLASSNAME + "-cell-content-" + style;
}
if (sorted) {
className += " " + CLASSNAME + "-cell-content-sorted";
}
td.setClassName(className);
container.setClassName(CLASSNAME + "-cell-wrapper");
// TODO most components work with this, but not all (e.g.
// Select)
// Old comment: make widget cells respect align.
// text-align:center for IE, margin: auto for others
if (align != ALIGN_LEFT) {
switch (align) {
case ALIGN_CENTER:
container.getStyle().setProperty("textAlign", "center");
break;
case ALIGN_RIGHT:
default:
container.getStyle().setProperty("textAlign", "right");
break;
}
}
td.appendChild(container);
getElement().appendChild(td);
// ensure widget not attached to another element (possible tBody
// change)
w.removeFromParent();
container.appendChild(w.getElement());
adopt(w);
childWidgets.add(w);
}
public Iterator<Widget> iterator() {
return childWidgets.iterator();
}
@Override
public boolean remove(Widget w) {
if (childWidgets.contains(w)) {
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()),
w.getElement());
childWidgets.remove(w);
return true;
} else {
return false;
}
}
private void handleClickEvent(Event event, Element targetTdOrTr) {
if (client.hasEventListeners(VScrollTable.this,
ITEM_CLICK_EVENT_ID)) {
boolean doubleClick = (DOM.eventGetType(event) == Event.ONDBLCLICK);
/* This row was clicked */
client.updateVariable(paintableId, "clickedKey", ""
+ rowKey, false);
if (getElement() == targetTdOrTr.getParentElement()) {
/* A specific column was clicked */
int childIndex = DOM.getChildIndex(getElement(),
targetTdOrTr);
String colKey = null;
colKey = tHead.getHeaderCell(childIndex).getColKey();
client.updateVariable(paintableId, "clickedColKey",
colKey, false);
}
MouseEventDetails details = new MouseEventDetails(event);
boolean imm = true;
if (immediate && event.getButton() == Event.BUTTON_LEFT
&& !doubleClick && isSelectable() && !isSelected()) {
/*
* A left click when the table is selectable and in
* immediate mode on a row that is not currently
* selected will cause a selection event to be fired
* after this click event. By making the click event
* non-immediate we avoid sending two separate messages
* to the server.
*/
imm = false;
}
client.updateVariable(paintableId, "clickEvent",
details.toString(), imm);
}
}
/*
* React on click that occur on content cells only
*/
@Override
public void onBrowserEvent(final Event event) {
if (enabled) {
final int type = event.getTypeInt();
final Element targetTdOrTr = getEventTargetTdOrTr(event);
if (type == Event.ONCONTEXTMENU) {
showContextMenu(event);
event.stopPropagation();
return;
}
boolean targetCellOrRowFound = targetTdOrTr != null;
switch (type) {
case Event.ONDBLCLICK:
if (targetCellOrRowFound) {
handleClickEvent(event, targetTdOrTr);
}
break;
case Event.ONMOUSEUP:
if (targetCellOrRowFound) {
mDown = false;
handleClickEvent(event, targetTdOrTr);
if (event.getButton() == Event.BUTTON_LEFT
&& isSelectable()) {
// Ctrl+Shift click
if ((event.getCtrlKey() || event.getMetaKey())
&& event.getShiftKey()
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
toggleShiftSelection(false);
setRowFocus(this);
// Ctrl click
} else if ((event.getCtrlKey() || event
.getMetaKey())
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
boolean wasSelected = isSelected();
toggleSelection();
setRowFocus(this);
/*
* next possible range select must start on
* this row
*/
selectionRangeStart = this;
if (wasSelected) {
removeRowFromUnsentSelectionRanges(this);
}
// Ctrl click (Single selection)
} else if ((event.getCtrlKey() || event
.getMetaKey()
&& selectMode == SELECT_MODE_SINGLE)) {
if (!isSelected()
|| (isSelected() && nullSelectionAllowed)) {
if (!isSelected()) {
deselectAll();
}
toggleSelection();
setRowFocus(this);
}
// Shift click
} else if (event.getShiftKey()
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
toggleShiftSelection(true);
// click
} else {
boolean currentlyJustThisRowSelected = selectedRowKeys
.size() == 1
&& selectedRowKeys
.contains(getKey());
if (!currentlyJustThisRowSelected) {
if (multiselectmode == MULTISELECT_MODE_DEFAULT) {
deselectAll();
}
toggleSelection();
} else if ((selectMode == SELECT_MODE_SINGLE || multiselectmode == MULTISELECT_MODE_SIMPLE)
&& nullSelectionAllowed) {
toggleSelection();
}/*
* else NOP to avoid excessive server
* visits (selection is removed with
* CTRL/META click)
*/
selectionRangeStart = this;
setRowFocus(this);
}
// Remove IE text selection hack
if (BrowserInfo.get().isIE()) {
((Element) event.getEventTarget().cast())
.setPropertyJSO("onselectstart",
null);
}
sendSelectedRows();
}
}
break;
case Event.ONTOUCHEND:
case Event.ONTOUCHCANCEL:
if (touchStart != null) {
/*
* Touch has not been handled as neither context or
* drag start, handle it as a click.
*/
Util.simulateClickFromTouchEvent(touchStart, this);
touchStart = null;
}
if (contextTouchTimeout != null) {
contextTouchTimeout.cancel();
}
break;
case Event.ONTOUCHMOVE:
if (isSignificantMove(event)) {
/*
* TODO figure out scroll delegate don't eat events
* if row is selected. Null check for active
* delegate is as a workaround.
*/
if (dragmode != 0
&& touchStart != null
&& (TouchScrollDelegate
.getActiveScrollDelegate() == null)) {
startRowDrag(touchStart, type, targetTdOrTr);
}
if (contextTouchTimeout != null) {
contextTouchTimeout.cancel();
}
/*
* Avoid clicks and drags by clearing touch start
* flag.
*/
touchStart = null;
}
break;
case Event.ONTOUCHSTART:
touchStart = event;
Touch touch = event.getChangedTouches().get(0);
// save position to fields, touches in events are same
// isntance during the operation.
touchStartX = touch.getClientX();
touchStartY = touch.getClientY();
/*
* Prevent simulated mouse events.
*/
touchStart.preventDefault();
if (dragmode != 0 || actionKeys != null) {
new Timer() {
@Override
public void run() {
TouchScrollDelegate activeScrollDelegate = TouchScrollDelegate
.getActiveScrollDelegate();
if (activeScrollDelegate != null
&& !activeScrollDelegate.isMoved()) {
/*
* scrolling hasn't started. Cancel
* scrolling and let row handle this as
* drag start or context menu.
*/
activeScrollDelegate.stopScrolling();
} else {
/*
* Scrolled or scrolling, clear touch
* start to indicate that row shouldn't
* handle touch move/end events.
*/
touchStart = null;
}
}
}.schedule(TOUCHSCROLL_TIMEOUT);
if (contextTouchTimeout == null
&& actionKeys != null) {
contextTouchTimeout = new Timer() {
@Override
public void run() {
if (touchStart != null) {
showContextMenu(touchStart);
touchStart = null;
}
}
};
}
contextTouchTimeout.cancel();
contextTouchTimeout
.schedule(TOUCH_CONTEXT_MENU_TIMEOUT);
}
break;
case Event.ONMOUSEDOWN:
if (targetCellOrRowFound) {
setRowFocus(this);
ensureFocus();
if (dragmode != 0
&& (event.getButton() == NativeEvent.BUTTON_LEFT)) {
startRowDrag(event, type, targetTdOrTr);
} else if (event.getCtrlKey()
|| event.getShiftKey()
|| event.getMetaKey()
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
// Prevent default text selection in Firefox
event.preventDefault();
// Prevent default text selection in IE
if (BrowserInfo.get().isIE()) {
((Element) event.getEventTarget().cast())
.setPropertyJSO(
"onselectstart",
getPreventTextSelectionIEHack());
}
event.stopPropagation();
}
}
break;
case Event.ONMOUSEOUT:
if (targetCellOrRowFound) {
mDown = false;
}
break;
default:
break;
}
}
super.onBrowserEvent(event);
}
private boolean isSignificantMove(Event event) {
if (touchStart == null) {
// no touch start
return false;
}
/*
* TODO calculate based on real distance instead of separate
* axis checks
*/
Touch touch = event.getChangedTouches().get(0);
if (Math.abs(touch.getClientX() - touchStartX) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
return true;
}
if (Math.abs(touch.getClientY() - touchStartY) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
return true;
}
return false;
}
protected void startRowDrag(Event event, final int type,
Element targetTdOrTr) {
mDown = true;
VTransferable transferable = new VTransferable();
transferable.setDragSource(VScrollTable.this);
transferable.setData("itemId", "" + rowKey);
NodeList<TableCellElement> cells = rowElement.getCells();
for (int i = 0; i < cells.getLength(); i++) {
if (cells.getItem(i).isOrHasChild(targetTdOrTr)) {
HeaderCell headerCell = tHead.getHeaderCell(i);
transferable.setData("propertyId", headerCell.cid);
break;
}
}
VDragEvent ev = VDragAndDropManager.get().startDrag(
transferable, event, true);
if (dragmode == DRAGMODE_MULTIROW
&& selectMode == SELECT_MODE_MULTI
&& selectedRowKeys.contains("" + rowKey)) {
ev.createDragImage(
(Element) scrollBody.tBodyElement.cast(), true);
Element dragImage = ev.getDragImage();
int i = 0;
for (Iterator<Widget> iterator = scrollBody.iterator(); iterator
.hasNext();) {
VScrollTableRow next = (VScrollTableRow) iterator
.next();
Element child = (Element) dragImage.getChild(i++);
if (!selectedRowKeys.contains("" + next.rowKey)) {
child.getStyle().setVisibility(Visibility.HIDDEN);
}
}
} else {
ev.createDragImage(getElement(), true);
}
if (type == Event.ONMOUSEDOWN) {
event.preventDefault();
}
event.stopPropagation();
}
/**
* Finds the TD that the event interacts with. Returns null if the
* target of the event should not be handled. If the event target is
* the row directly this method returns the TR element instead of
* the TD.
*
* @param event
* @return TD or TR element that the event targets (the actual event
* target is this element or a child of it)
*/
private Element getEventTargetTdOrTr(Event event) {
final Element eventTarget = event.getEventTarget().cast();
Widget widget = Util.findWidget(eventTarget, null);
final Element thisTrElement = getElement();
if (widget != this) {
/*
* This is a workaround to make Labels, read only TextFields
* and Embedded in a Table clickable (see #2688). It is
* really not a fix as it does not work with a custom read
* only components (not extending VLabel/VEmbedded).
*/
while (widget != null && widget.getParent() != this) {
widget = widget.getParent();
}
if (!(widget instanceof VLabel)
&& !(widget instanceof VEmbedded)
&& !(widget instanceof VTextField && ((VTextField) widget)
.isReadOnly())) {
return null;
}
}
if (eventTarget == thisTrElement) {
// This was a click on the TR element
return thisTrElement;
}
// Iterate upwards until we find the TR element
Element element = eventTarget;
while (element != null
&& element.getParentElement().cast() != thisTrElement) {
element = element.getParentElement().cast();
}
return element;
}
public void showContextMenu(Event event) {
if (enabled && actionKeys != null) {
int left = Util.getTouchOrMouseClientX(event);
int top = Util.getTouchOrMouseClientY(event);
top += Window.getScrollTop();
left += Window.getScrollLeft();
client.getContextMenu().showAt(this, left, top);
}
event.stopPropagation();
event.preventDefault();
}
/**
* Has the row been selected?
*
* @return Returns true if selected, else false
*/
public boolean isSelected() {
return selected;
}
/**
* Toggle the selection of the row
*/
public void toggleSelection() {
selected = !selected;
selectionChanged = true;
if (selected) {
selectedRowKeys.add(String.valueOf(rowKey));
addStyleName("v-selected");
} else {
removeStyleName("v-selected");
selectedRowKeys.remove(String.valueOf(rowKey));
}
}
/**
* Is called when a user clicks an item when holding SHIFT key down.
* This will select a new range from the last focused row
*
* @param deselectPrevious
* Should the previous selected range be deselected
*/
private void toggleShiftSelection(boolean deselectPrevious) {
/*
* Ensures that we are in multiselect mode and that we have a
* previous selection which was not a deselection
*/
if (selectMode == SELECT_MODE_SINGLE) {
// No previous selection found
deselectAll();
toggleSelection();
return;
}
// Set the selectable range
VScrollTableRow endRow = this;
VScrollTableRow startRow = selectionRangeStart;
if (startRow == null) {
startRow = focusedRow;
// If start row is null then we have a multipage selection
// from
// above
if (startRow == null) {
startRow = (VScrollTableRow) scrollBody.iterator()
.next();
setRowFocus(endRow);
}
}
// Deselect previous items if so desired
if (deselectPrevious) {
deselectAll();
}
// we'll ensure GUI state from top down even though selection
// was the opposite way
if (!startRow.isBefore(endRow)) {
VScrollTableRow tmp = startRow;
startRow = endRow;
endRow = tmp;
}
SelectionRange range = new SelectionRange(startRow, endRow);
for (Widget w : scrollBody) {
VScrollTableRow row = (VScrollTableRow) w;
if (range.inRange(row)) {
if (!row.isSelected()) {
row.toggleSelection();
}
selectedRowKeys.add(row.getKey());
}
}
// Add range
if (startRow != endRow) {
selectedRowRanges.add(range);
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.ui.IActionOwner#getActions ()
*/
public Action[] getActions() {
if (actionKeys == null) {
return new Action[] {};
}
final Action[] actions = new Action[actionKeys.length];
for (int i = 0; i < actions.length; i++) {
final String actionKey = actionKeys[i];
final TreeAction a = new TreeAction(this,
String.valueOf(rowKey), actionKey) {
@Override
public void execute() {
super.execute();
lazyRevertFocusToRow(VScrollTableRow.this);
}
};
a.setCaption(getActionCaption(actionKey));
a.setIconUrl(getActionIcon(actionKey));
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
public RenderSpace getAllocatedSpace(Widget child) {
int w = 0;
int i = getColIndexOf(child);
HeaderCell headerCell = tHead.getHeaderCell(i);
if (headerCell != null) {
if (initializedAndAttached) {
w = headerCell.getWidth();
} else {
// header offset width is not absolutely correct value,
// but a best guess (expecting similar content in all
// columns ->
// if one component is relative width so are others)
w = headerCell.getOffsetWidth() - getCellExtraWidth();
}
}
return new RenderSpace(w, 0) {
@Override
public int getHeight() {
return (int) getRowHeight();
}
};
}
private int getColIndexOf(Widget child) {
com.google.gwt.dom.client.Element widgetCell = child
.getElement().getParentElement().getParentElement();
NodeList<TableCellElement> cells = rowElement.getCells();
for (int i = 0; i < cells.getLength(); i++) {
if (cells.getItem(i) == widgetCell) {
return i;
}
}
return -1;
}
public boolean hasChildComponent(Widget component) {
return childWidgets.contains(component);
}
public void replaceChildComponent(Widget oldComponent,
Widget newComponent) {
com.google.gwt.dom.client.Element parentElement = oldComponent
.getElement().getParentElement();
int index = childWidgets.indexOf(oldComponent);
oldComponent.removeFromParent();
parentElement.appendChild(newComponent.getElement());
childWidgets.add(index, newComponent);
adopt(newComponent);
}
public boolean requestLayout(Set<Paintable> children) {
// row size should never change and system wouldn't event
// survive as this is a kind of fake paitable
return true;
}
public void updateCaption(Paintable component, UIDL uidl) {
// NOP, not rendered
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Should never be called,
// Component container interface faked here to get layouts
// render properly
}
}
/**
* Ensure the component has a focus.
*
* TODO the current implementation simply always calls focus for the
* component. In case the Table at some point implements focus/blur
* listeners, this method needs to be evolved to conditionally call
* focus only if not currently focused.
*/
protected void ensureFocus() {
if (!hasFocus) {
scrollBodyPanel.setFocus(true);
}
}
}
/**
* Deselects all items
*/
public void deselectAll() {
for (Widget w : scrollBody) {
VScrollTableRow row = (VScrollTableRow) w;
if (row.isSelected()) {
row.toggleSelection();
}
}
// still ensure all selects are removed from (not necessary rendered)
selectedRowKeys.clear();
selectedRowRanges.clear();
// also notify server that it clears all previous selections (the client
// side does not know about the invisible ones)
instructServerToForgetPreviousSelections();
}
/**
* Used in multiselect mode when the client side knows that all selections
* are in the next request.
*/
private void instructServerToForgetPreviousSelections() {
client.updateVariable(paintableId, "clearSelections", true, false);
}
/**
* Determines the pagelength when the table height is fixed.
*/
public void updatePageLength() {
// Only update if visible and enabled
if (!isVisible() || !enabled) {
return;
}
if (scrollBody == null) {
return;
}
if (height == null || height.equals("")) {
return;
}
int rowHeight = (int) Math.round(scrollBody.getRowHeight());
int bodyH = scrollBodyPanel.getOffsetHeight();
int rowsAtOnce = bodyH / rowHeight;
boolean anotherPartlyVisible = ((bodyH % rowHeight) != 0);
if (anotherPartlyVisible) {
rowsAtOnce++;
}
if (pageLength != rowsAtOnce) {
pageLength = rowsAtOnce;
client.updateVariable(paintableId, "pagelength", pageLength, false);
if (!rendering) {
int currentlyVisible = scrollBody.lastRendered
- scrollBody.firstRendered;
if (currentlyVisible < pageLength
&& currentlyVisible < totalRows) {
// shake scrollpanel to fill empty space
scrollBodyPanel.setScrollPosition(scrollTop + 1);
scrollBodyPanel.setScrollPosition(scrollTop - 1);
}
}
}
}
@Override
public void setWidth(String width) {
if (this.width.equals(width)) {
return;
}
this.width = width;
if (width != null && !"".equals(width)) {
super.setWidth(width);
int innerPixels = getOffsetWidth() - getBorderWidth();
if (innerPixels < 0) {
innerPixels = 0;
}
setContentWidth(innerPixels);
// readjust undefined width columns
lazyAdjustColumnWidths.cancel();
lazyAdjustColumnWidths.schedule(LAZY_COLUMN_ADJUST_TIMEOUT);
} else {
// Undefined width
super.setWidth("");
// Readjust size of table
sizeInit();
// readjust undefined width columns
lazyAdjustColumnWidths.cancel();
lazyAdjustColumnWidths.schedule(LAZY_COLUMN_ADJUST_TIMEOUT);
}
/*
* setting width may affect wheter the component has scrollbars -> needs
* scrolling or not
*/
setProperTabIndex();
}
private static final int LAZY_COLUMN_ADJUST_TIMEOUT = 300;
private final Timer lazyAdjustColumnWidths = new Timer() {
/**
* Check for column widths, and available width, to see if we can fix
* column widths "optimally". Doing this lazily to avoid expensive
* calculation when resizing is not yet finished.
*/
@Override
public void run() {
Iterator<Widget> headCells = tHead.iterator();
int usedMinimumWidth = 0;
int totalExplicitColumnsWidths = 0;
float expandRatioDivider = 0;
int colIndex = 0;
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
if (hCell.isDefinedWidth()) {
totalExplicitColumnsWidths += hCell.getWidth();
usedMinimumWidth += hCell.getWidth();
} else {
usedMinimumWidth += hCell.getNaturalColumnWidth(colIndex);
expandRatioDivider += hCell.getExpandRatio();
}
colIndex++;
}
int availW = scrollBody.getAvailableWidth();
// Hey IE, are you really sure about this?
availW = scrollBody.getAvailableWidth();
int visibleCellCount = tHead.getVisibleCellCount();
availW -= scrollBody.getCellExtraWidth() * visibleCellCount;
if (willHaveScrollbars()) {
availW -= Util.getNativeScrollbarSize();
}
int extraSpace = availW - usedMinimumWidth;
if (extraSpace < 0) {
extraSpace = 0;
}
int totalUndefinedNaturaWidths = usedMinimumWidth
- totalExplicitColumnsWidths;
// we have some space that can be divided optimally
HeaderCell hCell;
colIndex = 0;
headCells = tHead.iterator();
while (headCells.hasNext()) {
hCell = (HeaderCell) headCells.next();
if (!hCell.isDefinedWidth()) {
int w = hCell.getNaturalColumnWidth(colIndex);
int newSpace;
if (expandRatioDivider > 0) {
// divide excess space by expand ratios
newSpace = (int) (w + extraSpace
* hCell.getExpandRatio() / expandRatioDivider);
} else {
if (totalUndefinedNaturaWidths != 0) {
// divide relatively to natural column widths
newSpace = w + extraSpace * w
/ totalUndefinedNaturaWidths;
} else {
newSpace = w;
}
}
setColWidth(colIndex, newSpace, false);
}
colIndex++;
}
if ((height == null || "".equals(height))
&& totalRows == pageLength) {
// fix body height (may vary if lazy loading is offhorizontal
// scrollbar appears/disappears)
int bodyHeight = scrollBody.getRequiredHeight();
boolean needsSpaceForHorizontalScrollbar = (availW < usedMinimumWidth);
if (needsSpaceForHorizontalScrollbar) {
bodyHeight += Util.getNativeScrollbarSize();
}
int heightBefore = getOffsetHeight();
scrollBodyPanel.setHeight(bodyHeight + "px");
if (heightBefore != getOffsetHeight()) {
Util.notifyParentOfSizeChange(VScrollTable.this, false);
}
}
scrollBody.reLayoutComponents();
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
});
forceRealignColumnHeaders();
}
};
private void forceRealignColumnHeaders() {
if (BrowserInfo.get().isIE()) {
/*
* IE does not fire onscroll event if scroll position is reverted to
* 0 due to the content element size growth. Ensure headers are in
* sync with content manually. Safe to use null event as we don't
* actually use the event object in listener.
*/
onScroll(null);
}
}
/**
* helper to set pixel size of head and body part
*
* @param pixels
*/
private void setContentWidth(int pixels) {
tHead.setWidth(pixels + "px");
scrollBodyPanel.setWidth(pixels + "px");
tFoot.setWidth(pixels + "px");
}
private int borderWidth = -1;
/**
* @return border left + border right
*/
private int getBorderWidth() {
if (borderWidth < 0) {
borderWidth = Util.measureHorizontalPaddingAndBorder(
scrollBodyPanel.getElement(), 2);
if (borderWidth < 0) {
borderWidth = 0;
}
}
return borderWidth;
}
/**
* Ensures scrollable area is properly sized. This method is used when fixed
* size is used.
*/
private int containerHeight;
private void setContainerHeight() {
if (height != null && !"".equals(height)) {
containerHeight = getOffsetHeight();
containerHeight -= showColHeaders ? tHead.getOffsetHeight() : 0;
containerHeight -= tFoot.getOffsetHeight();
containerHeight -= getContentAreaBorderHeight();
if (containerHeight < 0) {
containerHeight = 0;
}
scrollBodyPanel.setHeight(containerHeight + "px");
}
}
private int contentAreaBorderHeight = -1;
private int scrollLeft;
private int scrollTop;
private VScrollTableDropHandler dropHandler;
private boolean navKeyDown;
private boolean multiselectPending;
/**
* @return border top + border bottom of the scrollable area of table
*/
private int getContentAreaBorderHeight() {
if (contentAreaBorderHeight < 0) {
if (BrowserInfo.get().isIE7() || BrowserInfo.get().isIE6()) {
contentAreaBorderHeight = Util
.measureVerticalBorder(scrollBodyPanel.getElement());
} else {
DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
"hidden");
int oh = scrollBodyPanel.getOffsetHeight();
int ch = scrollBodyPanel.getElement().getPropertyInt(
"clientHeight");
contentAreaBorderHeight = oh - ch;
DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
"auto");
}
}
return contentAreaBorderHeight;
}
@Override
public void setHeight(String height) {
this.height = height;
super.setHeight(height);
setContainerHeight();
if (initializedAndAttached) {
updatePageLength();
}
if (!rendering) {
// Webkit may sometimes get an odd rendering bug (white space
// between header and body), see bug #3875. Running
// overflow hack here to shake body element a bit.
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
/*
* setting height may affect wheter the component has scrollbars ->
* needs scrolling or not
*/
setProperTabIndex();
}
/*
* Overridden due Table might not survive of visibility change (scroll pos
* lost). Example ITabPanel just set contained components invisible and back
* when changing tabs.
*/
@Override
public void setVisible(boolean visible) {
if (isVisible() != visible) {
super.setVisible(visible);
if (initializedAndAttached) {
if (visible) {
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
scrollBodyPanel
.setScrollPosition((int) (firstRowInViewPort * scrollBody
.getRowHeight()));
}
});
}
}
}
}
/**
* Helper function to build html snippet for column or row headers
*
* @param uidl
* possibly with values caption and icon
* @return html snippet containing possibly an icon + caption text
*/
protected String buildCaptionHtmlSnippet(UIDL uidl) {
String s = uidl.hasAttribute("caption") ? uidl
.getStringAttribute("caption") : "";
if (uidl.hasAttribute("icon")) {
s = "<img src=\""
+ client.translateVaadinUri(uidl.getStringAttribute("icon"))
+ "\" alt=\"icon\" class=\"v-icon\">" + s;
}
return s;
}
/**
* This method has logic which rows needs to be requested from server when
* user scrolls
*/
public void onScroll(ScrollEvent event) {
scrollLeft = scrollBodyPanel.getElement().getScrollLeft();
scrollTop = scrollBodyPanel.getScrollPosition();
if (!initializedAndAttached) {
return;
}
if (!enabled) {
scrollBodyPanel
.setScrollPosition((int) (firstRowInViewPort * scrollBody
.getRowHeight()));
return;
}
rowRequestHandler.cancel();
if (BrowserInfo.get().isSafari() && event != null && scrollTop == 0) {
// due to the webkitoverflowworkaround, top may sometimes report 0
// for webkit, although it really is not. Expecting to have the
// correct
// value available soon.
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
onScroll(null);
}
});
return;
}
// fix headers horizontal scrolling
tHead.setHorizontalScrollPosition(scrollLeft);
// fix footers horizontal scrolling
tFoot.setHorizontalScrollPosition(scrollLeft);
firstRowInViewPort = (int) Math.ceil(scrollTop
/ scrollBody.getRowHeight());
if (firstRowInViewPort > totalRows - pageLength) {
firstRowInViewPort = totalRows - pageLength;
}
int postLimit = (int) (firstRowInViewPort + (pageLength - 1) + pageLength
* cache_react_rate);
if (postLimit > totalRows - 1) {
postLimit = totalRows - 1;
}
int preLimit = (int) (firstRowInViewPort - pageLength
* cache_react_rate);
if (preLimit < 0) {
preLimit = 0;
}
final int lastRendered = scrollBody.getLastRendered();
final int firstRendered = scrollBody.getFirstRendered();
if (postLimit <= lastRendered && preLimit >= firstRendered) {
// remember which firstvisible we requested, in case the server has
// a differing opinion
lastRequestedFirstvisible = firstRowInViewPort;
client.updateVariable(paintableId, "firstvisible",
firstRowInViewPort, false);
return; // scrolled withing "non-react area"
}
if (firstRowInViewPort - pageLength * cache_rate > lastRendered
|| firstRowInViewPort + pageLength + pageLength * cache_rate < firstRendered) {
// need a totally new set
rowRequestHandler
.setReqFirstRow((firstRowInViewPort - (int) (pageLength * cache_rate)));
int last = firstRowInViewPort + (int) (cache_rate * pageLength)
+ pageLength - 1;
if (last >= totalRows) {
last = totalRows - 1;
}
rowRequestHandler.setReqRows(last
- rowRequestHandler.getReqFirstRow() + 1);
rowRequestHandler.deferRowFetch();
return;
}
if (preLimit < firstRendered) {
// need some rows to the beginning of the rendered area
rowRequestHandler
.setReqFirstRow((int) (firstRowInViewPort - pageLength
* cache_rate));
rowRequestHandler.setReqRows(firstRendered
- rowRequestHandler.getReqFirstRow());
rowRequestHandler.deferRowFetch();
return;
}
if (postLimit > lastRendered) {
// need some rows to the end of the rendered area
rowRequestHandler.setReqFirstRow(lastRendered + 1);
rowRequestHandler.setReqRows((int) ((firstRowInViewPort
+ pageLength + pageLength * cache_rate) - lastRendered));
rowRequestHandler.deferRowFetch();
}
}
public VScrollTableDropHandler getDropHandler() {
return dropHandler;
}
private static class TableDDDetails {
int overkey = -1;
VerticalDropLocation dropLocation;
String colkey;
@Override
public boolean equals(Object obj) {
if (obj instanceof TableDDDetails) {
TableDDDetails other = (TableDDDetails) obj;
return dropLocation == other.dropLocation
&& overkey == other.overkey
&& ((colkey != null && colkey.equals(other.colkey)) || (colkey == null && other.colkey == null));
}
return false;
}
// @Override
// public int hashCode() {
// return overkey;
// }
}
public class VScrollTableDropHandler extends VAbstractDropHandler {
private static final String ROWSTYLEBASE = "v-table-row-drag-";
private TableDDDetails dropDetails;
private TableDDDetails lastEmphasized;
@Override
public void dragEnter(VDragEvent drag) {
updateDropDetails(drag);
super.dragEnter(drag);
}
private void updateDropDetails(VDragEvent drag) {
dropDetails = new TableDDDetails();
Element elementOver = drag.getElementOver();
VScrollTableRow row = Util.findWidget(elementOver, getRowClass());
if (row != null) {
dropDetails.overkey = row.rowKey;
Element tr = row.getElement();
Element element = elementOver;
while (element != null && element.getParentElement() != tr) {
element = (Element) element.getParentElement();
}
int childIndex = DOM.getChildIndex(tr, element);
dropDetails.colkey = tHead.getHeaderCell(childIndex)
.getColKey();
dropDetails.dropLocation = DDUtil.getVerticalDropLocation(
row.getElement(), drag.getCurrentGwtEvent(), 0.2);
}
drag.getDropDetails().put("itemIdOver", dropDetails.overkey + "");
drag.getDropDetails().put(
"detail",
dropDetails.dropLocation != null ? dropDetails.dropLocation
.toString() : null);
}
private Class<? extends Widget> getRowClass() {
// get the row type this way to make dd work in derived
// implementations
return scrollBody.iterator().next().getClass();
}
@Override
public void dragOver(VDragEvent drag) {
TableDDDetails oldDetails = dropDetails;
updateDropDetails(drag);
if (!oldDetails.equals(dropDetails)) {
deEmphasis();
final TableDDDetails newDetails = dropDetails;
VAcceptCallback cb = new VAcceptCallback() {
public void accepted(VDragEvent event) {
if (newDetails.equals(dropDetails)) {
dragAccepted(event);
}
/*
* Else new target slot already defined, ignore
*/
}
};
validate(cb, drag);
}
}
@Override
public void dragLeave(VDragEvent drag) {
deEmphasis();
super.dragLeave(drag);
}
@Override
public boolean drop(VDragEvent drag) {
deEmphasis();
return super.drop(drag);
}
private void deEmphasis() {
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", false);
if (lastEmphasized == null) {
return;
}
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (lastEmphasized != null
&& row.rowKey == lastEmphasized.overkey) {
String stylename = ROWSTYLEBASE
+ lastEmphasized.dropLocation.toString()
.toLowerCase();
VScrollTableRow.setStyleName(row.getElement(), stylename,
false);
lastEmphasized = null;
return;
}
}
}
/**
* TODO needs different drop modes ?? (on cells, on rows), now only
* supports rows
*/
private void emphasis(TableDDDetails details) {
deEmphasis();
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", true);
// iterate old and new emphasized row
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (details != null && details.overkey == row.rowKey) {
String stylename = ROWSTYLEBASE
+ details.dropLocation.toString().toLowerCase();
VScrollTableRow.setStyleName(row.getElement(), stylename,
true);
lastEmphasized = details;
return;
}
}
}
@Override
protected void dragAccepted(VDragEvent drag) {
emphasis(dropDetails);
}
@Override
public Paintable getPaintable() {
return VScrollTable.this;
}
public ApplicationConnection getApplicationConnection() {
return client;
}
}
protected VScrollTableRow getFocusedRow() {
return focusedRow;
}
/**
* Moves the selection head to a specific row
*
* @param row
* The row to where the selection head should move
* @return Returns true if focus was moved successfully, else false
*/
private boolean setRowFocus(VScrollTableRow row) {
if (selectMode == SELECT_MODE_NONE) {
return false;
}
// Remove previous selection
if (focusedRow != null && focusedRow != row) {
focusedRow.removeStyleName(CLASSNAME_SELECTION_FOCUS);
}
if (row != null) {
// Apply focus style to new selection
row.addStyleName(CLASSNAME_SELECTION_FOCUS);
/*
* Trying to set focus on already focused row
*/
if (row == focusedRow) {
return false;
}
// Set new focused row
focusedRow = row;
ensureRowIsVisible(row);
return true;
}
return false;
}
/**
* Ensures that the row is visible
*
* @param row
* The row to ensure is visible
*/
private void ensureRowIsVisible(VScrollTableRow row) {
scrollIntoViewVertically(row.getElement());
}
/**
* Scrolls an element into view vertically only. Modified version of
* Element.scrollIntoView.
*
* @param elem
* The element to scroll into view
*/
private native void scrollIntoViewVertically(Element elem)
/*-{
var top = elem.offsetTop;
var height = elem.offsetHeight;
if (elem.parentNode != elem.offsetParent) {
top -= elem.parentNode.offsetTop;
}
var cur = elem.parentNode;
while (cur && (cur.nodeType == 1)) {
if (top < cur.scrollTop) {
cur.scrollTop = top;
}
if (top + height > cur.scrollTop + cur.clientHeight) {
cur.scrollTop = (top + height) - cur.clientHeight;
}
var offsetTop = cur.offsetTop;
if (cur.parentNode != cur.offsetParent) {
offsetTop -= cur.parentNode.offsetTop;
}
top += offsetTop - cur.scrollTop;
cur = cur.parentNode;
}
}-*/;
/**
* Handles the keyboard events handled by the table
*
* @param event
* The keyboard event received
* @return true iff the navigation event was handled
*/
protected boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
if (keycode == KeyCodes.KEY_TAB || keycode == KeyCodes.KEY_SHIFT) {
// Do not handle tab key
return false;
}
// Down navigation
if (selectMode == SELECT_MODE_NONE && keycode == getNavigationDownKey()) {
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() + scrollingVelocity);
return true;
} else if (keycode == getNavigationDownKey()) {
if (selectMode == SELECT_MODE_MULTI && moveFocusDown()) {
selectFocusedRow(ctrl, shift);
} else if (selectMode == SELECT_MODE_SINGLE && !shift
&& moveFocusDown()) {
selectFocusedRow(ctrl, shift);
}
return true;
}
// Up navigation
if (selectMode == SELECT_MODE_NONE && keycode == getNavigationUpKey()) {
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() - scrollingVelocity);
return true;
} else if (keycode == getNavigationUpKey()) {
if (selectMode == SELECT_MODE_MULTI && moveFocusUp()) {
selectFocusedRow(ctrl, shift);
} else if (selectMode == SELECT_MODE_SINGLE && !shift
&& moveFocusUp()) {
selectFocusedRow(ctrl, shift);
}
return true;
}
if (keycode == getNavigationLeftKey()) {
// Left navigation
scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
.getHorizontalScrollPosition() - scrollingVelocity);
return true;
} else if (keycode == getNavigationRightKey()) {
// Right navigation
scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
.getHorizontalScrollPosition() + scrollingVelocity);
return true;
}
// Select navigation
if (isSelectable() && keycode == getNavigationSelectKey()) {
if (selectMode == SELECT_MODE_SINGLE) {
boolean wasSelected = focusedRow.isSelected();
deselectAll();
if (!wasSelected || !nullSelectionAllowed) {
focusedRow.toggleSelection();
}
} else {
focusedRow.toggleSelection();
removeRowFromUnsentSelectionRanges(focusedRow);
}
sendSelectedRows();
return true;
}
// Page Down navigation
if (keycode == getNavigationPageDownKey()) {
if (isSelectable()) {
/*
* If selectable we plagiate MSW behaviour: first scroll to the
* end of current view. If at the end, scroll down one page
* length and keep the selected row in the bottom part of
* visible area.
*/
if (!isFocusAtTheEndOfTable()) {
VScrollTableRow lastVisibleRowInViewPort = scrollBody
.getRowByRowIndex(firstRowInViewPort
+ getFullyVisibleRowCount() - 1);
if (lastVisibleRowInViewPort != null
&& lastVisibleRowInViewPort != focusedRow) {
// focused row is not at the end of the table, move
// focus and select the last visible row
setRowFocus(lastVisibleRowInViewPort);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
} else {
int indexOfToBeFocused = focusedRow.getIndex()
+ getFullyVisibleRowCount();
if (indexOfToBeFocused >= totalRows) {
indexOfToBeFocused = totalRows - 1;
}
VScrollTableRow toBeFocusedRow = scrollBody
.getRowByRowIndex(indexOfToBeFocused);
if (toBeFocusedRow != null) {
/*
* if the next focused row is rendered
*/
setRowFocus(toBeFocusedRow);
selectFocusedRow(ctrl, shift);
// TODO needs scrollintoview ?
sendSelectedRows();
} else {
// scroll down by pixels and return, to wait for
// new rows, then select the last item in the
// viewport
selectLastItemInNextRender = true;
multiselectPending = shift;
scrollByPagelenght(1);
}
}
}
} else {
/* No selections, go page down by scrolling */
scrollByPagelenght(1);
}
return true;
}
// Page Up navigation
if (keycode == getNavigationPageUpKey()) {
if (isSelectable()) {
/*
* If selectable we plagiate MSW behaviour: first scroll to the
* end of current view. If at the end, scroll down one page
* length and keep the selected row in the bottom part of
* visible area.
*/
if (!isFocusAtTheBeginningOfTable()) {
VScrollTableRow firstVisibleRowInViewPort = scrollBody
.getRowByRowIndex(firstRowInViewPort);
if (firstVisibleRowInViewPort != null
&& firstVisibleRowInViewPort != focusedRow) {
// focus is not at the beginning of the table, move
// focus and select the first visible row
setRowFocus(firstVisibleRowInViewPort);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
} else {
int indexOfToBeFocused = focusedRow.getIndex()
- getFullyVisibleRowCount();
if (indexOfToBeFocused < 0) {
indexOfToBeFocused = 0;
}
VScrollTableRow toBeFocusedRow = scrollBody
.getRowByRowIndex(indexOfToBeFocused);
if (toBeFocusedRow != null) { // if the next focused row
// is rendered
setRowFocus(toBeFocusedRow);
selectFocusedRow(ctrl, shift);
// TODO needs scrollintoview ?
sendSelectedRows();
} else {
// unless waiting for the next rowset already
// scroll down by pixels and return, to wait for
// new rows, then select the last item in the
// viewport
selectFirstItemInNextRender = true;
multiselectPending = shift;
scrollByPagelenght(-1);
}
}
}
} else {
/* No selections, go page up by scrolling */
scrollByPagelenght(-1);
}
return true;
}
// Goto start navigation
if (keycode == getNavigationStartKey()) {
scrollBodyPanel.setScrollPosition(0);
if (isSelectable()) {
if (focusedRow != null && focusedRow.getIndex() == 0) {
return false;
} else {
VScrollTableRow rowByRowIndex = (VScrollTableRow) scrollBody
.iterator().next();
if (rowByRowIndex.getIndex() == 0) {
setRowFocus(rowByRowIndex);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
} else {
// first row of table will come in next row fetch
if (ctrl) {
focusFirstItemInNextRender = true;
} else {
selectFirstItemInNextRender = true;
multiselectPending = shift;
}
}
}
}
return true;
}
// Goto end navigation
if (keycode == getNavigationEndKey()) {
scrollBodyPanel.setScrollPosition(scrollBody.getOffsetHeight());
if (isSelectable()) {
final int lastRendered = scrollBody.getLastRendered();
if (lastRendered + 1 == totalRows) {
VScrollTableRow rowByRowIndex = scrollBody
.getRowByRowIndex(lastRendered);
if (focusedRow != rowByRowIndex) {
setRowFocus(rowByRowIndex);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
}
} else {
if (ctrl) {
focusLastItemInNextRender = true;
} else {
selectLastItemInNextRender = true;
multiselectPending = shift;
}
}
}
return true;
}
return false;
}
private boolean isFocusAtTheBeginningOfTable() {
return focusedRow.getIndex() == 0;
}
private boolean isFocusAtTheEndOfTable() {
return focusedRow.getIndex() + 1 >= totalRows;
}
private int getFullyVisibleRowCount() {
return (int) (scrollBodyPanel.getOffsetHeight() / scrollBody
.getRowHeight());
}
private void scrollByPagelenght(int i) {
int pixels = i
* (int) (getFullyVisibleRowCount() * scrollBody.getRowHeight());
int newPixels = scrollBodyPanel.getScrollPosition() + pixels;
if (newPixels < 0) {
newPixels = 0;
} // else if too high, NOP (all know browsers accept illegally big
// values here)
scrollBodyPanel.setScrollPosition(newPixels);
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
* .dom.client.FocusEvent)
*/
public void onFocus(FocusEvent event) {
if (isFocusable()) {
hasFocus = true;
// Focus a row if no row is in focus
if (focusedRow == null) {
focusRowFromBody();
} else {
setRowFocus(focusedRow);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
* .dom.client.BlurEvent)
*/
public void onBlur(BlurEvent event) {
hasFocus = false;
navKeyDown = false;
if (isFocusable()) {
// Unfocus any row
setRowFocus(null);
}
}
/**
* Removes a key from a range if the key is found in a selected range
*
* @param key
* The key to remove
*/
private void removeRowFromUnsentSelectionRanges(VScrollTableRow row) {
Collection<SelectionRange> newRanges = null;
for (Iterator<SelectionRange> iterator = selectedRowRanges.iterator(); iterator
.hasNext();) {
SelectionRange range = iterator.next();
if (range.inRange(row)) {
// Split the range if given row is in range
Collection<SelectionRange> splitranges = range.split(row);
if (newRanges == null) {
newRanges = new ArrayList<SelectionRange>();
}
newRanges.addAll(splitranges);
iterator.remove();
}
}
if (newRanges != null) {
selectedRowRanges.addAll(newRanges);
}
}
/**
* Can the Table be focused?
*
* @return True if the table can be focused, else false
*/
public boolean isFocusable() {
if (scrollBody != null && enabled) {
boolean hasVerticalScrollbars = scrollBody.getOffsetHeight() > scrollBodyPanel
.getOffsetHeight();
boolean hasHorizontalScrollbars = scrollBody.getOffsetWidth() > scrollBodyPanel
.getOffsetWidth();
return !(!hasHorizontalScrollbars && !hasVerticalScrollbars && selectMode == SELECT_MODE_NONE);
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.Focusable#focus()
*/
public void focus() {
if (isFocusable()) {
scrollBodyPanel.focus();
}
}
/**
* Sets the proper tabIndex for scrollBodyPanel (the focusable elemen in the
* component).
*
* If the component has no explicit tabIndex a zero is given (default
* tabbing order based on dom hierarchy) or -1 if the component does not
* need to gain focus. The component needs no focus if it has no scrollabars
* (not scrollable) and not selectable. Note that in the future shortcut
* actions may need focus.
*
*/
private void setProperTabIndex() {
int storedScrollTop = 0;
int storedScrollLeft = 0;
if (BrowserInfo.get().getOperaVersion() >= 11) {
// Workaround for Opera scroll bug when changing tabIndex (#6222)
storedScrollTop = scrollBodyPanel.getScrollPosition();
storedScrollLeft = scrollBodyPanel.getHorizontalScrollPosition();
}
if (tabIndex == 0 && !isFocusable()) {
scrollBodyPanel.setTabIndex(-1);
} else {
scrollBodyPanel.setTabIndex(tabIndex);
}
if (BrowserInfo.get().getOperaVersion() >= 11) {
// Workaround for Opera scroll bug when changing tabIndex (#6222)
scrollBodyPanel.setScrollPosition(storedScrollTop);
scrollBodyPanel.setHorizontalScrollPosition(storedScrollLeft);
}
}
public void startScrollingVelocityTimer() {
if (scrollingVelocityTimer == null) {
scrollingVelocityTimer = new Timer() {
@Override
public void run() {
scrollingVelocity++;
}
};
scrollingVelocityTimer.scheduleRepeating(100);
}
}
public void cancelScrollingVelocityTimer() {
if (scrollingVelocityTimer != null) {
// Remove velocityTimer if it exists and the Table is disabled
scrollingVelocityTimer.cancel();
scrollingVelocityTimer = null;
scrollingVelocity = 10;
}
}
/**
*
* @param keyCode
* @return true if the given keyCode is used by the table for navigation
*/
private boolean isNavigationKey(int keyCode) {
return keyCode == getNavigationUpKey()
|| keyCode == getNavigationLeftKey()
|| keyCode == getNavigationRightKey()
|| keyCode == getNavigationDownKey()
|| keyCode == getNavigationPageUpKey()
|| keyCode == getNavigationPageDownKey()
|| keyCode == getNavigationEndKey()
|| keyCode == getNavigationStartKey();
}
public void lazyRevertFocusToRow(final VScrollTableRow currentlyFocusedRow) {
Scheduler.get().scheduleFinally(new ScheduledCommand() {
public void execute() {
if (currentlyFocusedRow != null) {
setRowFocus(currentlyFocusedRow);
} else {
VConsole.log("no row?");
focusRowFromBody();
}
scrollBody.ensureFocus();
}
});
}
public Action[] getActions() {
if (bodyActionKeys == null) {
return new Action[] {};
}
final Action[] actions = new Action[bodyActionKeys.length];
for (int i = 0; i < actions.length; i++) {
final String actionKey = bodyActionKeys[i];
Action bodyAction = new TreeAction(this, null, actionKey);
bodyAction.setCaption(getActionCaption(actionKey));
bodyAction.setIconUrl(getActionIcon(actionKey));
actions[i] = bodyAction;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
/**
* Add this to the element mouse down event by using element.setPropertyJSO
* ("onselectstart",applyDisableTextSelectionIEHack()); Remove it then again
* when the mouse is depressed in the mouse up event.
*
* @return Returns the JSO preventing text selection
*/
private static native JavaScriptObject getPreventTextSelectionIEHack()
/*-{
return function(){ return false; };
}-*/;
}
| src/com/vaadin/terminal/gwt/client/ui/VScrollTable.java | /*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.dom.client.TableRowElement;
import com.google.gwt.dom.client.TableSectionElement;
import com.google.gwt.dom.client.Touch;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.event.dom.client.TouchStartEvent;
import com.google.gwt.event.dom.client.TouchStartHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Focusable;
import com.vaadin.terminal.gwt.client.MouseEventDetails;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.VConsole;
import com.vaadin.terminal.gwt.client.ui.VScrollTable.VScrollTableBody.VScrollTableRow;
import com.vaadin.terminal.gwt.client.ui.dd.DDUtil;
import com.vaadin.terminal.gwt.client.ui.dd.VAbstractDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VAcceptCallback;
import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager;
import com.vaadin.terminal.gwt.client.ui.dd.VDragEvent;
import com.vaadin.terminal.gwt.client.ui.dd.VHasDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VTransferable;
import com.vaadin.terminal.gwt.client.ui.dd.VerticalDropLocation;
/**
* VScrollTable
*
* VScrollTable is a FlowPanel having two widgets in it: * TableHead component *
* ScrollPanel
*
* TableHead contains table's header and widgets + logic for resizing,
* reordering and hiding columns.
*
* ScrollPanel contains VScrollTableBody object which handles content. To save
* some bandwidth and to improve clients responsiveness with loads of data, in
* VScrollTableBody all rows are not necessary rendered. There are "spacers" in
* VScrollTableBody to use the exact same space as non-rendered rows would use.
* This way we can use seamlessly traditional scrollbars and scrolling to fetch
* more rows instead of "paging".
*
* In VScrollTable we listen to scroll events. On horizontal scrolling we also
* update TableHeads scroll position which has its scrollbars hidden. On
* vertical scroll events we will check if we are reaching the end of area where
* we have rows rendered and
*
* TODO implement unregistering for child components in Cells
*/
public class VScrollTable extends FlowPanel implements Table, ScrollHandler,
VHasDropHandler, FocusHandler, BlurHandler, Focusable, ActionOwner {
private static final String ROW_HEADER_COLUMN_KEY = "0";
public static final String CLASSNAME = "v-table";
public static final String CLASSNAME_SELECTION_FOCUS = CLASSNAME + "-focus";
public static final String ITEM_CLICK_EVENT_ID = "itemClick";
public static final String HEADER_CLICK_EVENT_ID = "handleHeaderClick";
public static final String FOOTER_CLICK_EVENT_ID = "handleFooterClick";
public static final String COLUMN_RESIZE_EVENT_ID = "columnResize";
public static final String COLUMN_REORDER_EVENT_ID = "columnReorder";
private static final double CACHE_RATE_DEFAULT = 2;
/**
* The default multi select mode where simple left clicks only selects one
* item, CTRL+left click selects multiple items and SHIFT-left click selects
* a range of items.
*/
private static final int MULTISELECT_MODE_DEFAULT = 0;
/**
* The simple multiselect mode is what the table used to have before
* ctrl/shift selections were added. That is that when this is set clicking
* on an item selects/deselects the item and no ctrl/shift selections are
* available.
*/
private static final int MULTISELECT_MODE_SIMPLE = 1;
/**
* multiple of pagelength which component will cache when requesting more
* rows
*/
private double cache_rate = CACHE_RATE_DEFAULT;
/**
* fraction of pageLenght which can be scrolled without making new request
*/
private double cache_react_rate = 0.75 * cache_rate;
public static final char ALIGN_CENTER = 'c';
public static final char ALIGN_LEFT = 'b';
public static final char ALIGN_RIGHT = 'e';
private static final int CHARCODE_SPACE = 32;
private int firstRowInViewPort = 0;
private int pageLength = 15;
private int lastRequestedFirstvisible = 0; // to detect "serverside scroll"
protected boolean showRowHeaders = false;
private String[] columnOrder;
protected ApplicationConnection client;
protected String paintableId;
private boolean immediate;
private boolean nullSelectionAllowed = true;
private int selectMode = Table.SELECT_MODE_NONE;
private final HashSet<String> selectedRowKeys = new HashSet<String>();
/*
* When scrolling and selecting at the same time, the selections are not in
* sync with the server while retrieving new rows (until key is released).
*/
private HashSet<Object> unSyncedselectionsBeforeRowFetch;
/*
* These are used when jumping between pages when pressing Home and End
*/
private boolean selectLastItemInNextRender = false;
private boolean selectFirstItemInNextRender = false;
private boolean focusFirstItemInNextRender = false;
private boolean focusLastItemInNextRender = false;
/*
* The currently focused row
*/
private VScrollTableRow focusedRow;
/*
* Helper to store selection range start in when using the keyboard
*/
private VScrollTableRow selectionRangeStart;
/*
* Flag for notifying when the selection has changed and should be sent to
* the server
*/
private boolean selectionChanged = false;
/*
* The speed (in pixels) which the scrolling scrolls vertically/horizontally
*/
private int scrollingVelocity = 10;
private Timer scrollingVelocityTimer = null;
private String[] bodyActionKeys;
/**
* Represents a select range of rows
*/
private class SelectionRange {
private VScrollTableRow startRow;
private final int length;
/**
* Constuctor.
*/
public SelectionRange(VScrollTableRow row1, VScrollTableRow row2) {
VScrollTableRow endRow;
if (row2.isBefore(row1)) {
startRow = row2;
endRow = row1;
} else {
startRow = row1;
endRow = row2;
}
length = endRow.getIndex() - startRow.getIndex() + 1;
}
public SelectionRange(VScrollTableRow row, int length) {
startRow = row;
this.length = length;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return startRow.getKey() + "-" + length;
}
private boolean inRange(VScrollTableRow row) {
return row.getIndex() >= startRow.getIndex()
&& row.getIndex() < startRow.getIndex() + length;
}
public Collection<SelectionRange> split(VScrollTableRow row) {
assert row.isAttached();
ArrayList<SelectionRange> ranges = new ArrayList<SelectionRange>(2);
int endOfFirstRange = row.getIndex() - 1;
if (!(endOfFirstRange - startRow.getIndex() < 0)) {
// create range of first part unless its length is < 1
VScrollTableRow endOfRange = scrollBody
.getRowByRowIndex(endOfFirstRange);
ranges.add(new SelectionRange(startRow, endOfRange));
}
int startOfSecondRange = row.getIndex() + 1;
if (!(getEndIndex() - startOfSecondRange < 0)) {
// create range of second part unless its length is < 1
VScrollTableRow startOfRange = scrollBody
.getRowByRowIndex(startOfSecondRange);
ranges.add(new SelectionRange(startOfRange, getEndIndex()
- startOfSecondRange + 1));
}
return ranges;
}
private int getEndIndex() {
return startRow.getIndex() + length - 1;
}
};
private final HashSet<SelectionRange> selectedRowRanges = new HashSet<SelectionRange>();
private boolean initializedAndAttached = false;
/**
* Flag to indicate if a column width recalculation is needed due update.
*/
private boolean headerChangedDuringUpdate = false;
private final TableHead tHead = new TableHead();
private final TableFooter tFoot = new TableFooter();
private final FocusableScrollPanel scrollBodyPanel = new FocusableScrollPanel(
true);
private KeyPressHandler navKeyPressHandler = new KeyPressHandler() {
public void onKeyPress(KeyPressEvent keyPressEvent) {
// This is used for Firefox only, since Firefox auto-repeat
// works correctly only if we use a key press handler, other
// browsers handle it correctly when using a key down handler
if (!BrowserInfo.get().isGecko()) {
return;
}
NativeEvent event = keyPressEvent.getNativeEvent();
if (!enabled) {
// Cancel default keyboard events on a disabled Table
// (prevents scrolling)
event.preventDefault();
} else if (hasFocus) {
// Key code in Firefox/onKeyPress is present only for
// special keys, otherwise 0 is returned
int keyCode = event.getKeyCode();
if (keyCode == 0 && event.getCharCode() == ' ') {
// Provide a keyCode for space to be compatible with
// FireFox keypress event
keyCode = CHARCODE_SPACE;
}
if (handleNavigation(keyCode,
event.getCtrlKey() || event.getMetaKey(),
event.getShiftKey())) {
event.preventDefault();
}
startScrollingVelocityTimer();
}
}
};
private KeyUpHandler navKeyUpHandler = new KeyUpHandler() {
public void onKeyUp(KeyUpEvent keyUpEvent) {
NativeEvent event = keyUpEvent.getNativeEvent();
int keyCode = event.getKeyCode();
if (!isFocusable()) {
cancelScrollingVelocityTimer();
} else if (isNavigationKey(keyCode)) {
if (keyCode == getNavigationDownKey()
|| keyCode == getNavigationUpKey()) {
/*
* in multiselect mode the server may still have value from
* previous page. Clear it unless doing multiselection or
* just moving focus.
*/
if (!event.getShiftKey() && !event.getCtrlKey()) {
instructServerToForgetPreviousSelections();
}
sendSelectedRows();
}
cancelScrollingVelocityTimer();
navKeyDown = false;
}
}
};
private KeyDownHandler navKeyDownHandler = new KeyDownHandler() {
public void onKeyDown(KeyDownEvent keyDownEvent) {
NativeEvent event = keyDownEvent.getNativeEvent();
// This is not used for Firefox
if (BrowserInfo.get().isGecko()) {
return;
}
if (!enabled) {
// Cancel default keyboard events on a disabled Table
// (prevents scrolling)
event.preventDefault();
} else if (hasFocus) {
if (handleNavigation(event.getKeyCode(), event.getCtrlKey()
|| event.getMetaKey(), event.getShiftKey())) {
navKeyDown = true;
event.preventDefault();
}
startScrollingVelocityTimer();
}
}
};
private int totalRows;
private Set<String> collapsedColumns;
private final RowRequestHandler rowRequestHandler;
private VScrollTableBody scrollBody;
private int firstvisible = 0;
private boolean sortAscending;
private String sortColumn;
private boolean columnReordering;
/**
* This map contains captions and icon urls for actions like: * "33_c" ->
* "Edit" * "33_i" -> "http://dom.com/edit.png"
*/
private final HashMap<Object, String> actionMap = new HashMap<Object, String>();
private String[] visibleColOrder;
private boolean initialContentReceived = false;
private Element scrollPositionElement;
private boolean enabled;
private boolean showColHeaders;
private boolean showColFooters;
/** flag to indicate that table body has changed */
private boolean isNewBody = true;
/*
* Read from the "recalcWidths" -attribute. When it is true, the table will
* recalculate the widths for columns - desirable in some cases. For #1983,
* marked experimental.
*/
boolean recalcWidths = false;
private final ArrayList<Panel> lazyUnregistryBag = new ArrayList<Panel>();
private String height;
private String width = "";
private boolean rendering = false;
private boolean hasFocus = false;
private int dragmode;
private int multiselectmode = BrowserInfo.get().isTouchDevice() ? MULTISELECT_MODE_SIMPLE
: MULTISELECT_MODE_DEFAULT;;
private int tabIndex;
private TouchScrollDelegate touchScrollDelegate;
public VScrollTable() {
scrollBodyPanel.setStyleName(CLASSNAME + "-body-wrapper");
scrollBodyPanel.addFocusHandler(this);
scrollBodyPanel.addBlurHandler(this);
scrollBodyPanel.addScrollHandler(this);
scrollBodyPanel.setStyleName(CLASSNAME + "-body");
/*
* Firefox auto-repeat works correctly only if we use a key press
* handler, other browsers handle it correctly when using a key down
* handler
*/
if (BrowserInfo.get().isGecko()) {
scrollBodyPanel.addKeyPressHandler(navKeyPressHandler);
} else {
scrollBodyPanel.addKeyDownHandler(navKeyDownHandler);
}
scrollBodyPanel.addKeyUpHandler(navKeyUpHandler);
scrollBodyPanel.sinkEvents(Event.TOUCHEVENTS);
scrollBodyPanel.addDomHandler(new TouchStartHandler() {
public void onTouchStart(TouchStartEvent event) {
getTouchScrollDelegate().onTouchStart(event);
}
}, TouchStartEvent.getType());
scrollBodyPanel.sinkEvents(Event.ONCONTEXTMENU);
scrollBodyPanel.addDomHandler(new ContextMenuHandler() {
public void onContextMenu(ContextMenuEvent event) {
handleBodyContextMenu(event);
}
}, ContextMenuEvent.getType());
setStyleName(CLASSNAME);
add(tHead);
add(scrollBodyPanel);
add(tFoot);
rowRequestHandler = new RowRequestHandler();
}
protected TouchScrollDelegate getTouchScrollDelegate() {
if (touchScrollDelegate == null) {
touchScrollDelegate = new TouchScrollDelegate(
scrollBodyPanel.getElement());
}
return touchScrollDelegate;
}
private void handleBodyContextMenu(ContextMenuEvent event) {
if (enabled && bodyActionKeys != null) {
int left = Util.getTouchOrMouseClientX(event.getNativeEvent());
int top = Util.getTouchOrMouseClientY(event.getNativeEvent());
top += Window.getScrollTop();
left += Window.getScrollLeft();
client.getContextMenu().showAt(this, left, top);
}
event.stopPropagation();
event.preventDefault();
}
/**
* Fires a column resize event which sends the resize information to the
* server.
*
* @param columnId
* The columnId of the column which was resized
* @param originalWidth
* The width in pixels of the column before the resize event
* @param newWidth
* The width in pixels of the column after the resize event
*/
private void fireColumnResizeEvent(String columnId, int originalWidth,
int newWidth) {
client.updateVariable(paintableId, "columnResizeEventColumn", columnId,
false);
client.updateVariable(paintableId, "columnResizeEventPrev",
originalWidth, false);
client.updateVariable(paintableId, "columnResizeEventCurr", newWidth,
immediate);
}
/**
* Non-immediate variable update of column widths for a collection of
* columns.
*
* @param columns
* the columns to trigger the events for.
*/
private void sendColumnWidthUpdates(Collection<HeaderCell> columns) {
String[] newSizes = new String[columns.size()];
int ix = 0;
for (HeaderCell cell : columns) {
newSizes[ix++] = cell.getColKey() + ":" + cell.getWidth();
}
client.updateVariable(paintableId, "columnWidthUpdates", newSizes,
false);
}
/**
* Moves the focus one step down
*
* @return Returns true if succeeded
*/
private boolean moveFocusDown() {
return moveFocusDown(0);
}
/**
* Moves the focus down by 1+offset rows
*
* @return Returns true if succeeded, else false if the selection could not
* be move downwards
*/
private boolean moveFocusDown(int offset) {
if (isSelectable()) {
if (focusedRow == null && scrollBody.iterator().hasNext()) {
// FIXME should focus first visible from top, not first rendered
// ??
return setRowFocus((VScrollTableRow) scrollBody.iterator()
.next());
} else {
VScrollTableRow next = getNextRow(focusedRow, offset);
if (next != null) {
return setRowFocus(next);
}
}
}
return false;
}
/**
* Moves the selection one step up
*
* @return Returns true if succeeded
*/
private boolean moveFocusUp() {
return moveFocusUp(0);
}
/**
* Moves the focus row upwards
*
* @return Returns true if succeeded, else false if the selection could not
* be move upwards
*
*/
private boolean moveFocusUp(int offset) {
if (isSelectable()) {
if (focusedRow == null && scrollBody.iterator().hasNext()) {
// FIXME logic is exactly the same as in moveFocusDown, should
// be the opposite??
return setRowFocus((VScrollTableRow) scrollBody.iterator()
.next());
} else {
VScrollTableRow prev = getPreviousRow(focusedRow, offset);
if (prev != null) {
return setRowFocus(prev);
} else {
VConsole.log("no previous available");
}
}
}
return false;
}
/**
* Selects a row where the current selection head is
*
* @param ctrlSelect
* Is the selection a ctrl+selection
* @param shiftSelect
* Is the selection a shift+selection
* @return Returns truw
*/
private void selectFocusedRow(boolean ctrlSelect, boolean shiftSelect) {
if (focusedRow != null) {
// Arrows moves the selection and clears previous selections
if (isSelectable() && !ctrlSelect && !shiftSelect) {
deselectAll();
focusedRow.toggleSelection();
selectionRangeStart = focusedRow;
}
// Ctrl+arrows moves selection head
else if (isSelectable() && ctrlSelect && !shiftSelect) {
selectionRangeStart = focusedRow;
// No selection, only selection head is moved
}
// Shift+arrows selection selects a range
else if (selectMode == SELECT_MODE_MULTI && !ctrlSelect
&& shiftSelect) {
focusedRow.toggleShiftSelection(shiftSelect);
}
}
}
/**
* Sends the selection to the server if changed since the last update/visit.
*/
protected void sendSelectedRows() {
// Don't send anything if selection has not changed
if (!selectionChanged) {
return;
}
// Reset selection changed flag
selectionChanged = false;
// Note: changing the immediateness of this might require changes to
// "clickEvent" immediateness also.
if (multiselectmode == MULTISELECT_MODE_DEFAULT) {
// Convert ranges to a set of strings
Set<String> ranges = new HashSet<String>();
for (SelectionRange range : selectedRowRanges) {
ranges.add(range.toString());
}
// Send the selected row ranges
client.updateVariable(paintableId, "selectedRanges",
ranges.toArray(new String[selectedRowRanges.size()]), false);
// clean selectedRowKeys so that they don't contain excess values
for (Iterator<String> iterator = selectedRowKeys.iterator(); iterator
.hasNext();) {
String key = iterator.next();
VScrollTableRow renderedRowByKey = getRenderedRowByKey(key);
if (renderedRowByKey != null) {
for (SelectionRange range : selectedRowRanges) {
if (range.inRange(renderedRowByKey)) {
iterator.remove();
}
}
} else {
// orphaned selected key, must be in a range, ignore
iterator.remove();
}
}
}
// Send the selected rows
client.updateVariable(paintableId, "selected",
selectedRowKeys.toArray(new String[selectedRowKeys.size()]),
immediate);
}
/**
* Get the key that moves the selection head upwards. By default it is the
* up arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationUpKey() {
return KeyCodes.KEY_UP;
}
/**
* Get the key that moves the selection head downwards. By default it is the
* down arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationDownKey() {
return KeyCodes.KEY_DOWN;
}
/**
* Get the key that scrolls to the left in the table. By default it is the
* left arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationLeftKey() {
return KeyCodes.KEY_LEFT;
}
/**
* Get the key that scroll to the right on the table. By default it is the
* right arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationRightKey() {
return KeyCodes.KEY_RIGHT;
}
/**
* Get the key that selects an item in the table. By default it is the space
* bar key but by overriding this you can change the key to whatever you
* want.
*
* @return
*/
protected int getNavigationSelectKey() {
return CHARCODE_SPACE;
}
/**
* Get the key the moves the selection one page up in the table. By default
* this is the Page Up key but by overriding this you can change the key to
* whatever you want.
*
* @return
*/
protected int getNavigationPageUpKey() {
return KeyCodes.KEY_PAGEUP;
}
/**
* Get the key the moves the selection one page down in the table. By
* default this is the Page Down key but by overriding this you can change
* the key to whatever you want.
*
* @return
*/
protected int getNavigationPageDownKey() {
return KeyCodes.KEY_PAGEDOWN;
}
/**
* Get the key the moves the selection to the beginning of the table. By
* default this is the Home key but by overriding this you can change the
* key to whatever you want.
*
* @return
*/
protected int getNavigationStartKey() {
return KeyCodes.KEY_HOME;
}
/**
* Get the key the moves the selection to the end of the table. By default
* this is the End key but by overriding this you can change the key to
* whatever you want.
*
* @return
*/
protected int getNavigationEndKey() {
return KeyCodes.KEY_END;
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.terminal.gwt.client.Paintable#updateFromUIDL(com.vaadin.terminal
* .gwt.client.UIDL, com.vaadin.terminal.gwt.client.ApplicationConnection)
*/
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
rendering = true;
/*
* We need to do this before updateComponent since updateComponent calls
* this.setHeight() which will calculate a new body height depending on
* the space available.
*/
if (uidl.hasAttribute("colfooters")) {
showColFooters = uidl.getBooleanAttribute("colfooters");
}
tFoot.setVisible(showColFooters);
if (client.updateComponent(this, uidl, true)) {
rendering = false;
return;
}
// we may have pending cache row fetch, cancel it. See #2136
rowRequestHandler.cancel();
enabled = !uidl.hasAttribute("disabled");
if (BrowserInfo.get().isIE8() && !enabled) {
/*
* The disabled shim will not cover the table body if it is
* relative in IE8. See #7324
*/
scrollBodyPanel.getElement().getStyle()
.setPosition(Position.STATIC);
} else if (BrowserInfo.get().isIE8()) {
scrollBodyPanel.getElement().getStyle()
.setPosition(Position.RELATIVE);
}
this.client = client;
paintableId = uidl.getStringAttribute("id");
immediate = uidl.getBooleanAttribute("immediate");
final int newTotalRows = uidl.getIntAttribute("totalrows");
if (newTotalRows != totalRows) {
if (scrollBody != null) {
if (totalRows == 0) {
tHead.clear();
tFoot.clear();
}
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
totalRows = newTotalRows;
}
dragmode = uidl.hasAttribute("dragmode") ? uidl
.getIntAttribute("dragmode") : 0;
if (BrowserInfo.get().isIE()) {
if (dragmode > 0) {
getElement().setPropertyJSO("onselectstart",
getPreventTextSelectionIEHack());
} else {
getElement().setPropertyJSO("onselectstart", null);
}
}
tabIndex = uidl.hasAttribute("tabindex") ? uidl
.getIntAttribute("tabindex") : 0;
if (!BrowserInfo.get().isTouchDevice()) {
multiselectmode = uidl.hasAttribute("multiselectmode") ? uidl
.getIntAttribute("multiselectmode")
: MULTISELECT_MODE_DEFAULT;
}
if (uidl.hasAttribute("alb")) {
bodyActionKeys = uidl.getStringArrayAttribute("alb");
} else {
// Need to clear the actions if the action handlers have been
// removed
bodyActionKeys = null;
}
setCacheRate(uidl.hasAttribute("cr") ? uidl.getDoubleAttribute("cr")
: CACHE_RATE_DEFAULT);
recalcWidths = uidl.hasAttribute("recalcWidths");
if (recalcWidths) {
tHead.clear();
tFoot.clear();
}
int oldPageLength = pageLength;
if (uidl.hasAttribute("pagelength")) {
pageLength = uidl.getIntAttribute("pagelength");
} else {
// pagelenght is "0" meaning scrolling is turned off
pageLength = totalRows;
}
if (oldPageLength != pageLength && initializedAndAttached) {
// page length changed, need to update size
sizeInit();
}
firstvisible = uidl.hasVariable("firstvisible") ? uidl
.getIntVariable("firstvisible") : 0;
if (firstvisible != lastRequestedFirstvisible && scrollBody != null) {
// received 'surprising' firstvisible from server: scroll there
firstRowInViewPort = firstvisible;
scrollBodyPanel.setScrollPosition((int) (firstvisible * scrollBody
.getRowHeight()));
}
showRowHeaders = uidl.getBooleanAttribute("rowheaders");
showColHeaders = uidl.getBooleanAttribute("colheaders");
nullSelectionAllowed = uidl.hasAttribute("nsa") ? uidl
.getBooleanAttribute("nsa") : true;
String oldSortColumn = sortColumn;
if (uidl.hasVariable("sortascending")) {
sortAscending = uidl.getBooleanVariable("sortascending");
sortColumn = uidl.getStringVariable("sortcolumn");
}
boolean keyboardSelectionOverRowFetchInProgress = false;
if (uidl.hasVariable("selected")) {
final Set<String> selectedKeys = uidl
.getStringArrayVariableAsSet("selected");
if (scrollBody != null) {
Iterator<Widget> iterator = scrollBody.iterator();
while (iterator.hasNext()) {
/*
* Make the focus reflect to the server side state unless we
* are currently selecting multiple rows with keyboard.
*/
VScrollTableRow row = (VScrollTableRow) iterator.next();
boolean selected = selectedKeys.contains(row.getKey());
if (!selected
&& unSyncedselectionsBeforeRowFetch != null
&& unSyncedselectionsBeforeRowFetch.contains(row
.getKey())) {
selected = true;
keyboardSelectionOverRowFetchInProgress = true;
}
if (selected != row.isSelected()) {
row.toggleSelection();
}
}
}
}
unSyncedselectionsBeforeRowFetch = null;
if (uidl.hasAttribute("selectmode")) {
if (uidl.getBooleanAttribute("readonly")) {
selectMode = Table.SELECT_MODE_NONE;
} else if (uidl.getStringAttribute("selectmode").equals("multi")) {
selectMode = Table.SELECT_MODE_MULTI;
} else if (uidl.getStringAttribute("selectmode").equals("single")) {
selectMode = Table.SELECT_MODE_SINGLE;
} else {
selectMode = Table.SELECT_MODE_NONE;
}
}
if (uidl.hasVariable("columnorder")) {
columnReordering = true;
columnOrder = uidl.getStringArrayVariable("columnorder");
} else {
columnReordering = false;
columnOrder = null;
}
if (uidl.hasVariable("collapsedcolumns")) {
tHead.setColumnCollapsingAllowed(true);
collapsedColumns = uidl
.getStringArrayVariableAsSet("collapsedcolumns");
} else {
tHead.setColumnCollapsingAllowed(false);
}
UIDL rowData = null;
UIDL ac = null;
for (final Iterator<Object> it = uidl.getChildIterator(); it.hasNext();) {
final UIDL c = (UIDL) it.next();
if (c.getTag().equals("rows")) {
rowData = c;
} else if (c.getTag().equals("actions")) {
updateActionMap(c);
} else if (c.getTag().equals("visiblecolumns")) {
tHead.updateCellsFromUIDL(c);
tFoot.updateCellsFromUIDL(c);
} else if (c.getTag().equals("-ac")) {
ac = c;
}
}
if (ac == null) {
if (dropHandler != null) {
// remove dropHandler if not present anymore
dropHandler = null;
}
} else {
if (dropHandler == null) {
dropHandler = new VScrollTableDropHandler();
}
dropHandler.updateAcceptRules(ac);
}
updateHeader(uidl.getStringArrayAttribute("vcolorder"));
updateFooter(uidl.getStringArrayAttribute("vcolorder"));
if (!recalcWidths && initializedAndAttached) {
updateBody(rowData, uidl.getIntAttribute("firstrow"),
uidl.getIntAttribute("rows"));
if (headerChangedDuringUpdate) {
lazyAdjustColumnWidths.schedule(1);
} else {
// webkits may still bug with their disturbing scrollbar bug,
// See #3457
// run overflow fix for scrollable area
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel
.getElement());
}
});
}
} else {
if (scrollBody != null) {
scrollBody.removeFromParent();
lazyUnregistryBag.add(scrollBody);
}
scrollBody = createScrollBody();
scrollBody.renderInitialRows(rowData,
uidl.getIntAttribute("firstrow"),
uidl.getIntAttribute("rows"));
scrollBodyPanel.add(scrollBody);
initialContentReceived = true;
if (isAttached()) {
sizeInit();
}
scrollBody.restoreRowVisibility();
}
if (selectMode == Table.SELECT_MODE_NONE) {
scrollBody.addStyleName(CLASSNAME + "-body-noselection");
} else {
scrollBody.removeStyleName(CLASSNAME + "-body-noselection");
}
hideScrollPositionAnnotation();
purgeUnregistryBag();
// selection is no in sync with server, avoid excessive server visits by
// clearing to flag used during the normal operation
if (!keyboardSelectionOverRowFetchInProgress) {
selectionChanged = false;
}
/*
* This is called when the Home or page up button has been pressed in
* selectable mode and the next selected row was not yet rendered in the
* client
*/
if (selectFirstItemInNextRender || focusFirstItemInNextRender) {
selectFirstRenderedRowInViewPort(focusFirstItemInNextRender);
selectFirstItemInNextRender = focusFirstItemInNextRender = false;
}
/*
* This is called when the page down or end button has been pressed in
* selectable mode and the next selected row was not yet rendered in the
* client
*/
if (selectLastItemInNextRender || focusLastItemInNextRender) {
selectLastRenderedRowInViewPort(focusLastItemInNextRender);
selectLastItemInNextRender = focusLastItemInNextRender = false;
}
multiselectPending = false;
if (focusedRow != null) {
if (!focusedRow.isAttached()) {
// focused row has been orphaned, can't focus
focusRowFromBody();
}
}
setProperTabIndex();
// Force recalculation of the captionContainer element inside the header
// cell to accomodate for the size of the sort arrow.
HeaderCell sortedHeader = tHead.getHeaderCell(sortColumn);
if (sortedHeader != null) {
sortedHeader.resizeCaptionContainer();
}
// Also recalculate the width of the captionContainer element in the
// previously sorted header, since this now has more room.
HeaderCell oldSortedHeader = tHead.getHeaderCell(oldSortColumn);
if (oldSortedHeader != null) {
oldSortedHeader.resizeCaptionContainer();
}
rendering = false;
headerChangedDuringUpdate = false;
}
private void focusRowFromBody() {
if (selectedRowKeys.size() == 1) {
// try to focus a row currently selected and in viewport
String selectedRowKey = selectedRowKeys.iterator().next();
if (selectedRowKey != null) {
VScrollTableRow renderedRow = getRenderedRowByKey(selectedRowKey);
if (renderedRow == null || !renderedRow.isInViewPort()) {
setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
} else {
setRowFocus(renderedRow);
}
}
} else {
// multiselect mode
setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
}
}
protected VScrollTableBody createScrollBody() {
return new VScrollTableBody();
}
/**
* Selects the last row visible in the table
*
* @param focusOnly
* Should the focus only be moved to the last row
*/
private void selectLastRenderedRowInViewPort(boolean focusOnly) {
int index = firstRowInViewPort + getFullyVisibleRowCount();
VScrollTableRow lastRowInViewport = scrollBody.getRowByRowIndex(index);
if (lastRowInViewport == null) {
// this should not happen in normal situations (white space at the
// end of viewport). Select the last rendered as a fallback.
lastRowInViewport = scrollBody.getRowByRowIndex(scrollBody
.getLastRendered());
if (lastRowInViewport == null) {
return; // empty table
}
}
setRowFocus(lastRowInViewport);
if (!focusOnly) {
selectFocusedRow(false, multiselectPending);
sendSelectedRows();
}
}
/**
* Selects the first row visible in the table
*
* @param focusOnly
* Should the focus only be moved to the first row
*/
private void selectFirstRenderedRowInViewPort(boolean focusOnly) {
int index = firstRowInViewPort;
VScrollTableRow firstInViewport = scrollBody.getRowByRowIndex(index);
if (firstInViewport == null) {
// this should not happen in normal situations
return;
}
setRowFocus(firstInViewport);
if (!focusOnly) {
selectFocusedRow(false, multiselectPending);
sendSelectedRows();
}
}
private void setCacheRate(double d) {
if (cache_rate != d) {
cache_rate = d;
cache_react_rate = 0.75 * d;
}
}
/**
* Unregisters Paintables in "trashed" HasWidgets (IScrollTableBodys or
* IScrollTableRows). This is done lazily as Table must survive from
* "subtreecaching" logic.
*/
private void purgeUnregistryBag() {
for (Iterator<Panel> iterator = lazyUnregistryBag.iterator(); iterator
.hasNext();) {
client.unregisterChildPaintables(iterator.next());
}
lazyUnregistryBag.clear();
}
private void updateActionMap(UIDL c) {
final Iterator<?> it = c.getChildIterator();
while (it.hasNext()) {
final UIDL action = (UIDL) it.next();
final String key = action.getStringAttribute("key");
final String caption = action.getStringAttribute("caption");
actionMap.put(key + "_c", caption);
if (action.hasAttribute("icon")) {
// TODO need some uri handling ??
actionMap.put(key + "_i", client.translateVaadinUri(action
.getStringAttribute("icon")));
} else {
actionMap.remove(key + "_i");
}
}
}
public String getActionCaption(String actionKey) {
return actionMap.get(actionKey + "_c");
}
public String getActionIcon(String actionKey) {
return actionMap.get(actionKey + "_i");
}
private void updateHeader(String[] strings) {
if (strings == null) {
return;
}
int visibleCols = strings.length;
int colIndex = 0;
if (showRowHeaders) {
tHead.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
visibleCols++;
visibleColOrder = new String[visibleCols];
visibleColOrder[colIndex] = ROW_HEADER_COLUMN_KEY;
colIndex++;
} else {
visibleColOrder = new String[visibleCols];
tHead.removeCell(ROW_HEADER_COLUMN_KEY);
}
int i;
for (i = 0; i < strings.length; i++) {
final String cid = strings[i];
visibleColOrder[colIndex] = cid;
tHead.enableColumn(cid, colIndex);
colIndex++;
}
tHead.setVisible(showColHeaders);
setContainerHeight();
}
/**
* Updates footers.
* <p>
* Update headers whould be called before this method is called!
* </p>
*
* @param strings
*/
private void updateFooter(String[] strings) {
if (strings == null) {
return;
}
// Add dummy column if row headers are present
int colIndex = 0;
if (showRowHeaders) {
tFoot.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
colIndex++;
} else {
tFoot.removeCell(ROW_HEADER_COLUMN_KEY);
}
int i;
for (i = 0; i < strings.length; i++) {
final String cid = strings[i];
tFoot.enableColumn(cid, colIndex);
colIndex++;
}
tFoot.setVisible(showColFooters);
}
/**
* @param uidl
* which contains row data
* @param firstRow
* first row in data set
* @param reqRows
* amount of rows in data set
*/
private void updateBody(UIDL uidl, int firstRow, int reqRows) {
if (uidl == null || reqRows < 1) {
// container is empty, remove possibly existing rows
if (firstRow < 0) {
while (scrollBody.getLastRendered() > scrollBody.firstRendered) {
scrollBody.unlinkRow(false);
}
scrollBody.unlinkRow(false);
}
return;
}
scrollBody.renderRows(uidl, firstRow, reqRows);
final int optimalFirstRow = (int) (firstRowInViewPort - pageLength
* cache_rate);
boolean cont = true;
while (cont && scrollBody.getLastRendered() > optimalFirstRow
&& scrollBody.getFirstRendered() < optimalFirstRow) {
// removing row from start
cont = scrollBody.unlinkRow(true);
}
final int optimalLastRow = (int) (firstRowInViewPort + pageLength + pageLength
* cache_rate);
cont = true;
while (cont && scrollBody.getLastRendered() > optimalLastRow) {
// removing row from the end
cont = scrollBody.unlinkRow(false);
}
scrollBody.fixSpacers();
scrollBody.restoreRowVisibility();
}
/**
* Gives correct column index for given column key ("cid" in UIDL).
*
* @param colKey
* @return column index of visible columns, -1 if column not visible
*/
private int getColIndexByKey(String colKey) {
// return 0 if asked for rowHeaders
if (ROW_HEADER_COLUMN_KEY.equals(colKey)) {
return 0;
}
for (int i = 0; i < visibleColOrder.length; i++) {
if (visibleColOrder[i].equals(colKey)) {
return i;
}
}
return -1;
}
protected boolean isSelectable() {
return selectMode > Table.SELECT_MODE_NONE;
}
private boolean isCollapsedColumn(String colKey) {
if (collapsedColumns == null) {
return false;
}
if (collapsedColumns.contains(colKey)) {
return true;
}
return false;
}
private String getColKeyByIndex(int index) {
return tHead.getHeaderCell(index).getColKey();
}
private void setColWidth(int colIndex, int w, boolean isDefinedWidth) {
final HeaderCell hcell = tHead.getHeaderCell(colIndex);
// Make sure that the column grows to accommodate the sort indicator if
// necessary.
if (w < hcell.getMinWidth()) {
w = hcell.getMinWidth();
}
// Set header column width
hcell.setWidth(w, isDefinedWidth);
// Set body column width
scrollBody.setColWidth(colIndex, w);
// Set footer column width
FooterCell fcell = tFoot.getFooterCell(colIndex);
fcell.setWidth(w, isDefinedWidth);
}
private int getColWidth(String colKey) {
return tHead.getHeaderCell(colKey).getWidth();
}
/**
* Get a rendered row by its key
*
* @param key
* The key to search with
* @return
*/
private VScrollTableRow getRenderedRowByKey(String key) {
if (scrollBody != null) {
final Iterator<Widget> it = scrollBody.iterator();
VScrollTableRow r = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (r.getKey().equals(key)) {
return r;
}
}
}
return null;
}
/**
* Returns the next row to the given row
*
* @param row
* The row to calculate from
*
* @return The next row or null if no row exists
*/
private VScrollTableRow getNextRow(VScrollTableRow row, int offset) {
final Iterator<Widget> it = scrollBody.iterator();
VScrollTableRow r = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (r == row) {
r = null;
while (offset >= 0 && it.hasNext()) {
r = (VScrollTableRow) it.next();
offset--;
}
return r;
}
}
return null;
}
/**
* Returns the previous row from the given row
*
* @param row
* The row to calculate from
* @return The previous row or null if no row exists
*/
private VScrollTableRow getPreviousRow(VScrollTableRow row, int offset) {
final Iterator<Widget> it = scrollBody.iterator();
final Iterator<Widget> offsetIt = scrollBody.iterator();
VScrollTableRow r = null;
VScrollTableRow prev = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (offset < 0) {
prev = (VScrollTableRow) offsetIt.next();
}
if (r == row) {
return prev;
}
offset--;
}
return null;
}
protected void reOrderColumn(String columnKey, int newIndex) {
final int oldIndex = getColIndexByKey(columnKey);
// Change header order
tHead.moveCell(oldIndex, newIndex);
// Change body order
scrollBody.moveCol(oldIndex, newIndex);
// Change footer order
tFoot.moveCell(oldIndex, newIndex);
/*
* Build new columnOrder and update it to server Note that columnOrder
* also contains collapsed columns so we cannot directly build it from
* cells vector Loop the old columnOrder and append in order to new
* array unless on moved columnKey. On new index also put the moved key
* i == index on columnOrder, j == index on newOrder
*/
final String oldKeyOnNewIndex = visibleColOrder[newIndex];
if (showRowHeaders) {
newIndex--; // columnOrder don't have rowHeader
}
// add back hidden rows,
for (int i = 0; i < columnOrder.length; i++) {
if (columnOrder[i].equals(oldKeyOnNewIndex)) {
break; // break loop at target
}
if (isCollapsedColumn(columnOrder[i])) {
newIndex++;
}
}
// finally we can build the new columnOrder for server
final String[] newOrder = new String[columnOrder.length];
for (int i = 0, j = 0; j < newOrder.length; i++) {
if (j == newIndex) {
newOrder[j] = columnKey;
j++;
}
if (i == columnOrder.length) {
break;
}
if (columnOrder[i].equals(columnKey)) {
continue;
}
newOrder[j] = columnOrder[i];
j++;
}
columnOrder = newOrder;
// also update visibleColumnOrder
int i = showRowHeaders ? 1 : 0;
for (int j = 0; j < newOrder.length; j++) {
final String cid = newOrder[j];
if (!isCollapsedColumn(cid)) {
visibleColOrder[i++] = cid;
}
}
client.updateVariable(paintableId, "columnorder", columnOrder, false);
if (client.hasEventListeners(this, COLUMN_REORDER_EVENT_ID)) {
client.sendPendingVariableChanges();
}
}
@Override
protected void onAttach() {
super.onAttach();
if (initialContentReceived) {
sizeInit();
}
}
@Override
protected void onDetach() {
rowRequestHandler.cancel();
super.onDetach();
// ensure that scrollPosElement will be detached
if (scrollPositionElement != null) {
final Element parent = DOM.getParent(scrollPositionElement);
if (parent != null) {
DOM.removeChild(parent, scrollPositionElement);
}
}
}
/**
* Run only once when component is attached and received its initial
* content. This function : * Syncs headers and bodys "natural widths and
* saves the values. * Sets proper width and height * Makes deferred request
* to get some cache rows
*/
private void sizeInit() {
/*
* We will use browsers table rendering algorithm to find proper column
* widths. If content and header take less space than available, we will
* divide extra space relatively to each column which has not width set.
*
* Overflow pixels are added to last column.
*/
Iterator<Widget> headCells = tHead.iterator();
Iterator<Widget> footCells = tFoot.iterator();
int i = 0;
int totalExplicitColumnsWidths = 0;
int total = 0;
float expandRatioDivider = 0;
final int[] widths = new int[tHead.visibleCells.size()];
tHead.enableBrowserIntelligence();
tFoot.enableBrowserIntelligence();
// first loop: collect natural widths
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
final FooterCell fCell = (FooterCell) footCells.next();
int w = hCell.getWidth();
if (hCell.isDefinedWidth()) {
// server has defined column width explicitly
totalExplicitColumnsWidths += w;
} else {
if (hCell.getExpandRatio() > 0) {
expandRatioDivider += hCell.getExpandRatio();
w = 0;
} else {
// get and store greater of header width and column width,
// and
// store it as a minimumn natural col width
int headerWidth = hCell.getNaturalColumnWidth(i);
int footerWidth = fCell.getNaturalColumnWidth(i);
w = headerWidth > footerWidth ? headerWidth : footerWidth;
}
hCell.setNaturalMinimumColumnWidth(w);
fCell.setNaturalMinimumColumnWidth(w);
}
widths[i] = w;
total += w;
i++;
}
tHead.disableBrowserIntelligence();
tFoot.disableBrowserIntelligence();
boolean willHaveScrollbarz = willHaveScrollbars();
// fix "natural" width if width not set
if (width == null || "".equals(width)) {
int w = total;
w += scrollBody.getCellExtraWidth() * visibleColOrder.length;
if (willHaveScrollbarz) {
w += Util.getNativeScrollbarSize();
}
setContentWidth(w);
}
int availW = scrollBody.getAvailableWidth();
if (BrowserInfo.get().isIE()) {
// Hey IE, are you really sure about this?
availW = scrollBody.getAvailableWidth();
}
availW -= scrollBody.getCellExtraWidth() * visibleColOrder.length;
if (willHaveScrollbarz) {
availW -= Util.getNativeScrollbarSize();
}
// TODO refactor this code to be the same as in resize timer
boolean needsReLayout = false;
if (availW > total) {
// natural size is smaller than available space
final int extraSpace = availW - total;
final int totalWidthR = total - totalExplicitColumnsWidths;
needsReLayout = true;
if (expandRatioDivider > 0) {
// visible columns have some active expand ratios, excess
// space is divided according to them
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hCell = (HeaderCell) headCells.next();
if (hCell.getExpandRatio() > 0) {
int w = widths[i];
final int newSpace = (int) (extraSpace * (hCell
.getExpandRatio() / expandRatioDivider));
w += newSpace;
widths[i] = w;
}
i++;
}
} else if (totalWidthR > 0) {
// no expand ratios defined, we will share extra space
// relatively to "natural widths" among those without
// explicit width
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hCell = (HeaderCell) headCells.next();
if (!hCell.isDefinedWidth()) {
int w = widths[i];
final int newSpace = extraSpace * w / totalWidthR;
w += newSpace;
widths[i] = w;
}
i++;
}
}
} else {
// bodys size will be more than available and scrollbar will appear
}
// last loop: set possibly modified values or reset if new tBody
i = 0;
headCells = tHead.iterator();
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
if (isNewBody || hCell.getWidth() == -1) {
final int w = widths[i];
setColWidth(i, w, false);
}
i++;
}
initializedAndAttached = true;
if (needsReLayout) {
scrollBody.reLayoutComponents();
}
updatePageLength();
/*
* Fix "natural" height if height is not set. This must be after width
* fixing so the components' widths have been adjusted.
*/
if (height == null || "".equals(height)) {
/*
* We must force an update of the row height as this point as it
* might have been (incorrectly) calculated earlier
*/
int bodyHeight;
if (pageLength == totalRows) {
/*
* A hack to support variable height rows when paging is off.
* Generally this is not supported by scrolltable. We want to
* show all rows so the bodyHeight should be equal to the table
* height.
*/
// int bodyHeight = scrollBody.getOffsetHeight();
bodyHeight = scrollBody.getRequiredHeight();
} else {
bodyHeight = (int) Math.round(scrollBody.getRowHeight(true)
* pageLength);
}
boolean needsSpaceForHorizontalSrollbar = (total > availW);
if (needsSpaceForHorizontalSrollbar) {
bodyHeight += Util.getNativeScrollbarSize();
}
scrollBodyPanel.setHeight(bodyHeight + "px");
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
isNewBody = false;
if (firstvisible > 0) {
// Deferred due some Firefox oddities. IE & Safari could survive
// without
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
scrollBodyPanel
.setScrollPosition((int) (firstvisible * scrollBody
.getRowHeight()));
firstRowInViewPort = firstvisible;
}
});
}
if (enabled) {
// Do we need cache rows
if (scrollBody.getLastRendered() + 1 < firstRowInViewPort
+ pageLength + (int) cache_react_rate * pageLength) {
if (totalRows - 1 > scrollBody.getLastRendered()) {
// fetch cache rows
int firstInNewSet = scrollBody.getLastRendered() + 1;
rowRequestHandler.setReqFirstRow(firstInNewSet);
int lastInNewSet = (int) (firstRowInViewPort + pageLength + cache_rate
* pageLength);
if (lastInNewSet > totalRows - 1) {
lastInNewSet = totalRows - 1;
}
rowRequestHandler.setReqRows(lastInNewSet - firstInNewSet
+ 1);
rowRequestHandler.deferRowFetch(1);
}
}
}
/*
* Ensures the column alignments are correct at initial loading. <br/>
* (child components widths are correct)
*/
scrollBody.reLayoutComponents();
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
});
}
/**
* Note, this method is not official api although declared as protected.
* Extend at you own risk.
*
* @return true if content area will have scrollbars visible.
*/
protected boolean willHaveScrollbars() {
if (!(height != null && !height.equals(""))) {
if (pageLength < totalRows) {
return true;
}
} else {
int fakeheight = (int) Math.round(scrollBody.getRowHeight()
* totalRows);
int availableHeight = scrollBodyPanel.getElement().getPropertyInt(
"clientHeight");
if (fakeheight > availableHeight) {
return true;
}
}
return false;
}
private void announceScrollPosition() {
if (scrollPositionElement == null) {
scrollPositionElement = DOM.createDiv();
scrollPositionElement.setClassName(CLASSNAME + "-scrollposition");
scrollPositionElement.getStyle().setPosition(Position.ABSOLUTE);
scrollPositionElement.getStyle().setDisplay(Display.NONE);
getElement().appendChild(scrollPositionElement);
}
Style style = scrollPositionElement.getStyle();
style.setMarginLeft(getElement().getOffsetWidth() / 2 - 80, Unit.PX);
style.setMarginTop(-scrollBodyPanel.getOffsetHeight(), Unit.PX);
// indexes go from 1-totalRows, as rowheaders in index-mode indicate
int last = (firstRowInViewPort + pageLength);
if (last > totalRows) {
last = totalRows;
}
scrollPositionElement.setInnerHTML("<span>" + (firstRowInViewPort + 1)
+ " – " + (last) + "..." + "</span>");
style.setDisplay(Display.BLOCK);
}
private void hideScrollPositionAnnotation() {
if (scrollPositionElement != null) {
DOM.setStyleAttribute(scrollPositionElement, "display", "none");
}
}
private class RowRequestHandler extends Timer {
private int reqFirstRow = 0;
private int reqRows = 0;
public void deferRowFetch() {
deferRowFetch(250);
}
public void deferRowFetch(int msec) {
if (reqRows > 0 && reqFirstRow < totalRows) {
schedule(msec);
// tell scroll position to user if currently "visible" rows are
// not rendered
if (totalRows > pageLength
&& ((firstRowInViewPort + pageLength > scrollBody
.getLastRendered()) || (firstRowInViewPort < scrollBody
.getFirstRendered()))) {
announceScrollPosition();
} else {
hideScrollPositionAnnotation();
}
}
}
public void setReqFirstRow(int reqFirstRow) {
if (reqFirstRow < 0) {
reqFirstRow = 0;
} else if (reqFirstRow >= totalRows) {
reqFirstRow = totalRows - 1;
}
this.reqFirstRow = reqFirstRow;
}
public void setReqRows(int reqRows) {
this.reqRows = reqRows;
}
@Override
public void run() {
if (client.hasActiveRequest() || navKeyDown) {
// if client connection is busy, don't bother loading it more
VConsole.log("Postponed rowfetch");
schedule(250);
} else {
int firstToBeRendered = scrollBody.firstRendered;
if (reqFirstRow < firstToBeRendered) {
firstToBeRendered = reqFirstRow;
} else if (firstRowInViewPort - (int) (cache_rate * pageLength) > firstToBeRendered) {
firstToBeRendered = firstRowInViewPort
- (int) (cache_rate * pageLength);
if (firstToBeRendered < 0) {
firstToBeRendered = 0;
}
}
int lastToBeRendered = scrollBody.lastRendered;
if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
lastToBeRendered = reqFirstRow + reqRows - 1;
} else if (firstRowInViewPort + pageLength + pageLength
* cache_rate < lastToBeRendered) {
lastToBeRendered = (firstRowInViewPort + pageLength + (int) (pageLength * cache_rate));
if (lastToBeRendered >= totalRows) {
lastToBeRendered = totalRows - 1;
}
// due Safari 3.1 bug (see #2607), verify reqrows, original
// problem unknown, but this should catch the issue
if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
reqRows = lastToBeRendered - reqFirstRow;
}
}
client.updateVariable(paintableId, "firstToBeRendered",
firstToBeRendered, false);
client.updateVariable(paintableId, "lastToBeRendered",
lastToBeRendered, false);
// remember which firstvisible we requested, in case the server
// has
// a differing opinion
lastRequestedFirstvisible = firstRowInViewPort;
client.updateVariable(paintableId, "firstvisible",
firstRowInViewPort, false);
client.updateVariable(paintableId, "reqfirstrow", reqFirstRow,
false);
client.updateVariable(paintableId, "reqrows", reqRows, true);
if (selectionChanged) {
unSyncedselectionsBeforeRowFetch = new HashSet<Object>(
selectedRowKeys);
}
}
}
public int getReqFirstRow() {
return reqFirstRow;
}
/**
* Sends request to refresh content at this position.
*/
public void refreshContent() {
int first = (int) (firstRowInViewPort - pageLength * cache_rate);
int reqRows = (int) (2 * pageLength * cache_rate + pageLength);
if (first < 0) {
reqRows = reqRows + first;
first = 0;
}
setReqFirstRow(first);
setReqRows(reqRows);
run();
}
}
public class HeaderCell extends Widget {
Element td = DOM.createTD();
Element captionContainer = DOM.createDiv();
Element sortIndicator = DOM.createDiv();
Element colResizeWidget = DOM.createDiv();
Element floatingCopyOfHeaderCell;
private boolean sortable = false;
private final String cid;
private boolean dragging;
private int dragStartX;
private int colIndex;
private int originalWidth;
private boolean isResizing;
private int headerX;
private boolean moved;
private int closestSlot;
private int width = -1;
private int naturalWidth = -1;
private char align = ALIGN_LEFT;
boolean definedWidth = false;
private float expandRatio = 0;
private boolean sorted;
public void setSortable(boolean b) {
sortable = b;
}
/**
* Makes room for the sorting indicator in case the column that the
* header cell belongs to is sorted. This is done by resizing the width
* of the caption container element by the correct amount
*/
public void resizeCaptionContainer() {
if (BrowserInfo.get().isIE6() || td.getClassName().contains("-asc")
|| td.getClassName().contains("-desc")) {
/*
* Room for the sort indicator is made by subtracting the styled
* margin and width of the resizer from the width of the caption
* container.
*/
int captionContainerWidth = width
- sortIndicator.getOffsetWidth()
- colResizeWidget.getOffsetWidth();
captionContainer.getStyle().setPropertyPx("width",
captionContainerWidth);
} else {
/*
* Set the caption container element as wide as possible when
* the sorting indicator is not visible.
*/
captionContainer.getStyle().setPropertyPx("width", width);
}
}
public void setNaturalMinimumColumnWidth(int w) {
naturalWidth = w;
}
public HeaderCell(String colId, String headerText) {
cid = colId;
DOM.setElementProperty(colResizeWidget, "className", CLASSNAME
+ "-resizer");
setText(headerText);
DOM.appendChild(td, colResizeWidget);
DOM.setElementProperty(sortIndicator, "className", CLASSNAME
+ "-sort-indicator");
DOM.appendChild(td, sortIndicator);
DOM.setElementProperty(captionContainer, "className", CLASSNAME
+ "-caption-container");
// ensure no clipping initially (problem on column additions)
DOM.setStyleAttribute(captionContainer, "overflow", "visible");
DOM.appendChild(td, captionContainer);
DOM.sinkEvents(td, Event.MOUSEEVENTS | Event.TOUCHEVENTS);
setElement(td);
setAlign(ALIGN_LEFT);
}
public void disableAutoWidthCalculation() {
definedWidth = true;
expandRatio = 0;
}
public void setWidth(int w, boolean ensureDefinedWidth) {
if (ensureDefinedWidth) {
definedWidth = true;
// on column resize expand ratio becomes zero
expandRatio = 0;
}
if (width == -1) {
// go to default mode, clip content if necessary
DOM.setStyleAttribute(captionContainer, "overflow", "");
}
width = w;
if (w == -1) {
DOM.setStyleAttribute(captionContainer, "width", "");
setWidth("");
} else {
resizeCaptionContainer();
/*
* if we already have tBody, set the header width properly, if
* not defer it. IE will fail with complex float in table header
* unless TD width is not explicitly set.
*/
if (scrollBody != null) {
int tdWidth = width + scrollBody.getCellExtraWidth();
setWidth(tdWidth + "px");
} else {
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
int tdWidth = width
+ scrollBody.getCellExtraWidth();
setWidth(tdWidth + "px");
}
});
}
}
}
public void setUndefinedWidth() {
definedWidth = false;
setWidth(-1, false);
}
/**
* Detects if width is fixed by developer on server side or resized to
* current width by user.
*
* @return true if defined, false if "natural" width
*/
public boolean isDefinedWidth() {
return definedWidth;
}
public int getWidth() {
return width;
}
public void setText(String headerText) {
DOM.setInnerHTML(captionContainer, headerText);
}
public String getColKey() {
return cid;
}
private void setSorted(boolean sorted) {
this.sorted = sorted;
if (sorted) {
if (sortAscending) {
this.setStyleName(CLASSNAME + "-header-cell-asc");
} else {
this.setStyleName(CLASSNAME + "-header-cell-desc");
}
} else {
this.setStyleName(CLASSNAME + "-header-cell");
}
}
/**
* Handle column reordering.
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled && event != null) {
if (isResizing
|| event.getEventTarget().cast() == colResizeWidget) {
if (dragging
&& (event.getTypeInt() == Event.ONMOUSEUP || event
.getTypeInt() == Event.ONTOUCHEND)) {
// Handle releasing column header on spacer #5318
handleCaptionEvent(event);
} else {
onResizeEvent(event);
}
} else {
/*
* Ensure focus before handling caption event. Otherwise
* variables changed from caption event may be before
* variables from other components that fire variables when
* they lose focus.
*/
if (event.getTypeInt() == Event.ONMOUSEDOWN
|| event.getTypeInt() == Event.ONTOUCHSTART) {
scrollBodyPanel.setFocus(true);
}
handleCaptionEvent(event);
event.stopPropagation();
event.preventDefault();
}
}
}
private void createFloatingCopy() {
floatingCopyOfHeaderCell = DOM.createDiv();
DOM.setInnerHTML(floatingCopyOfHeaderCell, DOM.getInnerHTML(td));
floatingCopyOfHeaderCell = DOM
.getChild(floatingCopyOfHeaderCell, 1);
DOM.setElementProperty(floatingCopyOfHeaderCell, "className",
CLASSNAME + "-header-drag");
updateFloatingCopysPosition(DOM.getAbsoluteLeft(td),
DOM.getAbsoluteTop(td));
DOM.appendChild(RootPanel.get().getElement(),
floatingCopyOfHeaderCell);
}
private void updateFloatingCopysPosition(int x, int y) {
x -= DOM.getElementPropertyInt(floatingCopyOfHeaderCell,
"offsetWidth") / 2;
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "left", x + "px");
if (y > 0) {
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "top", (y + 7)
+ "px");
}
}
private void hideFloatingCopy() {
DOM.removeChild(RootPanel.get().getElement(),
floatingCopyOfHeaderCell);
floatingCopyOfHeaderCell = null;
}
/**
* Fires a header click event after the user has clicked a column header
* cell
*
* @param event
* The click event
*/
private void fireHeaderClickedEvent(Event event) {
if (client.hasEventListeners(VScrollTable.this,
HEADER_CLICK_EVENT_ID)) {
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "headerClickEvent",
details.toString(), false);
client.updateVariable(paintableId, "headerClickCID", cid, true);
}
}
protected void handleCaptionEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONTOUCHSTART:
case Event.ONMOUSEDOWN:
if (columnReordering) {
if (event.getTypeInt() == Event.ONTOUCHSTART) {
/*
* prevent using this event in e.g. scrolling
*/
event.stopPropagation();
}
dragging = true;
moved = false;
colIndex = getColIndexByKey(cid);
DOM.setCapture(getElement());
headerX = tHead.getAbsoluteLeft();
event.preventDefault(); // prevent selecting text &&
// generated touch events
}
break;
case Event.ONMOUSEUP:
case Event.ONTOUCHEND:
case Event.ONTOUCHCANCEL:
if (columnReordering) {
dragging = false;
DOM.releaseCapture(getElement());
if (moved) {
hideFloatingCopy();
tHead.removeSlotFocus();
if (closestSlot != colIndex
&& closestSlot != (colIndex + 1)) {
if (closestSlot > colIndex) {
reOrderColumn(cid, closestSlot - 1);
} else {
reOrderColumn(cid, closestSlot);
}
}
}
if (Util.isTouchEvent(event)) {
/*
* Prevent using in e.g. scrolling and prevent generated
* events.
*/
event.preventDefault();
event.stopPropagation();
}
}
if (!moved) {
// mouse event was a click to header -> sort column
if (sortable) {
if (sortColumn.equals(cid)) {
// just toggle order
client.updateVariable(paintableId, "sortascending",
!sortAscending, false);
} else {
// set table sorted by this column
client.updateVariable(paintableId, "sortcolumn",
cid, false);
}
// get also cache columns at the same request
scrollBodyPanel.setScrollPosition(0);
firstvisible = 0;
rowRequestHandler.setReqFirstRow(0);
rowRequestHandler.setReqRows((int) (2 * pageLength
* cache_rate + pageLength));
rowRequestHandler.deferRowFetch(); // some validation +
// defer 250ms
rowRequestHandler.cancel(); // instead of waiting
rowRequestHandler.run(); // run immediately
}
fireHeaderClickedEvent(event);
if (Util.isTouchEvent(event)) {
/*
* Prevent using in e.g. scrolling and prevent generated
* events.
*/
event.preventDefault();
event.stopPropagation();
}
break;
}
break;
case Event.ONTOUCHMOVE:
case Event.ONMOUSEMOVE:
if (dragging) {
if (event.getTypeInt() == Event.ONTOUCHMOVE) {
/*
* prevent using this event in e.g. scrolling
*/
event.stopPropagation();
}
if (!moved) {
createFloatingCopy();
moved = true;
}
final int clientX = Util.getTouchOrMouseClientX(event);
final int x = clientX + tHead.hTableWrapper.getScrollLeft();
int slotX = headerX;
closestSlot = colIndex;
int closestDistance = -1;
int start = 0;
if (showRowHeaders) {
start++;
}
final int visibleCellCount = tHead.getVisibleCellCount();
for (int i = start; i <= visibleCellCount; i++) {
if (i > 0) {
final String colKey = getColKeyByIndex(i - 1);
slotX += getColWidth(colKey);
}
final int dist = Math.abs(x - slotX);
if (closestDistance == -1 || dist < closestDistance) {
closestDistance = dist;
closestSlot = i;
}
}
tHead.focusSlot(closestSlot);
updateFloatingCopysPosition(clientX, -1);
}
break;
default:
break;
}
}
private void onResizeEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
isResizing = true;
DOM.setCapture(getElement());
dragStartX = DOM.eventGetClientX(event);
colIndex = getColIndexByKey(cid);
originalWidth = getWidth();
DOM.eventPreventDefault(event);
break;
case Event.ONMOUSEUP:
isResizing = false;
DOM.releaseCapture(getElement());
tHead.disableAutoColumnWidthCalculation(this);
fireColumnResizeEvent(cid, originalWidth, getColWidth(cid));
break;
case Event.ONMOUSEMOVE:
if (isResizing) {
final int deltaX = DOM.eventGetClientX(event) - dragStartX;
if (deltaX == 0) {
return;
}
int newWidth = originalWidth + deltaX;
if (newWidth < getMinWidth()) {
newWidth = getMinWidth();
}
setColWidth(colIndex, newWidth, true);
forceRealignColumnHeaders();
}
break;
default:
break;
}
}
public int getMinWidth() {
int cellExtraWidth = 0;
if (scrollBody != null) {
cellExtraWidth += scrollBody.getCellExtraWidth();
}
return cellExtraWidth + sortIndicator.getOffsetWidth();
}
public String getCaption() {
return DOM.getInnerText(captionContainer);
}
public boolean isEnabled() {
return getParent() != null;
}
public void setAlign(char c) {
final String ALIGN_PREFIX = CLASSNAME + "-caption-container-align-";
if (align != c) {
captionContainer.removeClassName(ALIGN_PREFIX + "center");
captionContainer.removeClassName(ALIGN_PREFIX + "right");
captionContainer.removeClassName(ALIGN_PREFIX + "left");
switch (c) {
case ALIGN_CENTER:
captionContainer.addClassName(ALIGN_PREFIX + "center");
break;
case ALIGN_RIGHT:
captionContainer.addClassName(ALIGN_PREFIX + "right");
break;
default:
captionContainer.addClassName(ALIGN_PREFIX + "left");
break;
}
}
align = c;
}
public char getAlign() {
return align;
}
/**
* Detects the natural minimum width for the column of this header cell.
* If column is resized by user or the width is defined by server the
* actual width is returned. Else the natural min width is returned.
*
* @param columnIndex
* column index hint, if -1 (unknown) it will be detected
*
* @return
*/
public int getNaturalColumnWidth(int columnIndex) {
if (isDefinedWidth()) {
return width;
} else {
if (naturalWidth < 0) {
// This is recently revealed column. Try to detect a proper
// value (greater of header and data
// cols)
int hw = captionContainer.getOffsetWidth()
+ scrollBody.getCellExtraWidth();
if (BrowserInfo.get().isGecko()
|| BrowserInfo.get().isIE7()) {
hw += sortIndicator.getOffsetWidth();
}
if (columnIndex < 0) {
columnIndex = 0;
for (Iterator<Widget> it = tHead.iterator(); it
.hasNext(); columnIndex++) {
if (it.next() == this) {
break;
}
}
}
final int cw = scrollBody.getColWidth(columnIndex);
naturalWidth = (hw > cw ? hw : cw);
}
return naturalWidth;
}
}
public void setExpandRatio(float floatAttribute) {
expandRatio = floatAttribute;
}
public float getExpandRatio() {
return expandRatio;
}
public boolean isSorted() {
return sorted;
}
}
/**
* HeaderCell that is header cell for row headers.
*
* Reordering disabled and clicking on it resets sorting.
*/
public class RowHeadersHeaderCell extends HeaderCell {
RowHeadersHeaderCell() {
super(ROW_HEADER_COLUMN_KEY, "");
this.setStyleName(CLASSNAME + "-header-cell-rowheader");
}
@Override
protected void handleCaptionEvent(Event event) {
// NOP: RowHeaders cannot be reordered
// TODO It'd be nice to reset sorting here
}
}
public class TableHead extends Panel implements ActionOwner {
private static final int WRAPPER_WIDTH = 900000;
ArrayList<Widget> visibleCells = new ArrayList<Widget>();
HashMap<String, HeaderCell> availableCells = new HashMap<String, HeaderCell>();
Element div = DOM.createDiv();
Element hTableWrapper = DOM.createDiv();
Element hTableContainer = DOM.createDiv();
Element table = DOM.createTable();
Element headerTableBody = DOM.createTBody();
Element tr = DOM.createTR();
private final Element columnSelector = DOM.createDiv();
private int focusedSlot = -1;
public TableHead() {
if (BrowserInfo.get().isIE()) {
table.setPropertyInt("cellSpacing", 0);
}
DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
+ "-header");
// TODO move styles to CSS
DOM.setElementProperty(columnSelector, "className", CLASSNAME
+ "-column-selector");
DOM.setStyleAttribute(columnSelector, "display", "none");
DOM.appendChild(table, headerTableBody);
DOM.appendChild(headerTableBody, tr);
DOM.appendChild(hTableContainer, table);
DOM.appendChild(hTableWrapper, hTableContainer);
DOM.appendChild(div, hTableWrapper);
DOM.appendChild(div, columnSelector);
setElement(div);
setStyleName(CLASSNAME + "-header-wrap");
DOM.sinkEvents(columnSelector, Event.ONCLICK);
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersHeaderCell());
}
@Override
public void clear() {
for (String cid : availableCells.keySet()) {
removeCell(cid);
}
availableCells.clear();
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersHeaderCell());
}
public void updateCellsFromUIDL(UIDL uidl) {
Iterator<?> it = uidl.getChildIterator();
HashSet<String> updated = new HashSet<String>();
while (it.hasNext()) {
final UIDL col = (UIDL) it.next();
final String cid = col.getStringAttribute("cid");
updated.add(cid);
String caption = buildCaptionHtmlSnippet(col);
HeaderCell c = getHeaderCell(cid);
if (c == null) {
c = new HeaderCell(cid, caption);
availableCells.put(cid, c);
if (initializedAndAttached) {
// we will need a column width recalculation
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
} else {
c.setText(caption);
}
if (col.hasAttribute("sortable")) {
c.setSortable(true);
if (cid.equals(sortColumn)) {
c.setSorted(true);
} else {
c.setSorted(false);
}
} else {
c.setSortable(false);
}
if (col.hasAttribute("align")) {
c.setAlign(col.getStringAttribute("align").charAt(0));
}
if (col.hasAttribute("width")) {
final String widthStr = col.getStringAttribute("width");
// Make sure to accomodate for the sort indicator if
// necessary.
int width = Integer.parseInt(widthStr);
if (width < c.getMinWidth()) {
width = c.getMinWidth();
}
c.setWidth(width, true);
} else if (recalcWidths) {
c.setUndefinedWidth();
}
if (col.hasAttribute("er")) {
c.setExpandRatio(col.getFloatAttribute("er"));
}
if (col.hasAttribute("collapsed")) {
// ensure header is properly removed from parent (case when
// collapsing happens via servers side api)
if (c.isAttached()) {
c.removeFromParent();
headerChangedDuringUpdate = true;
}
}
}
// check for orphaned header cells
for (Iterator<String> cit = availableCells.keySet().iterator(); cit
.hasNext();) {
String cid = cit.next();
if (!updated.contains(cid)) {
removeCell(cid);
cit.remove();
}
}
}
public void enableColumn(String cid, int index) {
final HeaderCell c = getHeaderCell(cid);
if (!c.isEnabled() || getHeaderCell(index) != c) {
setHeaderCell(index, c);
if (initializedAndAttached) {
headerChangedDuringUpdate = true;
}
}
}
public int getVisibleCellCount() {
return visibleCells.size();
}
public void setHorizontalScrollPosition(int scrollLeft) {
if (BrowserInfo.get().isIE6()) {
hTableWrapper.getStyle().setProperty("position", "relative");
hTableWrapper.getStyle().setPropertyPx("left", -scrollLeft);
} else {
hTableWrapper.setScrollLeft(scrollLeft);
}
}
public void setColumnCollapsingAllowed(boolean cc) {
if (cc) {
DOM.setStyleAttribute(columnSelector, "display", "block");
} else {
DOM.setStyleAttribute(columnSelector, "display", "none");
}
}
public void disableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH
+ "px");
}
public void enableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", "");
}
public void setHeaderCell(int index, HeaderCell cell) {
if (cell.isEnabled()) {
// we're moving the cell
DOM.removeChild(tr, cell.getElement());
orphan(cell);
visibleCells.remove(cell);
}
if (index < visibleCells.size()) {
// insert to right slot
DOM.insertChild(tr, cell.getElement(), index);
adopt(cell);
visibleCells.add(index, cell);
} else if (index == visibleCells.size()) {
// simply append
DOM.appendChild(tr, cell.getElement());
adopt(cell);
visibleCells.add(cell);
} else {
throw new RuntimeException(
"Header cells must be appended in order");
}
}
public HeaderCell getHeaderCell(int index) {
if (index < visibleCells.size()) {
return (HeaderCell) visibleCells.get(index);
} else {
return null;
}
}
/**
* Get's HeaderCell by it's column Key.
*
* Note that this returns HeaderCell even if it is currently collapsed.
*
* @param cid
* Column key of accessed HeaderCell
* @return HeaderCell
*/
public HeaderCell getHeaderCell(String cid) {
return availableCells.get(cid);
}
public void moveCell(int oldIndex, int newIndex) {
final HeaderCell hCell = getHeaderCell(oldIndex);
final Element cell = hCell.getElement();
visibleCells.remove(oldIndex);
DOM.removeChild(tr, cell);
DOM.insertChild(tr, cell, newIndex);
visibleCells.add(newIndex, hCell);
}
public Iterator<Widget> iterator() {
return visibleCells.iterator();
}
@Override
public boolean remove(Widget w) {
if (visibleCells.contains(w)) {
visibleCells.remove(w);
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
return true;
}
return false;
}
public void removeCell(String colKey) {
final HeaderCell c = getHeaderCell(colKey);
remove(c);
}
private void focusSlot(int index) {
removeSlotFocus();
if (index > 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, index - 1)),
"className", CLASSNAME + "-resizer " + CLASSNAME
+ "-focus-slot-right");
} else {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, index)),
"className", CLASSNAME + "-resizer " + CLASSNAME
+ "-focus-slot-left");
}
focusedSlot = index;
}
private void removeSlotFocus() {
if (focusedSlot < 0) {
return;
}
if (focusedSlot == 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, focusedSlot)),
"className", CLASSNAME + "-resizer");
} else if (focusedSlot > 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, focusedSlot - 1)),
"className", CLASSNAME + "-resizer");
}
focusedSlot = -1;
}
@Override
public void onBrowserEvent(Event event) {
if (enabled) {
if (event.getEventTarget().cast() == columnSelector) {
final int left = DOM.getAbsoluteLeft(columnSelector);
final int top = DOM.getAbsoluteTop(columnSelector)
+ DOM.getElementPropertyInt(columnSelector,
"offsetHeight");
client.getContextMenu().showAt(this, left, top);
}
}
}
@Override
protected void onDetach() {
super.onDetach();
if (client != null) {
client.getContextMenu().ensureHidden(this);
}
}
class VisibleColumnAction extends Action {
String colKey;
private boolean collapsed;
private VScrollTableRow currentlyFocusedRow;
public VisibleColumnAction(String colKey) {
super(VScrollTable.TableHead.this);
this.colKey = colKey;
caption = tHead.getHeaderCell(colKey).getCaption();
currentlyFocusedRow = focusedRow;
}
@Override
public void execute() {
client.getContextMenu().hide();
// toggle selected column
if (collapsedColumns.contains(colKey)) {
collapsedColumns.remove(colKey);
} else {
tHead.removeCell(colKey);
collapsedColumns.add(colKey);
lazyAdjustColumnWidths.schedule(1);
}
// update variable to server
client.updateVariable(paintableId, "collapsedcolumns",
collapsedColumns.toArray(new String[collapsedColumns
.size()]), false);
// let rowRequestHandler determine proper rows
rowRequestHandler.refreshContent();
lazyRevertFocusToRow(currentlyFocusedRow);
}
public void setCollapsed(boolean b) {
collapsed = b;
}
/**
* Override default method to distinguish on/off columns
*/
@Override
public String getHTML() {
final StringBuffer buf = new StringBuffer();
if (collapsed) {
buf.append("<span class=\"v-off\">");
} else {
buf.append("<span class=\"v-on\">");
}
buf.append(super.getHTML());
buf.append("</span>");
return buf.toString();
}
}
/*
* Returns columns as Action array for column select popup
*/
public Action[] getActions() {
Object[] cols;
if (columnReordering && columnOrder != null) {
cols = columnOrder;
} else {
// if columnReordering is disabled, we need different way to get
// all available columns
cols = visibleColOrder;
cols = new Object[visibleColOrder.length
+ collapsedColumns.size()];
int i;
for (i = 0; i < visibleColOrder.length; i++) {
cols[i] = visibleColOrder[i];
}
for (final Iterator<String> it = collapsedColumns.iterator(); it
.hasNext();) {
cols[i++] = it.next();
}
}
final Action[] actions = new Action[cols.length];
for (int i = 0; i < cols.length; i++) {
final String cid = (String) cols[i];
final HeaderCell c = getHeaderCell(cid);
final VisibleColumnAction a = new VisibleColumnAction(
c.getColKey());
a.setCaption(c.getCaption());
if (!c.isEnabled()) {
a.setCollapsed(true);
}
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
/**
* Returns column alignments for visible columns
*/
public char[] getColumnAlignments() {
final Iterator<Widget> it = visibleCells.iterator();
final char[] aligns = new char[visibleCells.size()];
int colIndex = 0;
while (it.hasNext()) {
aligns[colIndex++] = ((HeaderCell) it.next()).getAlign();
}
return aligns;
}
/**
* Disables the automatic calculation of all column widths by forcing
* the widths to be "defined" thus turning off expand ratios and such.
*/
public void disableAutoColumnWidthCalculation(HeaderCell source) {
for (HeaderCell cell : availableCells.values()) {
cell.disableAutoWidthCalculation();
}
// fire column resize events for all columns but the source of the
// resize action, since an event will fire separately for this.
ArrayList<HeaderCell> columns = new ArrayList<HeaderCell>(
availableCells.values());
columns.remove(source);
sendColumnWidthUpdates(columns);
forceRealignColumnHeaders();
}
}
/**
* A cell in the footer
*/
public class FooterCell extends Widget {
private final Element td = DOM.createTD();
private final Element captionContainer = DOM.createDiv();
private char align = ALIGN_LEFT;
private int width = -1;
private float expandRatio = 0;
private final String cid;
boolean definedWidth = false;
private int naturalWidth = -1;
public FooterCell(String colId, String headerText) {
cid = colId;
setText(headerText);
DOM.setElementProperty(captionContainer, "className", CLASSNAME
+ "-footer-container");
// ensure no clipping initially (problem on column additions)
DOM.setStyleAttribute(captionContainer, "overflow", "visible");
DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS);
DOM.appendChild(td, captionContainer);
DOM.sinkEvents(td, Event.MOUSEEVENTS);
setElement(td);
}
/**
* Sets the text of the footer
*
* @param footerText
* The text in the footer
*/
public void setText(String footerText) {
DOM.setInnerHTML(captionContainer, footerText);
}
/**
* Set alignment of the text in the cell
*
* @param c
* The alignment which can be ALIGN_CENTER, ALIGN_LEFT,
* ALIGN_RIGHT
*/
public void setAlign(char c) {
if (align != c) {
switch (c) {
case ALIGN_CENTER:
DOM.setStyleAttribute(captionContainer, "textAlign",
"center");
break;
case ALIGN_RIGHT:
DOM.setStyleAttribute(captionContainer, "textAlign",
"right");
break;
default:
DOM.setStyleAttribute(captionContainer, "textAlign", "");
break;
}
}
align = c;
}
/**
* Get the alignment of the text int the cell
*
* @return Returns either ALIGN_CENTER, ALIGN_LEFT or ALIGN_RIGHT
*/
public char getAlign() {
return align;
}
/**
* Sets the width of the cell
*
* @param w
* The width of the cell
* @param ensureDefinedWidth
* Ensures the the given width is not recalculated
*/
public void setWidth(int w, boolean ensureDefinedWidth) {
if (ensureDefinedWidth) {
definedWidth = true;
// on column resize expand ratio becomes zero
expandRatio = 0;
}
if (width == w) {
return;
}
if (width == -1) {
// go to default mode, clip content if necessary
DOM.setStyleAttribute(captionContainer, "overflow", "");
}
width = w;
if (w == -1) {
DOM.setStyleAttribute(captionContainer, "width", "");
setWidth("");
} else {
/*
* Reduce width with one pixel for the right border since the
* footers does not have any spacers between them.
*/
int borderWidths = 1;
// Set the container width (check for negative value)
if (w - borderWidths >= 0) {
captionContainer.getStyle().setPropertyPx("width",
w - borderWidths);
} else {
captionContainer.getStyle().setPropertyPx("width", 0);
}
/*
* if we already have tBody, set the header width properly, if
* not defer it. IE will fail with complex float in table header
* unless TD width is not explicitly set.
*/
if (scrollBody != null) {
/*
* Reduce with one since footer does not have any spacers,
* instead a 1 pixel border.
*/
int tdWidth = width + scrollBody.getCellExtraWidth()
- borderWidths;
setWidth(tdWidth + "px");
} else {
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
int borderWidths = 1;
int tdWidth = width
+ scrollBody.getCellExtraWidth()
- borderWidths;
setWidth(tdWidth + "px");
}
});
}
}
}
/**
* Sets the width to undefined
*/
public void setUndefinedWidth() {
setWidth(-1, false);
}
/**
* Detects if width is fixed by developer on server side or resized to
* current width by user.
*
* @return true if defined, false if "natural" width
*/
public boolean isDefinedWidth() {
return definedWidth;
}
/**
* Returns the pixels width of the footer cell
*
* @return The width in pixels
*/
public int getWidth() {
return width;
}
/**
* Sets the expand ratio of the cell
*
* @param floatAttribute
* The expand ratio
*/
public void setExpandRatio(float floatAttribute) {
expandRatio = floatAttribute;
}
/**
* Returns the expand ration of the cell
*
* @return The expand ratio
*/
public float getExpandRatio() {
return expandRatio;
}
/**
* Is the cell enabled?
*
* @return True if enabled else False
*/
public boolean isEnabled() {
return getParent() != null;
}
/**
* Handle column clicking
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled && event != null) {
handleCaptionEvent(event);
if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
scrollBodyPanel.setFocus(true);
}
event.stopPropagation();
event.preventDefault();
}
}
/**
* Handles a event on the captions
*
* @param event
* The event to handle
*/
protected void handleCaptionEvent(Event event) {
if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
fireFooterClickedEvent(event);
}
}
/**
* Fires a footer click event after the user has clicked a column footer
* cell
*
* @param event
* The click event
*/
private void fireFooterClickedEvent(Event event) {
if (client.hasEventListeners(VScrollTable.this,
FOOTER_CLICK_EVENT_ID)) {
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "footerClickEvent",
details.toString(), false);
client.updateVariable(paintableId, "footerClickCID", cid, true);
}
}
/**
* Returns the column key of the column
*
* @return The column key
*/
public String getColKey() {
return cid;
}
/**
* Detects the natural minimum width for the column of this header cell.
* If column is resized by user or the width is defined by server the
* actual width is returned. Else the natural min width is returned.
*
* @param columnIndex
* column index hint, if -1 (unknown) it will be detected
*
* @return
*/
public int getNaturalColumnWidth(int columnIndex) {
if (isDefinedWidth()) {
return width;
} else {
if (naturalWidth < 0) {
// This is recently revealed column. Try to detect a proper
// value (greater of header and data
// cols)
final int hw = ((Element) getElement().getLastChild())
.getOffsetWidth() + scrollBody.getCellExtraWidth();
if (columnIndex < 0) {
columnIndex = 0;
for (Iterator<Widget> it = tHead.iterator(); it
.hasNext(); columnIndex++) {
if (it.next() == this) {
break;
}
}
}
final int cw = scrollBody.getColWidth(columnIndex);
naturalWidth = (hw > cw ? hw : cw);
}
return naturalWidth;
}
}
public void setNaturalMinimumColumnWidth(int w) {
naturalWidth = w;
}
}
/**
* HeaderCell that is header cell for row headers.
*
* Reordering disabled and clicking on it resets sorting.
*/
public class RowHeadersFooterCell extends FooterCell {
RowHeadersFooterCell() {
super(ROW_HEADER_COLUMN_KEY, "");
}
@Override
protected void handleCaptionEvent(Event event) {
// NOP: RowHeaders cannot be reordered
// TODO It'd be nice to reset sorting here
}
}
/**
* The footer of the table which can be seen in the bottom of the Table.
*/
public class TableFooter extends Panel {
private static final int WRAPPER_WIDTH = 900000;
ArrayList<Widget> visibleCells = new ArrayList<Widget>();
HashMap<String, FooterCell> availableCells = new HashMap<String, FooterCell>();
Element div = DOM.createDiv();
Element hTableWrapper = DOM.createDiv();
Element hTableContainer = DOM.createDiv();
Element table = DOM.createTable();
Element headerTableBody = DOM.createTBody();
Element tr = DOM.createTR();
public TableFooter() {
DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
+ "-footer");
DOM.appendChild(table, headerTableBody);
DOM.appendChild(headerTableBody, tr);
DOM.appendChild(hTableContainer, table);
DOM.appendChild(hTableWrapper, hTableContainer);
DOM.appendChild(div, hTableWrapper);
setElement(div);
setStyleName(CLASSNAME + "-footer-wrap");
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersFooterCell());
}
@Override
public void clear() {
for (String cid : availableCells.keySet()) {
removeCell(cid);
}
availableCells.clear();
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersFooterCell());
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.user.client.ui.Panel#remove(com.google.gwt.user.client
* .ui.Widget)
*/
@Override
public boolean remove(Widget w) {
if (visibleCells.contains(w)) {
visibleCells.remove(w);
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.HasWidgets#iterator()
*/
public Iterator<Widget> iterator() {
return visibleCells.iterator();
}
/**
* Gets a footer cell which represents the given columnId
*
* @param cid
* The columnId
*
* @return The cell
*/
public FooterCell getFooterCell(String cid) {
return availableCells.get(cid);
}
/**
* Gets a footer cell by using a column index
*
* @param index
* The index of the column
* @return The Cell
*/
public FooterCell getFooterCell(int index) {
if (index < visibleCells.size()) {
return (FooterCell) visibleCells.get(index);
} else {
return null;
}
}
/**
* Updates the cells contents when updateUIDL request is received
*
* @param uidl
* The UIDL
*/
public void updateCellsFromUIDL(UIDL uidl) {
Iterator<?> columnIterator = uidl.getChildIterator();
HashSet<String> updated = new HashSet<String>();
while (columnIterator.hasNext()) {
final UIDL col = (UIDL) columnIterator.next();
final String cid = col.getStringAttribute("cid");
updated.add(cid);
String caption = col.hasAttribute("fcaption") ? col
.getStringAttribute("fcaption") : "";
FooterCell c = getFooterCell(cid);
if (c == null) {
c = new FooterCell(cid, caption);
availableCells.put(cid, c);
if (initializedAndAttached) {
// we will need a column width recalculation
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
} else {
c.setText(caption);
}
if (col.hasAttribute("align")) {
c.setAlign(col.getStringAttribute("align").charAt(0));
}
if (col.hasAttribute("width")) {
final String width = col.getStringAttribute("width");
c.setWidth(Integer.parseInt(width), true);
} else if (recalcWidths) {
c.setUndefinedWidth();
}
if (col.hasAttribute("er")) {
c.setExpandRatio(col.getFloatAttribute("er"));
}
if (col.hasAttribute("collapsed")) {
// ensure header is properly removed from parent (case when
// collapsing happens via servers side api)
if (c.isAttached()) {
c.removeFromParent();
headerChangedDuringUpdate = true;
}
}
}
// check for orphaned header cells
for (Iterator<String> cit = availableCells.keySet().iterator(); cit
.hasNext();) {
String cid = cit.next();
if (!updated.contains(cid)) {
removeCell(cid);
cit.remove();
}
}
}
/**
* Set a footer cell for a specified column index
*
* @param index
* The index
* @param cell
* The footer cell
*/
public void setFooterCell(int index, FooterCell cell) {
if (cell.isEnabled()) {
// we're moving the cell
DOM.removeChild(tr, cell.getElement());
orphan(cell);
visibleCells.remove(cell);
}
if (index < visibleCells.size()) {
// insert to right slot
DOM.insertChild(tr, cell.getElement(), index);
adopt(cell);
visibleCells.add(index, cell);
} else if (index == visibleCells.size()) {
// simply append
DOM.appendChild(tr, cell.getElement());
adopt(cell);
visibleCells.add(cell);
} else {
throw new RuntimeException(
"Header cells must be appended in order");
}
}
/**
* Remove a cell by using the columnId
*
* @param colKey
* The columnId to remove
*/
public void removeCell(String colKey) {
final FooterCell c = getFooterCell(colKey);
remove(c);
}
/**
* Enable a column (Sets the footer cell)
*
* @param cid
* The columnId
* @param index
* The index of the column
*/
public void enableColumn(String cid, int index) {
final FooterCell c = getFooterCell(cid);
if (!c.isEnabled() || getFooterCell(index) != c) {
setFooterCell(index, c);
if (initializedAndAttached) {
headerChangedDuringUpdate = true;
}
}
}
/**
* Disable browser measurement of the table width
*/
public void disableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH
+ "px");
}
/**
* Enable browser measurement of the table width
*/
public void enableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", "");
}
/**
* Set the horizontal position in the cell in the footer. This is done
* when a horizontal scrollbar is present.
*
* @param scrollLeft
* The value of the leftScroll
*/
public void setHorizontalScrollPosition(int scrollLeft) {
if (BrowserInfo.get().isIE6()) {
hTableWrapper.getStyle().setProperty("position", "relative");
hTableWrapper.getStyle().setPropertyPx("left", -scrollLeft);
} else {
hTableWrapper.setScrollLeft(scrollLeft);
}
}
/**
* Swap cells when the column are dragged
*
* @param oldIndex
* The old index of the cell
* @param newIndex
* The new index of the cell
*/
public void moveCell(int oldIndex, int newIndex) {
final FooterCell hCell = getFooterCell(oldIndex);
final Element cell = hCell.getElement();
visibleCells.remove(oldIndex);
DOM.removeChild(tr, cell);
DOM.insertChild(tr, cell, newIndex);
visibleCells.add(newIndex, hCell);
}
}
/**
* This Panel can only contain VScrollTableRow type of widgets. This
* "simulates" very large table, keeping spacers which take room of
* unrendered rows.
*
*/
public class VScrollTableBody extends Panel {
public static final int DEFAULT_ROW_HEIGHT = 24;
private double rowHeight = -1;
private final List<Widget> renderedRows = new ArrayList<Widget>();
/**
* Due some optimizations row height measuring is deferred and initial
* set of rows is rendered detached. Flag set on when table body has
* been attached in dom and rowheight has been measured.
*/
private boolean tBodyMeasurementsDone = false;
Element preSpacer = DOM.createDiv();
Element postSpacer = DOM.createDiv();
Element container = DOM.createDiv();
TableSectionElement tBodyElement = Document.get().createTBodyElement();
Element table = DOM.createTable();
private int firstRendered;
private int lastRendered;
private char[] aligns;
protected VScrollTableBody() {
constructDOM();
setElement(container);
}
public VScrollTableRow getRowByRowIndex(int indexInTable) {
int internalIndex = indexInTable - firstRendered;
if (internalIndex >= 0 && internalIndex < renderedRows.size()) {
return (VScrollTableRow) renderedRows.get(internalIndex);
} else {
return null;
}
}
/**
* @return the height of scrollable body, subpixels ceiled.
*/
public int getRequiredHeight() {
return preSpacer.getOffsetHeight() + postSpacer.getOffsetHeight()
+ Util.getRequiredHeight(table);
}
private void constructDOM() {
DOM.setElementProperty(table, "className", CLASSNAME + "-table");
if (BrowserInfo.get().isIE()) {
table.setPropertyInt("cellSpacing", 0);
}
DOM.setElementProperty(preSpacer, "className", CLASSNAME
+ "-row-spacer");
DOM.setElementProperty(postSpacer, "className", CLASSNAME
+ "-row-spacer");
table.appendChild(tBodyElement);
DOM.appendChild(container, preSpacer);
DOM.appendChild(container, table);
DOM.appendChild(container, postSpacer);
}
public int getAvailableWidth() {
int availW = scrollBodyPanel.getOffsetWidth() - getBorderWidth();
return availW;
}
public void renderInitialRows(UIDL rowData, int firstIndex, int rows) {
firstRendered = firstIndex;
lastRendered = firstIndex + rows - 1;
final Iterator<?> it = rowData.getChildIterator();
aligns = tHead.getColumnAlignments();
while (it.hasNext()) {
final VScrollTableRow row = createRow((UIDL) it.next(), aligns);
addRow(row);
}
if (isAttached()) {
fixSpacers();
}
}
public void renderRows(UIDL rowData, int firstIndex, int rows) {
// FIXME REVIEW
aligns = tHead.getColumnAlignments();
final Iterator<?> it = rowData.getChildIterator();
if (firstIndex == lastRendered + 1) {
while (it.hasNext()) {
final VScrollTableRow row = prepareRow((UIDL) it.next());
addRow(row);
lastRendered++;
}
fixSpacers();
} else if (firstIndex + rows == firstRendered) {
final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
int i = rows;
while (it.hasNext()) {
i--;
rowArray[i] = prepareRow((UIDL) it.next());
}
for (i = 0; i < rows; i++) {
addRowBeforeFirstRendered(rowArray[i]);
firstRendered--;
}
} else {
// completely new set of rows
while (lastRendered + 1 > firstRendered) {
unlinkRow(false);
}
final VScrollTableRow row = prepareRow((UIDL) it.next());
firstRendered = firstIndex;
lastRendered = firstIndex - 1;
addRow(row);
lastRendered++;
setContainerHeight();
fixSpacers();
while (it.hasNext()) {
addRow(prepareRow((UIDL) it.next()));
lastRendered++;
}
fixSpacers();
}
// this may be a new set of rows due content change,
// ensure we have proper cache rows
int reactFirstRow = (int) (firstRowInViewPort - pageLength
* cache_react_rate);
int reactLastRow = (int) (firstRowInViewPort + pageLength + pageLength
* cache_react_rate);
if (reactFirstRow < 0) {
reactFirstRow = 0;
}
if (reactLastRow >= totalRows) {
reactLastRow = totalRows - 1;
}
if (lastRendered < reactLastRow) {
// get some cache rows below visible area
rowRequestHandler.setReqFirstRow(lastRendered + 1);
rowRequestHandler.setReqRows(reactLastRow - lastRendered);
rowRequestHandler.deferRowFetch(1);
} else if (scrollBody.getFirstRendered() > reactFirstRow) {
/*
* Branch for fetching cache above visible area.
*
* If cache needed for both before and after visible area, this
* will be rendered after-cache is reveived and rendered. So in
* some rare situations table may take two cache visits to
* server.
*/
rowRequestHandler.setReqFirstRow(reactFirstRow);
rowRequestHandler.setReqRows(firstRendered - reactFirstRow);
rowRequestHandler.deferRowFetch(1);
}
}
/**
* This method is used to instantiate new rows for this table. It
* automatically sets correct widths to rows cells and assigns correct
* client reference for child widgets.
*
* This method can be called only after table has been initialized
*
* @param uidl
*/
private VScrollTableRow prepareRow(UIDL uidl) {
final VScrollTableRow row = createRow(uidl, aligns);
final int cells = DOM.getChildCount(row.getElement());
for (int i = 0; i < cells; i++) {
final Element cell = DOM.getChild(row.getElement(), i);
int w = VScrollTable.this.getColWidth(getColKeyByIndex(i));
if (w < 0) {
w = 0;
}
cell.getFirstChildElement().getStyle()
.setPropertyPx("width", w);
cell.getStyle().setPropertyPx("width", w);
}
return row;
}
protected VScrollTableRow createRow(UIDL uidl, char[] aligns2) {
return new VScrollTableRow(uidl, aligns);
}
private void addRowBeforeFirstRendered(VScrollTableRow row) {
row.setIndex(firstRendered - 1);
if (row.isSelected()) {
row.addStyleName("v-selected");
}
tBodyElement.insertBefore(row.getElement(),
tBodyElement.getFirstChild());
adopt(row);
renderedRows.add(0, row);
}
private void addRow(VScrollTableRow row) {
row.setIndex(firstRendered + renderedRows.size());
if (row.isSelected()) {
row.addStyleName("v-selected");
}
tBodyElement.appendChild(row.getElement());
adopt(row);
renderedRows.add(row);
}
public Iterator<Widget> iterator() {
return renderedRows.iterator();
}
/**
* @return false if couldn't remove row
*/
public boolean unlinkRow(boolean fromBeginning) {
if (lastRendered - firstRendered < 0) {
return false;
}
int index;
if (fromBeginning) {
index = 0;
firstRendered++;
} else {
index = renderedRows.size() - 1;
lastRendered--;
}
if (index >= 0) {
final VScrollTableRow toBeRemoved = (VScrollTableRow) renderedRows
.get(index);
lazyUnregistryBag.add(toBeRemoved);
tBodyElement.removeChild(toBeRemoved.getElement());
orphan(toBeRemoved);
renderedRows.remove(index);
fixSpacers();
return true;
} else {
return false;
}
}
@Override
public boolean remove(Widget w) {
throw new UnsupportedOperationException();
}
@Override
protected void onAttach() {
super.onAttach();
setContainerHeight();
}
/**
* Fix container blocks height according to totalRows to avoid
* "bouncing" when scrolling
*/
private void setContainerHeight() {
fixSpacers();
DOM.setStyleAttribute(container, "height", totalRows
* getRowHeight() + "px");
}
private void fixSpacers() {
int prepx = (int) Math.round(getRowHeight() * firstRendered);
if (prepx < 0) {
prepx = 0;
}
preSpacer.getStyle().setPropertyPx("height", prepx);
int postpx = (int) (getRowHeight() * (totalRows - 1 - lastRendered));
if (postpx < 0) {
postpx = 0;
}
postSpacer.getStyle().setPropertyPx("height", postpx);
}
public double getRowHeight() {
return getRowHeight(false);
}
public double getRowHeight(boolean forceUpdate) {
if (tBodyMeasurementsDone && !forceUpdate) {
return rowHeight;
} else {
if (tBodyElement.getRows().getLength() > 0) {
int tableHeight = getTableHeight();
int rowCount = tBodyElement.getRows().getLength();
rowHeight = tableHeight / (double) rowCount;
} else {
if (isAttached()) {
// measure row height by adding a dummy row
VScrollTableRow scrollTableRow = new VScrollTableRow();
tBodyElement.appendChild(scrollTableRow.getElement());
getRowHeight(forceUpdate);
tBodyElement.removeChild(scrollTableRow.getElement());
} else {
// TODO investigate if this can never happen anymore
return DEFAULT_ROW_HEIGHT;
}
}
tBodyMeasurementsDone = true;
return rowHeight;
}
}
public int getTableHeight() {
return table.getOffsetHeight();
}
/**
* Returns the width available for column content.
*
* @param columnIndex
* @return
*/
public int getColWidth(int columnIndex) {
if (tBodyMeasurementsDone) {
NodeList<TableRowElement> rows = tBodyElement.getRows();
if (rows.getLength() == 0) {
// no rows yet rendered
return 0;
} else {
com.google.gwt.dom.client.Element wrapperdiv = rows
.getItem(0).getCells().getItem(columnIndex)
.getFirstChildElement();
return wrapperdiv.getOffsetWidth();
}
} else {
return 0;
}
}
/**
* Sets the content width of a column.
*
* Due IE limitation, we must set the width to a wrapper elements inside
* table cells (with overflow hidden, which does not work on td
* elements).
*
* To get this work properly crossplatform, we will also set the width
* of td.
*
* @param colIndex
* @param w
*/
public void setColWidth(int colIndex, int w) {
NodeList<TableRowElement> rows2 = tBodyElement.getRows();
final int rows = rows2.getLength();
for (int i = 0; i < rows; i++) {
TableRowElement row = rows2.getItem(i);
TableCellElement cell = row.getCells().getItem(colIndex);
cell.getFirstChildElement().getStyle()
.setPropertyPx("width", w);
cell.getStyle().setPropertyPx("width", w);
}
}
private int cellExtraWidth = -1;
/**
* Method to return the space used for cell paddings + border.
*/
private int getCellExtraWidth() {
if (cellExtraWidth < 0) {
detectExtrawidth();
}
return cellExtraWidth;
}
private void detectExtrawidth() {
NodeList<TableRowElement> rows = tBodyElement.getRows();
if (rows.getLength() == 0) {
/* need to temporary add empty row and detect */
VScrollTableRow scrollTableRow = new VScrollTableRow();
tBodyElement.appendChild(scrollTableRow.getElement());
detectExtrawidth();
tBodyElement.removeChild(scrollTableRow.getElement());
} else {
boolean noCells = false;
TableRowElement item = rows.getItem(0);
TableCellElement firstTD = item.getCells().getItem(0);
if (firstTD == null) {
// content is currently empty, we need to add a fake cell
// for measuring
noCells = true;
VScrollTableRow next = (VScrollTableRow) iterator().next();
next.addCell(null, "", ALIGN_LEFT, "", true, tHead
.getHeaderCell(0).isSorted());
firstTD = item.getCells().getItem(0);
}
com.google.gwt.dom.client.Element wrapper = firstTD
.getFirstChildElement();
cellExtraWidth = firstTD.getOffsetWidth()
- wrapper.getOffsetWidth();
if (noCells) {
firstTD.getParentElement().removeChild(firstTD);
}
}
}
private void reLayoutComponents() {
for (Widget w : this) {
VScrollTableRow r = (VScrollTableRow) w;
for (Widget widget : r) {
client.handleComponentRelativeSize(widget);
}
}
}
public int getLastRendered() {
return lastRendered;
}
public int getFirstRendered() {
return firstRendered;
}
public void moveCol(int oldIndex, int newIndex) {
// loop all rows and move given index to its new place
final Iterator<?> rows = iterator();
while (rows.hasNext()) {
final VScrollTableRow row = (VScrollTableRow) rows.next();
final Element td = DOM.getChild(row.getElement(), oldIndex);
DOM.removeChild(row.getElement(), td);
DOM.insertChild(row.getElement(), td, newIndex);
}
}
/**
* Restore row visibility which is set to "none" when the row is
* rendered (due a performance optimization).
*/
private void restoreRowVisibility() {
for (Widget row : renderedRows) {
row.getElement().getStyle().setProperty("visibility", "");
}
}
public class VScrollTableRow extends Panel implements ActionOwner,
Container {
private static final int TOUCHSCROLL_TIMEOUT = 70;
private static final int DRAGMODE_MULTIROW = 2;
protected ArrayList<Widget> childWidgets = new ArrayList<Widget>();
private boolean selected = false;
protected final int rowKey;
private List<UIDL> pendingComponentPaints;
private String[] actionKeys = null;
private final TableRowElement rowElement;
private boolean mDown;
private int index;
private Event touchStart;
private static final String ROW_CLASSNAME_EVEN = CLASSNAME + "-row";
private static final String ROW_CLASSNAME_ODD = CLASSNAME
+ "-row-odd";
private static final int TOUCH_CONTEXT_MENU_TIMEOUT = 500;
private Timer contextTouchTimeout;
private int touchStartY;
private int touchStartX;
private VScrollTableRow(int rowKey) {
this.rowKey = rowKey;
rowElement = Document.get().createTRElement();
setElement(rowElement);
DOM.sinkEvents(getElement(), Event.MOUSEEVENTS
| Event.TOUCHEVENTS | Event.ONDBLCLICK
| Event.ONCONTEXTMENU);
}
/**
* Detects whether row is visible in tables viewport.
*
* @return
*/
public boolean isInViewPort() {
int absoluteTop = getAbsoluteTop();
int scrollPosition = scrollBodyPanel.getScrollPosition();
if (absoluteTop < scrollPosition) {
return false;
}
int maxVisible = scrollPosition
+ scrollBodyPanel.getOffsetHeight() - getOffsetHeight();
if (absoluteTop > maxVisible) {
return false;
}
return true;
}
/**
* Makes a check based on indexes whether the row is before the
* compared row.
*
* @param row1
* @return true if this rows index is smaller than in the row1
*/
public boolean isBefore(VScrollTableRow row1) {
return getIndex() < row1.getIndex();
}
/**
* Sets the index of the row in the whole table. Currently used just
* to set even/odd classname
*
* @param indexInWholeTable
*/
private void setIndex(int indexInWholeTable) {
index = indexInWholeTable;
boolean isOdd = indexInWholeTable % 2 == 0;
// Inverted logic to be backwards compatible with earlier 6.4.
// It is very strange because rows 1,3,5 are considered "even"
// and 2,4,6 "odd".
if (!isOdd) {
addStyleName(ROW_CLASSNAME_ODD);
} else {
addStyleName(ROW_CLASSNAME_EVEN);
}
}
public int getIndex() {
return index;
}
private void paintComponent(Paintable p, UIDL uidl) {
if (isAttached()) {
p.updateFromUIDL(uidl, client);
} else {
if (pendingComponentPaints == null) {
pendingComponentPaints = new LinkedList<UIDL>();
}
pendingComponentPaints.add(uidl);
}
}
@Override
protected void onAttach() {
super.onAttach();
if (pendingComponentPaints != null) {
for (UIDL uidl : pendingComponentPaints) {
Paintable paintable = client.getPaintable(uidl);
paintable.updateFromUIDL(uidl, client);
}
}
}
@Override
protected void onDetach() {
super.onDetach();
client.getContextMenu().ensureHidden(this);
}
public String getKey() {
return String.valueOf(rowKey);
}
public VScrollTableRow(UIDL uidl, char[] aligns) {
this(uidl.getIntAttribute("key"));
/*
* Rendering the rows as hidden improves Firefox and Safari
* performance drastically.
*/
getElement().getStyle().setProperty("visibility", "hidden");
String rowStyle = uidl.getStringAttribute("rowstyle");
if (rowStyle != null) {
addStyleName(CLASSNAME + "-row-" + rowStyle);
}
tHead.getColumnAlignments();
int col = 0;
int visibleColumnIndex = -1;
// row header
if (showRowHeaders) {
boolean sorted = tHead.getHeaderCell(col).isSorted();
addCell(uidl, buildCaptionHtmlSnippet(uidl), aligns[col++],
"rowheader", true, sorted);
visibleColumnIndex++;
}
if (uidl.hasAttribute("al")) {
actionKeys = uidl.getStringArrayAttribute("al");
}
final Iterator<?> cells = uidl.getChildIterator();
while (cells.hasNext()) {
final Object cell = cells.next();
visibleColumnIndex++;
String columnId = visibleColOrder[visibleColumnIndex];
String style = "";
if (uidl.hasAttribute("style-" + columnId)) {
style = uidl.getStringAttribute("style-" + columnId);
}
boolean sorted = tHead.getHeaderCell(col).isSorted();
if (cell instanceof String) {
addCell(uidl, cell.toString(), aligns[col++], style,
false, sorted);
} else {
final Paintable cellContent = client
.getPaintable((UIDL) cell);
addCell(uidl, (Widget) cellContent, aligns[col++],
style, sorted);
paintComponent(cellContent, (UIDL) cell);
}
}
if (uidl.hasAttribute("selected") && !isSelected()) {
toggleSelection();
}
}
/**
* Add a dummy row, used for measurements if Table is empty.
*/
public VScrollTableRow() {
this(0);
addStyleName(CLASSNAME + "-row");
addCell(null, "_", 'b', "", true, false);
}
public void addCell(UIDL rowUidl, String text, char align,
String style, boolean textIsHTML, boolean sorted) {
// String only content is optimized by not using Label widget
final Element td = DOM.createTD();
final Element container = DOM.createDiv();
String className = CLASSNAME + "-cell-content";
if (style != null && !style.equals("")) {
className += " " + CLASSNAME + "-cell-content-" + style;
}
if (sorted) {
className += " " + CLASSNAME + "-cell-content-sorted";
}
td.setClassName(className);
container.setClassName(CLASSNAME + "-cell-wrapper");
if (textIsHTML) {
container.setInnerHTML(text);
} else {
container.setInnerText(text);
}
if (align != ALIGN_LEFT) {
switch (align) {
case ALIGN_CENTER:
container.getStyle().setProperty("textAlign", "center");
break;
case ALIGN_RIGHT:
default:
container.getStyle().setProperty("textAlign", "right");
break;
}
}
td.appendChild(container);
getElement().appendChild(td);
}
public void addCell(UIDL rowUidl, Widget w, char align,
String style, boolean sorted) {
final Element td = DOM.createTD();
final Element container = DOM.createDiv();
String className = CLASSNAME + "-cell-content";
if (style != null && !style.equals("")) {
className += " " + CLASSNAME + "-cell-content-" + style;
}
if (sorted) {
className += " " + CLASSNAME + "-cell-content-sorted";
}
td.setClassName(className);
container.setClassName(CLASSNAME + "-cell-wrapper");
// TODO most components work with this, but not all (e.g.
// Select)
// Old comment: make widget cells respect align.
// text-align:center for IE, margin: auto for others
if (align != ALIGN_LEFT) {
switch (align) {
case ALIGN_CENTER:
container.getStyle().setProperty("textAlign", "center");
break;
case ALIGN_RIGHT:
default:
container.getStyle().setProperty("textAlign", "right");
break;
}
}
td.appendChild(container);
getElement().appendChild(td);
// ensure widget not attached to another element (possible tBody
// change)
w.removeFromParent();
container.appendChild(w.getElement());
adopt(w);
childWidgets.add(w);
}
public Iterator<Widget> iterator() {
return childWidgets.iterator();
}
@Override
public boolean remove(Widget w) {
if (childWidgets.contains(w)) {
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()),
w.getElement());
childWidgets.remove(w);
return true;
} else {
return false;
}
}
private void handleClickEvent(Event event, Element targetTdOrTr) {
if (client.hasEventListeners(VScrollTable.this,
ITEM_CLICK_EVENT_ID)) {
boolean doubleClick = (DOM.eventGetType(event) == Event.ONDBLCLICK);
/* This row was clicked */
client.updateVariable(paintableId, "clickedKey", ""
+ rowKey, false);
if (getElement() == targetTdOrTr.getParentElement()) {
/* A specific column was clicked */
int childIndex = DOM.getChildIndex(getElement(),
targetTdOrTr);
String colKey = null;
colKey = tHead.getHeaderCell(childIndex).getColKey();
client.updateVariable(paintableId, "clickedColKey",
colKey, false);
}
MouseEventDetails details = new MouseEventDetails(event);
boolean imm = true;
if (immediate && event.getButton() == Event.BUTTON_LEFT
&& !doubleClick && isSelectable() && !isSelected()) {
/*
* A left click when the table is selectable and in
* immediate mode on a row that is not currently
* selected will cause a selection event to be fired
* after this click event. By making the click event
* non-immediate we avoid sending two separate messages
* to the server.
*/
imm = false;
}
client.updateVariable(paintableId, "clickEvent",
details.toString(), imm);
}
}
/*
* React on click that occur on content cells only
*/
@Override
public void onBrowserEvent(final Event event) {
if (enabled) {
final int type = event.getTypeInt();
final Element targetTdOrTr = getEventTargetTdOrTr(event);
if (type == Event.ONCONTEXTMENU) {
showContextMenu(event);
event.stopPropagation();
return;
}
boolean targetCellOrRowFound = targetTdOrTr != null;
switch (type) {
case Event.ONDBLCLICK:
if (targetCellOrRowFound) {
handleClickEvent(event, targetTdOrTr);
}
break;
case Event.ONMOUSEUP:
if (targetCellOrRowFound) {
mDown = false;
handleClickEvent(event, targetTdOrTr);
if (event.getButton() == Event.BUTTON_LEFT
&& isSelectable()) {
// Ctrl+Shift click
if ((event.getCtrlKey() || event.getMetaKey())
&& event.getShiftKey()
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
toggleShiftSelection(false);
setRowFocus(this);
// Ctrl click
} else if ((event.getCtrlKey() || event
.getMetaKey())
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
boolean wasSelected = isSelected();
toggleSelection();
setRowFocus(this);
/*
* next possible range select must start on
* this row
*/
selectionRangeStart = this;
if (wasSelected) {
removeRowFromUnsentSelectionRanges(this);
}
// Ctrl click (Single selection)
} else if ((event.getCtrlKey() || event
.getMetaKey()
&& selectMode == SELECT_MODE_SINGLE)) {
if (!isSelected()
|| (isSelected() && nullSelectionAllowed)) {
if (!isSelected()) {
deselectAll();
}
toggleSelection();
setRowFocus(this);
}
// Shift click
} else if (event.getShiftKey()
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
toggleShiftSelection(true);
// click
} else {
boolean currentlyJustThisRowSelected = selectedRowKeys
.size() == 1
&& selectedRowKeys
.contains(getKey());
if (!currentlyJustThisRowSelected) {
if (multiselectmode == MULTISELECT_MODE_DEFAULT) {
deselectAll();
}
toggleSelection();
} else if ((selectMode == SELECT_MODE_SINGLE || multiselectmode == MULTISELECT_MODE_SIMPLE)
&& nullSelectionAllowed) {
toggleSelection();
}/*
* else NOP to avoid excessive server
* visits (selection is removed with
* CTRL/META click)
*/
selectionRangeStart = this;
setRowFocus(this);
}
// Remove IE text selection hack
if (BrowserInfo.get().isIE()) {
((Element) event.getEventTarget().cast())
.setPropertyJSO("onselectstart",
null);
}
sendSelectedRows();
}
}
break;
case Event.ONTOUCHEND:
case Event.ONTOUCHCANCEL:
if (touchStart != null) {
/*
* Touch has not been handled as neither context or
* drag start, handle it as a click.
*/
Util.simulateClickFromTouchEvent(touchStart, this);
touchStart = null;
}
if (contextTouchTimeout != null) {
contextTouchTimeout.cancel();
}
break;
case Event.ONTOUCHMOVE:
if (isSignificantMove(event)) {
/*
* TODO figure out scroll delegate don't eat events
* if row is selected. Null check for active
* delegate is as a workaround.
*/
if (dragmode != 0
&& touchStart != null
&& (TouchScrollDelegate
.getActiveScrollDelegate() == null)) {
startRowDrag(touchStart, type, targetTdOrTr);
}
if (contextTouchTimeout != null) {
contextTouchTimeout.cancel();
}
/*
* Avoid clicks and drags by clearing touch start
* flag.
*/
touchStart = null;
}
break;
case Event.ONTOUCHSTART:
touchStart = event;
Touch touch = event.getChangedTouches().get(0);
// save position to fields, touches in events are same
// isntance during the operation.
touchStartX = touch.getClientX();
touchStartY = touch.getClientY();
/*
* Prevent simulated mouse events.
*/
touchStart.preventDefault();
if (dragmode != 0 || actionKeys != null) {
new Timer() {
@Override
public void run() {
TouchScrollDelegate activeScrollDelegate = TouchScrollDelegate
.getActiveScrollDelegate();
if (activeScrollDelegate != null
&& !activeScrollDelegate.isMoved()) {
/*
* scrolling hasn't started. Cancel
* scrolling and let row handle this as
* drag start or context menu.
*/
activeScrollDelegate.stopScrolling();
} else {
/*
* Scrolled or scrolling, clear touch
* start to indicate that row shouldn't
* handle touch move/end events.
*/
touchStart = null;
}
}
}.schedule(TOUCHSCROLL_TIMEOUT);
if (contextTouchTimeout == null
&& actionKeys != null) {
contextTouchTimeout = new Timer() {
@Override
public void run() {
if (touchStart != null) {
showContextMenu(touchStart);
touchStart = null;
}
}
};
}
contextTouchTimeout.cancel();
contextTouchTimeout
.schedule(TOUCH_CONTEXT_MENU_TIMEOUT);
}
break;
case Event.ONMOUSEDOWN:
if (targetCellOrRowFound) {
setRowFocus(this);
ensureFocus();
if (dragmode != 0
&& (event.getButton() == NativeEvent.BUTTON_LEFT)) {
startRowDrag(event, type, targetTdOrTr);
} else if (event.getCtrlKey()
|| event.getShiftKey()
|| event.getMetaKey()
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
// Prevent default text selection in Firefox
event.preventDefault();
// Prevent default text selection in IE
if (BrowserInfo.get().isIE()) {
((Element) event.getEventTarget().cast())
.setPropertyJSO(
"onselectstart",
getPreventTextSelectionIEHack());
}
event.stopPropagation();
}
}
break;
case Event.ONMOUSEOUT:
if (targetCellOrRowFound) {
mDown = false;
}
break;
default:
break;
}
}
super.onBrowserEvent(event);
}
private boolean isSignificantMove(Event event) {
if (touchStart == null) {
// no touch start
return false;
}
/*
* TODO calculate based on real distance instead of separate
* axis checks
*/
Touch touch = event.getChangedTouches().get(0);
if (Math.abs(touch.getClientX() - touchStartX) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
return true;
}
if (Math.abs(touch.getClientY() - touchStartY) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
return true;
}
return false;
}
protected void startRowDrag(Event event, final int type,
Element targetTdOrTr) {
mDown = true;
VTransferable transferable = new VTransferable();
transferable.setDragSource(VScrollTable.this);
transferable.setData("itemId", "" + rowKey);
NodeList<TableCellElement> cells = rowElement.getCells();
for (int i = 0; i < cells.getLength(); i++) {
if (cells.getItem(i).isOrHasChild(targetTdOrTr)) {
HeaderCell headerCell = tHead.getHeaderCell(i);
transferable.setData("propertyId", headerCell.cid);
break;
}
}
VDragEvent ev = VDragAndDropManager.get().startDrag(
transferable, event, true);
if (dragmode == DRAGMODE_MULTIROW
&& selectMode == SELECT_MODE_MULTI
&& selectedRowKeys.contains("" + rowKey)) {
ev.createDragImage(
(Element) scrollBody.tBodyElement.cast(), true);
Element dragImage = ev.getDragImage();
int i = 0;
for (Iterator<Widget> iterator = scrollBody.iterator(); iterator
.hasNext();) {
VScrollTableRow next = (VScrollTableRow) iterator
.next();
Element child = (Element) dragImage.getChild(i++);
if (!selectedRowKeys.contains("" + next.rowKey)) {
child.getStyle().setVisibility(Visibility.HIDDEN);
}
}
} else {
ev.createDragImage(getElement(), true);
}
if (type == Event.ONMOUSEDOWN) {
event.preventDefault();
}
event.stopPropagation();
}
/**
* Finds the TD that the event interacts with. Returns null if the
* target of the event should not be handled. If the event target is
* the row directly this method returns the TR element instead of
* the TD.
*
* @param event
* @return TD or TR element that the event targets (the actual event
* target is this element or a child of it)
*/
private Element getEventTargetTdOrTr(Event event) {
final Element eventTarget = event.getEventTarget().cast();
Widget widget = Util.findWidget(eventTarget, null);
final Element thisTrElement = getElement();
if (widget != this) {
/*
* This is a workaround to make Labels, read only TextFields
* and Embedded in a Table clickable (see #2688). It is
* really not a fix as it does not work with a custom read
* only components (not extending VLabel/VEmbedded).
*/
while (widget != null && widget.getParent() != this) {
widget = widget.getParent();
}
if (!(widget instanceof VLabel)
&& !(widget instanceof VEmbedded)
&& !(widget instanceof VTextField && ((VTextField) widget)
.isReadOnly())) {
return null;
}
}
if (eventTarget == thisTrElement) {
// This was a click on the TR element
return thisTrElement;
}
// Iterate upwards until we find the TR element
Element element = eventTarget;
while (element != null
&& element.getParentElement().cast() != thisTrElement) {
element = element.getParentElement().cast();
}
return element;
}
public void showContextMenu(Event event) {
if (enabled && actionKeys != null) {
int left = Util.getTouchOrMouseClientX(event);
int top = Util.getTouchOrMouseClientY(event);
top += Window.getScrollTop();
left += Window.getScrollLeft();
client.getContextMenu().showAt(this, left, top);
}
event.stopPropagation();
event.preventDefault();
}
/**
* Has the row been selected?
*
* @return Returns true if selected, else false
*/
public boolean isSelected() {
return selected;
}
/**
* Toggle the selection of the row
*/
public void toggleSelection() {
selected = !selected;
selectionChanged = true;
if (selected) {
selectedRowKeys.add(String.valueOf(rowKey));
addStyleName("v-selected");
} else {
removeStyleName("v-selected");
selectedRowKeys.remove(String.valueOf(rowKey));
}
}
/**
* Is called when a user clicks an item when holding SHIFT key down.
* This will select a new range from the last focused row
*
* @param deselectPrevious
* Should the previous selected range be deselected
*/
private void toggleShiftSelection(boolean deselectPrevious) {
/*
* Ensures that we are in multiselect mode and that we have a
* previous selection which was not a deselection
*/
if (selectMode == SELECT_MODE_SINGLE) {
// No previous selection found
deselectAll();
toggleSelection();
return;
}
// Set the selectable range
VScrollTableRow endRow = this;
VScrollTableRow startRow = selectionRangeStart;
if (startRow == null) {
startRow = focusedRow;
// If start row is null then we have a multipage selection
// from
// above
if (startRow == null) {
startRow = (VScrollTableRow) scrollBody.iterator()
.next();
setRowFocus(endRow);
}
}
// Deselect previous items if so desired
if (deselectPrevious) {
deselectAll();
}
// we'll ensure GUI state from top down even though selection
// was the opposite way
if (!startRow.isBefore(endRow)) {
VScrollTableRow tmp = startRow;
startRow = endRow;
endRow = tmp;
}
SelectionRange range = new SelectionRange(startRow, endRow);
for (Widget w : scrollBody) {
VScrollTableRow row = (VScrollTableRow) w;
if (range.inRange(row)) {
if (!row.isSelected()) {
row.toggleSelection();
}
selectedRowKeys.add(row.getKey());
}
}
// Add range
if (startRow != endRow) {
selectedRowRanges.add(range);
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.ui.IActionOwner#getActions ()
*/
public Action[] getActions() {
if (actionKeys == null) {
return new Action[] {};
}
final Action[] actions = new Action[actionKeys.length];
for (int i = 0; i < actions.length; i++) {
final String actionKey = actionKeys[i];
final TreeAction a = new TreeAction(this,
String.valueOf(rowKey), actionKey) {
@Override
public void execute() {
super.execute();
lazyRevertFocusToRow(VScrollTableRow.this);
}
};
a.setCaption(getActionCaption(actionKey));
a.setIconUrl(getActionIcon(actionKey));
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
public RenderSpace getAllocatedSpace(Widget child) {
int w = 0;
int i = getColIndexOf(child);
HeaderCell headerCell = tHead.getHeaderCell(i);
if (headerCell != null) {
if (initializedAndAttached) {
w = headerCell.getWidth();
} else {
// header offset width is not absolutely correct value,
// but a best guess (expecting similar content in all
// columns ->
// if one component is relative width so are others)
w = headerCell.getOffsetWidth() - getCellExtraWidth();
}
}
return new RenderSpace(w, 0) {
@Override
public int getHeight() {
return (int) getRowHeight();
}
};
}
private int getColIndexOf(Widget child) {
com.google.gwt.dom.client.Element widgetCell = child
.getElement().getParentElement().getParentElement();
NodeList<TableCellElement> cells = rowElement.getCells();
for (int i = 0; i < cells.getLength(); i++) {
if (cells.getItem(i) == widgetCell) {
return i;
}
}
return -1;
}
public boolean hasChildComponent(Widget component) {
return childWidgets.contains(component);
}
public void replaceChildComponent(Widget oldComponent,
Widget newComponent) {
com.google.gwt.dom.client.Element parentElement = oldComponent
.getElement().getParentElement();
int index = childWidgets.indexOf(oldComponent);
oldComponent.removeFromParent();
parentElement.appendChild(newComponent.getElement());
childWidgets.add(index, newComponent);
adopt(newComponent);
}
public boolean requestLayout(Set<Paintable> children) {
// row size should never change and system wouldn't event
// survive as this is a kind of fake paitable
return true;
}
public void updateCaption(Paintable component, UIDL uidl) {
// NOP, not rendered
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Should never be called,
// Component container interface faked here to get layouts
// render properly
}
}
/**
* Ensure the component has a focus.
*
* TODO the current implementation simply always calls focus for the
* component. In case the Table at some point implements focus/blur
* listeners, this method needs to be evolved to conditionally call
* focus only if not currently focused.
*/
protected void ensureFocus() {
if (!hasFocus) {
scrollBodyPanel.setFocus(true);
}
}
}
/**
* Deselects all items
*/
public void deselectAll() {
for (Widget w : scrollBody) {
VScrollTableRow row = (VScrollTableRow) w;
if (row.isSelected()) {
row.toggleSelection();
}
}
// still ensure all selects are removed from (not necessary rendered)
selectedRowKeys.clear();
selectedRowRanges.clear();
// also notify server that it clears all previous selections (the client
// side does not know about the invisible ones)
instructServerToForgetPreviousSelections();
}
/**
* Used in multiselect mode when the client side knows that all selections
* are in the next request.
*/
private void instructServerToForgetPreviousSelections() {
client.updateVariable(paintableId, "clearSelections", true, false);
}
/**
* Determines the pagelength when the table height is fixed.
*/
public void updatePageLength() {
// Only update if visible and enabled
if (!isVisible() || !enabled) {
return;
}
if (scrollBody == null) {
return;
}
if (height == null || height.equals("")) {
return;
}
int rowHeight = (int) Math.round(scrollBody.getRowHeight());
int bodyH = scrollBodyPanel.getOffsetHeight();
int rowsAtOnce = bodyH / rowHeight;
boolean anotherPartlyVisible = ((bodyH % rowHeight) != 0);
if (anotherPartlyVisible) {
rowsAtOnce++;
}
if (pageLength != rowsAtOnce) {
pageLength = rowsAtOnce;
client.updateVariable(paintableId, "pagelength", pageLength, false);
if (!rendering) {
int currentlyVisible = scrollBody.lastRendered
- scrollBody.firstRendered;
if (currentlyVisible < pageLength
&& currentlyVisible < totalRows) {
// shake scrollpanel to fill empty space
scrollBodyPanel.setScrollPosition(scrollTop + 1);
scrollBodyPanel.setScrollPosition(scrollTop - 1);
}
}
}
}
@Override
public void setWidth(String width) {
if (this.width.equals(width)) {
return;
}
this.width = width;
if (width != null && !"".equals(width)) {
super.setWidth(width);
int innerPixels = getOffsetWidth() - getBorderWidth();
if (innerPixels < 0) {
innerPixels = 0;
}
setContentWidth(innerPixels);
// readjust undefined width columns
lazyAdjustColumnWidths.cancel();
lazyAdjustColumnWidths.schedule(LAZY_COLUMN_ADJUST_TIMEOUT);
} else {
// Undefined width
super.setWidth("");
// Readjust size of table
sizeInit();
// readjust undefined width columns
lazyAdjustColumnWidths.cancel();
lazyAdjustColumnWidths.schedule(LAZY_COLUMN_ADJUST_TIMEOUT);
}
/*
* setting width may affect wheter the component has scrollbars -> needs
* scrolling or not
*/
setProperTabIndex();
}
private static final int LAZY_COLUMN_ADJUST_TIMEOUT = 300;
private final Timer lazyAdjustColumnWidths = new Timer() {
/**
* Check for column widths, and available width, to see if we can fix
* column widths "optimally". Doing this lazily to avoid expensive
* calculation when resizing is not yet finished.
*/
@Override
public void run() {
Iterator<Widget> headCells = tHead.iterator();
int usedMinimumWidth = 0;
int totalExplicitColumnsWidths = 0;
float expandRatioDivider = 0;
int colIndex = 0;
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
if (hCell.isDefinedWidth()) {
totalExplicitColumnsWidths += hCell.getWidth();
usedMinimumWidth += hCell.getWidth();
} else {
usedMinimumWidth += hCell.getNaturalColumnWidth(colIndex);
expandRatioDivider += hCell.getExpandRatio();
}
colIndex++;
}
int availW = scrollBody.getAvailableWidth();
// Hey IE, are you really sure about this?
availW = scrollBody.getAvailableWidth();
int visibleCellCount = tHead.getVisibleCellCount();
availW -= scrollBody.getCellExtraWidth() * visibleCellCount;
if (willHaveScrollbars()) {
availW -= Util.getNativeScrollbarSize();
}
int extraSpace = availW - usedMinimumWidth;
if (extraSpace < 0) {
extraSpace = 0;
}
int totalUndefinedNaturaWidths = usedMinimumWidth
- totalExplicitColumnsWidths;
// we have some space that can be divided optimally
HeaderCell hCell;
colIndex = 0;
headCells = tHead.iterator();
while (headCells.hasNext()) {
hCell = (HeaderCell) headCells.next();
if (!hCell.isDefinedWidth()) {
int w = hCell.getNaturalColumnWidth(colIndex);
int newSpace;
if (expandRatioDivider > 0) {
// divide excess space by expand ratios
newSpace = (int) (w + extraSpace
* hCell.getExpandRatio() / expandRatioDivider);
} else {
if (totalUndefinedNaturaWidths != 0) {
// divide relatively to natural column widths
newSpace = w + extraSpace * w
/ totalUndefinedNaturaWidths;
} else {
newSpace = w;
}
}
setColWidth(colIndex, newSpace, false);
}
colIndex++;
}
if ((height == null || "".equals(height))
&& totalRows == pageLength) {
// fix body height (may vary if lazy loading is offhorizontal
// scrollbar appears/disappears)
int bodyHeight = scrollBody.getRequiredHeight();
boolean needsSpaceForHorizontalScrollbar = (availW < usedMinimumWidth);
if (needsSpaceForHorizontalScrollbar) {
bodyHeight += Util.getNativeScrollbarSize();
}
int heightBefore = getOffsetHeight();
scrollBodyPanel.setHeight(bodyHeight + "px");
if (heightBefore != getOffsetHeight()) {
Util.notifyParentOfSizeChange(VScrollTable.this, false);
}
}
scrollBody.reLayoutComponents();
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
});
forceRealignColumnHeaders();
}
};
private void forceRealignColumnHeaders() {
if (BrowserInfo.get().isIE()) {
/*
* IE does not fire onscroll event if scroll position is reverted to
* 0 due to the content element size growth. Ensure headers are in
* sync with content manually. Safe to use null event as we don't
* actually use the event object in listener.
*/
onScroll(null);
}
}
/**
* helper to set pixel size of head and body part
*
* @param pixels
*/
private void setContentWidth(int pixels) {
tHead.setWidth(pixels + "px");
scrollBodyPanel.setWidth(pixels + "px");
tFoot.setWidth(pixels + "px");
}
private int borderWidth = -1;
/**
* @return border left + border right
*/
private int getBorderWidth() {
if (borderWidth < 0) {
borderWidth = Util.measureHorizontalPaddingAndBorder(
scrollBodyPanel.getElement(), 2);
if (borderWidth < 0) {
borderWidth = 0;
}
}
return borderWidth;
}
/**
* Ensures scrollable area is properly sized. This method is used when fixed
* size is used.
*/
private int containerHeight;
private void setContainerHeight() {
if (height != null && !"".equals(height)) {
containerHeight = getOffsetHeight();
containerHeight -= showColHeaders ? tHead.getOffsetHeight() : 0;
containerHeight -= tFoot.getOffsetHeight();
containerHeight -= getContentAreaBorderHeight();
if (containerHeight < 0) {
containerHeight = 0;
}
scrollBodyPanel.setHeight(containerHeight + "px");
}
}
private int contentAreaBorderHeight = -1;
private int scrollLeft;
private int scrollTop;
private VScrollTableDropHandler dropHandler;
private boolean navKeyDown;
private boolean multiselectPending;
/**
* @return border top + border bottom of the scrollable area of table
*/
private int getContentAreaBorderHeight() {
if (contentAreaBorderHeight < 0) {
if (BrowserInfo.get().isIE7() || BrowserInfo.get().isIE6()) {
contentAreaBorderHeight = Util
.measureVerticalBorder(scrollBodyPanel.getElement());
} else {
DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
"hidden");
int oh = scrollBodyPanel.getOffsetHeight();
int ch = scrollBodyPanel.getElement().getPropertyInt(
"clientHeight");
contentAreaBorderHeight = oh - ch;
DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
"auto");
}
}
return contentAreaBorderHeight;
}
@Override
public void setHeight(String height) {
this.height = height;
super.setHeight(height);
setContainerHeight();
if (initializedAndAttached) {
updatePageLength();
}
if (!rendering) {
// Webkit may sometimes get an odd rendering bug (white space
// between header and body), see bug #3875. Running
// overflow hack here to shake body element a bit.
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
/*
* setting height may affect wheter the component has scrollbars ->
* needs scrolling or not
*/
setProperTabIndex();
}
/*
* Overridden due Table might not survive of visibility change (scroll pos
* lost). Example ITabPanel just set contained components invisible and back
* when changing tabs.
*/
@Override
public void setVisible(boolean visible) {
if (isVisible() != visible) {
super.setVisible(visible);
if (initializedAndAttached) {
if (visible) {
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
scrollBodyPanel
.setScrollPosition((int) (firstRowInViewPort * scrollBody
.getRowHeight()));
}
});
}
}
}
}
/**
* Helper function to build html snippet for column or row headers
*
* @param uidl
* possibly with values caption and icon
* @return html snippet containing possibly an icon + caption text
*/
protected String buildCaptionHtmlSnippet(UIDL uidl) {
String s = uidl.hasAttribute("caption") ? uidl
.getStringAttribute("caption") : "";
if (uidl.hasAttribute("icon")) {
s = "<img src=\""
+ client.translateVaadinUri(uidl.getStringAttribute("icon"))
+ "\" alt=\"icon\" class=\"v-icon\">" + s;
}
return s;
}
/**
* This method has logic which rows needs to be requested from server when
* user scrolls
*/
public void onScroll(ScrollEvent event) {
scrollLeft = scrollBodyPanel.getElement().getScrollLeft();
scrollTop = scrollBodyPanel.getScrollPosition();
if (!initializedAndAttached) {
return;
}
if (!enabled) {
scrollBodyPanel
.setScrollPosition((int) (firstRowInViewPort * scrollBody
.getRowHeight()));
return;
}
rowRequestHandler.cancel();
if (BrowserInfo.get().isSafari() && event != null && scrollTop == 0) {
// due to the webkitoverflowworkaround, top may sometimes report 0
// for webkit, although it really is not. Expecting to have the
// correct
// value available soon.
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
onScroll(null);
}
});
return;
}
// fix headers horizontal scrolling
tHead.setHorizontalScrollPosition(scrollLeft);
// fix footers horizontal scrolling
tFoot.setHorizontalScrollPosition(scrollLeft);
firstRowInViewPort = (int) Math.ceil(scrollTop
/ scrollBody.getRowHeight());
if (firstRowInViewPort > totalRows - pageLength) {
firstRowInViewPort = totalRows - pageLength;
}
int postLimit = (int) (firstRowInViewPort + (pageLength - 1) + pageLength
* cache_react_rate);
if (postLimit > totalRows - 1) {
postLimit = totalRows - 1;
}
int preLimit = (int) (firstRowInViewPort - pageLength
* cache_react_rate);
if (preLimit < 0) {
preLimit = 0;
}
final int lastRendered = scrollBody.getLastRendered();
final int firstRendered = scrollBody.getFirstRendered();
if (postLimit <= lastRendered && preLimit >= firstRendered) {
// remember which firstvisible we requested, in case the server has
// a differing opinion
lastRequestedFirstvisible = firstRowInViewPort;
client.updateVariable(paintableId, "firstvisible",
firstRowInViewPort, false);
return; // scrolled withing "non-react area"
}
if (firstRowInViewPort - pageLength * cache_rate > lastRendered
|| firstRowInViewPort + pageLength + pageLength * cache_rate < firstRendered) {
// need a totally new set
rowRequestHandler
.setReqFirstRow((firstRowInViewPort - (int) (pageLength * cache_rate)));
int last = firstRowInViewPort + (int) (cache_rate * pageLength)
+ pageLength - 1;
if (last >= totalRows) {
last = totalRows - 1;
}
rowRequestHandler.setReqRows(last
- rowRequestHandler.getReqFirstRow() + 1);
rowRequestHandler.deferRowFetch();
return;
}
if (preLimit < firstRendered) {
// need some rows to the beginning of the rendered area
rowRequestHandler
.setReqFirstRow((int) (firstRowInViewPort - pageLength
* cache_rate));
rowRequestHandler.setReqRows(firstRendered
- rowRequestHandler.getReqFirstRow());
rowRequestHandler.deferRowFetch();
return;
}
if (postLimit > lastRendered) {
// need some rows to the end of the rendered area
rowRequestHandler.setReqFirstRow(lastRendered + 1);
rowRequestHandler.setReqRows((int) ((firstRowInViewPort
+ pageLength + pageLength * cache_rate) - lastRendered));
rowRequestHandler.deferRowFetch();
}
}
public VScrollTableDropHandler getDropHandler() {
return dropHandler;
}
private static class TableDDDetails {
int overkey = -1;
VerticalDropLocation dropLocation;
String colkey;
@Override
public boolean equals(Object obj) {
if (obj instanceof TableDDDetails) {
TableDDDetails other = (TableDDDetails) obj;
return dropLocation == other.dropLocation
&& overkey == other.overkey
&& ((colkey != null && colkey.equals(other.colkey)) || (colkey == null && other.colkey == null));
}
return false;
}
// @Override
// public int hashCode() {
// return overkey;
// }
}
public class VScrollTableDropHandler extends VAbstractDropHandler {
private static final String ROWSTYLEBASE = "v-table-row-drag-";
private TableDDDetails dropDetails;
private TableDDDetails lastEmphasized;
@Override
public void dragEnter(VDragEvent drag) {
updateDropDetails(drag);
super.dragEnter(drag);
}
private void updateDropDetails(VDragEvent drag) {
dropDetails = new TableDDDetails();
Element elementOver = drag.getElementOver();
VScrollTableRow row = Util.findWidget(elementOver, getRowClass());
if (row != null) {
dropDetails.overkey = row.rowKey;
Element tr = row.getElement();
Element element = elementOver;
while (element != null && element.getParentElement() != tr) {
element = (Element) element.getParentElement();
}
int childIndex = DOM.getChildIndex(tr, element);
dropDetails.colkey = tHead.getHeaderCell(childIndex)
.getColKey();
dropDetails.dropLocation = DDUtil.getVerticalDropLocation(
row.getElement(), drag.getCurrentGwtEvent(), 0.2);
}
drag.getDropDetails().put("itemIdOver", dropDetails.overkey + "");
drag.getDropDetails().put(
"detail",
dropDetails.dropLocation != null ? dropDetails.dropLocation
.toString() : null);
}
private Class<? extends Widget> getRowClass() {
// get the row type this way to make dd work in derived
// implementations
return scrollBody.iterator().next().getClass();
}
@Override
public void dragOver(VDragEvent drag) {
TableDDDetails oldDetails = dropDetails;
updateDropDetails(drag);
if (!oldDetails.equals(dropDetails)) {
deEmphasis();
final TableDDDetails newDetails = dropDetails;
VAcceptCallback cb = new VAcceptCallback() {
public void accepted(VDragEvent event) {
if (newDetails.equals(dropDetails)) {
dragAccepted(event);
}
/*
* Else new target slot already defined, ignore
*/
}
};
validate(cb, drag);
}
}
@Override
public void dragLeave(VDragEvent drag) {
deEmphasis();
super.dragLeave(drag);
}
@Override
public boolean drop(VDragEvent drag) {
deEmphasis();
return super.drop(drag);
}
private void deEmphasis() {
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", false);
if (lastEmphasized == null) {
return;
}
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (lastEmphasized != null
&& row.rowKey == lastEmphasized.overkey) {
String stylename = ROWSTYLEBASE
+ lastEmphasized.dropLocation.toString()
.toLowerCase();
VScrollTableRow.setStyleName(row.getElement(), stylename,
false);
lastEmphasized = null;
return;
}
}
}
/**
* TODO needs different drop modes ?? (on cells, on rows), now only
* supports rows
*/
private void emphasis(TableDDDetails details) {
deEmphasis();
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", true);
// iterate old and new emphasized row
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (details != null && details.overkey == row.rowKey) {
String stylename = ROWSTYLEBASE
+ details.dropLocation.toString().toLowerCase();
VScrollTableRow.setStyleName(row.getElement(), stylename,
true);
lastEmphasized = details;
return;
}
}
}
@Override
protected void dragAccepted(VDragEvent drag) {
emphasis(dropDetails);
}
@Override
public Paintable getPaintable() {
return VScrollTable.this;
}
public ApplicationConnection getApplicationConnection() {
return client;
}
}
protected VScrollTableRow getFocusedRow() {
return focusedRow;
}
/**
* Moves the selection head to a specific row
*
* @param row
* The row to where the selection head should move
* @return Returns true if focus was moved successfully, else false
*/
private boolean setRowFocus(VScrollTableRow row) {
if (selectMode == SELECT_MODE_NONE) {
return false;
}
// Remove previous selection
if (focusedRow != null && focusedRow != row) {
focusedRow.removeStyleName(CLASSNAME_SELECTION_FOCUS);
}
if (row != null) {
// Apply focus style to new selection
row.addStyleName(CLASSNAME_SELECTION_FOCUS);
/*
* Trying to set focus on already focused row
*/
if (row == focusedRow) {
return false;
}
// Set new focused row
focusedRow = row;
ensureRowIsVisible(row);
return true;
}
return false;
}
/**
* Ensures that the row is visible
*
* @param row
* The row to ensure is visible
*/
private void ensureRowIsVisible(VScrollTableRow row) {
scrollIntoViewVertically(row.getElement());
}
/**
* Scrolls an element into view vertically only. Modified version of
* Element.scrollIntoView.
*
* @param elem
* The element to scroll into view
*/
private native void scrollIntoViewVertically(Element elem)
/*-{
var top = elem.offsetTop;
var height = elem.offsetHeight;
if (elem.parentNode != elem.offsetParent) {
top -= elem.parentNode.offsetTop;
}
var cur = elem.parentNode;
while (cur && (cur.nodeType == 1)) {
if (top < cur.scrollTop) {
cur.scrollTop = top;
}
if (top + height > cur.scrollTop + cur.clientHeight) {
cur.scrollTop = (top + height) - cur.clientHeight;
}
var offsetTop = cur.offsetTop;
if (cur.parentNode != cur.offsetParent) {
offsetTop -= cur.parentNode.offsetTop;
}
top += offsetTop - cur.scrollTop;
cur = cur.parentNode;
}
}-*/;
/**
* Handles the keyboard events handled by the table
*
* @param event
* The keyboard event received
* @return true iff the navigation event was handled
*/
protected boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
if (keycode == KeyCodes.KEY_TAB || keycode == KeyCodes.KEY_SHIFT) {
// Do not handle tab key
return false;
}
// Down navigation
if (selectMode == SELECT_MODE_NONE && keycode == getNavigationDownKey()) {
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() + scrollingVelocity);
return true;
} else if (keycode == getNavigationDownKey()) {
if (selectMode == SELECT_MODE_MULTI && moveFocusDown()) {
selectFocusedRow(ctrl, shift);
} else if (selectMode == SELECT_MODE_SINGLE && !shift
&& moveFocusDown()) {
selectFocusedRow(ctrl, shift);
}
return true;
}
// Up navigation
if (selectMode == SELECT_MODE_NONE && keycode == getNavigationUpKey()) {
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() - scrollingVelocity);
return true;
} else if (keycode == getNavigationUpKey()) {
if (selectMode == SELECT_MODE_MULTI && moveFocusUp()) {
selectFocusedRow(ctrl, shift);
} else if (selectMode == SELECT_MODE_SINGLE && !shift
&& moveFocusUp()) {
selectFocusedRow(ctrl, shift);
}
return true;
}
if (keycode == getNavigationLeftKey()) {
// Left navigation
scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
.getHorizontalScrollPosition() - scrollingVelocity);
return true;
} else if (keycode == getNavigationRightKey()) {
// Right navigation
scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
.getHorizontalScrollPosition() + scrollingVelocity);
return true;
}
// Select navigation
if (isSelectable() && keycode == getNavigationSelectKey()) {
if (selectMode == SELECT_MODE_SINGLE) {
boolean wasSelected = focusedRow.isSelected();
deselectAll();
if (!wasSelected || !nullSelectionAllowed) {
focusedRow.toggleSelection();
}
} else {
focusedRow.toggleSelection();
removeRowFromUnsentSelectionRanges(focusedRow);
}
sendSelectedRows();
return true;
}
// Page Down navigation
if (keycode == getNavigationPageDownKey()) {
if (isSelectable()) {
/*
* If selectable we plagiate MSW behaviour: first scroll to the
* end of current view. If at the end, scroll down one page
* length and keep the selected row in the bottom part of
* visible area.
*/
if (!isFocusAtTheEndOfTable()) {
VScrollTableRow lastVisibleRowInViewPort = scrollBody
.getRowByRowIndex(firstRowInViewPort
+ getFullyVisibleRowCount() - 1);
if (lastVisibleRowInViewPort != null
&& lastVisibleRowInViewPort != focusedRow) {
// focused row is not at the end of the table, move
// focus and select the last visible row
setRowFocus(lastVisibleRowInViewPort);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
} else {
int indexOfToBeFocused = focusedRow.getIndex()
+ getFullyVisibleRowCount();
if (indexOfToBeFocused >= totalRows) {
indexOfToBeFocused = totalRows - 1;
}
VScrollTableRow toBeFocusedRow = scrollBody
.getRowByRowIndex(indexOfToBeFocused);
if (toBeFocusedRow != null) {
/*
* if the next focused row is rendered
*/
setRowFocus(toBeFocusedRow);
selectFocusedRow(ctrl, shift);
// TODO needs scrollintoview ?
sendSelectedRows();
} else {
// scroll down by pixels and return, to wait for
// new rows, then select the last item in the
// viewport
selectLastItemInNextRender = true;
multiselectPending = shift;
scrollByPagelenght(1);
}
}
}
} else {
/* No selections, go page down by scrolling */
scrollByPagelenght(1);
}
return true;
}
// Page Up navigation
if (keycode == getNavigationPageUpKey()) {
if (isSelectable()) {
/*
* If selectable we plagiate MSW behaviour: first scroll to the
* end of current view. If at the end, scroll down one page
* length and keep the selected row in the bottom part of
* visible area.
*/
if (!isFocusAtTheBeginningOfTable()) {
VScrollTableRow firstVisibleRowInViewPort = scrollBody
.getRowByRowIndex(firstRowInViewPort);
if (firstVisibleRowInViewPort != null
&& firstVisibleRowInViewPort != focusedRow) {
// focus is not at the beginning of the table, move
// focus and select the first visible row
setRowFocus(firstVisibleRowInViewPort);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
} else {
int indexOfToBeFocused = focusedRow.getIndex()
- getFullyVisibleRowCount();
if (indexOfToBeFocused < 0) {
indexOfToBeFocused = 0;
}
VScrollTableRow toBeFocusedRow = scrollBody
.getRowByRowIndex(indexOfToBeFocused);
if (toBeFocusedRow != null) { // if the next focused row
// is rendered
setRowFocus(toBeFocusedRow);
selectFocusedRow(ctrl, shift);
// TODO needs scrollintoview ?
sendSelectedRows();
} else {
// unless waiting for the next rowset already
// scroll down by pixels and return, to wait for
// new rows, then select the last item in the
// viewport
selectFirstItemInNextRender = true;
multiselectPending = shift;
scrollByPagelenght(-1);
}
}
}
} else {
/* No selections, go page up by scrolling */
scrollByPagelenght(-1);
}
return true;
}
// Goto start navigation
if (keycode == getNavigationStartKey()) {
scrollBodyPanel.setScrollPosition(0);
if (isSelectable()) {
if (focusedRow != null && focusedRow.getIndex() == 0) {
return false;
} else {
VScrollTableRow rowByRowIndex = (VScrollTableRow) scrollBody
.iterator().next();
if (rowByRowIndex.getIndex() == 0) {
setRowFocus(rowByRowIndex);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
} else {
// first row of table will come in next row fetch
if (ctrl) {
focusFirstItemInNextRender = true;
} else {
selectFirstItemInNextRender = true;
multiselectPending = shift;
}
}
}
}
return true;
}
// Goto end navigation
if (keycode == getNavigationEndKey()) {
scrollBodyPanel.setScrollPosition(scrollBody.getOffsetHeight());
if (isSelectable()) {
final int lastRendered = scrollBody.getLastRendered();
if (lastRendered + 1 == totalRows) {
VScrollTableRow rowByRowIndex = scrollBody
.getRowByRowIndex(lastRendered);
if (focusedRow != rowByRowIndex) {
setRowFocus(rowByRowIndex);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
}
} else {
if (ctrl) {
focusLastItemInNextRender = true;
} else {
selectLastItemInNextRender = true;
multiselectPending = shift;
}
}
}
return true;
}
return false;
}
private boolean isFocusAtTheBeginningOfTable() {
return focusedRow.getIndex() == 0;
}
private boolean isFocusAtTheEndOfTable() {
return focusedRow.getIndex() + 1 >= totalRows;
}
private int getFullyVisibleRowCount() {
return (int) (scrollBodyPanel.getOffsetHeight() / scrollBody
.getRowHeight());
}
private void scrollByPagelenght(int i) {
int pixels = i
* (int) (getFullyVisibleRowCount() * scrollBody.getRowHeight());
int newPixels = scrollBodyPanel.getScrollPosition() + pixels;
if (newPixels < 0) {
newPixels = 0;
} // else if too high, NOP (all know browsers accept illegally big
// values here)
scrollBodyPanel.setScrollPosition(newPixels);
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
* .dom.client.FocusEvent)
*/
public void onFocus(FocusEvent event) {
if (isFocusable()) {
hasFocus = true;
// Focus a row if no row is in focus
if (focusedRow == null) {
focusRowFromBody();
} else {
setRowFocus(focusedRow);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
* .dom.client.BlurEvent)
*/
public void onBlur(BlurEvent event) {
hasFocus = false;
navKeyDown = false;
if (isFocusable()) {
// Unfocus any row
setRowFocus(null);
}
}
/**
* Removes a key from a range if the key is found in a selected range
*
* @param key
* The key to remove
*/
private void removeRowFromUnsentSelectionRanges(VScrollTableRow row) {
Collection<SelectionRange> newRanges = null;
for (Iterator<SelectionRange> iterator = selectedRowRanges.iterator(); iterator
.hasNext();) {
SelectionRange range = iterator.next();
if (range.inRange(row)) {
// Split the range if given row is in range
Collection<SelectionRange> splitranges = range.split(row);
if (newRanges == null) {
newRanges = new ArrayList<SelectionRange>();
}
newRanges.addAll(splitranges);
iterator.remove();
}
}
if (newRanges != null) {
selectedRowRanges.addAll(newRanges);
}
}
/**
* Can the Table be focused?
*
* @return True if the table can be focused, else false
*/
public boolean isFocusable() {
if (scrollBody != null && enabled) {
boolean hasVerticalScrollbars = scrollBody.getOffsetHeight() > scrollBodyPanel
.getOffsetHeight();
boolean hasHorizontalScrollbars = scrollBody.getOffsetWidth() > scrollBodyPanel
.getOffsetWidth();
return !(!hasHorizontalScrollbars && !hasVerticalScrollbars && selectMode == SELECT_MODE_NONE);
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.Focusable#focus()
*/
public void focus() {
if (isFocusable()) {
scrollBodyPanel.focus();
}
}
/**
* Sets the proper tabIndex for scrollBodyPanel (the focusable elemen in the
* component).
*
* If the component has no explicit tabIndex a zero is given (default
* tabbing order based on dom hierarchy) or -1 if the component does not
* need to gain focus. The component needs no focus if it has no scrollabars
* (not scrollable) and not selectable. Note that in the future shortcut
* actions may need focus.
*
*/
private void setProperTabIndex() {
int storedScrollTop = 0;
int storedScrollLeft = 0;
if (BrowserInfo.get().getOperaVersion() >= 11) {
// Workaround for Opera scroll bug when changing tabIndex (#6222)
storedScrollTop = scrollBodyPanel.getScrollPosition();
storedScrollLeft = scrollBodyPanel.getHorizontalScrollPosition();
}
if (tabIndex == 0 && !isFocusable()) {
scrollBodyPanel.setTabIndex(-1);
} else {
scrollBodyPanel.setTabIndex(tabIndex);
}
if (BrowserInfo.get().getOperaVersion() >= 11) {
// Workaround for Opera scroll bug when changing tabIndex (#6222)
scrollBodyPanel.setScrollPosition(storedScrollTop);
scrollBodyPanel.setHorizontalScrollPosition(storedScrollLeft);
}
}
public void startScrollingVelocityTimer() {
if (scrollingVelocityTimer == null) {
scrollingVelocityTimer = new Timer() {
@Override
public void run() {
scrollingVelocity++;
}
};
scrollingVelocityTimer.scheduleRepeating(100);
}
}
public void cancelScrollingVelocityTimer() {
if (scrollingVelocityTimer != null) {
// Remove velocityTimer if it exists and the Table is disabled
scrollingVelocityTimer.cancel();
scrollingVelocityTimer = null;
scrollingVelocity = 10;
}
}
/**
*
* @param keyCode
* @return true if the given keyCode is used by the table for navigation
*/
private boolean isNavigationKey(int keyCode) {
return keyCode == getNavigationUpKey()
|| keyCode == getNavigationLeftKey()
|| keyCode == getNavigationRightKey()
|| keyCode == getNavigationDownKey()
|| keyCode == getNavigationPageUpKey()
|| keyCode == getNavigationPageDownKey()
|| keyCode == getNavigationEndKey()
|| keyCode == getNavigationStartKey();
}
public void lazyRevertFocusToRow(final VScrollTableRow currentlyFocusedRow) {
Scheduler.get().scheduleFinally(new ScheduledCommand() {
public void execute() {
if (currentlyFocusedRow != null) {
setRowFocus(currentlyFocusedRow);
} else {
VConsole.log("no row?");
focusRowFromBody();
}
scrollBody.ensureFocus();
}
});
}
public Action[] getActions() {
if (bodyActionKeys == null) {
return new Action[] {};
}
final Action[] actions = new Action[bodyActionKeys.length];
for (int i = 0; i < actions.length; i++) {
final String actionKey = bodyActionKeys[i];
Action bodyAction = new TreeAction(this, null, actionKey);
bodyAction.setCaption(getActionCaption(actionKey));
bodyAction.setIconUrl(getActionIcon(actionKey));
actions[i] = bodyAction;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
/**
* Add this to the element mouse down event by using element.setPropertyJSO
* ("onselectstart",applyDisableTextSelectionIEHack()); Remove it then again
* when the mouse is depressed in the mouse up event.
*
* @return Returns the JSO preventing text selection
*/
private static native JavaScriptObject getPreventTextSelectionIEHack()
/*-{
return function(){ return false; };
}-*/;
}
| Code cleanup.
svn changeset:19990/svn branch:6.6
| src/com/vaadin/terminal/gwt/client/ui/VScrollTable.java | Code cleanup. | <ide><path>rc/com/vaadin/terminal/gwt/client/ui/VScrollTable.java
<ide>
<ide> public void setHorizontalScrollPosition(int scrollLeft) {
<ide> if (BrowserInfo.get().isIE6()) {
<del> hTableWrapper.getStyle().setProperty("position", "relative");
<del> hTableWrapper.getStyle().setPropertyPx("left", -scrollLeft);
<add> hTableWrapper.getStyle().setPosition(Position.RELATIVE);
<add> hTableWrapper.getStyle().setLeft(-scrollLeft, Unit.PX);
<ide> } else {
<ide> hTableWrapper.setScrollLeft(scrollLeft);
<ide> }
<ide>
<ide> public void setColumnCollapsingAllowed(boolean cc) {
<ide> if (cc) {
<del> DOM.setStyleAttribute(columnSelector, "display", "block");
<add> columnSelector.getStyle().setDisplay(Display.BLOCK);
<ide> } else {
<del> DOM.setStyleAttribute(columnSelector, "display", "none");
<add> columnSelector.getStyle().setDisplay(Display.NONE);
<ide> }
<ide> }
<ide>
<ide> public void disableBrowserIntelligence() {
<del> DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH
<del> + "px");
<add> hTableContainer.getStyle().setWidth(WRAPPER_WIDTH, Unit.PX);
<ide> }
<ide>
<ide> public void enableBrowserIntelligence() {
<del> DOM.setStyleAttribute(hTableContainer, "width", "");
<add> hTableContainer.getStyle().clearWidth();
<ide> }
<ide>
<ide> public void setHeaderCell(int index, HeaderCell cell) { |
|
JavaScript | bsd-3-clause | c97f002a878c7d480f2294fe16bb0261e49a33fc | 0 | splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js | var Backbone = require('backbone');
var Model = require('../../../src/core/model');
var VisModel = require('../../../src/vis/vis');
var RangeFilter = require('../../../src/windshaft/filters/range');
var HistogramDataviewModel = require('../../../src/dataviews/histogram-dataview-model');
describe('dataviews/histogram-dataview-model', function () {
beforeEach(function () {
this.map = jasmine.createSpyObj('map', ['getViewBounds', 'bind']);
this.map.getViewBounds.and.returnValue([[1, 2], [3, 4]]);
this.vis = new VisModel();
spyOn(this.vis, 'reload');
this.filter = new RangeFilter();
this.layer = new Model();
this.layer.getDataProvider = jasmine.createSpy('layer.getDataProvider');
this.analysisCollection = new Backbone.Collection();
spyOn(HistogramDataviewModel.prototype, 'listenTo').and.callThrough();
spyOn(HistogramDataviewModel.prototype, 'fetch').and.callThrough();
this.model = new HistogramDataviewModel({
source: { id: 'a0' }
}, {
map: this.map,
vis: this.vis,
layer: this.layer,
filter: this.filter,
analysisCollection: new Backbone.Collection()
});
});
it('defaults', function () {
expect(this.model.get('type')).toBe('histogram');
expect(this.model.get('bins')).toBe(10);
expect(this.model.get('totalAmount')).toBe(0);
expect(this.model.get('filteredAmount')).toBe(0);
});
it('should not listen any url change from the beginning', function () {
this.model.set('url', 'https://carto.com');
expect(this.model.fetch).not.toHaveBeenCalled();
});
it('should set unfiltered model url when model has changed it', function () {
spyOn(this.model._unfilteredData, 'setUrl');
this.model.set('url', 'hey!');
expect(this.model._unfilteredData.setUrl).toHaveBeenCalled();
});
it('should set the api_key attribute on the internal models', function () {
this.model = new HistogramDataviewModel({
apiKey: 'API_KEY',
source: { id: 'a0' }
}, {
map: this.map,
vis: this.vis,
layer: jasmine.createSpyObj('layer', ['get', 'getDataProvider']),
filter: this.filter,
analysisCollection: new Backbone.Collection()
});
expect(this.model._unfilteredData.get('apiKey')).toEqual('API_KEY');
});
describe('should get the correct histogram shape', function () {
beforeEach(function () {
this.model.set('bins', 6);
});
it('when it is flat', function () {
this.model.set('data', [
{bin: 0, freq: 25},
{bin: 1, freq: 26},
{bin: 2, freq: 25},
{bin: 3, freq: 26},
{bin: 4, freq: 26},
{bin: 5, freq: 25}
]);
expect(this.model.getDistributionType()).toEqual('F');
});
it('when it is A', function () {
this.model.set('data', [
{bin: 0, freq: 0},
{bin: 1, freq: 5},
{bin: 2, freq: 25},
{bin: 3, freq: 18},
{bin: 4, freq: 8},
{bin: 5, freq: 2}
]);
expect(this.model.getDistributionType()).toEqual('A');
});
it('when it is J', function () {
this.model.set('data', [
{bin: 0, freq: 0},
{bin: 1, freq: 2},
{bin: 2, freq: 5},
{bin: 3, freq: 8},
{bin: 4, freq: 18},
{bin: 5, freq: 25}
]);
expect(this.model.getDistributionType()).toEqual('J');
});
it('when it is L', function () {
this.model.set('data', [
{bin: 0, freq: 25},
{bin: 1, freq: 18},
{bin: 4, freq: 8},
{bin: 2, freq: 5},
{bin: 5, freq: 2},
{bin: 3, freq: 0}
]);
expect(this.model.getDistributionType()).toEqual('L');
});
xit('when it is clustered', function () {
this.model.set('data', [
{bin: 0, freq: 20},
{bin: 1, freq: 18},
{bin: 2, freq: 5},
{bin: 3, freq: 0},
{bin: 4, freq: 32},
{bin: 5, freq: 16}
]);
expect(this.model.getDistributionType()).toEqual('C');
});
});
describe('on unfiltered data model fetch', function () {
beforeEach(function () {
var histogramData = {
'bin_width': 10,
'bins_count': 3,
'bins_start': 1,
'nulls': 0
};
spyOn(this.model._unfilteredData, 'sync').and.callFake(function (method, model, options) {
options.success(histogramData);
});
});
it('should calculate start, end and bins', function () {
expect(this.model.get('start')).toBeUndefined();
expect(this.model.get('end')).toBeUndefined();
this.model._unfilteredData.fetch();
expect(this.model.get('start')).toEqual(1);
expect(this.model.get('end')).toEqual(31);
expect(this.model.get('bins')).toEqual(3);
});
it('should run _onChangeBins', function () {
spyOn(this.model, '_onChangeBinds');
this.model._unfilteredData.fetch();
expect(this.model._onChangeBinds).toHaveBeenCalled();
});
});
describe('when column changes', function () {
it('should reload map and force fetch', function () {
this.vis.reload.calls.reset();
this.model.set('column', 'random_col');
expect(this.vis.reload).toHaveBeenCalledWith({ forceFetch: true, sourceId: 'a0' });
});
});
describe('when bins change', function () {
beforeEach(function () {
this.vis.reload.calls.reset();
spyOn(this.model.filter, 'unsetRange');
this.model.set('bins', 123);
});
it('should refresh data on bins change', function () {
expect(this.vis.reload).not.toHaveBeenCalled();
expect(this.model.fetch).toHaveBeenCalled();
});
it('should disable filter', function () {
expect(this.model.get('own_filter')).toBeUndefined();
});
it('should unset range filter', function () {
expect(this.model.filter.unsetRange).toHaveBeenCalled();
});
});
describe('when start change', function () {
beforeEach(function () {
this.vis.reload.calls.reset();
spyOn(this.model.filter, 'unsetRange');
this.model.set('start', 0);
});
it('should refresh data on bins change', function () {
expect(this.vis.reload).not.toHaveBeenCalled();
expect(this.model.fetch).toHaveBeenCalled();
});
it('should disable filter', function () {
expect(this.model.get('own_filter')).toBeUndefined();
});
it('should unset range filter', function () {
expect(this.model.filter.unsetRange).toHaveBeenCalled();
});
});
describe('when end change', function () {
beforeEach(function () {
this.vis.reload.calls.reset();
spyOn(this.model.filter, 'unsetRange');
this.model.set('end', 0);
});
it('should refresh data on bins change', function () {
expect(this.vis.reload).not.toHaveBeenCalled();
expect(this.model.fetch).toHaveBeenCalled();
});
it('should disable filter', function () {
expect(this.model.get('own_filter')).toBeUndefined();
});
it('should unset range filter', function () {
expect(this.model.filter.unsetRange).toHaveBeenCalled();
});
});
it('should parse the bins', function () {
var data = {
bin_width: 14490.25,
bins: [
{ bin: 0, freq: 2, max: 70151, min: 55611 },
{ bin: 1, freq: 2, max: 79017, min: 78448 },
{ bin: 3, freq: 1, max: 113572, min: 113572 }
],
bins_count: 4,
bins_start: 55611,
nulls: 0,
type: 'histogram'
};
this.model.parse(data);
var parsedData = this.model.getData();
expect(data.nulls).toBe(0);
expect(parsedData.length).toBe(4);
expect(JSON.stringify(parsedData)).toBe('[{"bin":0,"start":55611,"end":70101.25,"freq":2,"max":70151,"min":55611},{"bin":1,"start":70101.25,"end":84591.5,"freq":2,"max":79017,"min":78448},{"bin":2,"start":84591.5,"end":99081.75,"freq":0},{"bin":3,"start":99081.75,"end":113572,"freq":1,"max":113572,"min":113572}]');
});
it('should calculate total amount and filtered amount in parse when a filter is present', function () {
var data = {
bin_width: 1,
bins: [
{ bin: 0, freq: 2 },
{ bin: 1, freq: 3 },
{ bin: 2, freq: 7 }
],
bins_count: 3,
bins_start: 1,
nulls: 0,
type: 'histogram'
};
this.model.filter = new RangeFilter({ min: 1, max: 3 });
var parsedData = this.model.parse(data);
expect(parsedData.totalAmount).toBe(12);
expect(parsedData.filteredAmount).toBe(5);
});
it('should calculate only total amount in parse when there is no filter', function () {
var data = {
bin_width: 1,
bins: [
{ bin: 0, freq: 2 },
{ bin: 1, freq: 3 },
{ bin: 2, freq: 7 }
],
bins_count: 3,
bins_start: 1,
nulls: 0,
type: 'histogram'
};
var parsedData = this.model.parse(data);
expect(parsedData.totalAmount).toBe(12);
expect(parsedData.filteredAmount).toBe(0);
});
it('parser do not fails when there are no bins', function () {
var data = {
bin_width: 0,
bins: [],
bins_count: 0,
bins_start: 0,
nulls: 0,
type: 'histogram'
};
this.model.parse(data);
var parsedData = this.model.getData();
expect(data.nulls).toBe(0);
expect(parsedData.length).toBe(0);
});
it('should parse the bins and fix end bucket issues', function () {
var data = {
'bin_width': 1041.66645833333,
'bins_count': 48,
'bins_start': 0.01,
'nulls': 0,
'avg': 55.5007561961441,
'bins': [{
'bin': 47,
'min': 50000,
'max': 50000,
'avg': 50000,
'freq': 6
// NOTE - The end of this bucket is 48 * 1041.66645833333 = 49999.98999999984
// but it must be corrected to 50.000.
}],
'type': 'histogram'
};
this.model.parse(data);
var parsedData = this.model.getData();
expect(data.nulls).toBe(0);
expect(parsedData.length).toBe(48);
expect(parsedData[47].end).not.toBeLessThan(parsedData[47].max);
});
describe('when layer changes meta', function () {
beforeEach(function () {
expect(this.model.filter.get('column_type')).not.toEqual('date');
this.model.layer.set({
meta: {
column_type: 'date'
}
});
});
it('should change the filter column_type', function () {
expect(this.model.filter.get('column_type')).toEqual('date');
});
});
describe('.url', function () {
it('should include bbox and initial bins', function () {
this.model.set('url', 'http://example.com');
expect(this.model.url()).toEqual('http://example.com?bbox=2,1,4,3&bins=10');
});
it('should include start, end and bins when own_filter is enabled', function () {
this.model.set({
'url': 'http://example.com',
'start': 0,
'end': 10,
'bins': 25
});
expect(this.model.url()).toEqual('http://example.com?bbox=2,1,4,3&start=0&end=10&bins=25');
this.model.enableFilter();
expect(this.model.url()).toEqual('http://example.com?bbox=2,1,4,3&own_filter=1');
});
});
describe('.enableFilter', function () {
it('should set the own_filter attribute', function () {
expect(this.model.get('own_filter')).toBeUndefined();
this.model.enableFilter();
expect(this.model.get('own_filter')).toEqual(1);
});
});
describe('.disableFilter', function () {
it('should unset the own_filter attribute', function () {
this.model.enableFilter();
this.model.disableFilter();
expect(this.model.get('own_filter')).toBeUndefined();
});
});
});
| test/spec/dataviews/histogram-dataview-model.spec.js | var Backbone = require('backbone');
var Model = require('../../../src/core/model');
var VisModel = require('../../../src/vis/vis');
var RangeFilter = require('../../../src/windshaft/filters/range');
var HistogramDataviewModel = require('../../../src/dataviews/histogram-dataview-model');
describe('dataviews/histogram-dataview-model', function () {
beforeEach(function () {
this.map = jasmine.createSpyObj('map', ['getViewBounds', 'bind']);
this.map.getViewBounds.and.returnValue([[1, 2], [3, 4]]);
this.vis = new VisModel();
spyOn(this.vis, 'reload');
this.filter = new RangeFilter();
this.layer = new Model();
this.layer.getDataProvider = jasmine.createSpy('layer.getDataProvider');
this.analysisCollection = new Backbone.Collection();
spyOn(HistogramDataviewModel.prototype, 'listenTo').and.callThrough();
spyOn(HistogramDataviewModel.prototype, 'fetch').and.callThrough();
this.model = new HistogramDataviewModel({
source: { id: 'a0' }
}, {
map: this.map,
vis: this.vis,
layer: this.layer,
filter: this.filter,
analysisCollection: new Backbone.Collection()
});
});
it('defaults', function () {
expect(this.model.get('type')).toBe('histogram');
expect(this.model.get('bins')).toBe(10);
expect(this.model.get('totalAmount')).toBe(0);
expect(this.model.get('filteredAmount')).toBe(0);
});
it('should not listen any url change from the beginning', function () {
this.model.set('url', 'https://carto.com');
expect(this.model.fetch).not.toHaveBeenCalled();
});
it('should set unfiltered model url when model has changed it', function () {
spyOn(this.model._unfilteredData, 'setUrl');
this.model.set('url', 'hey!');
expect(this.model._unfilteredData.setUrl).toHaveBeenCalled();
});
it('should set the api_key attribute on the internal models', function () {
this.model = new HistogramDataviewModel({
apiKey: 'API_KEY',
source: { id: 'a0' }
}, {
map: this.map,
vis: this.vis,
layer: jasmine.createSpyObj('layer', ['get', 'getDataProvider']),
filter: this.filter,
analysisCollection: new Backbone.Collection()
});
expect(this.model._unfilteredData.get('apiKey')).toEqual('API_KEY');
});
describe('should get the correct histogram shape', function () {
beforeEach(function () {
this.model.set('bins', 6);
});
it('when it is flat', function () {
this.model.set('data', [
{bin: 0, freq: 25},
{bin: 1, freq: 26},
{bin: 2, freq: 25},
{bin: 3, freq: 26},
{bin: 4, freq: 26},
{bin: 5, freq: 25}
]);
expect(this.model.getDistributionType()).toEqual('F');
});
it('when it is A', function () {
this.model.set('data', [
{bin: 0, freq: 0},
{bin: 1, freq: 5},
{bin: 2, freq: 25},
{bin: 3, freq: 18},
{bin: 4, freq: 8},
{bin: 5, freq: 2}
]);
expect(this.model.getDistributionType()).toEqual('A');
});
it('when it is J', function () {
this.model.set('data', [
{bin: 0, freq: 0},
{bin: 1, freq: 2},
{bin: 2, freq: 5},
{bin: 3, freq: 8},
{bin: 4, freq: 18},
{bin: 5, freq: 25}
]);
expect(this.model.getDistributionType()).toEqual('J');
});
it('when it is L', function () {
this.model.set('data', [
{bin: 0, freq: 25},
{bin: 1, freq: 18},
{bin: 4, freq: 8},
{bin: 2, freq: 5},
{bin: 5, freq: 2},
{bin: 3, freq: 0}
]);
expect(this.model.getDistributionType()).toEqual('L');
});
xit('when it is clustered', function () {
this.model.set('data', [
{bin: 0, freq: 20},
{bin: 1, freq: 18},
{bin: 2, freq: 5},
{bin: 3, freq: 0},
{bin: 4, freq: 32},
{bin: 5, freq: 16}
]);
expect(this.model.getDistributionType()).toEqual('C');
});
});
describe('on unfiltered data model fetch', function () {
beforeEach(function () {
var histogramData = {
'bin_width': 10,
'bins_count': 3,
'bins_start': 1,
'nulls': 0
};
spyOn(this.model._unfilteredData, 'sync').and.callFake(function (method, model, options) {
options.success(histogramData);
});
});
it('should calculate start, end and bins', function () {
expect(this.model.get('start')).toBeUndefined();
expect(this.model.get('end')).toBeUndefined();
this.model._unfilteredData.fetch();
expect(this.model.get('start')).toEqual(1);
expect(this.model.get('end')).toEqual(31);
expect(this.model.get('bins')).toEqual(3);
});
it('should run _onChangeBins', function () {
spyOn(this.model, '_onChangeBinds');
this.model._unfilteredData.fetch();
expect(this.model._onChangeBinds).toHaveBeenCalled();
});
});
describe('when column changes', function () {
it('should reload map and force fetch', function () {
this.vis.reload.calls.reset();
this.model.set('column', 'random_col');
expect(this.vis.reload).toHaveBeenCalledWith({ forceFetch: true, sourceId: 'a0' });
});
});
describe('when bins change', function () {
beforeEach(function () {
this.vis.reload.calls.reset();
spyOn(this.model.filter, 'unsetRange');
this.model.set('bins', 123);
});
it('should refresh data on bins change', function () {
expect(this.vis.reload).not.toHaveBeenCalled();
expect(this.model.fetch).toHaveBeenCalled();
});
it('should disable filter', function () {
expect(this.model.get('own_filter')).toBeUndefined();
});
it('should unset range filter', function () {
expect(this.model.filter.unsetRange).toHaveBeenCalled();
});
});
describe('when start change', function () {
beforeEach(function () {
this.vis.reload.calls.reset();
spyOn(this.model.filter, 'unsetRange');
this.model.set('start', 0);
});
it('should refresh data on bins change', function () {
expect(this.vis.reload).not.toHaveBeenCalled();
expect(this.model.fetch).toHaveBeenCalled();
});
it('should disable filter', function () {
expect(this.model.get('own_filter')).toBeUndefined();
});
it('should unset range filter', function () {
expect(this.model.filter.unsetRange).toHaveBeenCalled();
});
});
describe('when end change', function () {
beforeEach(function () {
this.vis.reload.calls.reset();
spyOn(this.model.filter, 'unsetRange');
this.model.set('end', 0);
});
it('should refresh data on bins change', function () {
expect(this.vis.reload).not.toHaveBeenCalled();
expect(this.model.fetch).toHaveBeenCalled();
});
it('should disable filter', function () {
expect(this.model.get('own_filter')).toBeUndefined();
});
it('should unset range filter', function () {
expect(this.model.filter.unsetRange).toHaveBeenCalled();
});
});
it('should parse the bins', function () {
var data = {
bin_width: 14490.25,
bins: [
{ bin: 0, freq: 2, max: 70151, min: 55611 },
{ bin: 1, freq: 2, max: 79017, min: 78448 },
{ bin: 3, freq: 1, max: 113572, min: 113572 }
],
bins_count: 4,
bins_start: 55611,
nulls: 0,
type: 'histogram'
};
this.model.parse(data);
var parsedData = this.model.getData();
expect(data.nulls).toBe(0);
expect(parsedData.length).toBe(4);
expect(JSON.stringify(parsedData)).toBe('[{"bin":0,"start":55611,"end":70101.25,"freq":2,"max":70151,"min":55611},{"bin":1,"start":70101.25,"end":84591.5,"freq":2,"max":79017,"min":78448},{"bin":2,"start":84591.5,"end":99081.75,"freq":0},{"bin":3,"start":99081.75,"end":113572,"freq":1,"max":113572,"min":113572}]');
});
it('should calculate total amount and filtered amount in parse', function () {
var data = {
bin_width: 1,
bins: [
{ bin: 0, freq: 2 },
{ bin: 1, freq: 3 },
{ bin: 2, freq: 7 }
],
bins_count: 3,
bins_start: 1,
nulls: 0,
type: 'histogram'
};
this.model.filter = new RangeFilter({ min: 1, max: 3 });
var parsedData = this.model.parse(data);
expect(parsedData.totalAmount).toBe(12);
expect(parsedData.filteredAmount).toBe(5);
});
it('parser do not fails when there are no bins', function () {
var data = {
bin_width: 0,
bins: [],
bins_count: 0,
bins_start: 0,
nulls: 0,
type: 'histogram'
};
this.model.parse(data);
var parsedData = this.model.getData();
expect(data.nulls).toBe(0);
expect(parsedData.length).toBe(0);
});
it('should parse the bins and fix end bucket issues', function () {
var data = {
'bin_width': 1041.66645833333,
'bins_count': 48,
'bins_start': 0.01,
'nulls': 0,
'avg': 55.5007561961441,
'bins': [{
'bin': 47,
'min': 50000,
'max': 50000,
'avg': 50000,
'freq': 6
// NOTE - The end of this bucket is 48 * 1041.66645833333 = 49999.98999999984
// but it must be corrected to 50.000.
}],
'type': 'histogram'
};
this.model.parse(data);
var parsedData = this.model.getData();
expect(data.nulls).toBe(0);
expect(parsedData.length).toBe(48);
expect(parsedData[47].end).not.toBeLessThan(parsedData[47].max);
});
describe('when layer changes meta', function () {
beforeEach(function () {
expect(this.model.filter.get('column_type')).not.toEqual('date');
this.model.layer.set({
meta: {
column_type: 'date'
}
});
});
it('should change the filter column_type', function () {
expect(this.model.filter.get('column_type')).toEqual('date');
});
});
describe('.url', function () {
it('should include bbox and initial bins', function () {
this.model.set('url', 'http://example.com');
expect(this.model.url()).toEqual('http://example.com?bbox=2,1,4,3&bins=10');
});
it('should include start, end and bins when own_filter is enabled', function () {
this.model.set({
'url': 'http://example.com',
'start': 0,
'end': 10,
'bins': 25
});
expect(this.model.url()).toEqual('http://example.com?bbox=2,1,4,3&start=0&end=10&bins=25');
this.model.enableFilter();
expect(this.model.url()).toEqual('http://example.com?bbox=2,1,4,3&own_filter=1');
});
});
describe('.enableFilter', function () {
it('should set the own_filter attribute', function () {
expect(this.model.get('own_filter')).toBeUndefined();
this.model.enableFilter();
expect(this.model.get('own_filter')).toEqual(1);
});
});
describe('.disabeFilter', function () {
it('should unset the own_filter attribute', function () {
this.model.enableFilter();
this.model.disableFilter();
expect(this.model.get('own_filter')).toBeUndefined();
});
});
describe('._sumBinsFreq', function () {
it('returns the sum of the freq in a range', function () {
var data = new Backbone.Collection([
{ freq: 33 },
{ freq: 44 }
]);
expect(this.model._sumBinsFreq(data, 0, 1)).toEqual(77);
});
});
describe('._findBinsIndexes', function () {
it('returns an object with the start and end bins', function () {
var data = new Backbone.Collection([
{ bin: 0, start: 1, end: 4 },
{ bin: 1, start: 4, end: 7 },
{ bin: 1, start: 7, end: 9 }
]);
expect(this.model._findBinsIndexes(data, 1, 7)).toEqual({
start: 0,
end: 1
});
});
});
describe('._calculateTotalAmount', function () {
it('returns the sum of all the freqs', function () {
var data = [
{ freq: 10 },
{ freq: 20 },
{ freq: 30 }
];
expect(this.model._calculateTotalAmount(data)).toEqual(60);
});
});
describe('._calculateFilteredAmount', function () {
it('calls ._findBinsIndexes and ._sumBinsFreq with the correct data', function () {
spyOn(this.model, '_findBinsIndexes').and.callThrough();
spyOn(this.model, '_sumBinsFreq').and.callThrough();
var data = new Backbone.Collection([
{ bin: 0, start: 1, end: 4, freq: 33 },
{ bin: 1, start: 4, end: 7, freq: 44 }
]);
this.filter = new RangeFilter({ min: 1, max: 7 });
var filteredAmount = this.model._calculateFilteredAmount(this.filter, data);
expect(this.model._findBinsIndexes).toHaveBeenCalledWith(data, 1, 7);
expect(this.model._sumBinsFreq).toHaveBeenCalledWith(data, 0, 1);
expect(filteredAmount).toEqual(77);
});
});
describe('._onFilterChanged', function () {
it('sets the model filteredAmount to ._calculateFilterAmount value', function () {
spyOn(this.model, '_calculateFilteredAmount').and.returnValue(123);
var filter = new RangeFilter({ min: 1, max: 7 });
this.model._onFilterChanged(filter);
expect(this.model._calculateFilteredAmount).toHaveBeenCalled();
expect(this.model.get('filteredAmount')).toEqual(123);
});
});
});
| Remove spec of private functions
| test/spec/dataviews/histogram-dataview-model.spec.js | Remove spec of private functions | <ide><path>est/spec/dataviews/histogram-dataview-model.spec.js
<ide> expect(JSON.stringify(parsedData)).toBe('[{"bin":0,"start":55611,"end":70101.25,"freq":2,"max":70151,"min":55611},{"bin":1,"start":70101.25,"end":84591.5,"freq":2,"max":79017,"min":78448},{"bin":2,"start":84591.5,"end":99081.75,"freq":0},{"bin":3,"start":99081.75,"end":113572,"freq":1,"max":113572,"min":113572}]');
<ide> });
<ide>
<del> it('should calculate total amount and filtered amount in parse', function () {
<add> it('should calculate total amount and filtered amount in parse when a filter is present', function () {
<ide> var data = {
<ide> bin_width: 1,
<ide> bins: [
<ide>
<ide> expect(parsedData.totalAmount).toBe(12);
<ide> expect(parsedData.filteredAmount).toBe(5);
<add> });
<add>
<add> it('should calculate only total amount in parse when there is no filter', function () {
<add> var data = {
<add> bin_width: 1,
<add> bins: [
<add> { bin: 0, freq: 2 },
<add> { bin: 1, freq: 3 },
<add> { bin: 2, freq: 7 }
<add> ],
<add> bins_count: 3,
<add> bins_start: 1,
<add> nulls: 0,
<add> type: 'histogram'
<add> };
<add>
<add> var parsedData = this.model.parse(data);
<add>
<add> expect(parsedData.totalAmount).toBe(12);
<add> expect(parsedData.filteredAmount).toBe(0);
<ide> });
<ide>
<ide> it('parser do not fails when there are no bins', function () {
<ide> });
<ide> });
<ide>
<del> describe('.disabeFilter', function () {
<add> describe('.disableFilter', function () {
<ide> it('should unset the own_filter attribute', function () {
<ide> this.model.enableFilter();
<ide> this.model.disableFilter();
<ide> expect(this.model.get('own_filter')).toBeUndefined();
<ide> });
<ide> });
<del>
<del> describe('._sumBinsFreq', function () {
<del> it('returns the sum of the freq in a range', function () {
<del> var data = new Backbone.Collection([
<del> { freq: 33 },
<del> { freq: 44 }
<del> ]);
<del> expect(this.model._sumBinsFreq(data, 0, 1)).toEqual(77);
<del> });
<del> });
<del>
<del> describe('._findBinsIndexes', function () {
<del> it('returns an object with the start and end bins', function () {
<del> var data = new Backbone.Collection([
<del> { bin: 0, start: 1, end: 4 },
<del> { bin: 1, start: 4, end: 7 },
<del> { bin: 1, start: 7, end: 9 }
<del> ]);
<del> expect(this.model._findBinsIndexes(data, 1, 7)).toEqual({
<del> start: 0,
<del> end: 1
<del> });
<del> });
<del> });
<del>
<del> describe('._calculateTotalAmount', function () {
<del> it('returns the sum of all the freqs', function () {
<del> var data = [
<del> { freq: 10 },
<del> { freq: 20 },
<del> { freq: 30 }
<del> ];
<del> expect(this.model._calculateTotalAmount(data)).toEqual(60);
<del> });
<del> });
<del>
<del> describe('._calculateFilteredAmount', function () {
<del> it('calls ._findBinsIndexes and ._sumBinsFreq with the correct data', function () {
<del> spyOn(this.model, '_findBinsIndexes').and.callThrough();
<del> spyOn(this.model, '_sumBinsFreq').and.callThrough();
<del>
<del> var data = new Backbone.Collection([
<del> { bin: 0, start: 1, end: 4, freq: 33 },
<del> { bin: 1, start: 4, end: 7, freq: 44 }
<del> ]);
<del> this.filter = new RangeFilter({ min: 1, max: 7 });
<del>
<del> var filteredAmount = this.model._calculateFilteredAmount(this.filter, data);
<del>
<del> expect(this.model._findBinsIndexes).toHaveBeenCalledWith(data, 1, 7);
<del> expect(this.model._sumBinsFreq).toHaveBeenCalledWith(data, 0, 1);
<del> expect(filteredAmount).toEqual(77);
<del> });
<del> });
<del>
<del> describe('._onFilterChanged', function () {
<del> it('sets the model filteredAmount to ._calculateFilterAmount value', function () {
<del> spyOn(this.model, '_calculateFilteredAmount').and.returnValue(123);
<del> var filter = new RangeFilter({ min: 1, max: 7 });
<del>
<del> this.model._onFilterChanged(filter);
<del>
<del> expect(this.model._calculateFilteredAmount).toHaveBeenCalled();
<del> expect(this.model.get('filteredAmount')).toEqual(123);
<del> });
<del> });
<ide> }); |
|
JavaScript | mit | 7ed7f8d650604b927cbbb5390840b3e1fa93d7d2 | 0 | wasi0013/wasi0013.github.io,wasi0013/wasi0013.github.io | var x
var y
var dx
var dy
var c
var width=300
var height=300
var paddlex,paddleh = 10,paddlew = 75
var rightDown = false,leftDown = false
var canvasMinX, canvasMaxX
var intervalId
var bricks
var rows = 5
var columns = 5
var brickwidth
var brickheight = 15
var padding = 1
var ballr = 10
var rowcolors = ["#FF1C0A", "#FFFD0A", "#00A308", "#0008DB", "#EB0093"]
var paddlecolor = "#FFFFFF"
var ballcolor = "#FFFFFF"
var backcolor = "#000000"
var counter=0, score=0,multiplier=1,highscore=0
function knuth_shuffle(array) {
//implementation of knuth_suffle algorithm
var i, tmp, rnd
for(i = array.length; 0!==i ;i--) {
rnd = Math.floor(Math.random() * i)
tmp = array[i]
array[i] = array[rnd]
array[rnd] = tmp
}
return array
}
function init() {
$("#start").attr('disabled','disabled')
c = $('#canvas')[0].getContext("2d")
paddlex = width / 2
brickwidth = (width/columns) - 1
canvasMinX = $("#canvas").offset().left
canvasMaxX = canvasMinX + width
x = 25
y = 250
dx = 1.5
dy = -4
paddleh = 10
paddlew = 75
rightDown = false
leftDown = false
rows = 5
columns = 5
brickheight = 15
padding = 1
ballRadius = 10
rowcolors = ["red", "green", "yellow", "blue", "violet","orange","white"]
rowcolors =knuth_shuffle(rowcolors)
paddlecolor = "white"
ballcolor = "white"
backcolor = "black"
initbricks()
intervalId = setInterval(draw, 10)
multiplier=1
}
function circle(x,y,r) {
c.beginPath()
c.arc(x, y, r, 0, Math.PI*2, true)
c.closePath()
c.fill()
}
function rect(x,y,w,h) {
c.beginPath()
c.rect(x,y,w,h)
c.closePath()
c.fill()
}
function clear() {
c.clearRect(0, 0, width, height)
rect(0,0,width,height)
}
function onKeyDown(evt) {
if (evt.keyCode == 39) rightDown = true
else if (evt.keyCode == 37) leftDown = true
}
function onKeyUp(evt) {
if (evt.keyCode == 39) rightDown = false
else if (evt.keyCode == 37) leftDown = false
}
function onMouseMove(evt) {
if (evt.pageX > canvasMinX && evt.pageX < canvasMaxX) {
paddlex = Math.max(evt.pageX - canvasMinX - (paddlew/2), 0)
paddlex = Math.min(width - paddlew, paddlex)
}
}
function initbricks() {
bricks = new Array(rows)
for (i=0 ;i < rows; i++) {
bricks[i] = new Array(columns)
for (j=0; j < columns; j++) {
bricks[i][j] = 1
}
}
}
function drawbricks() {
for (i=0; i < rows; i++) {
c.fillStyle = rowcolors[i]
for (j=0; j < columns; j++) {
if (bricks[i][j] == 1) {
rect((j* (brickwidth + padding)) + padding,
(i * (brickheight + padding)) + padding,
brickwidth, brickheight)
}
}
}
}
function startScreen(){
c = $('#canvas')[0].getContext("2d")
c.fillStyle="black"
rect(0,0,width,height)
c.fillStyle="white"
c.font="bold 20px 'Century Gothic', Arial"
c.fillText("Classic Brick Breaker",50,150)
c.font="bold 14px 'Century Gothic', Arial"
c.fillText("Click Start! to play",90,180)
c.clearRect(300, 0, 370, 300)
c.fillStyle ="black"
rect(300, 0, 370, 300)
c.fillStyle="white"
rect(300,0,1,300)
c.fillStyle="white"
rect(301,0,1,300)
c.fillStyle="white"
rect(301,150,370,2)
c.fillStyle = "white"
c.fillText("Score",310,20)
c.fillText(score,310,50)
c.fillText("Highest",310,170)
c.fillText(highscore,310,200)
}
function drawScore(){
c.clearRect(300, 0, 370, 300)
c.fillStyle ="black"
rect(300, 0, 370, 300)
c.fillStyle="white"
rect(300,0,1,300)
c.fillStyle="white"
rect(301,0,1,300)
c.fillStyle="white"
rect(301,150,370,2)
c.fillStyle = "white"
c.fillText("Score",310,20)
c.fillText(score,310,50)
c.fillText("Highest",310,170)
c.fillText(highscore,310,200)
}
function draw() {
c.fillStyle = backcolor
clear()
c.fillStyle = ballcolor
circle(x, y, ballRadius)
if (rightDown) paddlex += paddlex<width-75?5:0
else if (leftDown) paddlex -= paddlex>0?5:0
c.fillStyle = paddlecolor
rect(paddlex, height-paddleh, paddlew, paddleh)
drawbricks()
drawScore()
rowheight = brickheight + padding
colwidth = brickwidth + padding
row = Math.floor(y/rowheight)
col = Math.floor(x/colwidth)
if (y < rows * rowheight && row >= 0 && col >= 0 && bricks[row][col] == 1) {
dy = -dy
bricks[row][col] = 0
counter++
score=score+multiplier
multiplier++
if(counter%(rows*columns)==0){
clearInterval(intervalId)
c.fillStyle="black"
clear()
c.fillStyle="white"
c.font="bold 26px 'Century Gothic', Arial"
c.fillText("Round clear!",75,150)
c.font="bold 14px 'Century Gothic', Arial"
drawScore()
alert("Get ready for next round")
clear()
init()
}
}
if (x + dx + ballRadius > width || x + dx - ballRadius < 0)
dx = -dx
if (y + dy - ballRadius < 0)
dy = -dy
else if (y + dy + ballRadius > height - paddleh) {
if (x > paddlex && x < paddlex + paddlew) {
dx = 8 * ((x-(paddlex+paddlew/2))/paddlew)
dy = -dy
multiplier=1
}
else if (y + dy + ballRadius > height){
clearInterval(intervalId)
c.fillStyle="black"
clear()
c.fillStyle="white"
c.font="bold 26px 'Century Gothic', Arial"
c.fillText("GAME OVER",75,150)
c.font="bold 14px 'Century Gothic', Arial"
c.fillText("Your score: "+score,110,180)
if(score>highscore)highscore=score
counter=score=0
multiplier=1
//start button enabled which was disabled
$("#start").removeAttr("disabled")
}
}
x += dx
y += dy
}
$(document).keydown(onKeyDown)
$(document).keyup(onKeyUp)
$(document).mousemove(onMouseMove)
$("#start").click(init)
| Brick/js/brick.js | var x
var y
var dx
var dy
var c
var width=300
var height=300
var paddlex,paddleh = 10,paddlew = 75
var rightDown = false,leftDown = false
var canvasMinX, canvasMaxX
var intervalId
var bricks
var rows = 5
var columns = 5
var brickwidth
var brickheight = 15
var padding = 1
var ballr = 10
var rowcolors = ["#FF1C0A", "#FFFD0A", "#00A308", "#0008DB", "#EB0093"]
var paddlecolor = "#FFFFFF"
var ballcolor = "#FFFFFF"
var backcolor = "#000000"
var counter=0, score=0,multiplier=1,highscore=0
function knuth_shuffle(array) {
//implementation of knuth_suffle algorithm
var i, tmp, rnd
for(i = array.length; 0!==i ;i--) {
rnd = Math.floor(Math.random() * i)
tmp = array[i]
array[i] = array[rnd]
array[rnd] = tmp
}
return array
}
function init() {
$("#start").attr('disabled','disabled')
c = $('#canvas')[0].getContext("2d")
paddlex = width / 2
brickwidth = (width/columns) - 1
canvasMinX = $("#canvas").offset().left
canvasMaxX = canvasMinX + width
x = 25
y = 250
dx = 1.5
dy = -4
paddleh = 10
paddlew = 75
rightDown = false
leftDown = false
rows = 5
columns = 5
brickheight = 15
padding = 1
ballRadius = 10
rowcolors = ["red", "green", "yellow", "blue", "violet","orange","white"]
rowcolors =knuth_shuffle(rowcolors)
paddlecolor = "white"
ballcolor = "white"
backcolor = "black"
initbricks()
intervalId = setInterval(draw, 10)
multiplier=1
}
function circle(x,y,r) {
c.beginPath()
c.arc(x, y, r, 0, Math.PI*2, true)
c.closePath()
c.fill()
}
function rect(x,y,w,h) {
c.beginPath()
c.rect(x,y,w,h)
c.closePath()
c.fill()
}
function clear() {
c.clearRect(0, 0, width, height)
rect(0,0,width,height)
}
function onKeyDown(evt) {
if (evt.keyCode == 39) rightDown = true
else if (evt.keyCode == 37) leftDown = true
}
function onKeyUp(evt) {
if (evt.keyCode == 39) rightDown = false
else if (evt.keyCode == 37) leftDown = false
}
function onMouseMove(evt) {
if (evt.pageX > canvasMinX && evt.pageX < canvasMaxX) {
paddlex = Math.max(evt.pageX - canvasMinX - (paddlew/2), 0)
paddlex = Math.min(width - paddlew, paddlex)
}
}
function initbricks() {
bricks = new Array(rows)
for (i=0 ;i < rows; i++) {
bricks[i] = new Array(columns)
for (j=0; j < columns; j++) {
bricks[i][j] = 1
}
}
}
function drawbricks() {
for (i=0; i < rows; i++) {
c.fillStyle = rowcolors[i]
for (j=0; j < columns; j++) {
if (bricks[i][j] == 1) {
rect((j* (brickwidth + padding)) + padding,
(i * (brickheight + padding)) + padding,
brickwidth, brickheight)
}
}
}
}
function startScreen(){
c = $('#canvas')[0].getContext("2d")
c.fillStyle="black"
rect(0,0,width,height)
c.fillStyle="white"
c.font="bold 20px 'Century Gothic', Arial"
c.fillText("Classic Brick Breaker",50,150)
c.font="bold 14px 'Century Gothic', Arial"
c.fillText("Click Start! to play",90,180)
c.clearRect(300, 0, 370, 300)
c.fillStyle ="black"
rect(300, 0, 370, 300)
c.fillStyle="white"
rect(300,0,1,300)
c.fillStyle="white"
rect(301,0,1,300)
c.fillStyle="white"
rect(301,150,370,2)
c.fillStyle = "white"
c.fillText("Score",310,20)
c.fillText(score,310,50)
c.fillText("Highest",310,170)
c.fillText(highscore,310,200)
}
function drawScore(){
c.clearRect(300, 0, 370, 300)
c.fillStyle ="black"
rect(300, 0, 370, 300)
c.fillStyle="white"
rect(300,0,1,300)
c.fillStyle="white"
rect(301,0,1,300)
c.fillStyle="white"
rect(301,150,370,2)
c.fillStyle = "white"
c.fillText("Score",310,20)
c.fillText(score,310,50)
c.fillText("Highest",310,170)
c.fillText(highscore,310,200)
}
function draw() {
c.fillStyle = backcolor
clear()
c.fillStyle = ballcolor
circle(x, y, ballRadius)
if (rightDown) paddlex += paddlex<width-75?5:0
else if (leftDown) paddlex -= paddlex>0?5:0
c.fillStyle = paddlecolor
rect(paddlex, height-paddleh, paddlew, paddleh)
drawbricks()
drawScore()
rowheight = brickheight + padding
colwidth = brickwidth + padding
row = Math.floor(y/rowheight)
col = Math.floor(x/colwidth)
if (y < rows * rowheight && row >= 0 && col >= 0 && bricks[row][col] == 1) {
dy = -dy
bricks[row][col] = 0
counter++
score=score+multiplier
multiplier++
if(counter%(rows*columns)==0){
clearInterval(intervalId)
c.fillStyle="black"
clear()
c.fillStyle="white"
c.font="bold 26px 'Century Gothic', Arial"
c.fillText("Round clear!",75,150)
c.font="bold 14px 'Century Gothic', Arial"
alert("Get ready for next round")
clear()
init()
}
}
if (x + dx + ballRadius > width || x + dx - ballRadius < 0)
dx = -dx
if (y + dy - ballRadius < 0)
dy = -dy
else if (y + dy + ballRadius > height - paddleh) {
if (x > paddlex && x < paddlex + paddlew) {
dx = 8 * ((x-(paddlex+paddlew/2))/paddlew)
dy = -dy
multiplier=1
}
else if (y + dy + ballRadius > height){
clearInterval(intervalId)
c.fillStyle="black"
clear()
c.fillStyle="white"
c.font="bold 26px 'Century Gothic', Arial"
c.fillText("GAME OVER",75,150)
c.font="bold 14px 'Century Gothic', Arial"
c.fillText("Your score: "+score,110,180)
if(score>highscore)highscore=score
counter=score=0
multiplier=1
//start button enabled which was disabled
$("#start").removeAttr("disabled")
}
}
x += dx
y += dy
}
$(document).keydown(onKeyDown)
$(document).keyup(onKeyUp)
$(document).mousemove(onMouseMove)
$("#start").click(init)
| Minor fix
| Brick/js/brick.js | Minor fix | <ide><path>rick/js/brick.js
<ide>
<ide> c.fillText("Round clear!",75,150)
<ide> c.font="bold 14px 'Century Gothic', Arial"
<del>
<add> drawScore()
<ide> alert("Get ready for next round")
<ide> clear()
<add>
<ide> init()
<ide>
<ide> }
<ide>
<ide> if (y + dy - ballRadius < 0)
<ide> dy = -dy
<add>
<add>
<add>
<ide> else if (y + dy + ballRadius > height - paddleh) {
<ide> if (x > paddlex && x < paddlex + paddlew) {
<ide> dx = 8 * ((x-(paddlex+paddlew/2))/paddlew) |
|
Java | apache-2.0 | bee51dbe02e83656037f2183cd5c52f4cba59fd6 | 0 | apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.airavata.helix.impl.task.submission.config;
import groovy.text.GStringTemplateEngine;
import groovy.text.TemplateEngine;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.helix.impl.task.TaskContext;
import org.apache.airavata.helix.impl.task.TaskOnFailException;
import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription;
import org.apache.airavata.model.appcatalog.appdeployment.CommandObject;
import org.apache.airavata.model.appcatalog.appdeployment.SetEnvPaths;
import org.apache.airavata.model.appcatalog.computeresource.*;
import org.apache.airavata.model.application.io.DataType;
import org.apache.airavata.model.application.io.InputDataObjectType;
import org.apache.airavata.model.application.io.OutputDataObjectType;
import org.apache.airavata.model.parallelism.ApplicationParallelismType;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.model.task.JobSubmissionTaskModel;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class GroovyMapBuilder {
private final static Logger logger = LoggerFactory.getLogger(GroovyMapBuilder.class);
public static final String MULTIPLE_INPUTS_SPLITTER = ",";
private TaskContext taskContext;
public GroovyMapBuilder(TaskContext taskContext) {
this.taskContext = taskContext;
}
public GroovyMapData build() throws Exception {
GroovyMapData mapData = new GroovyMapData();
setMailAddresses(taskContext, mapData);
mapData.setInputDir(taskContext.getInputDir());
mapData.setOutputDir(taskContext.getOutputDir());
mapData.setExecutablePath(taskContext.getApplicationDeploymentDescription().getExecutablePath());
mapData.setStdoutFile(taskContext.getStdoutLocation());
mapData.setStderrFile(taskContext.getStderrLocation());
mapData.setScratchLocation(taskContext.getScratchLocation());
mapData.setGatewayId(taskContext.getGatewayId());
mapData.setGatewayUserName(taskContext.getProcessModel().getUserName());
mapData.setApplicationName(taskContext.getApplicationInterfaceDescription().getApplicationName());
mapData.setQueueSpecificMacros(taskContext.getQueueSpecificMacros());
mapData.setAccountString(taskContext.getAllocationProjectNumber());
mapData.setReservation(taskContext.getReservation());
mapData.setJobName("A" + String.valueOf(generateJobName()));
mapData.setWorkingDirectory(taskContext.getWorkingDir());
mapData.setTaskId(taskContext.getTaskId());
mapData.setExperimentDataDir(taskContext.getProcessModel().getExperimentDataDir());
//List<String> emails = taskContext.getUserProfile().getEmails();
//if (emails != null && emails.size() > 0) {
// mapData.setGatewayUserEmail(emails.get(0));
//}
List<String> inputValues = getProcessInputValues(taskContext.getProcessModel().getProcessInputs(), true);
inputValues.addAll(getProcessOutputValues(taskContext.getProcessModel().getProcessOutputs(), true));
mapData.setInputs(inputValues);
List<String> inputValuesAll = getProcessInputValues(taskContext.getProcessModel().getProcessInputs(), false);
inputValuesAll.addAll(getProcessOutputValues(taskContext.getProcessModel().getProcessOutputs(), false));
mapData.setInputsAll(inputValuesAll);
mapData.setUserName(taskContext.getComputeResourceLoginUserName());
mapData.setShellName("/bin/bash");
if (taskContext != null) {
try {
JobSubmissionTaskModel jobSubmissionTaskModel = ((JobSubmissionTaskModel) taskContext.getSubTaskModel());
if (jobSubmissionTaskModel.getWallTime() > 0) {
mapData.setMaxWallTime(maxWallTimeCalculator(jobSubmissionTaskModel.getWallTime()));
// TODO fix this
/*if (resourceJobManager != null) {
if (resourceJobManager.getResourceJobManagerType().equals(ResourceJobManagerType.LSF)) {
groovyMap.add(Script.MAX_WALL_TIME,
GFacUtils.maxWallTimeCalculatorForLSF(jobSubmissionTaskModel.getWallTime()));
}
}*/
}
} catch (TException e) {
logger.error("Error while getting job submission sub task model", e);
}
}
// NOTE: Give precedence to data comes with experiment
// qos per queue
String qoS = getQoS(taskContext.getQualityOfService(), taskContext.getQueueName());
if (qoS != null) {
mapData.setQualityOfService(qoS);
}
ComputationalResourceSchedulingModel scheduling = taskContext.getProcessModel().getProcessResourceSchedule();
if (scheduling != null) {
int totalNodeCount = scheduling.getNodeCount();
int totalCPUCount = scheduling.getTotalCPUCount();
if (isValid(scheduling.getQueueName())) {
mapData.setQueueName(scheduling.getQueueName());
}
if (totalNodeCount > 0) {
mapData.setNodes(totalNodeCount);
}
if (totalCPUCount > 0) {
int ppn = totalCPUCount / totalNodeCount;
mapData.setProcessPerNode(ppn);
mapData.setCpuCount(totalCPUCount);
}
// max wall time may be set before this level if jobsubmission task has wall time configured to this job,
// if so we ignore scheduling configuration.
if (scheduling.getWallTimeLimit() > 0 && mapData.getMaxWallTime() == null) {
mapData.setMaxWallTime(maxWallTimeCalculator(scheduling.getWallTimeLimit()));
// TODO fix this
/*
if (resourceJobManager != null) {
if (resourceJobManager.getResourceJobManagerType().equals(ResourceJobManagerType.LSF)) {
mapData.setMaxWallTime(maxWallTimeCalculatorForLSF(scheduling.getWallTimeLimit()));
}
}
*/
}
if (scheduling.getTotalPhysicalMemory() > 0) {
mapData.setUsedMem(scheduling.getTotalPhysicalMemory());
}
if (isValid(scheduling.getOverrideLoginUserName())) {
mapData.setUserName(scheduling.getOverrideLoginUserName());
}
if (isValid(scheduling.getOverrideAllocationProjectNumber())) {
mapData.setAccountString(scheduling.getOverrideAllocationProjectNumber());
}
if (isValid(scheduling.getStaticWorkingDir())) {
mapData.setWorkingDirectory(scheduling.getStaticWorkingDir());
}
} else {
logger.error("Task scheduling cannot be null at this point..");
}
ApplicationDeploymentDescription appDepDescription = taskContext.getApplicationDeploymentDescription();
List<SetEnvPaths> exportCommands = appDepDescription.getSetEnvironment();
if (exportCommands != null) {
List<String> exportCommandList = exportCommands.stream()
.sorted((e1, e2) -> e1.getEnvPathOrder() - e2.getEnvPathOrder())
.map(map -> map.getName() + "=" + map.getValue())
.collect(Collectors.toList());
mapData.setExports(exportCommandList);
}
List<CommandObject> moduleCmds = appDepDescription.getModuleLoadCmds();
if (moduleCmds != null) {
List<String> modulesCmdCollect = moduleCmds.stream()
.sorted((e1, e2) -> e1.getCommandOrder() - e2.getCommandOrder())
.map(map -> map.getCommand())
.collect(Collectors.toList());
mapData.setModuleCommands(modulesCmdCollect);
}
List<CommandObject> preJobCommands = appDepDescription.getPreJobCommands();
if (preJobCommands != null) {
List<String> preJobCmdCollect = preJobCommands.stream()
.sorted((e1, e2) -> e1.getCommandOrder() - e2.getCommandOrder())
.map(map -> parseCommands(map.getCommand(), mapData))
.collect(Collectors.toList());
mapData.setPreJobCommands(preJobCmdCollect);
}
List<CommandObject> postJobCommands = appDepDescription.getPostJobCommands();
if (postJobCommands != null) {
List<String> postJobCmdCollect = postJobCommands.stream()
.sorted((e1, e2) -> e1.getCommandOrder() - e2.getCommandOrder())
.map(map -> parseCommands(map.getCommand(), mapData))
.collect(Collectors.toList());
mapData.setPostJobCommands(postJobCmdCollect);
}
ApplicationParallelismType parallelism = appDepDescription.getParallelism();
if (parallelism != null) {
if (parallelism != ApplicationParallelismType.SERIAL) {
Map<ApplicationParallelismType, String> parallelismPrefix = taskContext.getResourceJobManager().getParallelismPrefix();
if (parallelismPrefix != null){
String parallelismCommand = parallelismPrefix.get(parallelism);
if (parallelismCommand != null){
mapData.setJobSubmitterCommand(parallelismCommand);
}else {
throw new Exception("Parallelism prefix is not defined for given parallelism type " + parallelism + ".. Please define the parallelism prefix at App Catalog");
}
}
}
}
return mapData;
}
public static int generateJobName() {
Random random = new Random();
int i = random.nextInt(Integer.MAX_VALUE);
i = i + 99999999;
if (i < 0) {
i = i * (-1);
}
return i;
}
private static List<String> getProcessInputValues(List<InputDataObjectType> processInputs, boolean commandLineOnly) {
List<String> inputValues = new ArrayList<String>();
if (processInputs != null) {
// sort the inputs first and then build the command ListR
Comparator<InputDataObjectType> inputOrderComparator = new Comparator<InputDataObjectType>() {
@Override
public int compare(InputDataObjectType inputDataObjectType, InputDataObjectType t1) {
return inputDataObjectType.getInputOrder() - t1.getInputOrder();
}
};
Set<InputDataObjectType> sortedInputSet = new TreeSet<InputDataObjectType>(inputOrderComparator);
for (InputDataObjectType input : processInputs) {
sortedInputSet.add(input);
}
for (InputDataObjectType inputDataObjectType : sortedInputSet) {
if (commandLineOnly && !inputDataObjectType.isRequiredToAddedToCommandLine()) {
continue;
}
if (inputDataObjectType.getApplicationArgument() != null
&& !inputDataObjectType.getApplicationArgument().equals("")) {
inputValues.add(inputDataObjectType.getApplicationArgument());
}
if (inputDataObjectType.getValue() != null
&& !inputDataObjectType.getValue().equals("")) {
if (inputDataObjectType.getType() == DataType.URI) {
// set only the relative path
String filePath = inputDataObjectType.getValue();
filePath = filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1, filePath.length());
inputValues.add(filePath);
} else if (inputDataObjectType.getType() == DataType.URI_COLLECTION) {
String filePaths = inputDataObjectType.getValue();
String[] paths = filePaths.split(MULTIPLE_INPUTS_SPLITTER);
String filePath;
String inputs = "";
int i = 0;
for (; i < paths.length - 1; i++) {
filePath = paths[i];
filePath = filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1, filePath.length());
// File names separate by a space
inputs += filePath + " ";
}
inputs += paths[i];
inputValues.add(inputs);
} else {
inputValues.add(inputDataObjectType.getValue());
}
}
}
}
return inputValues;
}
private static List<String> getProcessOutputValues(List<OutputDataObjectType> processOutputs, boolean commandLineOnly) {
List<String> inputValues = new ArrayList<>();
if (processOutputs != null) {
for (OutputDataObjectType output : processOutputs) {
if (output.getApplicationArgument() != null
&& !output.getApplicationArgument().equals("")) {
inputValues.add(output.getApplicationArgument());
}
if(commandLineOnly){
if (output.getValue() != null && !output.getValue().equals("") && output.isRequiredToAddedToCommandLine()) {
if (output.getType() == DataType.URI) {
String filePath = output.getValue();
filePath = filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1, filePath.length());
inputValues.add(filePath);
}
}
}else{
if (output.getValue() != null && !output.getValue().equals("")) {
if (output.getType() == DataType.URI) {
String filePath = output.getValue();
filePath = filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1, filePath.length());
inputValues.add(filePath);
}
}
}
}
}
return inputValues;
}
static String getQoS(String qualityOfService, String preferredBatchQueue) {
if(preferredBatchQueue == null || preferredBatchQueue.isEmpty()
|| qualityOfService == null || qualityOfService.isEmpty()) return null;
final String qos = "qos";
Pattern pattern = Pattern.compile(preferredBatchQueue + "=(?<" + qos + ">[^,]*)");
Matcher matcher = pattern.matcher(qualityOfService);
if (matcher.find()) {
return matcher.group(qos);
}
return null;
}
public static String maxWallTimeCalculator(int maxWalltime) {
if (maxWalltime < 60) {
return "00:" + maxWalltime + ":00";
} else {
int minutes = maxWalltime % 60;
int hours = maxWalltime / 60;
return hours + ":" + minutes + ":00";
}
}
public static String maxWallTimeCalculatorForLSF(int maxWalltime) {
if (maxWalltime < 60) {
return "00:" + maxWalltime;
} else {
int minutes = maxWalltime % 60;
int hours = maxWalltime / 60;
return hours + ":" + minutes;
}
}
private static boolean isValid(String str) {
return str != null && !str.isEmpty();
}
static String parseCommands(String value, GroovyMapData bindMap) {
TemplateEngine templateEngine = new GStringTemplateEngine();
try {
return templateEngine.createTemplate(value).make(bindMap.toImmutableMap()).toString();
} catch (ClassNotFoundException | IOException e) {
throw new IllegalArgumentException("Error while parsing command " + value
+ " , Invalid command or incomplete bind map");
}
}
private static void setMailAddresses(TaskContext taskContext, GroovyMapData groovyMap) throws
ApplicationSettingsException, TException, TaskOnFailException {
ProcessModel processModel = taskContext.getProcessModel();
String emailIds = null;
if (isEmailBasedJobMonitor(taskContext)) {
emailIds = ServerSettings.getEmailBasedMonitorAddress();
}
if (ServerSettings.getSetting(ServerSettings.JOB_NOTIFICATION_ENABLE).equalsIgnoreCase("true")) {
String userJobNotifEmailIds = ServerSettings.getSetting(ServerSettings.JOB_NOTIFICATION_EMAILIDS);
if (userJobNotifEmailIds != null && !userJobNotifEmailIds.isEmpty()) {
if (emailIds != null && !emailIds.isEmpty()) {
emailIds += ("," + userJobNotifEmailIds);
} else {
emailIds = userJobNotifEmailIds;
}
}
if (processModel.isEnableEmailNotification()) {
List<String> emailList = processModel.getEmailAddresses();
if (emailList == null) {
throw new TaskOnFailException("At least one email should be provided as the email notification is turned on", false, null);
}
String elist = listToCsv(emailList, ',');
if (elist != null && !elist.isEmpty()) {
if (emailIds != null && !emailIds.isEmpty()) {
emailIds = emailIds + "," + elist;
} else {
emailIds = elist;
}
}
}
}
if (emailIds != null && !emailIds.isEmpty()) {
logger.info("Email list: " + emailIds);
groovyMap.setMailAddress(emailIds);
}
}
public static boolean isEmailBasedJobMonitor(TaskContext taskContext) throws TException, TaskOnFailException {
JobSubmissionProtocol jobSubmissionProtocol = taskContext.getPreferredJobSubmissionProtocol();
JobSubmissionInterface jobSubmissionInterface = taskContext.getPreferredJobSubmissionInterface();
if (jobSubmissionProtocol == JobSubmissionProtocol.SSH) {
String jobSubmissionInterfaceId = jobSubmissionInterface.getJobSubmissionInterfaceId();
SSHJobSubmission sshJobSubmission = taskContext.getRegistryClient().getSSHJobSubmission(jobSubmissionInterfaceId);
MonitorMode monitorMode = sshJobSubmission.getMonitorMode();
return monitorMode != null && monitorMode == MonitorMode.JOB_EMAIL_NOTIFICATION_MONITOR;
} else {
return false;
}
}
public static String listToCsv(List<String> listOfStrings, char separator) {
StringBuilder sb = new StringBuilder();
// all but last
for (int i = 0; i < listOfStrings.size() - 1; i++) {
sb.append(listOfStrings.get(i));
sb.append(separator);
}
// last string, no separator
if (listOfStrings.size() > 0) {
sb.append(listOfStrings.get(listOfStrings.size() - 1));
}
return sb.toString();
}
}
| modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/GroovyMapBuilder.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.airavata.helix.impl.task.submission.config;
import groovy.text.GStringTemplateEngine;
import groovy.text.TemplateEngine;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.helix.impl.task.TaskContext;
import org.apache.airavata.helix.impl.task.TaskOnFailException;
import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription;
import org.apache.airavata.model.appcatalog.appdeployment.CommandObject;
import org.apache.airavata.model.appcatalog.appdeployment.SetEnvPaths;
import org.apache.airavata.model.appcatalog.computeresource.*;
import org.apache.airavata.model.application.io.DataType;
import org.apache.airavata.model.application.io.InputDataObjectType;
import org.apache.airavata.model.application.io.OutputDataObjectType;
import org.apache.airavata.model.parallelism.ApplicationParallelismType;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.model.task.JobSubmissionTaskModel;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class GroovyMapBuilder {
private final static Logger logger = LoggerFactory.getLogger(GroovyMapBuilder.class);
public static final String MULTIPLE_INPUTS_SPLITTER = ",";
private TaskContext taskContext;
public GroovyMapBuilder(TaskContext taskContext) {
this.taskContext = taskContext;
}
public GroovyMapData build() throws Exception {
GroovyMapData mapData = new GroovyMapData();
setMailAddresses(taskContext, mapData);
mapData.setInputDir(taskContext.getInputDir());
mapData.setOutputDir(taskContext.getOutputDir());
mapData.setExecutablePath(taskContext.getApplicationDeploymentDescription().getExecutablePath());
mapData.setStdoutFile(taskContext.getStdoutLocation());
mapData.setStderrFile(taskContext.getStderrLocation());
mapData.setScratchLocation(taskContext.getScratchLocation());
mapData.setGatewayId(taskContext.getGatewayId());
mapData.setGatewayUserName(taskContext.getProcessModel().getUserName());
mapData.setApplicationName(taskContext.getApplicationInterfaceDescription().getApplicationName());
mapData.setQueueSpecificMacros(taskContext.getQueueSpecificMacros());
mapData.setAccountString(taskContext.getAllocationProjectNumber());
mapData.setReservation(taskContext.getReservation());
mapData.setJobName("A" + String.valueOf(generateJobName()));
mapData.setWorkingDirectory(taskContext.getWorkingDir());
mapData.setTaskId(taskContext.getTaskId());
mapData.setExperimentDataDir(taskContext.getProcessModel().getExperimentDataDir());
//List<String> emails = taskContext.getUserProfile().getEmails();
//if (emails != null && emails.size() > 0) {
// mapData.setGatewayUserEmail(emails.get(0));
//}
List<String> inputValues = getProcessInputValues(taskContext.getProcessModel().getProcessInputs(), true);
inputValues.addAll(getProcessOutputValues(taskContext.getProcessModel().getProcessOutputs(), true));
mapData.setInputs(inputValues);
List<String> inputValuesAll = getProcessInputValues(taskContext.getProcessModel().getProcessInputs(), false);
inputValuesAll.addAll(getProcessOutputValues(taskContext.getProcessModel().getProcessOutputs(), false));
mapData.setInputsAll(inputValuesAll);
mapData.setUserName(taskContext.getComputeResourceLoginUserName());
mapData.setShellName("/bin/bash");
if (taskContext != null) {
try {
JobSubmissionTaskModel jobSubmissionTaskModel = ((JobSubmissionTaskModel) taskContext.getSubTaskModel());
if (jobSubmissionTaskModel.getWallTime() > 0) {
mapData.setMaxWallTime(maxWallTimeCalculator(jobSubmissionTaskModel.getWallTime()));
// TODO fix this
/*if (resourceJobManager != null) {
if (resourceJobManager.getResourceJobManagerType().equals(ResourceJobManagerType.LSF)) {
groovyMap.add(Script.MAX_WALL_TIME,
GFacUtils.maxWallTimeCalculatorForLSF(jobSubmissionTaskModel.getWallTime()));
}
}*/
}
} catch (TException e) {
logger.error("Error while getting job submission sub task model", e);
}
}
// NOTE: Give precedence to data comes with experiment
// qos per queue
String qoS = getQoS(taskContext.getQualityOfService(), taskContext.getQueueName());
if (qoS != null) {
mapData.setQualityOfService(qoS);
}
ComputationalResourceSchedulingModel scheduling = taskContext.getProcessModel().getProcessResourceSchedule();
if (scheduling != null) {
int totalNodeCount = scheduling.getNodeCount();
int totalCPUCount = scheduling.getTotalCPUCount();
if (isValid(scheduling.getQueueName())) {
mapData.setQueueName(scheduling.getQueueName());
}
if (totalNodeCount > 0) {
mapData.setNodes(totalNodeCount);
}
if (totalCPUCount > 0) {
int ppn = totalCPUCount / totalNodeCount;
mapData.setProcessPerNode(ppn);
mapData.setCpuCount(totalCPUCount);
}
// max wall time may be set before this level if jobsubmission task has wall time configured to this job,
// if so we ignore scheduling configuration.
if (scheduling.getWallTimeLimit() > 0 && mapData.getMaxWallTime() == null) {
mapData.setMaxWallTime(maxWallTimeCalculator(scheduling.getWallTimeLimit()));
// TODO fix this
/*
if (resourceJobManager != null) {
if (resourceJobManager.getResourceJobManagerType().equals(ResourceJobManagerType.LSF)) {
mapData.setMaxWallTime(maxWallTimeCalculatorForLSF(scheduling.getWallTimeLimit()));
}
}
*/
}
if (scheduling.getTotalPhysicalMemory() > 0) {
mapData.setUsedMem(scheduling.getTotalPhysicalMemory());
}
if (isValid(scheduling.getOverrideLoginUserName())) {
mapData.setUserName(scheduling.getOverrideLoginUserName());
}
if (isValid(scheduling.getOverrideAllocationProjectNumber())) {
mapData.setAccountString(scheduling.getOverrideAllocationProjectNumber());
}
if (isValid(scheduling.getStaticWorkingDir())) {
mapData.setWorkingDirectory(scheduling.getStaticWorkingDir());
}
} else {
logger.error("Task scheduling cannot be null at this point..");
}
ApplicationDeploymentDescription appDepDescription = taskContext.getApplicationDeploymentDescription();
List<SetEnvPaths> exportCommands = appDepDescription.getSetEnvironment();
if (exportCommands != null) {
List<String> exportCommandList = exportCommands.stream()
.sorted((e1, e2) -> e1.getEnvPathOrder() - e2.getEnvPathOrder())
.map(map -> map.getName() + "=" + map.getValue())
.collect(Collectors.toList());
mapData.setExports(exportCommandList);
}
List<CommandObject> moduleCmds = appDepDescription.getModuleLoadCmds();
if (moduleCmds != null) {
List<String> modulesCmdCollect = moduleCmds.stream()
.sorted((e1, e2) -> e1.getCommandOrder() - e2.getCommandOrder())
.map(map -> map.getCommand())
.collect(Collectors.toList());
mapData.setModuleCommands(modulesCmdCollect);
}
List<CommandObject> preJobCommands = appDepDescription.getPreJobCommands();
if (preJobCommands != null) {
List<String> preJobCmdCollect = preJobCommands.stream()
.sorted((e1, e2) -> e1.getCommandOrder() - e2.getCommandOrder())
.map(map -> parseCommands(map.getCommand(), mapData))
.collect(Collectors.toList());
mapData.setPreJobCommands(preJobCmdCollect);
}
List<CommandObject> postJobCommands = appDepDescription.getPostJobCommands();
if (postJobCommands != null) {
List<String> postJobCmdCollect = postJobCommands.stream()
.sorted((e1, e2) -> e1.getCommandOrder() - e2.getCommandOrder())
.map(map -> parseCommands(map.getCommand(), mapData))
.collect(Collectors.toList());
mapData.setPostJobCommands(postJobCmdCollect);
}
ApplicationParallelismType parallelism = appDepDescription.getParallelism();
if (parallelism != null) {
if (parallelism != ApplicationParallelismType.SERIAL) {
Map<ApplicationParallelismType, String> parallelismPrefix = taskContext.getResourceJobManager().getParallelismPrefix();
if (parallelismPrefix != null){
String parallelismCommand = parallelismPrefix.get(parallelism);
if (parallelismCommand != null){
mapData.setJobSubmitterCommand(parallelismCommand);
}else {
throw new Exception("Parallelism prefix is not defined for given parallelism type " + parallelism + ".. Please define the parallelism prefix at App Catalog");
}
}
}
}
return mapData;
}
public static int generateJobName() {
Random random = new Random();
int i = random.nextInt(Integer.MAX_VALUE);
i = i + 99999999;
if (i < 0) {
i = i * (-1);
}
return i;
}
private static List<String> getProcessInputValues(List<InputDataObjectType> processInputs, boolean commandLineOnly) {
List<String> inputValues = new ArrayList<String>();
if (processInputs != null) {
// sort the inputs first and then build the command ListR
Comparator<InputDataObjectType> inputOrderComparator = new Comparator<InputDataObjectType>() {
@Override
public int compare(InputDataObjectType inputDataObjectType, InputDataObjectType t1) {
return inputDataObjectType.getInputOrder() - t1.getInputOrder();
}
};
Set<InputDataObjectType> sortedInputSet = new TreeSet<InputDataObjectType>(inputOrderComparator);
for (InputDataObjectType input : processInputs) {
sortedInputSet.add(input);
}
for (InputDataObjectType inputDataObjectType : sortedInputSet) {
if (commandLineOnly && !inputDataObjectType.isRequiredToAddedToCommandLine()) {
continue;
}
if (inputDataObjectType.getApplicationArgument() != null
&& !inputDataObjectType.getApplicationArgument().equals("")) {
inputValues.add(inputDataObjectType.getApplicationArgument());
}
if (inputDataObjectType.getValue() != null
&& !inputDataObjectType.getValue().equals("")) {
if (inputDataObjectType.getType() == DataType.URI) {
// set only the relative path
String filePath = inputDataObjectType.getValue();
filePath = filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1, filePath.length());
inputValues.add(filePath);
} else if (inputDataObjectType.getType() == DataType.URI_COLLECTION) {
String filePaths = inputDataObjectType.getValue();
String[] paths = filePaths.split(MULTIPLE_INPUTS_SPLITTER);
String filePath;
String inputs = "";
int i = 0;
for (; i < paths.length - 1; i++) {
filePath = paths[i];
filePath = filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1, filePath.length());
// File names separate by a space
inputs += filePath + " ";
}
inputs += paths[i];
inputValues.add(inputs);
} else {
inputValues.add(inputDataObjectType.getValue());
}
}
}
}
return inputValues;
}
private static List<String> getProcessOutputValues(List<OutputDataObjectType> processOutputs, boolean commandLineOnly) {
List<String> inputValues = new ArrayList<>();
if (processOutputs != null) {
for (OutputDataObjectType output : processOutputs) {
if (output.getApplicationArgument() != null
&& !output.getApplicationArgument().equals("")) {
inputValues.add(output.getApplicationArgument());
}
if(commandLineOnly){
if (output.getValue() != null && !output.getValue().equals("") && output.isRequiredToAddedToCommandLine()) {
if (output.getType() == DataType.URI) {
String filePath = output.getValue();
filePath = filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1, filePath.length());
inputValues.add(filePath);
}
}
}else{
if (output.getValue() != null && !output.getValue().equals("")) {
if (output.getType() == DataType.URI) {
String filePath = output.getValue();
filePath = filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1, filePath.length());
inputValues.add(filePath);
}
}
}
}
}
return inputValues;
}
static String getQoS(String qualityOfService, String preferredBatchQueue) {
if(preferredBatchQueue == null || preferredBatchQueue.isEmpty()
|| qualityOfService == null || qualityOfService.isEmpty()) return null;
final String qos = "qos";
Pattern pattern = Pattern.compile(preferredBatchQueue + "=(?<" + qos + ">[^,]*)");
Matcher matcher = pattern.matcher(qualityOfService);
if (matcher.find()) {
return matcher.group(qos);
}
return null;
}
public static String maxWallTimeCalculator(int maxWalltime) {
if (maxWalltime < 60) {
return "00:" + maxWalltime + ":00";
} else {
int minutes = maxWalltime % 60;
int hours = maxWalltime / 60;
return hours + ":" + minutes + ":00";
}
}
public static String maxWallTimeCalculatorForLSF(int maxWalltime) {
if (maxWalltime < 60) {
return "00:" + maxWalltime;
} else {
int minutes = maxWalltime % 60;
int hours = maxWalltime / 60;
return hours + ":" + minutes;
}
}
private static boolean isValid(String str) {
return str != null && !str.isEmpty();
}
static String parseCommands(String value, GroovyMapData bindMap) {
TemplateEngine templateEngine = new GStringTemplateEngine();
try {
return templateEngine.createTemplate(value).make(bindMap.toImmutableMap()).toString();
} catch (ClassNotFoundException | IOException e) {
throw new IllegalArgumentException("Error while parsing command " + value
+ " , Invalid command or incomplete bind map");
}
}
private static void setMailAddresses(TaskContext taskContext, GroovyMapData groovyMap) throws
ApplicationSettingsException, TException, TaskOnFailException {
ProcessModel processModel = taskContext.getProcessModel();
String emailIds = null;
if (isEmailBasedJobMonitor(taskContext)) {
emailIds = ServerSettings.getEmailBasedMonitorAddress();
}
if (ServerSettings.getSetting(ServerSettings.JOB_NOTIFICATION_ENABLE).equalsIgnoreCase("true")) {
String userJobNotifEmailIds = ServerSettings.getSetting(ServerSettings.JOB_NOTIFICATION_EMAILIDS);
if (userJobNotifEmailIds != null && !userJobNotifEmailIds.isEmpty()) {
if (emailIds != null && !emailIds.isEmpty()) {
emailIds += ("," + userJobNotifEmailIds);
} else {
emailIds = userJobNotifEmailIds;
}
}
if (processModel.isEnableEmailNotification()) {
List<String> emailList = processModel.getEmailAddresses();
String elist = listToCsv(emailList, ',');
if (elist != null && !elist.isEmpty()) {
if (emailIds != null && !emailIds.isEmpty()) {
emailIds = emailIds + "," + elist;
} else {
emailIds = elist;
}
}
}
}
if (emailIds != null && !emailIds.isEmpty()) {
logger.info("Email list: " + emailIds);
groovyMap.setMailAddress(emailIds);
}
}
public static boolean isEmailBasedJobMonitor(TaskContext taskContext) throws TException, TaskOnFailException {
JobSubmissionProtocol jobSubmissionProtocol = taskContext.getPreferredJobSubmissionProtocol();
JobSubmissionInterface jobSubmissionInterface = taskContext.getPreferredJobSubmissionInterface();
if (jobSubmissionProtocol == JobSubmissionProtocol.SSH) {
String jobSubmissionInterfaceId = jobSubmissionInterface.getJobSubmissionInterfaceId();
SSHJobSubmission sshJobSubmission = taskContext.getRegistryClient().getSSHJobSubmission(jobSubmissionInterfaceId);
MonitorMode monitorMode = sshJobSubmission.getMonitorMode();
return monitorMode != null && monitorMode == MonitorMode.JOB_EMAIL_NOTIFICATION_MONITOR;
} else {
return false;
}
}
public static String listToCsv(List<String> listOfStrings, char separator) {
StringBuilder sb = new StringBuilder();
// all but last
for (int i = 0; i < listOfStrings.size() - 1; i++) {
sb.append(listOfStrings.get(i));
sb.append(separator);
}
// last string, no separator
if (listOfStrings.size() > 0) {
sb.append(listOfStrings.get(listOfStrings.size() - 1));
}
return sb.toString();
}
}
| Showing a friendly message when the email is not provided
| modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/GroovyMapBuilder.java | Showing a friendly message when the email is not provided | <ide><path>odules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/GroovyMapBuilder.java
<ide> }
<ide> if (processModel.isEnableEmailNotification()) {
<ide> List<String> emailList = processModel.getEmailAddresses();
<add> if (emailList == null) {
<add> throw new TaskOnFailException("At least one email should be provided as the email notification is turned on", false, null);
<add> }
<ide> String elist = listToCsv(emailList, ',');
<ide> if (elist != null && !elist.isEmpty()) {
<ide> if (emailIds != null && !emailIds.isEmpty()) { |
|
Java | apache-2.0 | 0e6ea6edbb2305f564ec67f87d42a1985abc65b6 | 0 | AVnetWS/Hentoid,AVnetWS/Hentoid,AVnetWS/Hentoid | package me.devsaki.hentoid.database.domains;
import androidx.annotation.NonNull;
import java.io.DataInputStream;
import java.io.IOException;
import javax.annotation.Nonnull;
import io.objectbox.annotation.Backlink;
import io.objectbox.annotation.Convert;
import io.objectbox.annotation.Entity;
import io.objectbox.annotation.Id;
import io.objectbox.annotation.Index;
import io.objectbox.annotation.Transient;
import io.objectbox.relation.ToMany;
import io.objectbox.relation.ToOne;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Site;
import timber.log.Timber;
/**
* Created by DevSaki on 09/05/2015.
* Attribute builder
*/
@Entity
public class Attribute {
@Id
private long id;
@Index
private String name;
@Index
@Convert(converter = AttributeType.AttributeTypeConverter.class, dbType = Integer.class)
private AttributeType type;
@Backlink(to = "attribute")
private ToMany<AttributeLocation> locations; // One entry per site
private ToOne<Group> group; // Associated group
// Runtime attributes; no need to expose them nor to persist them
@Transient
private boolean excluded = false;
@Transient
private int count;
@Transient
private int externalId = 0;
@Backlink(to = "attributes") // backed by the to-many relation in Content
public ToMany<Content> contents;
public Attribute() {
} // No-arg constructor required by ObjectBox
public Attribute(@Nonnull AttributeType type, @Nonnull String name) {
this.type = type;
this.name = name;
}
public Attribute(@Nonnull AttributeType type, @Nonnull String name, @Nonnull String url, @Nonnull Site site) {
this.type = type;
this.name = name;
computeLocation(site, url);
}
public Attribute(@Nonnull DataInputStream input) throws IOException {
input.readInt(); // file version
name = input.readUTF();
type = AttributeType.searchByCode(input.readInt());
count = input.readInt();
externalId = input.readInt();
int nbLocations = input.readInt();
for (int i = 0; i < nbLocations; i++) locations.add(new AttributeLocation(input));
}
public long getId() {
return (0 == externalId) ? this.id : this.externalId;
}
public Attribute setId(long id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public void setName(@Nonnull String name) {
this.name = name;
}
public AttributeType getType() {
return type;
}
public Attribute setExcluded(boolean toExclude) {
excluded = toExclude;
return this;
}
public boolean isExcluded() {
return excluded;
}
public void setType(@Nonnull AttributeType type) {
this.type = type;
}
public ToMany<AttributeLocation> getLocations() {
return locations;
}
public void setLocations(ToMany<AttributeLocation> locations) {
this.locations = locations;
}
public int getCount() {
return count;
}
public Attribute setCount(int count) {
this.count = count;
return this;
}
public ToOne<Group> getGroup() {
return group;
}
public void putGroup(@NonNull Group group) {
this.group.setAndPutTarget(group);
}
public Attribute setExternalId(int id) {
this.externalId = id;
return this;
}
Attribute computeLocation(Site site, String url) {
locations.add(new AttributeLocation(site, url));
return this;
}
public void addLocationsFrom(Attribute sourceAttribute) {
for (AttributeLocation sourceLocation : sourceAttribute.getLocations()) {
boolean foundSite = false;
for (AttributeLocation loc : this.locations) {
if (sourceLocation.site.equals(loc.site)) {
foundSite = true;
if (!sourceLocation.url.equals(loc.url))
Timber.w("'%s' Attribute location mismatch : current '%s' vs. add's target '%s'", this.name, loc.url, sourceLocation.url);
break;
}
}
if (!foundSite) this.locations.add(sourceLocation);
}
}
@NonNull
@Override
public String toString() {
return getName();
}
public String formatLabel(boolean useNamespace) {
return String.format("%s%s %s", useNamespace ? type.getDisplayName().toLowerCase() + ":" : "", getName(), getCount() > 0 ? "(" + getCount() + ")" : "");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Attribute attribute = (Attribute) o;
if ((externalId != 0 && attribute.externalId != 0) && externalId != attribute.externalId)
return false;
if ((id != 0 && attribute.id != 0) && id != attribute.id) return false;
if (!name.equals(attribute.name)) return false;
return type == attribute.type;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + type.hashCode();
result = 31 * result + externalId;
return result;
}
}
| app/src/main/java/me/devsaki/hentoid/database/domains/Attribute.java | package me.devsaki.hentoid.database.domains;
import androidx.annotation.NonNull;
import java.io.DataInputStream;
import java.io.IOException;
import javax.annotation.Nonnull;
import io.objectbox.annotation.Backlink;
import io.objectbox.annotation.Convert;
import io.objectbox.annotation.Entity;
import io.objectbox.annotation.Id;
import io.objectbox.annotation.Index;
import io.objectbox.annotation.Transient;
import io.objectbox.relation.ToMany;
import io.objectbox.relation.ToOne;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Site;
import timber.log.Timber;
/**
* Created by DevSaki on 09/05/2015.
* Attribute builder
*/
@Entity
public class Attribute {
@Id
private long id;
@Index
private String name;
@Index
@Convert(converter = AttributeType.AttributeTypeConverter.class, dbType = Integer.class)
private AttributeType type;
@Backlink(to = "attribute")
private ToMany<AttributeLocation> locations; // One entry per site
private ToOne<Group> group; // Associated group
// Runtime attributes; no need to expose them nor to persist them
@Transient
private boolean excluded = false;
@Transient
private int count;
@Transient
private int externalId = 0;
@Backlink(to = "attributes") // backed by the to-many relation in Content
public ToMany<Content> contents;
public Attribute() {
} // No-arg constructor required by ObjectBox
public Attribute(@Nonnull AttributeType type, @Nonnull String name) {
this.type = type;
this.name = name;
}
public Attribute(@Nonnull AttributeType type, @Nonnull String name, @Nonnull String url, @Nonnull Site site) {
this.type = type;
this.name = name;
computeLocation(site, url);
}
public Attribute(@Nonnull DataInputStream input) throws IOException {
input.readInt(); // file version
name = input.readUTF();
type = AttributeType.searchByCode(input.readInt());
count = input.readInt();
externalId = input.readInt();
int nbLocations = input.readInt();
for (int i = 0; i < nbLocations; i++) locations.add(new AttributeLocation(input));
}
public long getId() {
return (0 == externalId) ? this.id : this.externalId;
}
public Attribute setId(long id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public void setName(@Nonnull String name) {
this.name = name;
}
public AttributeType getType() {
return type;
}
public Attribute setExcluded(boolean toExclude){
excluded = toExclude;
return this;
}
public boolean isExcluded(){return excluded; };
public void setType(@Nonnull AttributeType type) {
this.type = type;
}
public ToMany<AttributeLocation> getLocations() {
return locations;
}
public void setLocations(ToMany<AttributeLocation> locations) {
this.locations = locations;
}
public int getCount() {
return count;
}
public Attribute setCount(int count) {
this.count = count;
return this;
}
public ToOne<Group> getGroup() {
return group;
}
public void putGroup(@NonNull Group group) {
this.group.setAndPutTarget(group);
}
public Attribute setExternalId(int id) {
this.externalId = id;
return this;
}
Attribute computeLocation(Site site, String url) {
locations.add(new AttributeLocation(site, url));
return this;
}
public void addLocationsFrom(Attribute sourceAttribute) {
for (AttributeLocation sourceLocation : sourceAttribute.getLocations()) {
boolean foundSite = false;
for (AttributeLocation loc : this.locations) {
if (sourceLocation.site.equals(loc.site)) {
foundSite = true;
if (!sourceLocation.url.equals(loc.url))
Timber.w("'%s' Attribute location mismatch : current '%s' vs. add's target '%s'", this.name, loc.url, sourceLocation.url);
break;
}
}
if (!foundSite) this.locations.add(sourceLocation);
}
}
@NonNull
@Override
public String toString() {
return getName();
}
public String formatLabel(boolean useNamespace) {
return String.format("%s%s %s", useNamespace ? type.getDisplayName().toLowerCase() + ":" : "", getName(), getCount() > 0 ? "(" + getCount() + ")" : "");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Attribute attribute = (Attribute) o;
if ((externalId != 0 && attribute.externalId != 0) && externalId != attribute.externalId)
return false;
if ((id != 0 && attribute.id != 0) && id != attribute.id) return false;
if (!name.equals(attribute.name)) return false;
return type == attribute.type;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + type.hashCode();
result = 31 * result + externalId;
return result;
}
}
| Make Sonar happy
| app/src/main/java/me/devsaki/hentoid/database/domains/Attribute.java | Make Sonar happy | <ide><path>pp/src/main/java/me/devsaki/hentoid/database/domains/Attribute.java
<ide> return type;
<ide> }
<ide>
<del> public Attribute setExcluded(boolean toExclude){
<add> public Attribute setExcluded(boolean toExclude) {
<ide> excluded = toExclude;
<ide> return this;
<ide> }
<del> public boolean isExcluded(){return excluded; };
<add>
<add> public boolean isExcluded() {
<add> return excluded;
<add> }
<ide>
<ide> public void setType(@Nonnull AttributeType type) {
<ide> this.type = type; |
|
Java | mit | 68b9844637e525ffd41f8a7075d321f923051afa | 0 | anagav/TinkerRocks | package com.tinkerrocks.structure;
import org.apache.tinkerpop.gremlin.structure.*;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import java.util.*;
/**
* Created by ashishn on 8/5/15.
*/
public class RocksVertex extends RocksElement implements Vertex {
public RocksVertex(byte[] id, String label, RocksGraph rocksGraph) {
super(id, label, rocksGraph);
}
public RocksVertex(byte[] id, RocksGraph rocksGraph) throws Exception {
super(id, rocksGraph.getStorageHandler().getVertexDB().getLabel(id), rocksGraph);
}
/**
* @param propertyKeys
* @param <V>
* @return
*/
@SuppressWarnings("unchecked")
@Override
public <V> Iterator<VertexProperty<V>> properties(String... propertyKeys) {
List<byte[]> propKeys = new ArrayList<>(propertyKeys.length);
for (String propertyKey : propertyKeys) {
propKeys.add(propertyKey.getBytes());
}
try {
return this.rocksGraph.getStorageHandler().getVertexDB().<V>getProperties(this, propKeys).iterator();
} catch (Exception e) {
e.printStackTrace();
throw Property.Exceptions.propertyDoesNotExist();
}
}
@Override
public <V> VertexProperty<V> property(final String key, final V value) {
if (this.removed) throw Element.Exceptions.elementAlreadyRemoved(Vertex.class, this.id);
return this.property(VertexProperty.Cardinality.single, key, value);
}
@Override
public Edge addEdge(String label, Vertex inVertex, Object... keyValues) {
if (null == inVertex) throw Graph.Exceptions.argumentCanNotBeNull("inVertex");
ElementHelper.legalPropertyKeyValueArray(keyValues);
checkRemoved();
if (label == null) {
throw Element.Exceptions.labelCanNotBeNull();
}
if (label.isEmpty()) {
throw Element.Exceptions.labelCanNotBeEmpty();
}
byte[] edge_id = String.valueOf(ElementHelper
.getIdValue(keyValues).orElse(UUID.randomUUID().toString().getBytes())).getBytes(); //UUID.randomUUID().toString().getBytes();
Edge edge = new RocksEdge(edge_id, label, this.rocksGraph, (byte[]) this.id(), (byte[]) inVertex.id(), keyValues);
try {
this.rocksGraph.getStorageHandler().getVertexDB().addEdge((byte[]) this.id(), edge, inVertex);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return edge;
}
@Override
public <V> VertexProperty<V> property(String key, V value, Object... keyValues) {
ElementHelper.legalPropertyKeyValueArray(keyValues);
return this.property(key, value);
}
@Override
public <V> VertexProperty<V> property(VertexProperty.Cardinality cardinality, String key, V value, Object... keyValues) {
if (this.removed) throw Element.Exceptions.elementAlreadyRemoved(Vertex.class, this.id);
this.rocksGraph.getStorageHandler().getVertexDB().setProperty((byte[]) this.id(), key, value, cardinality);
properties(key).forEachRemaining(objectVertexProperty -> this.rocksGraph.getVertexIndex().
autoUpdate(key, value, objectVertexProperty.value(), this));
return new RocksVertexProperty<>(this, key, value);
}
@Override
public Iterator<Edge> edges(Direction direction, String... edgeLabels) {
if (this.removed) throw Element.Exceptions.elementAlreadyRemoved(Vertex.class, this.id);
List<byte[]> edgeIds = this.rocksGraph.getStorageHandler().getVertexDB().getEdgeIDs((byte[]) this.id(),
direction, edgeLabels);
if (edgeIds.size() == 0) {
return Collections.emptyListIterator();
}
try {
return this.rocksGraph.getStorageHandler().getEdgeDB().edges(edgeIds, this.rocksGraph).iterator();
} catch (Exception e) {
e.printStackTrace();
}
return Collections.emptyListIterator();
}
/**
* Gets an {@link Iterator} of adjacent vertices.
*
* @param direction The adjacency direction of the vertices to retrieve off this vertex
* @param edgeLabels The labels of the edges associated with the vertices to retrieve. If no labels are provided, then get all edges.
* @return An iterator of vertices meeting the provided specification
*/
@Override
public Iterator<Vertex> vertices(Direction direction, String... edgeLabels) {
List<byte[]> edgeIds = this.rocksGraph.getStorageHandler().getVertexDB().getEdgeIDs((byte[]) this.id(), direction, edgeLabels);
if (edgeIds.size() == 0) {
return Collections.emptyIterator();
}
//conservative allocations
List<byte[]> vertexIds = new ArrayList<>(150);
for (byte[] edgeId : edgeIds) {
vertexIds.addAll(this.rocksGraph.getStorageHandler().getEdgeDB().getVertexIDs(edgeId, direction));
}
try {
return this.rocksGraph.getStorageHandler().getVertexDB().vertices(vertexIds, this.rocksGraph).iterator();
} catch (Exception e) {
e.printStackTrace();
}
return Collections.emptyIterator();
}
@Override
public Graph graph() {
return this.rocksGraph;
}
@Override
public void remove() {
this.removed = true;
edges(Direction.BOTH).forEachRemaining(Element::remove);
try {
this.rocksGraph.getStorageHandler().getVertexDB().remove(this);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return "V" + "[" + new String((byte[]) id()) + "]";
}
}
| src/main/java/com/tinkerrocks/structure/RocksVertex.java | package com.tinkerrocks.structure;
import org.apache.tinkerpop.gremlin.structure.*;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import java.util.*;
/**
* Created by ashishn on 8/5/15.
*/
public class RocksVertex extends RocksElement implements Vertex {
public RocksVertex(byte[] id, String label, RocksGraph rocksGraph) {
super(id, label, rocksGraph);
}
public RocksVertex(byte[] id, RocksGraph rocksGraph) throws Exception {
super(id, rocksGraph.getStorageHandler().getVertexDB().getLabel(id), rocksGraph);
}
/**
* @param propertyKeys
* @param <V>
* @return
*/
@SuppressWarnings("unchecked")
@Override
public <V> Iterator<VertexProperty<V>> properties(String... propertyKeys) {
List<byte[]> propKeys = new ArrayList<>();
for (String propertyKey : propertyKeys) {
propKeys.add(propertyKey.getBytes());
}
try {
return this.rocksGraph.getStorageHandler().getVertexDB().<V>getProperties(this, propKeys).iterator();
} catch (Exception e) {
e.printStackTrace();
throw Property.Exceptions.propertyDoesNotExist();
}
}
@Override
public <V> VertexProperty<V> property(final String key, final V value) {
if (this.removed) throw Element.Exceptions.elementAlreadyRemoved(Vertex.class, this.id);
return this.property(VertexProperty.Cardinality.single, key, value);
}
@Override
public Edge addEdge(String label, Vertex inVertex, Object... keyValues) {
if (null == inVertex) throw Graph.Exceptions.argumentCanNotBeNull("inVertex");
ElementHelper.legalPropertyKeyValueArray(keyValues);
checkRemoved();
if (label == null) {
throw Element.Exceptions.labelCanNotBeNull();
}
if (label.isEmpty()) {
throw Element.Exceptions.labelCanNotBeEmpty();
}
byte[] edge_id = String.valueOf(ElementHelper
.getIdValue(keyValues).orElse(UUID.randomUUID().toString().getBytes())).getBytes(); //UUID.randomUUID().toString().getBytes();
Edge edge = new RocksEdge(edge_id, label, this.rocksGraph, (byte[]) this.id(), (byte[]) inVertex.id(), keyValues);
try {
this.rocksGraph.getStorageHandler().getVertexDB().addEdge((byte[]) this.id(), edge, inVertex);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return edge;
}
@Override
public <V> VertexProperty<V> property(String key, V value, Object... keyValues) {
ElementHelper.legalPropertyKeyValueArray(keyValues);
return this.property(key, value);
}
@Override
public <V> VertexProperty<V> property(VertexProperty.Cardinality cardinality, String key, V value, Object... keyValues) {
if (this.removed) throw Element.Exceptions.elementAlreadyRemoved(Vertex.class, this.id);
this.rocksGraph.getStorageHandler().getVertexDB().setProperty((byte[]) this.id(), key, value, cardinality);
properties(key).forEachRemaining(objectVertexProperty -> this.rocksGraph.getVertexIndex().
autoUpdate(key, value, objectVertexProperty.value(), this));
return new RocksVertexProperty<>(this, key, value);
}
@Override
public Iterator<Edge> edges(Direction direction, String... edgeLabels) {
if (this.removed) throw Element.Exceptions.elementAlreadyRemoved(Vertex.class, this.id);
List<byte[]> edgeIds = this.rocksGraph.getStorageHandler().getVertexDB().getEdgeIDs((byte[]) this.id(),
direction, edgeLabels);
if (edgeIds.size() == 0) {
return Collections.emptyListIterator();
}
try {
return this.rocksGraph.getStorageHandler().getEdgeDB().edges(edgeIds, this.rocksGraph).iterator();
} catch (Exception e) {
e.printStackTrace();
}
return Collections.emptyListIterator();
}
/**
* Gets an {@link Iterator} of adjacent vertices.
*
* @param direction The adjacency direction of the vertices to retrieve off this vertex
* @param edgeLabels The labels of the edges associated with the vertices to retrieve. If no labels are provided, then get all edges.
* @return An iterator of vertices meeting the provided specification
*/
@Override
public Iterator<Vertex> vertices(Direction direction, String... edgeLabels) {
List<byte[]> edgeIds = this.rocksGraph.getStorageHandler().getVertexDB().getEdgeIDs((byte[]) this.id(), direction, edgeLabels);
if (edgeIds.size() == 0) {
return Collections.emptyIterator();
}
//conservative allocations
List<byte[]> vertexIds = new ArrayList<>(150);
for (byte[] edgeId : edgeIds) {
vertexIds.addAll(this.rocksGraph.getStorageHandler().getEdgeDB().getVertexIDs(edgeId, direction));
}
try {
return this.rocksGraph.getStorageHandler().getVertexDB().vertices(vertexIds, this.rocksGraph).iterator();
} catch (Exception e) {
e.printStackTrace();
}
return Collections.emptyIterator();
}
@Override
public Graph graph() {
return this.rocksGraph;
}
@Override
public void remove() {
this.removed = true;
edges(Direction.BOTH).forEachRemaining(Element::remove);
try {
this.rocksGraph.getStorageHandler().getVertexDB().remove(this);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return "V" + "[" + new String((byte[]) id()) + "]";
}
}
| optimizations
| src/main/java/com/tinkerrocks/structure/RocksVertex.java | optimizations | <ide><path>rc/main/java/com/tinkerrocks/structure/RocksVertex.java
<ide> @SuppressWarnings("unchecked")
<ide> @Override
<ide> public <V> Iterator<VertexProperty<V>> properties(String... propertyKeys) {
<del> List<byte[]> propKeys = new ArrayList<>();
<add> List<byte[]> propKeys = new ArrayList<>(propertyKeys.length);
<ide> for (String propertyKey : propertyKeys) {
<ide> propKeys.add(propertyKey.getBytes());
<ide> } |
|
Java | apache-2.0 | d568d34b2411c021453f418b8650b711e7efe4f1 | 0 | michaelmaguire/twosidedsearch,michaelmaguire/twosidedsearch,michaelmaguire/twosidedsearch,michaelmaguire/twosidedsearch,michaelmaguire/twosidedsearch,michaelmaguire/twosidedsearch,michaelmaguire/twosidedsearch,michaelmaguire/twosidedsearch | package com.speedycrew.client.sql;
import java.util.List;
import java.util.Vector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
public class SyncedContentProvider extends ContentProvider {
private static final String LOGTAG = SyncedContentProvider.class.getName();
SyncedSQLiteOpenHelper mSyncedSQLiteOpenHelper;
// used for the UriMacher
private static final int URI_SEARCH_INDEX = 10;
private static final int URI_MATCH_INDEX = 20;
private static final String AUTHORITY = "com.speedycrew.client.sql.synced.contentprovider";
private static final String BASE_PATH = "/";
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY);
public static final Uri SEARCH_URI = Uri.parse("content://" + AUTHORITY + BASE_PATH + Search.TABLE_NAME);
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
/**
* SQLite has a handy hidden _rowid_ columns.
*/
public static final String SQLITE_ROWID = "_rowid_";
public static final String METHOD_FETCH_TIMELINE_SEQUENCE = "timeline";
public static final String METHOD_ON_SYNCHRONIZE_RESPONSE = "synchronize";
static {
sURIMatcher.addURI(AUTHORITY, Search.TABLE_NAME, URI_SEARCH_INDEX);
sURIMatcher.addURI(AUTHORITY, Search.TABLE_NAME + "/*/" + Match.TABLE_NAME, URI_MATCH_INDEX);
}
@Override
public boolean onCreate() {
mSyncedSQLiteOpenHelper = new SyncedSQLiteOpenHelper(getContext());
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Log.i(LOGTAG, "query URI[" + uri + "]");
// For our query below, make sure that we have an '_id' column as
// required by Google Adapter classes, even if our table doesn't
// really contain one. To do this, use SQLite's _rowid_.
//
// See: http://www.sqlite.org/lang_createtable.html#rowid
// and:
// http://stackoverflow.com/questions/11365097/sqlite-create-table-with-an-alias-for-rowid
Vector<String> newProjectionVector = new Vector<String>();
for (String passedIn : projection) {
if (BaseColumns._ID.equalsIgnoreCase(passedIn)) {
newProjectionVector.add(SQLITE_ROWID + " as _id");
} else {
newProjectionVector.add(passedIn);
}
}
String[] newProjection = newProjectionVector.toArray(new String[projection.length]);
// Using SQLiteQueryBuilder instead of query() method
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
List<String> pathSegments = uri.getPathSegments();
int uriIndex = sURIMatcher.match(uri);
switch (uriIndex) {
case URI_SEARCH_INDEX:
queryBuilder.setTables(Search.TABLE_NAME);
break;
case URI_MATCH_INDEX:
queryBuilder.setTables(Match.TABLE_NAME);
queryBuilder.appendWhere(Match.SEARCH + "='" + pathSegments.get(1) + "'");
break;
default:
Log.e(LOGTAG, "Unhandled URI[" + uri + "]");
return null;
}
// check if the caller has requested a column which does not exists
// checkColumns(projection);
SQLiteDatabase db = mSyncedSQLiteOpenHelper.getReadableDatabase();
Cursor cursor = queryBuilder.query(db, newProjection, selection, selectionArgs, null, null, sortOrder);
// make sure that potential listeners are getting notified
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Override
public Bundle call(String method, String arg, Bundle extras) {
Log.i(LOGTAG, "call method[" + method + "] arg[" + arg + "]");
Bundle bundle = null;
if (METHOD_ON_SYNCHRONIZE_RESPONSE.equals(method)) {
try {
JSONObject jsonResponse = new JSONObject(arg);
Log.i(LOGTAG, "call: jsonResponse[" + jsonResponse + "]");
JSONArray sqlArray = jsonResponse.getJSONArray("sql");
if (sqlArray != null) {
SQLiteDatabase db = mSyncedSQLiteOpenHelper.getWritableDatabase();
String sqlStatement = null;
int i = 0;
try {
db.beginTransaction();
final int length = sqlArray.length();
for (i = 0; i < length; ++i) {
sqlStatement = sqlArray.getString(i);
Log.i(LOGTAG, "call: SQL sqlStatement[" + sqlStatement + "]");
db.execSQL(sqlStatement);
}
db.setTransactionSuccessful();
} catch (SQLException sqle) {
Log.e(LOGTAG, "call: SQLException for sqlStatement(" + i + ")[" + sqlStatement + "]", sqle);
} finally {
db.endTransaction();
}
}
} catch (JSONException jsone) {
Log.i(LOGTAG, "call: error parsing as JSON" + jsone.getMessage());
}
// make sure that potential listeners are getting notified
getContext().getContentResolver().notifyChange(BASE_URI, null);
} else if (METHOD_FETCH_TIMELINE_SEQUENCE.equals(method)) {
long timeline = 0;
long sequence = 0;
try {
SQLiteDatabase db = mSyncedSQLiteOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + Control.TABLE_NAME, null);
if (cursor.moveToFirst()) {
timeline = cursor.getLong(cursor.getColumnIndex(Control.TIMELINE));
sequence = cursor.getLong(cursor.getColumnIndex(Control.SEQUENCE));
} else {
Log.w(LOGTAG, "call: empty cursor, starting sync from 0, 0");
}
} catch (Exception e) {
Log.w(LOGTAG, "call: problem querying timeline and sequence, restarting sync from 0, 0", e);
}
bundle = new Bundle();
// We'll use column names as bundle keys here.
bundle.putLong(Control.TIMELINE, timeline);
bundle.putLong(Control.SEQUENCE, sequence);
} else {
Log.w(LOGTAG, "call: unsupported method[" + method + "]");
}
return bundle;
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
}
| client/android/main/src/com/speedycrew/client/sql/SyncedContentProvider.java | package com.speedycrew.client.sql;
import java.util.List;
import java.util.Vector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
public class SyncedContentProvider extends ContentProvider {
private static final String LOGTAG = SyncedContentProvider.class.getName();
SyncedSQLiteOpenHelper mSyncedSQLiteOpenHelper;
// used for the UriMacher
private static final int URI_SEARCH_INDEX = 10;
private static final int URI_MATCH_INDEX = 20;
private static final String AUTHORITY = "com.speedycrew.client.sql.synced.contentprovider";
private static final String BASE_PATH = "/";
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY);
public static final Uri SEARCH_URI = Uri.parse("content://" + AUTHORITY + BASE_PATH + Search.TABLE_NAME);
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
/**
* SQLite has a handy hidden _rowid_ columns.
*/
public static final String SQLITE_ROWID = "_rowid_";
public static final String METHOD_FETCH_TIMELINE_SEQUENCE = "timeline";
public static final String METHOD_ON_SYNCHRONIZE_RESPONSE = "synchronize";
static {
sURIMatcher.addURI(AUTHORITY, Search.TABLE_NAME, URI_SEARCH_INDEX);
sURIMatcher.addURI(AUTHORITY, Search.TABLE_NAME + "/*/" + Match.TABLE_NAME, URI_MATCH_INDEX);
}
@Override
public boolean onCreate() {
mSyncedSQLiteOpenHelper = new SyncedSQLiteOpenHelper(getContext());
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Log.i(LOGTAG, "query URI[" + uri + "]");
// For our query below, make sure that we have an '_id' column as
// required by Google Adapter classes, even if our table doesn't
// really contain one. To do this, use SQLite's _rowid_.
//
// See: http://www.sqlite.org/lang_createtable.html#rowid
// and:
// http://stackoverflow.com/questions/11365097/sqlite-create-table-with-an-alias-for-rowid
Vector<String> newProjectionVector = new Vector<String>();
for (String passedIn : projection) {
if (BaseColumns._ID.equalsIgnoreCase(passedIn)) {
newProjectionVector.add(SQLITE_ROWID + " as _id");
} else {
newProjectionVector.add(passedIn);
}
}
String[] newProjection = newProjectionVector.toArray(new String[projection.length]);
// Using SQLiteQueryBuilder instead of query() method
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
List<String> pathSegments = uri.getPathSegments();
int uriIndex = sURIMatcher.match(uri);
switch (uriIndex) {
case URI_SEARCH_INDEX:
queryBuilder.setTables(Search.TABLE_NAME);
break;
case URI_MATCH_INDEX:
queryBuilder.setTables(Match.TABLE_NAME);
queryBuilder.appendWhere(Match.SEARCH + "='" + pathSegments.get(1) + "'");
break;
default:
Log.e(LOGTAG, "Unhandled URI[" + uri + "]");
return null;
}
// check if the caller has requested a column which does not exists
// checkColumns(projection);
SQLiteDatabase db = mSyncedSQLiteOpenHelper.getReadableDatabase();
Cursor cursor = queryBuilder.query(db, newProjection, selection, selectionArgs, null, null, sortOrder);
// make sure that potential listeners are getting notified
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Override
public Bundle call(String method, String arg, Bundle extras) {
Log.i(LOGTAG, "call method[" + method + "] arg[" + arg + "]");
Bundle bundle = null;
if (METHOD_ON_SYNCHRONIZE_RESPONSE.equals(method)) {
try {
JSONObject jsonResponse = new JSONObject(arg);
Log.i(LOGTAG, "call: jsonResponse[" + jsonResponse + "]");
JSONArray sqlArray = jsonResponse.getJSONArray("sql");
if (sqlArray != null) {
SQLiteDatabase db = mSyncedSQLiteOpenHelper.getWritableDatabase();
String sqlStatement = null;
try {
db.beginTransaction();
final int length = sqlArray.length();
for (int i = 0; i < length; ++i) {
sqlStatement = sqlArray.getString(i);
Log.i(LOGTAG, "call: SQL sqlStatement[" + sqlStatement + "]");
db.execSQL(sqlStatement);
}
db.setTransactionSuccessful();
} catch (SQLException sqle) {
Log.e(LOGTAG, "call: SQLException for sqlStatement[" + sqlStatement + "]", sqle);
} finally {
db.endTransaction();
}
}
} catch (JSONException jsone) {
Log.i(LOGTAG, "call: error parsing as JSON" + jsone.getMessage());
}
// make sure that potential listeners are getting notified
getContext().getContentResolver().notifyChange(BASE_URI, null);
} else if (METHOD_FETCH_TIMELINE_SEQUENCE.equals(method)) {
long timeline = 0;
long sequence = 0;
try {
SQLiteDatabase db = mSyncedSQLiteOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + Control.TABLE_NAME, null);
if (cursor.moveToFirst()) {
timeline = cursor.getLong(cursor.getColumnIndex(Control.TIMELINE));
sequence = cursor.getLong(cursor.getColumnIndex(Control.SEQUENCE));
} else {
Log.w(LOGTAG, "call: empty cursor, starting sync from 0, 0");
}
} catch (Exception e) {
Log.w(LOGTAG, "call: problem querying timeline and sequence, restarting sync from 0, 0", e);
}
bundle = new Bundle();
// We'll use column names as bundle keys here.
bundle.putLong(Control.TIMELINE, timeline);
bundle.putLong(Control.SEQUENCE, sequence);
} else {
Log.w(LOGTAG, "call: unsupported method[" + method + "]");
}
return bundle;
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
}
| Add an extra little bit of logging about sql execution
| client/android/main/src/com/speedycrew/client/sql/SyncedContentProvider.java | Add an extra little bit of logging about sql execution | <ide><path>lient/android/main/src/com/speedycrew/client/sql/SyncedContentProvider.java
<ide> if (sqlArray != null) {
<ide> SQLiteDatabase db = mSyncedSQLiteOpenHelper.getWritableDatabase();
<ide> String sqlStatement = null;
<add> int i = 0;
<ide> try {
<ide> db.beginTransaction();
<ide>
<ide> final int length = sqlArray.length();
<del> for (int i = 0; i < length; ++i) {
<add> for (i = 0; i < length; ++i) {
<ide> sqlStatement = sqlArray.getString(i);
<ide> Log.i(LOGTAG, "call: SQL sqlStatement[" + sqlStatement + "]");
<ide> db.execSQL(sqlStatement);
<ide> }
<ide> db.setTransactionSuccessful();
<ide> } catch (SQLException sqle) {
<del> Log.e(LOGTAG, "call: SQLException for sqlStatement[" + sqlStatement + "]", sqle);
<add> Log.e(LOGTAG, "call: SQLException for sqlStatement(" + i + ")[" + sqlStatement + "]", sqle);
<ide> } finally {
<ide> db.endTransaction();
<ide> } |
|
Java | apache-2.0 | 6e23f7ece029fb1c38f4d97cd67323b373f1af5d | 0 | oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,MaxRau/CoffeeMud,oriontribunal/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,Tycheo/coffeemud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,oriontribunal/CoffeeMud,bozimmerman/CoffeeMud,sfunk1x/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,oriontribunal/CoffeeMud | package com.planet_ink.coffee_mud.core.smtp;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.JournalsLibrary;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import com.planet_ink.coffee_mud.core.exceptions.*;
import java.io.*;
/*
Copyright 2000-2013 Bo Zimmerman
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.
*/
public class ProcessSMTPrequest implements Runnable
{
private final static String cr = "\r\n";
private final static String S_250 = "250 OK";
private static volatile AtomicInteger instanceCnt = new AtomicInteger(0);
private Socket sock;
private SMTPserver server=null;
private StringBuffer data=null;
protected String from=null;
protected String domain=null;
protected String runnableName;
protected boolean debug=false;
protected Vector<String> to=null;
public ProcessSMTPrequest(Socket a_sock, SMTPserver a_Server)
{
runnableName="SMTPrq"+(instanceCnt.addAndGet(1));
server = a_Server;
sock = a_sock;
}
public String validLocalAccount(String s)
{
int x=s.indexOf('@');
String name=s;
if(x>0)
{
name=s.substring(0,x).trim();
String domain=s.substring(x+1).trim();
if(!domain.toUpperCase().endsWith(server.domainName().toUpperCase()))
{
if(server.mailboxName().length()>0)
{
name=CMLib.database().DBEmailSearch(s);
if(name!=null) return name;
}
return null;
}
}
if(server.getAnEmailJournal(name)!=null)
return server.getAnEmailJournal(name);
if(server.mailboxName().length()>0)
{
if(CMLib.players().playerExists(name))
return CMStrings.capitalizeAndLower(name);
}
return null;
}
public void cleanHtml(String journal, StringBuffer finalData)
{
if(journal!= null)
{
// the input MUST be html -- text that only might be need not apply
JournalsLibrary.ForumJournal forum=CMLib.journals().getForumJournal(journal);
if(forum!=null)
CMStrings.stripHeadHtmlTags(finalData);
else
CMStrings.convertHtmlToText(finalData);
}
else
CMStrings.convertHtmlToText(finalData);
}
public void run()
{
BufferedReader sin = null;
PrintWriter sout = null;
int failures=0;
debug = CMSecurity.isDebugging(CMSecurity.DbgFlag.SMTPSERVER);
byte[] replyData = null;
byte[] lastReplyData = null;
try
{
sock.setSoTimeout(100);
sout=new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"US-ASCII")));
sin=new BufferedReader(new InputStreamReader(sock.getInputStream(),"US-ASCII"));
sout.write("220 ESMTP "+server.domainName()+" "+SMTPserver.ServerVersionString+"; "+CMLib.time().date2String(System.currentTimeMillis())+cr);
sout.flush();
boolean quitFlag=false;
boolean dataMode=false;
LinkedList<String> cmdQueue=new LinkedList<String>();
LinkedList<byte[]> respQueue=new LinkedList<byte[]>();
long timeSinceLastChar=System.currentTimeMillis();
while(!quitFlag)
{
char lastc=(char)-1;
char c=(char)-1;
StringBuffer input=new StringBuffer("");
while(!quitFlag)
{
lastc=c;
try
{
c=(char)sin.read();
}
catch(java.net.SocketTimeoutException ioe)
{
final long ellapsed = System.currentTimeMillis()-timeSinceLastChar;
if(ellapsed > (10 * 1000))
throw ioe;
else
break;
}
if(c<0) throw new IOException("reset by peer");
timeSinceLastChar=System.currentTimeMillis();
if((lastc==cr.charAt(0))&&(c==cr.charAt(1)))
{
cmdQueue.add(input.substring(0,input.length()-1));
input.setLength(0);
continue;
}
if(c!=65535)
input.append(c);
if(input.length()>server.getMaxMsgSize())
{
if(debug)
{
StringBuilder str=new StringBuilder("");
for(int i=0;i<10 && i<input.length();i++)
str.append((int)input.charAt(i)).append(",");
Log.debugOut(runnableName,"Internal: 552 String exceeds size limit ("+server.getMaxMsgSize()+"): "+str.toString());
}
//Log.errOut("SMTPR","Long request from "+sock.getInetAddress());
sout.write("552 String exceeds size limit. You are very bad!"+cr);
sout.flush();
quitFlag=true;
input.setLength(0);
}
}
while(cmdQueue.size()>0)
{
final String s=cmdQueue.removeFirst();
String parm="";
int cmdindex=s.indexOf(' ');
String cmd=s.toUpperCase();
if(cmdindex>0)
{
cmd=s.substring(0,cmdindex).toUpperCase();
parm=s.substring(cmdindex+1);
}
if(debug) Log.debugOut(runnableName,"Input: "+cmd+" "+parm);
if((dataMode)&&(s.equals(".")))
{
if(debug) Log.debugOut(runnableName,"End of data reached.");
dataMode=false;
boolean translateEqualSigns=false;
/*When the SMTP server accepts a message either for relaying or for final delivery, it inserts a trace record (also referred to interchangeably as a "time stamp line" or "Received" line) at the top of the mail data. This trace record indicates the identity of the host that sent the message, the identity of the host that received the message (and is inserting this time stamp), and the date and time the message was received.*/
if(data.length()>=server.getMaxMsgSize())
replyData=("552 Message exceeds size limit."+cr).getBytes();
else
{
replyData=("250 Message accepted for delivery."+cr).getBytes();
boolean startBuffering=false;
StringBuffer finalData=new StringBuffer("");
char bodyType='t'; // h=html, t=text
String subject=null;
String boundry=null;
Map<Character,StringBuffer> dataBlocks=new Hashtable<Character,StringBuffer>();
// -1=waitForHeaderDone,
// 0=waitForFirstHeaderDone,
// 1=waitForBoundry,
// 2=waitForContentTypeConfirmation
int boundryState=-1;
try
{
BufferedReader lineR=new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data.toString().getBytes())));
while(true)
{
String s2=lineR.readLine();
if(s2==null) break;
String s2u=s2.toUpperCase();
if(debug) Log.debugOut(runnableName,"Header State="+boundryState+", "+s2);
if((startBuffering)&&(boundry!=null)&&(s2.indexOf(boundry)>=0))
{
if(debug) Log.debugOut(runnableName,"Multipart boundary "+boundry+" completed.");
if(finalData.length()>0)
dataBlocks.put(Character.valueOf(bodyType), finalData);
finalData=new StringBuffer("");
boundryState=-1;
startBuffering=false;
continue;
}
else
if(startBuffering)
{
boolean nextAppended=false;
if(translateEqualSigns)
{
if(s2.indexOf('=')>=0)
{
StringBuffer newStr=new StringBuffer(s2);
for(int c1=0;c1<newStr.length()-2;c1++)
if(newStr.charAt(c1)=='=')
{
if(("0123456789ABCDEF".indexOf(Character.toUpperCase(newStr.charAt(c1+1)))>=0)
&&("0123456789ABCDEF".indexOf(Character.toUpperCase(newStr.charAt(c1+2)))>=0))
{
int x=(16*("0123456789ABCDEF".indexOf(Character.toUpperCase(newStr.charAt(c1+1)))))
+"0123456789ABCDEF".indexOf(Character.toUpperCase(newStr.charAt(c1+2)));
newStr.replace(c1,c1+3,""+((char)x));
}
}
s2=newStr.toString();
}
if(s2.endsWith("="))
{
nextAppended=true;
s2=s2.substring(0,s2.length()-1);
}
else
if(s2.endsWith("=<BR>"))
{
nextAppended=true;
s2=s2.substring(0,s2.length()-5);
}
}
if(nextAppended)
finalData.append(s2);
else
finalData.append(s2+cr);
}
else
if((s2.length()==0)&&(boundryState<0))
startBuffering=true;
else
if((s2.length()==0)&&(boundryState==0))
boundryState=1;
else
if(boundryState==1)
{
if(debug) Log.debugOut(runnableName,"Boundary "+boundry+" spotted -- state is now 2.");
if(s2.indexOf(boundry)>=0)
boundryState=2;
continue;
}
else
if((s2u.startsWith("SUBJECT: "))&&(boundryState<2))
{
subject=s2.substring(9).trim();
if(debug) Log.debugOut(runnableName,"Subject="+subject);
}
else
if((s2u.startsWith("CONTENT-TRANSFER-ENCODING: "))
||(s2u.startsWith("CONTENT TRANSFER ENCODING: ")))
{
if(s2u.substring(27).trim().startsWith("QUOTED-PRINTABLE")
||s2u.substring(27).trim().startsWith("QUOTED PRINTABLE"))
translateEqualSigns=true;
else
translateEqualSigns=false;
if(debug) Log.debugOut(runnableName,"Transfer Equal Sign="+translateEqualSigns);
}
else
if((s2u.startsWith("CONTENT TYPE: ")||s2u.startsWith("CONTENT-TYPE: ")))
{
if((boundryState<0)&&(s2u.substring(14).trim().startsWith("MULTIPART/")))
{
String contentType=s2.substring(14).trim();
int y=s2u.indexOf(';');
if(y>=0) contentType=s2.substring(14,y).trim();
int x=s2u.indexOf("BOUNDARY=");
for(int z=0;(z<5)&&(x<0);z++)
{
s2=lineR.readLine();
if(s2==null) break;
s2u=s2.toUpperCase();
x=s2u.indexOf("BOUNDARY=");
}
if(x<0)
{
replyData=("552 Message content type '"+contentType+"' not accepted without boundry."+cr).getBytes();
subject=null;
break;
}
if(s2!=null)
{
boundry=s2.substring(x+9).trim();
y=s2.indexOf(';');
if(y>=0) s2=s2.substring(0,y).trim();
if(boundry.startsWith("\"")&&boundry.endsWith("\""))
boundry=boundry.substring(1,boundry.length()-1).trim();
boundryState=0;
}
}
else
if(s2u.substring(14).trim().startsWith("TEXT/HTML"))
{
if(boundryState==2)
boundryState=-1;
bodyType='h';
}
else
if(!s2u.substring(14).trim().startsWith("TEXT/PLAIN"))
{
bodyType='t';
if(boundryState==2)
boundryState=0;
else
{
replyData=("552 Message content type '"+s2u.substring(14).trim()+"' not accepted."+cr).getBytes();
subject=null;
break;
}
}
else
if(boundryState==2)
boundryState=-1;
}
}
}
catch(IOException e){}
if((replyData!=null)&&(new String(replyData).startsWith("250")))
{
if((finalData.length()==0)&&(!startBuffering))
{
finalData=new StringBuffer(data.toString());
if(subject==null) subject="";
}
if(dataBlocks.containsKey(Character.valueOf('h')))
{
bodyType='h';
finalData=dataBlocks.get(Character.valueOf('h'));
}
else
if(finalData.toString().trim().length()==0)
{
if(dataBlocks.size()>0)
{
bodyType=dataBlocks.keySet().iterator().next().charValue();
finalData=dataBlocks.get(Character.valueOf(bodyType));
}
}
if((finalData.toString().trim().length()>0) && (subject!=null))
{
if(subject.toUpperCase().startsWith("MOTD")
||subject.toUpperCase().startsWith("MOTM")
||subject.toUpperCase().startsWith("MOTY"))
{
MOB M=CMLib.players().getLoadPlayer(from);
if((M==null)||(!CMSecurity.isAllowedAnywhere(M,CMSecurity.SecFlag.JOURNALS)))
subject=subject.substring(4);
}
for(int i=0;i<to.size();i++)
{
String journal=server.getAnEmailJournal(to.elementAt(i));
if(journal!=null)
{
String parentKey="";
String fdat=finalData.toString().trim();
if((subject!=null)
&&(!subject.trim().equalsIgnoreCase("subscribe"))
&&(!subject.trim().equalsIgnoreCase("unsubscribe"))
&&(!fdat.trim().equalsIgnoreCase("subscribe"))
&&(!fdat.trim().equalsIgnoreCase("unsubscribe"))
&&(server.isAForwardingJournal(journal)))
{
if(server.isASubscribeOnlyJournal(journal))
{
MOB M=CMLib.players().getLoadPlayer(from);
if((M==null)||(!CMSecurity.isAllowedAnywhere(M,CMSecurity.SecFlag.JOURNALS)))
{
replyData=("552 Mailbox '"+journal+"' only accepts subscribe/unsubscribe."+cr).getBytes();
break;
}
}
else
{
Map<String, List<String>> lists=Resources.getCachedMultiLists("mailinglists.txt",true);
List<String> mylist=null;
if(lists!=null) mylist=lists.get(journal);
if((mylist==null)||(!mylist.contains(from)))
{
if(debug) Log.debugOut(runnableName,from+" is not in mailing list for journal "+journal);
replyData=("552 Mailbox '"+journal+"' only accepts messages from subscribers. Send an email with 'subscribe' as the subject."+cr).getBytes();
break;
}
JournalsLibrary.ForumJournal forum=CMLib.journals().getForumJournal(journal);
if((forum != null)
&&(subject.trim().toUpperCase().startsWith("RE:")||subject.trim().toUpperCase().startsWith("RE ")))
{
String realSubject=subject.substring(3).trim();
if(realSubject.toUpperCase().startsWith("["+journal.toUpperCase()+"]"))
realSubject=realSubject.substring(journal.length()+2).trim();
List<JournalsLibrary.JournalEntry> entries = CMLib.database().DBReadJournalPageMsgs(journal, null, realSubject, 0, 0);
for(final JournalsLibrary.JournalEntry entry : entries)
if(entry.subj.equalsIgnoreCase(realSubject))
{
parentKey=entry.key;
break;
}
}
}
}
if(debug) Log.debugOut(runnableName,"Written: "+journal+"/"+from+"/ALL/"+bodyType);
StringBuffer finalFinalData=new StringBuffer(finalData);
if(bodyType=='h')
cleanHtml(journal, finalFinalData);
CMLib.database().DBWriteJournalChild(journal, "",from, "ALL", parentKey,
CMLib.coffeeFilter().simpleInFilter(new StringBuffer(subject),false).toString(),
CMLib.coffeeFilter().simpleInFilter(finalData,false).toString());
}
else
{
if(debug) Log.debugOut(runnableName,"Written: "+server.mailboxName()+"/"+from+"/"+to.elementAt(i)+"/"+bodyType);
StringBuffer finalFinalData=new StringBuffer(finalData);
if(bodyType=='h')
cleanHtml(journal, finalFinalData);
CMLib.database().DBWriteJournal(server.mailboxName(),
from,
to.elementAt(i),
CMLib.coffeeFilter().simpleInFilter(new StringBuffer(subject),false).toString(),
CMLib.coffeeFilter().simpleInFilter(finalFinalData,false).toString());
}
}
}
}
}
}
else
if(cmd.equals("RSET"))
{
replyData=("250 Reset state"+cr).getBytes();
dataMode=false;
from=null;
to=null;
data=null;
}
else
if(dataMode)
{
if(data==null) data=new StringBuffer("");
if(data.length()<server.getMaxMsgSize())
data.append(s+cr);
}
else
if(cmd.equals("HELP"))
{
parm=parm.toUpperCase();
if(parm.length()==0)
{
replyData=(
"214-This is "+SMTPserver.ServerVersionString+cr+
"214-Topics:"+cr+
"214- HELO EHLO MAIL RCPT DATA"+cr+
"214- RSET NOOP QUIT HELP VRFY"+cr+
"214- EXPN VERB ETRN DSN"+cr+
"214-For more info use \"HELP <topic>\"."+cr+
"214-For local information send email to your local Archon."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("NOOP"))
{
replyData=(
"214-NOOP"+cr+
"214- Do nothing."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("HELO"))
{
replyData=(
"214-HELO <hostname>"+cr+
"214- Introduce yourself."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("EHLO"))
{
replyData=(
"214-EHLO"+cr+
"214- Introduce yourself, and request extended SMTP mode."+cr+
"214-Possible replies include:"+cr+
"214- SEND Send as mail [RFC821]"+cr+
"214- SOML Send as mail or terminal [RFC821]"+cr+
"214- SAML Send as mail and terminal [RFC821]"+cr+
"214- EXPN Expand the mailing list [RFC821]"+cr+
"214- HELP Supply helpful information [RFC821]"+cr+
"214- TURN Turn the operation around [RFC821]"+cr+
"214- 8BITMIME Use 8-bit data [RFC1652]"+cr+
"214- SIZE Message size declaration [RFC1870]"+cr+
"214- VERB Verbose [Allman]"+cr+
"214- ONEX One message transaction only [Allman]"+cr+
"214- CHUNKING Chunking [RFC1830]"+cr+
"214- BINARYMIME Binary MIME [RFC1830]"+cr+
"214- PIPELINING Command Pipelining [RFC1854]"+cr+
"214- DSN Delivery Status Notification [RFC1891]"+cr+
"214- ETRN Remote Message Queue Starting [RFC1985]"+cr+
"214- XUSR Initial (user) submission [Allman]"+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("MAIL"))
{
replyData=(
"214-MAIL FROM: <sender> [ <parameters> ]"+cr+
"214- Specifies the sender. Parameters are ESMTP extensions."+cr+
"214- See \"HELP DSN\" for details."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("DATA"))
{
replyData=(
"214-DATA"+cr+
"214- Following text is collected as the message."+cr+
"214- End with a single dot."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("RSET"))
{
replyData=(
"214-RSET"+cr+
"214- Resets the system."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("QUIT"))
{
replyData=(
"214-QUIT"+cr+
"214- Exit SMTP."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("VRFY"))
{
replyData=(
"214-VRFY <recipient>"+cr+
"214- Verify an address. If you want to see what it aliases"+cr+
"214- to, use EXPN instead."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("EXPN"))
{
replyData=(
"214-EXPN <recipient>"+cr+
"214- Expand an address. If the address indicates a mailing"+cr+
"214- list, return the contents of that list."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("VERB"))
{
replyData=(
"214-VERB"+cr+
"214- Not implemented in this server."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("ETRN"))
{
replyData=(
"214-ETRN [ <hostname> | @<domain> | #<queuename> ]"+cr+
"214- Not implemented in this server."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("DSN"))
{
replyData=(
"214-MAIL FROM: <sender> [ RET={ FULL | HDRS} ] [ ENVID=<envid> ]"+cr+
"214-RCPT TO: <recipient> [ NOTIFY={NEVER,SUCCESS,FAILURE,DELAY} ]"+cr+
"214- [ ORCPT=<recipient> ]"+cr+
"214- SMTP Delivery Status Notifications."+cr+
"214-Descriptions:"+cr+
"214- RET Return either the full message or only headers."+cr+
"214- ENVID Sender's \"envelope identifier\" for tracking."+cr+
"214- NOTIFY When to send a DSN. Multiple options are OK, comma-"+cr+
"214- delimited. NEVER must appear by itself."+cr+
"214- ORCPT Original recipient."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("RCPT"))
{
replyData=(
"214-RCPT TO: <recipient> [ <parameters> ]"+cr+
"214- Specifies the recipient. Can be used any number of times."+cr+
"214- Parameters are ESMTP extensions. See \"HELP DSN\" for details."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
replyData=("504 Help topic \""+parm+"\" unknown"+cr).getBytes();
}
else
if(cmd.equals("NOOP"))
replyData=(S_250+cr).getBytes();
else
if(cmd.equals("HELO")
||cmd.equals("EHLO"))
{
if((domain!=null)&&(parm.trim().length()==0))
replyData=("503 "+sock.getLocalAddress().getHostName()+" Duplicate HELO/EHLO"+cr).getBytes();
else
if(parm.trim().length()==0)
replyData=("501 "+cmd+" requires domain address"+cr).getBytes();
else
{
domain=parm;
replyData=("250 "+sock.getLocalAddress().getHostName()+" Hello "+sock.getInetAddress().getHostName()+" ["+sock.getInetAddress().getHostAddress()+"], pleased to meet you"+cr).getBytes();
if(cmd.equals("EHLO"))
{
replyData=(new String(replyData)
+"250-8BITMIME"+cr
+"250-SIZE "+server.getMaxMsgSize()+cr
+"250-DSN"+cr
+"250-ONEX"+cr
+"250 HELP"+cr).getBytes();
}
}
}
else
if(cmd.equals("MAIL"))
{
int x=parm.indexOf(':');
if(x<0)
replyData=("501 Syntax error in \""+parm+"\""+cr).getBytes();
else
{
String to2=parm.substring(0,x).trim();
if(!to2.equalsIgnoreCase("from"))
replyData=("500 Unrecognized command \""+cmd+"\""+cr).getBytes();
else
{
parm=parm.substring(x+1).trim();
String parmparms="";
boolean error=false;
if(parm.startsWith("<"))
{
x=parm.indexOf('>');
if(x<0)
{
replyData=("501 Syntax error in \""+parm+"\""+cr).getBytes();
error=true;
}
else
{
parmparms=parm.substring(x+1).trim();
parm=parm.substring(1,x);
}
}
else
if(parm.indexOf(' ')>=0)
{
replyData=("501 Syntax error in \""+parm+"\""+cr).getBytes();
error=true;
}
if(parmparms.trim().length()>0)
{
if((parmparms.trim().toUpperCase().startsWith("SIZE="))
||(!CMath.isNumber(parmparms.trim().toUpperCase().substring(5))))
{
int size=CMath.s_int(parmparms.trim().toUpperCase().substring(5));
if(size>server.getMaxMsgSize())
{
replyData=("552 String exceeds size limit. But you were nice to tell me!"+cr).getBytes();
error=true;
}
}
else
{
replyData=("502 Parameters not supported... \""+parmparms+"\""+cr).getBytes();
error=true;
}
}
if(!error)
{
String name=validLocalAccount(parm);
if(name==null)
{
if((++failures)==3)
{
replyData=("421 Quit Fishing!"+cr).getBytes();
quitFlag=true;
}
else
replyData=("551 Requested action not taken: User is not local."+cr).getBytes();
}
else
{
replyData=("250 OK "+name+cr).getBytes();
from=name;
}
}
}
}
}
else
if(cmd.equals("DATA"))
{
if(from==null)
replyData=("503 Need MAIL command"+cr).getBytes();
else
if(to==null)
replyData=("503 Need RCPT (recipient)"+cr).getBytes();
else
{
replyData=("354 Enter mail, end with \".\" on a line by itself"+cr).getBytes();
dataMode=true;
}
}
else
if(cmd.equals("QUIT"))
{
replyData=("221 "+server.domainName()+" closing connection"+cr).getBytes();
quitFlag=true;
}
else
if(cmd.equals("VRFY"))
replyData=("252 Cannot VRFY user; try RCPT to attempt delivery (or try finger)"+cr).getBytes();
else
if(cmd.equals("EXPN"))
replyData=("502 Sorry, we don't allow mailing lists"+cr).getBytes();
else
if(cmd.equals("VERB"))
replyData=("502 Verbose unavailable"+cr).getBytes();
else
if(cmd.equals("ETRN"))
replyData=("502 ETRN not implemented"+cr).getBytes();
else
if(cmd.equals("RCPT"))
{
int x=parm.indexOf(':');
if(x<0)
replyData=("501 Syntax error in \""+parm+"\""+cr).getBytes();
else
{
String to2=parm.substring(0,x).trim();
if(!to2.equalsIgnoreCase("to"))
replyData=("500 Unrecognized command \""+cmd+"\""+cr).getBytes();
else
{
parm=parm.substring(x+1).trim();
String parmparms="";
boolean error=false;
if(parm.startsWith("<"))
{
x=parm.indexOf('>');
if(x<0)
{
replyData=("501 Syntax error in \""+parm+"\""+cr).getBytes();
error=true;
}
else
{
parmparms=parm.substring(x+1).trim();
parm=parm.substring(1,x);
}
}
else
if(parm.indexOf(' ')>=0)
{
replyData=("501 Syntax error in \""+parm+"\""+cr).getBytes();
error=true;
}
if(parmparms.trim().length()>0)
{
if((parmparms.trim().toUpperCase().startsWith("SIZE="))
||(!CMath.isNumber(parmparms.trim().toUpperCase().substring(5))))
{
int size=CMath.s_int(parmparms.trim().toUpperCase().substring(5));
if(size>server.getMaxMsgSize())
replyData=("552 String exceeds size limit. But you were nice to tell me!"+cr).getBytes();
}
else
replyData=("502 Parameters not supported... \""+parmparms+"\""+cr).getBytes();
}
else
if(parm.indexOf('@')<0)
replyData=("550 "+parm+" user unknown."+cr).getBytes();
else
if(!error)
{
String name=validLocalAccount(parm);
if(name==null)
{
if((++failures)==3)
{
replyData=("421 Quit Fishing!"+cr).getBytes();
quitFlag=true;
}
else
replyData=("553 Requested action not taken: User is not local."+cr).getBytes();
}
else
{
if(server.getAnEmailJournal(name)!=null)
{
boolean jerror=false;
if(server.getJournalCriteria(name)!=null)
{
if(from==null)
{
replyData=("503 Need MAIL before RCPT"+cr).getBytes();
jerror=true;
}
else
{
MOB M=CMLib.players().getPlayer(from);
if((M==null)
||(!CMLib.masking().maskCheck(server.getJournalCriteria(name),M,false)))
{
replyData=("552 User '"+from+"' may not send emails to '"+name+"'."+cr).getBytes();
jerror=true;
}
}
}
if(!jerror)
{
replyData=("250 OK "+name+cr).getBytes();
if(to==null) to=new Vector<String>();
if(!to.contains(name))
to.addElement(name);
}
}
else
if(CMLib.database().DBCountJournal(server.mailboxName(),null,name)>=server.getMaxMsgs())
replyData=("552 Mailbox '"+name+"' is full."+cr).getBytes();
else
{
replyData=("250 OK "+name+cr).getBytes();
if(to==null) to=new Vector<String>();
if(!to.contains(name))
to.addElement(name);
}
}
}
}
}
}
else
replyData=lastReplyData;//("500 Command Unrecognized: \""+cmd+"\""+cr).getBytes();
if ((replyData != null))
{
respQueue.add(replyData);
replyData=null;
if(cmdQueue.size()==0)
{
// we should be looping through these .. why does ZD act so wierd?!
byte [] resp=respQueue.getLast();
if(debug) Log.debugOut(runnableName,"Reply: "+CMStrings.replaceAll(new String(resp),cr,"\\r\\n"));
// must insert a blank line before message body
sout.write(new String(resp));
sout.flush();
respQueue.clear();
}
}
}
}
}
catch (java.net.SocketTimeoutException e2)
{
try
{
if (sout != null)
{
sout.write("421 You're taking too long. I'm outa here."+cr);
sout.flush();
}
}
catch(Exception e)
{
Log.errOut(runnableName,"Exception2: " + e.getMessage() );
}
}
catch (Exception e)
{
final String errorMessage=e.getMessage();
final StringBuilder msg = new StringBuilder(errorMessage==null?"EMPTY e.getMessage()":errorMessage);
final StackTraceElement[] ts = e.getStackTrace();
if(ts != null)
for(StackTraceElement t : ts)
msg.append(" ").append(t.getFileName()).append("(").append(t.getLineNumber()).append(")");
Log.errOut(runnableName,"Exception: " + msg.toString() );
}
try
{
if (sout != null)
{
sout.flush();
sout.close();
sout = null;
}
}
catch (Exception e) {}
try
{
if (sin != null)
{
sin.close();
sin = null;
}
}
catch (Exception e) {}
try
{
if (sock != null)
{
sock.close();
sock = null;
}
}
catch (Exception e) {}
}
}
| com/planet_ink/coffee_mud/core/smtp/ProcessSMTPrequest.java | package com.planet_ink.coffee_mud.core.smtp;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.JournalsLibrary;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import com.planet_ink.coffee_mud.core.exceptions.*;
import java.io.*;
/*
Copyright 2000-2013 Bo Zimmerman
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.
*/
public class ProcessSMTPrequest implements Runnable
{
private final static String cr = "\r\n";
private final static String S_250 = "250 OK";
private static volatile AtomicInteger instanceCnt = new AtomicInteger(0);
private Socket sock;
private SMTPserver server=null;
private StringBuffer data=null;
protected String from=null;
protected String domain=null;
protected String runnableName;
protected boolean debug=false;
protected Vector<String> to=null;
public ProcessSMTPrequest(Socket a_sock, SMTPserver a_Server)
{
runnableName="SMTPrq"+(instanceCnt.addAndGet(1));
server = a_Server;
sock = a_sock;
}
public String validLocalAccount(String s)
{
int x=s.indexOf('@');
String name=s;
if(x>0)
{
name=s.substring(0,x).trim();
String domain=s.substring(x+1).trim();
if(!domain.toUpperCase().endsWith(server.domainName().toUpperCase()))
{
if(server.mailboxName().length()>0)
{
name=CMLib.database().DBEmailSearch(s);
if(name!=null) return name;
}
return null;
}
}
if(server.getAnEmailJournal(name)!=null)
return server.getAnEmailJournal(name);
if(server.mailboxName().length()>0)
{
if(CMLib.players().playerExists(name))
return CMStrings.capitalizeAndLower(name);
}
return null;
}
public void cleanHtml(String journal, StringBuffer finalData)
{
if(journal!= null)
{
// the input MUST be html -- text that only might be need not apply
JournalsLibrary.ForumJournal forum=CMLib.journals().getForumJournal(journal);
if(forum!=null)
CMStrings.stripHeadHtmlTags(finalData);
else
CMStrings.convertHtmlToText(finalData);
}
else
CMStrings.convertHtmlToText(finalData);
}
public void run()
{
BufferedReader sin = null;
PrintWriter sout = null;
int failures=0;
debug = CMSecurity.isDebugging(CMSecurity.DbgFlag.SMTPSERVER);
byte[] replyData = null;
byte[] lastReplyData = null;
try
{
sock.setSoTimeout(100);
sout=new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"US-ASCII")));
sin=new BufferedReader(new InputStreamReader(sock.getInputStream(),"US-ASCII"));
sout.write("220 ESMTP "+server.domainName()+" "+SMTPserver.ServerVersionString+"; "+CMLib.time().date2String(System.currentTimeMillis())+cr);
sout.flush();
boolean quitFlag=false;
boolean dataMode=false;
LinkedList<String> cmdQueue=new LinkedList<String>();
LinkedList<byte[]> respQueue=new LinkedList<byte[]>();
long timeSinceLastChar=System.currentTimeMillis();
while(!quitFlag)
{
char lastc=(char)-1;
char c=(char)-1;
StringBuffer input=new StringBuffer("");
while(!quitFlag)
{
lastc=c;
try
{
c=(char)sin.read();
}
catch(java.net.SocketTimeoutException ioe)
{
final long ellapsed = System.currentTimeMillis()-timeSinceLastChar;
if(ellapsed > (10 * 1000))
throw ioe;
else
break;
}
if(c<0) throw new IOException("reset by peer");
timeSinceLastChar=System.currentTimeMillis();
if((lastc==cr.charAt(0))&&(c==cr.charAt(1)))
{
cmdQueue.add(input.substring(0,input.length()-1));
input.setLength(0);
continue;
}
input.append(c);
if(input.length()>server.getMaxMsgSize())
{
if(debug)
{
StringBuilder str=new StringBuilder("");
for(int i=0;i<10 && i<input.length();i++)
str.append((int)input.charAt(i)).append(",");
Log.debugOut(runnableName,"Internal: 552 String exceeds size limit ("+server.getMaxMsgSize()+"): "+str.toString());
}
//Log.errOut("SMTPR","Long request from "+sock.getInetAddress());
sout.write("552 String exceeds size limit. You are very bad!"+cr);
sout.flush();
quitFlag=true;
input.setLength(0);
}
}
while(cmdQueue.size()>0)
{
final String s=cmdQueue.removeFirst();
String parm="";
int cmdindex=s.indexOf(' ');
String cmd=s.toUpperCase();
if(cmdindex>0)
{
cmd=s.substring(0,cmdindex).toUpperCase();
parm=s.substring(cmdindex+1);
}
if(debug) Log.debugOut(runnableName,"Input: "+cmd+" "+parm);
if((dataMode)&&(s.equals(".")))
{
if(debug) Log.debugOut(runnableName,"End of data reached.");
dataMode=false;
boolean translateEqualSigns=false;
/*When the SMTP server accepts a message either for relaying or for final delivery, it inserts a trace record (also referred to interchangeably as a "time stamp line" or "Received" line) at the top of the mail data. This trace record indicates the identity of the host that sent the message, the identity of the host that received the message (and is inserting this time stamp), and the date and time the message was received.*/
if(data.length()>=server.getMaxMsgSize())
replyData=("552 Message exceeds size limit."+cr).getBytes();
else
{
replyData=("250 Message accepted for delivery."+cr).getBytes();
boolean startBuffering=false;
StringBuffer finalData=new StringBuffer("");
char bodyType='t'; // h=html, t=text
String subject=null;
String boundry=null;
Map<Character,StringBuffer> dataBlocks=new Hashtable<Character,StringBuffer>();
// -1=waitForHeaderDone,
// 0=waitForFirstHeaderDone,
// 1=waitForBoundry,
// 2=waitForContentTypeConfirmation
int boundryState=-1;
try
{
BufferedReader lineR=new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data.toString().getBytes())));
while(true)
{
String s2=lineR.readLine();
if(s2==null) break;
String s2u=s2.toUpperCase();
if(debug) Log.debugOut(runnableName,"Header State="+boundryState+", "+s2);
if((startBuffering)&&(boundry!=null)&&(s2.indexOf(boundry)>=0))
{
if(debug) Log.debugOut(runnableName,"Multipart boundary "+boundry+" completed.");
if(finalData.length()>0)
dataBlocks.put(Character.valueOf(bodyType), finalData);
finalData=new StringBuffer("");
boundryState=-1;
startBuffering=false;
continue;
}
else
if(startBuffering)
{
boolean nextAppended=false;
if(translateEqualSigns)
{
if(s2.indexOf('=')>=0)
{
StringBuffer newStr=new StringBuffer(s2);
for(int c1=0;c1<newStr.length()-2;c1++)
if(newStr.charAt(c1)=='=')
{
if(("0123456789ABCDEF".indexOf(Character.toUpperCase(newStr.charAt(c1+1)))>=0)
&&("0123456789ABCDEF".indexOf(Character.toUpperCase(newStr.charAt(c1+2)))>=0))
{
int x=(16*("0123456789ABCDEF".indexOf(Character.toUpperCase(newStr.charAt(c1+1)))))
+"0123456789ABCDEF".indexOf(Character.toUpperCase(newStr.charAt(c1+2)));
newStr.replace(c1,c1+3,""+((char)x));
}
}
s2=newStr.toString();
}
if(s2.endsWith("="))
{
nextAppended=true;
s2=s2.substring(0,s2.length()-1);
}
else
if(s2.endsWith("=<BR>"))
{
nextAppended=true;
s2=s2.substring(0,s2.length()-5);
}
}
if(nextAppended)
finalData.append(s2);
else
finalData.append(s2+cr);
}
else
if((s2.length()==0)&&(boundryState<0))
startBuffering=true;
else
if((s2.length()==0)&&(boundryState==0))
boundryState=1;
else
if(boundryState==1)
{
if(debug) Log.debugOut(runnableName,"Boundary "+boundry+" spotted -- state is now 2.");
if(s2.indexOf(boundry)>=0)
boundryState=2;
continue;
}
else
if((s2u.startsWith("SUBJECT: "))&&(boundryState<2))
{
subject=s2.substring(9).trim();
if(debug) Log.debugOut(runnableName,"Subject="+subject);
}
else
if((s2u.startsWith("CONTENT-TRANSFER-ENCODING: "))
||(s2u.startsWith("CONTENT TRANSFER ENCODING: ")))
{
if(s2u.substring(27).trim().startsWith("QUOTED-PRINTABLE")
||s2u.substring(27).trim().startsWith("QUOTED PRINTABLE"))
translateEqualSigns=true;
else
translateEqualSigns=false;
if(debug) Log.debugOut(runnableName,"Transfer Equal Sign="+translateEqualSigns);
}
else
if((s2u.startsWith("CONTENT TYPE: ")||s2u.startsWith("CONTENT-TYPE: ")))
{
if((boundryState<0)&&(s2u.substring(14).trim().startsWith("MULTIPART/")))
{
String contentType=s2.substring(14).trim();
int y=s2u.indexOf(';');
if(y>=0) contentType=s2.substring(14,y).trim();
int x=s2u.indexOf("BOUNDARY=");
for(int z=0;(z<5)&&(x<0);z++)
{
s2=lineR.readLine();
if(s2==null) break;
s2u=s2.toUpperCase();
x=s2u.indexOf("BOUNDARY=");
}
if(x<0)
{
replyData=("552 Message content type '"+contentType+"' not accepted without boundry."+cr).getBytes();
subject=null;
break;
}
if(s2!=null)
{
boundry=s2.substring(x+9).trim();
y=s2.indexOf(';');
if(y>=0) s2=s2.substring(0,y).trim();
if(boundry.startsWith("\"")&&boundry.endsWith("\""))
boundry=boundry.substring(1,boundry.length()-1).trim();
boundryState=0;
}
}
else
if(s2u.substring(14).trim().startsWith("TEXT/HTML"))
{
if(boundryState==2)
boundryState=-1;
bodyType='h';
}
else
if(!s2u.substring(14).trim().startsWith("TEXT/PLAIN"))
{
bodyType='t';
if(boundryState==2)
boundryState=0;
else
{
replyData=("552 Message content type '"+s2u.substring(14).trim()+"' not accepted."+cr).getBytes();
subject=null;
break;
}
}
else
if(boundryState==2)
boundryState=-1;
}
}
}
catch(IOException e){}
if((replyData!=null)&&(new String(replyData).startsWith("250")))
{
if((finalData.length()==0)&&(!startBuffering))
{
finalData=new StringBuffer(data.toString());
if(subject==null) subject="";
}
if(dataBlocks.containsKey(Character.valueOf('h')))
{
bodyType='h';
finalData=dataBlocks.get(Character.valueOf('h'));
}
else
if(finalData.toString().trim().length()==0)
{
if(dataBlocks.size()>0)
{
bodyType=dataBlocks.keySet().iterator().next().charValue();
finalData=dataBlocks.get(Character.valueOf(bodyType));
}
}
if((finalData.toString().trim().length()>0) && (subject!=null))
{
if(subject.toUpperCase().startsWith("MOTD")
||subject.toUpperCase().startsWith("MOTM")
||subject.toUpperCase().startsWith("MOTY"))
{
MOB M=CMLib.players().getLoadPlayer(from);
if((M==null)||(!CMSecurity.isAllowedAnywhere(M,CMSecurity.SecFlag.JOURNALS)))
subject=subject.substring(4);
}
for(int i=0;i<to.size();i++)
{
String journal=server.getAnEmailJournal(to.elementAt(i));
if(journal!=null)
{
String parentKey="";
String fdat=finalData.toString().trim();
if((subject!=null)
&&(!subject.trim().equalsIgnoreCase("subscribe"))
&&(!subject.trim().equalsIgnoreCase("unsubscribe"))
&&(!fdat.trim().equalsIgnoreCase("subscribe"))
&&(!fdat.trim().equalsIgnoreCase("unsubscribe"))
&&(server.isAForwardingJournal(journal)))
{
if(server.isASubscribeOnlyJournal(journal))
{
MOB M=CMLib.players().getLoadPlayer(from);
if((M==null)||(!CMSecurity.isAllowedAnywhere(M,CMSecurity.SecFlag.JOURNALS)))
{
replyData=("552 Mailbox '"+journal+"' only accepts subscribe/unsubscribe."+cr).getBytes();
break;
}
}
else
{
Map<String, List<String>> lists=Resources.getCachedMultiLists("mailinglists.txt",true);
List<String> mylist=null;
if(lists!=null) mylist=lists.get(journal);
if((mylist==null)||(!mylist.contains(from)))
{
if(debug) Log.debugOut(runnableName,from+" is not in mailing list for journal "+journal);
replyData=("552 Mailbox '"+journal+"' only accepts messages from subscribers. Send an email with 'subscribe' as the subject."+cr).getBytes();
break;
}
JournalsLibrary.ForumJournal forum=CMLib.journals().getForumJournal(journal);
if((forum != null)
&&(subject.trim().toUpperCase().startsWith("RE:")||subject.trim().toUpperCase().startsWith("RE ")))
{
String realSubject=subject.substring(3).trim();
if(realSubject.toUpperCase().startsWith("["+journal.toUpperCase()+"]"))
realSubject=realSubject.substring(journal.length()+2).trim();
List<JournalsLibrary.JournalEntry> entries = CMLib.database().DBReadJournalPageMsgs(journal, null, realSubject, 0, 0);
for(final JournalsLibrary.JournalEntry entry : entries)
if(entry.subj.equalsIgnoreCase(realSubject))
{
parentKey=entry.key;
break;
}
}
}
}
if(debug) Log.debugOut(runnableName,"Written: "+journal+"/"+from+"/ALL/"+bodyType);
StringBuffer finalFinalData=new StringBuffer(finalData);
if(bodyType=='h')
cleanHtml(journal, finalFinalData);
CMLib.database().DBWriteJournalChild(journal, "",from, "ALL", parentKey,
CMLib.coffeeFilter().simpleInFilter(new StringBuffer(subject),false).toString(),
CMLib.coffeeFilter().simpleInFilter(finalData,false).toString());
}
else
{
if(debug) Log.debugOut(runnableName,"Written: "+server.mailboxName()+"/"+from+"/"+to.elementAt(i)+"/"+bodyType);
StringBuffer finalFinalData=new StringBuffer(finalData);
if(bodyType=='h')
cleanHtml(journal, finalFinalData);
CMLib.database().DBWriteJournal(server.mailboxName(),
from,
to.elementAt(i),
CMLib.coffeeFilter().simpleInFilter(new StringBuffer(subject),false).toString(),
CMLib.coffeeFilter().simpleInFilter(finalFinalData,false).toString());
}
}
}
}
}
}
else
if(cmd.equals("RSET"))
{
replyData=("250 Reset state"+cr).getBytes();
dataMode=false;
from=null;
to=null;
data=null;
}
else
if(dataMode)
{
if(data==null) data=new StringBuffer("");
if(data.length()<server.getMaxMsgSize())
data.append(s+cr);
}
else
if(cmd.equals("HELP"))
{
parm=parm.toUpperCase();
if(parm.length()==0)
{
replyData=(
"214-This is "+SMTPserver.ServerVersionString+cr+
"214-Topics:"+cr+
"214- HELO EHLO MAIL RCPT DATA"+cr+
"214- RSET NOOP QUIT HELP VRFY"+cr+
"214- EXPN VERB ETRN DSN"+cr+
"214-For more info use \"HELP <topic>\"."+cr+
"214-For local information send email to your local Archon."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("NOOP"))
{
replyData=(
"214-NOOP"+cr+
"214- Do nothing."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("HELO"))
{
replyData=(
"214-HELO <hostname>"+cr+
"214- Introduce yourself."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("EHLO"))
{
replyData=(
"214-EHLO"+cr+
"214- Introduce yourself, and request extended SMTP mode."+cr+
"214-Possible replies include:"+cr+
"214- SEND Send as mail [RFC821]"+cr+
"214- SOML Send as mail or terminal [RFC821]"+cr+
"214- SAML Send as mail and terminal [RFC821]"+cr+
"214- EXPN Expand the mailing list [RFC821]"+cr+
"214- HELP Supply helpful information [RFC821]"+cr+
"214- TURN Turn the operation around [RFC821]"+cr+
"214- 8BITMIME Use 8-bit data [RFC1652]"+cr+
"214- SIZE Message size declaration [RFC1870]"+cr+
"214- VERB Verbose [Allman]"+cr+
"214- ONEX One message transaction only [Allman]"+cr+
"214- CHUNKING Chunking [RFC1830]"+cr+
"214- BINARYMIME Binary MIME [RFC1830]"+cr+
"214- PIPELINING Command Pipelining [RFC1854]"+cr+
"214- DSN Delivery Status Notification [RFC1891]"+cr+
"214- ETRN Remote Message Queue Starting [RFC1985]"+cr+
"214- XUSR Initial (user) submission [Allman]"+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("MAIL"))
{
replyData=(
"214-MAIL FROM: <sender> [ <parameters> ]"+cr+
"214- Specifies the sender. Parameters are ESMTP extensions."+cr+
"214- See \"HELP DSN\" for details."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("DATA"))
{
replyData=(
"214-DATA"+cr+
"214- Following text is collected as the message."+cr+
"214- End with a single dot."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("RSET"))
{
replyData=(
"214-RSET"+cr+
"214- Resets the system."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("QUIT"))
{
replyData=(
"214-QUIT"+cr+
"214- Exit SMTP."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("VRFY"))
{
replyData=(
"214-VRFY <recipient>"+cr+
"214- Verify an address. If you want to see what it aliases"+cr+
"214- to, use EXPN instead."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("EXPN"))
{
replyData=(
"214-EXPN <recipient>"+cr+
"214- Expand an address. If the address indicates a mailing"+cr+
"214- list, return the contents of that list."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("VERB"))
{
replyData=(
"214-VERB"+cr+
"214- Not implemented in this server."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("ETRN"))
{
replyData=(
"214-ETRN [ <hostname> | @<domain> | #<queuename> ]"+cr+
"214- Not implemented in this server."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("DSN"))
{
replyData=(
"214-MAIL FROM: <sender> [ RET={ FULL | HDRS} ] [ ENVID=<envid> ]"+cr+
"214-RCPT TO: <recipient> [ NOTIFY={NEVER,SUCCESS,FAILURE,DELAY} ]"+cr+
"214- [ ORCPT=<recipient> ]"+cr+
"214- SMTP Delivery Status Notifications."+cr+
"214-Descriptions:"+cr+
"214- RET Return either the full message or only headers."+cr+
"214- ENVID Sender's \"envelope identifier\" for tracking."+cr+
"214- NOTIFY When to send a DSN. Multiple options are OK, comma-"+cr+
"214- delimited. NEVER must appear by itself."+cr+
"214- ORCPT Original recipient."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
if(parm.equals("RCPT"))
{
replyData=(
"214-RCPT TO: <recipient> [ <parameters> ]"+cr+
"214- Specifies the recipient. Can be used any number of times."+cr+
"214- Parameters are ESMTP extensions. See \"HELP DSN\" for details."+cr+
"214 End of HELP info"+cr).getBytes();
}
else
replyData=("504 Help topic \""+parm+"\" unknown"+cr).getBytes();
}
else
if(cmd.equals("NOOP"))
replyData=(S_250+cr).getBytes();
else
if(cmd.equals("HELO")
||cmd.equals("EHLO"))
{
if((domain!=null)&&(parm.trim().length()==0))
replyData=("503 "+sock.getLocalAddress().getHostName()+" Duplicate HELO/EHLO"+cr).getBytes();
else
if(parm.trim().length()==0)
replyData=("501 "+cmd+" requires domain address"+cr).getBytes();
else
{
domain=parm;
replyData=("250 "+sock.getLocalAddress().getHostName()+" Hello "+sock.getInetAddress().getHostName()+" ["+sock.getInetAddress().getHostAddress()+"], pleased to meet you"+cr).getBytes();
if(cmd.equals("EHLO"))
{
replyData=(new String(replyData)
+"250-8BITMIME"+cr
+"250-SIZE "+server.getMaxMsgSize()+cr
+"250-DSN"+cr
+"250-ONEX"+cr
+"250 HELP"+cr).getBytes();
}
}
}
else
if(cmd.equals("MAIL"))
{
int x=parm.indexOf(':');
if(x<0)
replyData=("501 Syntax error in \""+parm+"\""+cr).getBytes();
else
{
String to2=parm.substring(0,x).trim();
if(!to2.equalsIgnoreCase("from"))
replyData=("500 Unrecognized command \""+cmd+"\""+cr).getBytes();
else
{
parm=parm.substring(x+1).trim();
String parmparms="";
boolean error=false;
if(parm.startsWith("<"))
{
x=parm.indexOf('>');
if(x<0)
{
replyData=("501 Syntax error in \""+parm+"\""+cr).getBytes();
error=true;
}
else
{
parmparms=parm.substring(x+1).trim();
parm=parm.substring(1,x);
}
}
else
if(parm.indexOf(' ')>=0)
{
replyData=("501 Syntax error in \""+parm+"\""+cr).getBytes();
error=true;
}
if(parmparms.trim().length()>0)
{
if((parmparms.trim().toUpperCase().startsWith("SIZE="))
||(!CMath.isNumber(parmparms.trim().toUpperCase().substring(5))))
{
int size=CMath.s_int(parmparms.trim().toUpperCase().substring(5));
if(size>server.getMaxMsgSize())
{
replyData=("552 String exceeds size limit. But you were nice to tell me!"+cr).getBytes();
error=true;
}
}
else
{
replyData=("502 Parameters not supported... \""+parmparms+"\""+cr).getBytes();
error=true;
}
}
if(!error)
{
String name=validLocalAccount(parm);
if(name==null)
{
if((++failures)==3)
{
replyData=("421 Quit Fishing!"+cr).getBytes();
quitFlag=true;
}
else
replyData=("551 Requested action not taken: User is not local."+cr).getBytes();
}
else
{
replyData=("250 OK "+name+cr).getBytes();
from=name;
}
}
}
}
}
else
if(cmd.equals("DATA"))
{
if(from==null)
replyData=("503 Need MAIL command"+cr).getBytes();
else
if(to==null)
replyData=("503 Need RCPT (recipient)"+cr).getBytes();
else
{
replyData=("354 Enter mail, end with \".\" on a line by itself"+cr).getBytes();
dataMode=true;
}
}
else
if(cmd.equals("QUIT"))
{
replyData=("221 "+server.domainName()+" closing connection"+cr).getBytes();
quitFlag=true;
}
else
if(cmd.equals("VRFY"))
replyData=("252 Cannot VRFY user; try RCPT to attempt delivery (or try finger)"+cr).getBytes();
else
if(cmd.equals("EXPN"))
replyData=("502 Sorry, we don't allow mailing lists"+cr).getBytes();
else
if(cmd.equals("VERB"))
replyData=("502 Verbose unavailable"+cr).getBytes();
else
if(cmd.equals("ETRN"))
replyData=("502 ETRN not implemented"+cr).getBytes();
else
if(cmd.equals("RCPT"))
{
int x=parm.indexOf(':');
if(x<0)
replyData=("501 Syntax error in \""+parm+"\""+cr).getBytes();
else
{
String to2=parm.substring(0,x).trim();
if(!to2.equalsIgnoreCase("to"))
replyData=("500 Unrecognized command \""+cmd+"\""+cr).getBytes();
else
{
parm=parm.substring(x+1).trim();
String parmparms="";
boolean error=false;
if(parm.startsWith("<"))
{
x=parm.indexOf('>');
if(x<0)
{
replyData=("501 Syntax error in \""+parm+"\""+cr).getBytes();
error=true;
}
else
{
parmparms=parm.substring(x+1).trim();
parm=parm.substring(1,x);
}
}
else
if(parm.indexOf(' ')>=0)
{
replyData=("501 Syntax error in \""+parm+"\""+cr).getBytes();
error=true;
}
if(parmparms.trim().length()>0)
{
if((parmparms.trim().toUpperCase().startsWith("SIZE="))
||(!CMath.isNumber(parmparms.trim().toUpperCase().substring(5))))
{
int size=CMath.s_int(parmparms.trim().toUpperCase().substring(5));
if(size>server.getMaxMsgSize())
replyData=("552 String exceeds size limit. But you were nice to tell me!"+cr).getBytes();
}
else
replyData=("502 Parameters not supported... \""+parmparms+"\""+cr).getBytes();
}
else
if(parm.indexOf('@')<0)
replyData=("550 "+parm+" user unknown."+cr).getBytes();
else
if(!error)
{
String name=validLocalAccount(parm);
if(name==null)
{
if((++failures)==3)
{
replyData=("421 Quit Fishing!"+cr).getBytes();
quitFlag=true;
}
else
replyData=("553 Requested action not taken: User is not local."+cr).getBytes();
}
else
{
if(server.getAnEmailJournal(name)!=null)
{
boolean jerror=false;
if(server.getJournalCriteria(name)!=null)
{
if(from==null)
{
replyData=("503 Need MAIL before RCPT"+cr).getBytes();
jerror=true;
}
else
{
MOB M=CMLib.players().getPlayer(from);
if((M==null)
||(!CMLib.masking().maskCheck(server.getJournalCriteria(name),M,false)))
{
replyData=("552 User '"+from+"' may not send emails to '"+name+"'."+cr).getBytes();
jerror=true;
}
}
}
if(!jerror)
{
replyData=("250 OK "+name+cr).getBytes();
if(to==null) to=new Vector<String>();
if(!to.contains(name))
to.addElement(name);
}
}
else
if(CMLib.database().DBCountJournal(server.mailboxName(),null,name)>=server.getMaxMsgs())
replyData=("552 Mailbox '"+name+"' is full."+cr).getBytes();
else
{
replyData=("250 OK "+name+cr).getBytes();
if(to==null) to=new Vector<String>();
if(!to.contains(name))
to.addElement(name);
}
}
}
}
}
}
else
replyData=lastReplyData;//("500 Command Unrecognized: \""+cmd+"\""+cr).getBytes();
if ((replyData != null))
{
respQueue.add(replyData);
replyData=null;
if(cmdQueue.size()==0)
{
// we should be looping through these .. why does ZD act so wierd?!
byte [] resp=respQueue.getLast();
if(debug) Log.debugOut(runnableName,"Reply: "+CMStrings.replaceAll(new String(resp),cr,"\\r\\n"));
// must insert a blank line before message body
sout.write(new String(resp));
sout.flush();
respQueue.clear();
}
}
}
}
}
catch (java.net.SocketTimeoutException e2)
{
try
{
if (sout != null)
{
sout.write("421 You're taking too long. I'm outa here."+cr);
sout.flush();
}
}
catch(Exception e)
{
Log.errOut(runnableName,"Exception2: " + e.getMessage() );
}
}
catch (Exception e)
{
final String errorMessage=e.getMessage();
final StringBuilder msg = new StringBuilder(errorMessage==null?"EMPTY e.getMessage()":errorMessage);
final StackTraceElement[] ts = e.getStackTrace();
if(ts != null)
for(StackTraceElement t : ts)
msg.append(" ").append(t.getFileName()).append("(").append(t.getLineNumber()).append(")");
Log.errOut(runnableName,"Exception: " + msg.toString() );
}
try
{
if (sout != null)
{
sout.flush();
sout.close();
sout = null;
}
}
catch (Exception e) {}
try
{
if (sin != null)
{
sin.close();
sin = null;
}
}
catch (Exception e) {}
try
{
if (sock != null)
{
sock.close();
sock = null;
}
}
catch (Exception e) {}
}
}
|
git-svn-id: svn://192.168.1.10/public/CoffeeMud@10377 0d6f1817-ed0e-0410-87c9-987e46238f29
| com/planet_ink/coffee_mud/core/smtp/ProcessSMTPrequest.java | <ide><path>om/planet_ink/coffee_mud/core/smtp/ProcessSMTPrequest.java
<ide> input.setLength(0);
<ide> continue;
<ide> }
<del> input.append(c);
<add> if(c!=65535)
<add> input.append(c);
<ide> if(input.length()>server.getMaxMsgSize())
<ide> {
<ide> if(debug) |
||
Java | apache-2.0 | bb99a30868df74c20508c9e83401f63e1e94bcd5 | 0 | swift-lang/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,swift-lang/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,swift-lang/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,ya7lelkom/swift-k | //----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------
/*
* Created on Feb 13, 2008
*/
package org.globus.cog.abstraction.coaster.service.job.manager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.log4j.Logger;
import org.globus.cog.abstraction.coaster.service.LocalTCPService;
import org.globus.cog.abstraction.coaster.service.job.manager.Worker.ShutdownCallback;
import org.globus.cog.abstraction.impl.common.AbstractionFactory;
import org.globus.cog.abstraction.impl.common.ProviderMethodException;
import org.globus.cog.abstraction.impl.common.StatusImpl;
import org.globus.cog.abstraction.impl.common.execution.WallTime;
import org.globus.cog.abstraction.impl.common.task.ExecutionServiceImpl;
import org.globus.cog.abstraction.impl.common.task.ExecutionTaskHandler;
import org.globus.cog.abstraction.impl.common.task.InvalidProviderException;
import org.globus.cog.abstraction.impl.common.task.InvalidServiceContactException;
import org.globus.cog.abstraction.impl.common.task.JobSpecificationImpl;
import org.globus.cog.abstraction.impl.common.task.TaskImpl;
import org.globus.cog.abstraction.impl.common.task.TaskSubmissionException;
import org.globus.cog.abstraction.interfaces.ExecutionService;
import org.globus.cog.abstraction.interfaces.JobSpecification;
import org.globus.cog.abstraction.interfaces.Status;
import org.globus.cog.abstraction.interfaces.Task;
import org.globus.cog.abstraction.interfaces.TaskHandler;
import org.globus.cog.karajan.workflow.service.channels.ChannelContext;
public class WorkerManager extends Thread {
public static final Logger logger = Logger.getLogger(WorkerManager.class);
/**
* We allow for at least one minute of extra time compared to the requested
* walltime
*/
public static final Seconds TIME_RESERVE = new Seconds(60);
public static final File scriptDir =
new File(System.getProperty("user.home") + File.separator + ".globus" + File.separator
+ "coasters");
public static final String SCRIPT = "worker.pl";
public static final int OVERALLOCATION_FACTOR = 10;
public static final int MAX_WORKERS = 256;
public static final int MAX_STARTING_WORKERS = 32;
public static final List coasterAttributes =
Arrays.asList(new String[] { "coasterspernode", "coasterinternalip",
"coasterworkermaxwalltime" });
private SortedMap ready;
private Map ids;
private Set busy;
private Set startingTasks;
private Map requested;
private boolean shutdownFlag;
private LinkedList allocationRequests;
private File script;
private IDGenerator sr;
private URI callbackURI;
private LocalTCPService localService;
private TaskHandler handler;
private int currentWorkers;
public WorkerManager(LocalTCPService localService) throws IOException {
super("Worker Manager");
ready = new TreeMap();
busy = new HashSet();
ids = new HashMap();
startingTasks = new HashSet();
requested = new HashMap();
allocationRequests = new LinkedList();
this.localService = localService;
this.callbackURI = localService.getContact();
writeScript();
sr = new IDGenerator();
handler = new ExecutionTaskHandler();
}
private void writeScript() throws IOException {
scriptDir.mkdirs();
if (!scriptDir.exists()) {
throw new IOException("Failed to create script dir (" + scriptDir + ")");
}
script = File.createTempFile("cscript", ".pl", scriptDir);
script.deleteOnExit();
InputStream is = WorkerManager.class.getClassLoader().getResourceAsStream(SCRIPT);
if (is == null) {
throw new IOException("Could not find resource in class path: " + SCRIPT);
}
FileOutputStream fos = new FileOutputStream(script);
byte[] buf = new byte[1024];
int len = is.read(buf);
while (len != -1) {
fos.write(buf, 0, len);
len = is.read(buf);
}
fos.close();
is.close();
}
public void run() {
try {
if (logger.isInfoEnabled()) {
startInfoThread();
}
AllocationRequest req;
while (!shutdownFlag) {
synchronized (allocationRequests) {
while (allocationRequests.isEmpty()) {
allocationRequests.wait();
}
req = (AllocationRequest) allocationRequests.removeFirst();
if (logger.isInfoEnabled()) {
logger.info("Got allocation request: " + req);
}
}
try {
startWorker(new Seconds(req.maxWallTime.getSeconds()).multiply(
OVERALLOCATION_FACTOR).add(TIME_RESERVE), req.prototype);
}
catch (NoClassDefFoundError e) {
req.prototype.setStatus(new StatusImpl(Status.FAILED, e.getMessage(),
new TaskSubmissionException(e)));
}
catch (Exception e) {
req.prototype.setStatus(new StatusImpl(Status.FAILED, e.getMessage(), e));
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (Error e) {
e.printStackTrace();
System.exit(126);
}
}
private void startWorker(Seconds maxWallTime, Task prototype)
throws InvalidServiceContactException, InvalidProviderException,
ProviderMethodException {
int numWorkers = this.getCoastersPerNode(prototype);
String workerMaxwalltimeString =
(String) ((JobSpecification) prototype.getSpecification()).getAttribute("coasterWorkerMaxwalltime");
if (workerMaxwalltimeString != null) {
// override the computed maxwalltime
maxWallTime = new Seconds(WallTime.timeToSeconds(workerMaxwalltimeString));
int taskSeconds = AssociatedTask.getMaxWallTime(prototype).getSeconds();
if (TIME_RESERVE.add(taskSeconds).isGreaterThan(maxWallTime)) {
prototype.setStatus(new StatusImpl(Status.FAILED,
"Job cannot be run with the given max walltime worker constraint (task: "
+ taskSeconds + ", maxwalltime: " + maxWallTime + ")", null));
return;
}
logger.debug("Overridden worker maxwalltime is " + maxWallTime);
}
logger.info("Starting new worker set with " + numWorkers + " workers");
Task t = new TaskImpl();
t.setType(Task.JOB_SUBMISSION);
t.setSpecification(buildSpecification(prototype));
copyAttributes(t, prototype, maxWallTime);
t.setRequiredService(1);
t.setService(0, buildService(prototype));
synchronized (this) {
if (!startingTasks.contains(prototype)) {
return;
}
}
Map newlyRequested = new HashMap();
for (int n = 0; n < numWorkers; n++) {
int id = sr.nextInt();
if (logger.isInfoEnabled()) {
logger.info("Starting worker with id=" + id + " and maxwalltime=" + maxWallTime);
}
String sid = String.valueOf(id);
((JobSpecification) t.getSpecification()).addArgument(sid);
try {
Worker wr = new Worker(this, sid, maxWallTime, t, prototype);
newlyRequested.put(sid, wr);
}
catch (Exception e) {
prototype.setStatus(new StatusImpl(Status.FAILED, e.getMessage(), e));
}
}
try {
handler.submit(t);
}
catch (Exception e) {
prototype.setStatus(new StatusImpl(Status.FAILED, e.getMessage(), e));
}
synchronized (this) {
requested.putAll(newlyRequested);
}
}
private JobSpecification buildSpecification(Task prototype) {
JobSpecification ps = (JobSpecification) prototype.getSpecification();
JobSpecification js = new JobSpecificationImpl();
js.setExecutable("/usr/bin/perl");
js.addArgument(script.getAbsolutePath());
String internalHostname = (String) ps.getAttribute("coasterInternalIP");
if (internalHostname != null) { // override automatically determined
// hostname
// TODO detect if we've done this already for a different
// value? (same non-determinism as for coastersPerWorker and
// walltime handling that jobs may come in with different
// values and we can only use one)
try {
logger.warn("original callback URI is " + callbackURI.toString());
callbackURI =
new URI(callbackURI.getScheme(), callbackURI.getUserInfo(),
internalHostname, callbackURI.getPort(), callbackURI.getPath(),
callbackURI.getQuery(), callbackURI.getFragment());
logger.warn("callback URI has been overridden to " + callbackURI.toString());
}
catch (URISyntaxException use) {
throw new RuntimeException(use);
}
// TODO nasty exception in the line above
}
js.addArgument(callbackURI.toString());
// js.addArgument(id);
return js;
}
public static ExecutionService buildService(Task prototype)
throws InvalidServiceContactException, InvalidProviderException,
ProviderMethodException {
ExecutionService s = new ExecutionServiceImpl();
s.setServiceContact(prototype.getService(0).getServiceContact());
ExecutionService p = (ExecutionService) prototype.getService(0);
String jm = p.getJobManager();
int colon = jm.indexOf(':');
// remove provider used to bootstrap coasters
jm = jm.substring(colon + 1);
colon = jm.indexOf(':');
if (colon == -1) {
s.setProvider(jm);
}
else {
s.setJobManager(jm.substring(colon + 1));
s.setProvider(jm.substring(0, colon));
}
if (p.getSecurityContext() != null) {
s.setSecurityContext(p.getSecurityContext());
}
else {
s.setSecurityContext(AbstractionFactory.newSecurityContext(s.getProvider()));
}
return s;
}
private void copyAttributes(Task t, Task prototype, Seconds maxWallTime) {
JobSpecification pspec = (JobSpecification) prototype.getSpecification();
JobSpecification tspec = (JobSpecification) t.getSpecification();
Iterator i = pspec.getAttributeNames().iterator();
while (i.hasNext()) {
String name = (String) i.next();
if (!coasterAttributes.contains(name)) {
tspec.setAttribute(name, pspec.getAttribute(name));
}
}
tspec.setAttribute("maxwalltime", new WallTime((int) maxWallTime.getSeconds()).format());
}
private int k;
private long last;
public Worker request(WallTime maxWallTime, Task prototype) throws InterruptedException {
WorkerKey key =
new WorkerKey(new Seconds(maxWallTime.getSeconds()).add(TIME_RESERVE).add(
Seconds.now()));
Worker w = null;
synchronized (this) {
if (logger.isInfoEnabled()) {
logger.info("Looking for worker for key " + key);
logger.info("Ready: " + ready);
}
Collection tm = ready.tailMap(key).values();
Iterator i = tm.iterator();
if (i.hasNext()) {
w = (Worker) i.next();
i.remove();
if (!w.isFailed()) {
busy.add(w);
startingTasks.remove(prototype);
}
else {
removeWorker(w);
}
}
}
if (w != null) {
if (k == 0) {
last = System.currentTimeMillis();
}
if (++k % 100 == 0) {
long crt = System.currentTimeMillis();
int js = 0;
if (last != 0) {
js = (int) (80000 / (crt - last));
}
last = crt;
System.err.println(" " + k / 80 + "; " + js + " J/s");
}
logger.info("Using worker " + w + " for task " + prototype);
w.setRunning(prototype);
return w;
}
else {
synchronized (this) {
if (currentWorkers >= MAX_WORKERS) {
this.wait(250);
return null;
}
boolean alreadyThere;
alreadyThere = !startingTasks.add(prototype);
if (!alreadyThere) {
currentWorkers += getCoastersPerNode(prototype);
if (logger.isInfoEnabled()) {
logger.info("No suitable worker found. Attempting to start a new one.");
}
synchronized (allocationRequests) {
if (allocationRequests.size() < MAX_STARTING_WORKERS) {
allocationRequests.add(new AllocationRequest(maxWallTime, prototype));
allocationRequests.notify();
}
else {
this.wait(250);
return null;
}
}
}
}
return null;
}
}
public void workerTerminated(Worker worker) {
if (logger.isInfoEnabled()) {
logger.info("Worker terminated: " + worker);
}
Status s = worker.getStatus();
Task running = worker.getRunning();
synchronized (this) {
if (s.getStatusCode() == Status.FAILED || requested.containsKey(worker.getId())) {
if (logger.isInfoEnabled()) {
logger.info("Failed or starting: " + worker);
}
worker.setFailed(true);
if (s.getStatusCode() != Status.FAILED) {
worker.setStatus(new StatusImpl(Status.FAILED, "Worker ended prematurely", null));
}
running.setStatus(new StatusImpl(Status.FAILED, "Failed to start worker: "
+ s.getMessage(), s.getException()));
}
else if (running != null) {
running.setStatus(new StatusImpl(Status.FAILED,
"Worker terminated while job was running", null));
}
removeWorker(worker);
}
}
public void registrationReceived(String id, String url, ChannelContext cc) {
Worker wr;
synchronized (this) {
wr = (Worker) requested.remove(id);
}
if (wr == null) {
logger.warn("Received unrequested registration (id = " + id + ", url = " + url);
throw new IllegalArgumentException("Invalid worker id (" + id
+ "). This worker manager instance does not "
+ "recall requesting a worker with such an id.");
}
wr.setScheduledTerminationTime(Seconds.now().add(wr.getMaxWallTime()));
wr.setChannelContext(cc);
if (logger.isInfoEnabled()) {
logger.info("Worker registration received: " + wr);
}
synchronized (this) {
startingTasks.remove(wr.getRunning());
ready.put(new WorkerKey(wr), wr);
ids.put(id, wr);
wr.workerRegistered();
}
}
public void removeWorker(Worker worker) {
synchronized (this) {
if (busy.remove(worker)) {
if (logger.isInfoEnabled()) {
logger.info(worker + " was busy");
}
}
if (ready.remove(new WorkerKey(worker)) != null) {
if (logger.isInfoEnabled()) {
logger.info(worker + " was ready");
}
}
startingTasks.remove(worker.getRunning());
if (ids.remove(worker.getId()) != null) {
currentWorkers--;
}
}
}
public void workerTaskDone(Worker wr) {
synchronized (this) {
// only add to ready if it was not removed previously
// as this method may be called after the worker task is done
if (busy.remove(wr)) {
ready.put(new WorkerKey(wr), wr);
}
notifyAll();
wr.setRunning(null);
}
}
public int availableWorkers() {
synchronized (this) {
return ready.size();
}
}
public ChannelContext getChannelContext(String id) {
Worker wr = (Worker) ids.get(id);
if (wr == null) {
throw new IllegalArgumentException("No worker with id=" + id);
}
else {
return wr.getChannelContext();
}
}
protected TaskHandler getTaskHandler() {
return handler;
}
protected int getCoastersPerNode(Task t) {
String numWorkersString =
(String) ((JobSpecification) t.getSpecification()).getAttribute("coastersPerNode");
if (numWorkersString == null) {
return 1;
}
else {
return Integer.parseInt(numWorkersString);
}
}
private static class AllocationRequest {
public WallTime maxWallTime;
public Task prototype;
public AllocationRequest(WallTime maxWallTime, Task prototype) {
this.maxWallTime = maxWallTime;
this.prototype = prototype;
}
}
public void shutdown() {
try {
synchronized (this) {
Iterator i;
List callbacks = new ArrayList();
//wr.shutdown removes the worker from this manager, which messes
//up with the iteration
i = new ArrayList(ready.values()).iterator();
while (i.hasNext()) {
Worker wr = (Worker) i.next();
callbacks.add(wr.shutdown());
}
i = callbacks.iterator();
while (i.hasNext()) {
ShutdownCallback cb = (ShutdownCallback) i.next();
if (cb != null) {
cb.waitFor();
}
}
i = new ArrayList(requested.values()).iterator();
while (i.hasNext()) {
Worker wr = (Worker) i.next();
try {
handler.cancel(wr.getWorkerTask());
}
catch (Exception e) {
logger.warn("Failed to cancel queued worker task " + wr.getWorkerTask(), e);
}
}
}
}
catch (InterruptedException e) {
logger.warn("Interrupted", e);
}
}
private void startInfoThread() {
new Thread() {
{
setDaemon(true);
}
public void run() {
while (true) {
try {
Thread.sleep(20000);
synchronized (WorkerManager.this) {
logger.info("Current workers: " + currentWorkers);
logger.info("Ready: " + ready);
logger.info("Busy: " + busy);
logger.info("Requested: " + requested);
logger.info("Starting: " + startingTasks);
logger.info("Ids: " + ids);
}
synchronized (allocationRequests) {
logger.info("AllocationR: " + allocationRequests);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
}
| src/cog/modules/provider-coaster/src/org/globus/cog/abstraction/coaster/service/job/manager/WorkerManager.java | //----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------
/*
* Created on Feb 13, 2008
*/
package org.globus.cog.abstraction.coaster.service.job.manager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.log4j.Logger;
import org.globus.cog.abstraction.coaster.service.LocalTCPService;
import org.globus.cog.abstraction.coaster.service.job.manager.Worker.ShutdownCallback;
import org.globus.cog.abstraction.impl.common.AbstractionFactory;
import org.globus.cog.abstraction.impl.common.ProviderMethodException;
import org.globus.cog.abstraction.impl.common.StatusImpl;
import org.globus.cog.abstraction.impl.common.execution.WallTime;
import org.globus.cog.abstraction.impl.common.task.ExecutionServiceImpl;
import org.globus.cog.abstraction.impl.common.task.ExecutionTaskHandler;
import org.globus.cog.abstraction.impl.common.task.InvalidProviderException;
import org.globus.cog.abstraction.impl.common.task.InvalidServiceContactException;
import org.globus.cog.abstraction.impl.common.task.JobSpecificationImpl;
import org.globus.cog.abstraction.impl.common.task.TaskImpl;
import org.globus.cog.abstraction.impl.common.task.TaskSubmissionException;
import org.globus.cog.abstraction.interfaces.ExecutionService;
import org.globus.cog.abstraction.interfaces.JobSpecification;
import org.globus.cog.abstraction.interfaces.Status;
import org.globus.cog.abstraction.interfaces.Task;
import org.globus.cog.abstraction.interfaces.TaskHandler;
import org.globus.cog.karajan.workflow.service.channels.ChannelContext;
public class WorkerManager extends Thread {
public static final Logger logger = Logger.getLogger(WorkerManager.class);
/**
* We allow for at least one minute of extra time compared to the requested
* walltime
*/
public static final Seconds TIME_RESERVE = new Seconds(60);
public static final File scriptDir =
new File(System.getProperty("user.home") + File.separator + ".globus" + File.separator
+ "coasters");
public static final String SCRIPT = "worker.pl";
public static final int OVERALLOCATION_FACTOR = 10;
public static final int MAX_WORKERS = 256;
public static final int MAX_STARTING_WORKERS = 32;
public static final List coasterAttributes =
Arrays.asList(new String[] { "coasterspernode", "coasterinternalip",
"coasterworkermaxwalltime" });
private SortedMap ready;
private Map ids;
private Set busy;
private Set startingTasks;
private Map requested;
private boolean shutdownFlag;
private LinkedList allocationRequests;
private File script;
private IDGenerator sr;
private URI callbackURI;
private LocalTCPService localService;
private TaskHandler handler;
private int currentWorkers;
public WorkerManager(LocalTCPService localService) throws IOException {
super("Worker Manager");
ready = new TreeMap();
busy = new HashSet();
ids = new HashMap();
startingTasks = new HashSet();
requested = new HashMap();
allocationRequests = new LinkedList();
this.localService = localService;
this.callbackURI = localService.getContact();
writeScript();
sr = new IDGenerator();
handler = new ExecutionTaskHandler();
}
private void writeScript() throws IOException {
scriptDir.mkdirs();
if (!scriptDir.exists()) {
throw new IOException("Failed to create script dir (" + scriptDir + ")");
}
script = File.createTempFile("cscript", ".pl", scriptDir);
script.deleteOnExit();
InputStream is = WorkerManager.class.getClassLoader().getResourceAsStream(SCRIPT);
if (is == null) {
throw new IOException("Could not find resource in class path: " + SCRIPT);
}
FileOutputStream fos = new FileOutputStream(script);
byte[] buf = new byte[1024];
int len = is.read(buf);
while (len != -1) {
fos.write(buf, 0, len);
len = is.read(buf);
}
fos.close();
is.close();
}
public void run() {
try {
if (logger.isInfoEnabled()) {
startInfoThread();
}
AllocationRequest req;
while (!shutdownFlag) {
synchronized (allocationRequests) {
while (allocationRequests.isEmpty()) {
allocationRequests.wait();
}
req = (AllocationRequest) allocationRequests.removeFirst();
if (logger.isInfoEnabled()) {
logger.info("Got allocation request: " + req);
}
}
try {
startWorker(new Seconds(req.maxWallTime.getSeconds()).multiply(
OVERALLOCATION_FACTOR).add(TIME_RESERVE), req.prototype);
}
catch (NoClassDefFoundError e) {
req.prototype.setStatus(new StatusImpl(Status.FAILED, e.getMessage(),
new TaskSubmissionException(e)));
}
catch (Exception e) {
req.prototype.setStatus(new StatusImpl(Status.FAILED, e.getMessage(), e));
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (Error e) {
e.printStackTrace();
System.exit(126);
}
}
private void startWorker(Seconds maxWallTime, Task prototype)
throws InvalidServiceContactException, InvalidProviderException,
ProviderMethodException {
int numWorkers = this.getCoastersPerNode(prototype);
String workerMaxwalltimeString =
(String) ((JobSpecification) prototype.getSpecification()).getAttribute("coasterWorkerMaxwalltime");
if (workerMaxwalltimeString != null) {
// override the computed maxwalltime
maxWallTime = new Seconds(WallTime.timeToSeconds(workerMaxwalltimeString));
int taskSeconds = AssociatedTask.getMaxWallTime(prototype).getSeconds();
if (TIME_RESERVE.add(taskSeconds).isGreaterThan(maxWallTime)) {
prototype.setStatus(new StatusImpl(Status.FAILED,
"Job cannot be run with the given max walltime worker constraint (task: "
+ taskSeconds + ", maxwalltime: " + maxWallTime + ")", null));
return;
}
logger.debug("Overridden worker maxwalltime is " + maxWallTime);
}
logger.info("Starting new worker set with " + numWorkers + " workers");
Task t = new TaskImpl();
t.setType(Task.JOB_SUBMISSION);
t.setSpecification(buildSpecification(prototype));
copyAttributes(t, prototype, maxWallTime);
t.setRequiredService(1);
t.setService(0, buildService(prototype));
synchronized (this) {
if (!startingTasks.contains(prototype)) {
return;
}
}
Map newlyRequested = new HashMap();
for (int n = 0; n < numWorkers; n++) {
int id = sr.nextInt();
if (logger.isInfoEnabled()) {
logger.info("Starting worker with id=" + id + " and maxwalltime=" + maxWallTime);
}
String sid = String.valueOf(id);
((JobSpecification) t.getSpecification()).addArgument(sid);
try {
Worker wr = new Worker(this, sid, maxWallTime, t, prototype);
newlyRequested.put(sid, wr);
}
catch (Exception e) {
prototype.setStatus(new StatusImpl(Status.FAILED, e.getMessage(), e));
}
}
try {
handler.submit(t);
}
catch (Exception e) {
prototype.setStatus(new StatusImpl(Status.FAILED, e.getMessage(), e));
}
synchronized (this) {
requested.putAll(newlyRequested);
}
}
private JobSpecification buildSpecification(Task prototype) {
JobSpecification ps = (JobSpecification) prototype.getSpecification();
JobSpecification js = new JobSpecificationImpl();
js.setExecutable("/usr/bin/perl");
js.addArgument(script.getAbsolutePath());
String internalHostname = (String) ps.getAttribute("coasterInternalIP");
if (internalHostname != null) { // override automatically determined
// hostname
// TODO detect if we've done this already for a different
// value? (same non-determinism as for coastersPerWorker and
// walltime handling that jobs may come in with different
// values and we can only use one)
try {
logger.warn("original callback URI is " + callbackURI.toString());
callbackURI =
new URI(callbackURI.getScheme(), callbackURI.getUserInfo(),
internalHostname, callbackURI.getPort(), callbackURI.getPath(),
callbackURI.getQuery(), callbackURI.getFragment());
logger.warn("callback URI has been overridden to " + callbackURI.toString());
}
catch (URISyntaxException use) {
throw new RuntimeException(use);
}
// TODO nasty exception in the line above
}
js.addArgument(callbackURI.toString());
// js.addArgument(id);
return js;
}
public static ExecutionService buildService(Task prototype)
throws InvalidServiceContactException, InvalidProviderException,
ProviderMethodException {
ExecutionService s = new ExecutionServiceImpl();
s.setServiceContact(prototype.getService(0).getServiceContact());
ExecutionService p = (ExecutionService) prototype.getService(0);
String jm = p.getJobManager();
int colon = jm.indexOf(':');
// remove provider used to bootstrap coasters
jm = jm.substring(colon + 1);
colon = jm.indexOf(':');
if (colon == -1) {
s.setProvider(jm);
}
else {
s.setJobManager(jm.substring(colon + 1));
s.setProvider(jm.substring(0, colon));
}
if (p.getSecurityContext() != null) {
s.setSecurityContext(p.getSecurityContext());
}
else {
s.setSecurityContext(AbstractionFactory.newSecurityContext(s.getProvider()));
}
return s;
}
private void copyAttributes(Task t, Task prototype, Seconds maxWallTime) {
JobSpecification pspec = (JobSpecification) prototype.getSpecification();
JobSpecification tspec = (JobSpecification) t.getSpecification();
Iterator i = pspec.getAttributeNames().iterator();
while (i.hasNext()) {
String name = (String) i.next();
if (!coasterAttributes.contains(name)) {
tspec.setAttribute(name, pspec.getAttribute(name));
}
}
tspec.setAttribute("maxwalltime", new WallTime((int) maxWallTime.getSeconds()).format());
}
private int k;
private long last;
public Worker request(WallTime maxWallTime, Task prototype) throws InterruptedException {
WorkerKey key =
new WorkerKey(new Seconds(maxWallTime.getSeconds()).add(TIME_RESERVE).add(
Seconds.now()));
Worker w = null;
synchronized (this) {
if (logger.isInfoEnabled()) {
logger.info("Looking for worker for key " + key);
logger.info("Ready: " + ready);
}
Collection tm = ready.tailMap(key).values();
Iterator i = tm.iterator();
if (i.hasNext()) {
w = (Worker) i.next();
i.remove();
if (!w.isFailed()) {
busy.add(w);
startingTasks.remove(prototype);
}
else {
removeWorker(w);
}
}
}
if (w != null) {
if (k == 0) {
last = System.currentTimeMillis();
}
if (++k % 100 == 0) {
long crt = System.currentTimeMillis();
int js = 0;
if (last != 0) {
js = (int) (80000 / (crt - last));
}
last = crt;
System.err.println(" " + k / 80 + "; " + js + " J/s");
}
logger.info("Using worker " + w + " for task " + prototype);
w.setRunning(prototype);
return w;
}
else {
synchronized (this) {
if (currentWorkers >= MAX_WORKERS) {
this.wait(250);
return null;
}
boolean alreadyThere;
alreadyThere = !startingTasks.add(prototype);
if (!alreadyThere) {
currentWorkers += getCoastersPerNode(prototype);
if (logger.isInfoEnabled()) {
logger.info("No suitable worker found. Attempting to start a new one.");
}
synchronized (allocationRequests) {
if (allocationRequests.size() < MAX_STARTING_WORKERS) {
allocationRequests.add(new AllocationRequest(maxWallTime, prototype));
allocationRequests.notify();
}
else {
this.wait(250);
return null;
}
}
}
}
return null;
}
}
public void workerTerminated(Worker worker) {
if (logger.isInfoEnabled()) {
logger.info("Worker terminated: " + worker);
}
Status s = worker.getStatus();
Task running = worker.getRunning();
synchronized (this) {
if (s.getStatusCode() == Status.FAILED || requested.containsKey(worker.getId())) {
if (logger.isInfoEnabled()) {
logger.info("Failed or starting: " + worker);
}
worker.setFailed(true);
if (s.getStatusCode() != Status.FAILED) {
worker.setStatus(new StatusImpl(Status.FAILED, "Worker ended prematurely", null));
}
running.setStatus(new StatusImpl(Status.FAILED, "Failed to start worker: "
+ s.getMessage(), s.getException()));
}
else if (running != null) {
running.setStatus(new StatusImpl(Status.FAILED,
"Worker terminated while job was running", null));
}
removeWorker(worker);
}
}
public void registrationReceived(String id, String url, ChannelContext cc) {
Worker wr;
synchronized (this) {
wr = (Worker) requested.remove(id);
}
if (wr == null) {
logger.warn("Received unrequested registration (id = " + id + ", url = " + url);
throw new IllegalArgumentException("Invalid worker id (" + id
+ "). This worker manager instance does not "
+ "recall requesting a worker with such an id.");
}
wr.setScheduledTerminationTime(Seconds.now().add(wr.getMaxWallTime()));
wr.setChannelContext(cc);
if (logger.isInfoEnabled()) {
logger.info("Worker registration received: " + wr);
}
synchronized (this) {
startingTasks.remove(wr.getRunning());
ready.put(new WorkerKey(wr), wr);
ids.put(id, wr);
wr.workerRegistered();
}
}
public void removeWorker(Worker worker) {
synchronized (this) {
if (busy.remove(worker)) {
if (logger.isInfoEnabled()) {
logger.info(worker + " was busy");
}
}
if (ready.remove(new WorkerKey(worker)) != null) {
if (logger.isInfoEnabled()) {
logger.info(worker + " was ready");
}
}
startingTasks.remove(worker.getRunning());
if (ids.remove(worker.getId()) != null) {
currentWorkers--;
}
}
}
public void workerTaskDone(Worker wr) {
synchronized (this) {
// only add to ready if it was not removed previously
// as this method may be called after the worker task is done
if (busy.remove(wr)) {
ready.put(new WorkerKey(wr), wr);
}
notifyAll();
wr.setRunning(null);
}
}
public int availableWorkers() {
synchronized (this) {
return ready.size();
}
}
public ChannelContext getChannelContext(String id) {
Worker wr = (Worker) ids.get(id);
if (wr == null) {
throw new IllegalArgumentException("No worker with id=" + id);
}
else {
return wr.getChannelContext();
}
}
protected TaskHandler getTaskHandler() {
return handler;
}
protected int getCoastersPerNode(Task t) {
String numWorkersString =
(String) ((JobSpecification) t.getSpecification()).getAttribute("coastersPerNode");
if (numWorkersString == null) {
return 1;
}
else {
return Integer.parseInt(numWorkersString);
}
}
private static class AllocationRequest {
public WallTime maxWallTime;
public Task prototype;
public AllocationRequest(WallTime maxWallTime, Task prototype) {
this.maxWallTime = maxWallTime;
this.prototype = prototype;
}
}
public void shutdown() {
try {
synchronized (this) {
Iterator i;
List callbacks = new ArrayList();
i = ready.values().iterator();
while (i.hasNext()) {
Worker wr = (Worker) i.next();
callbacks.add(wr.shutdown());
}
i = callbacks.iterator();
while (i.hasNext()) {
ShutdownCallback cb = (ShutdownCallback) i.next();
if (cb != null) {
cb.waitFor();
}
}
i = new ArrayList(requested.values()).iterator();
while (i.hasNext()) {
Worker wr = (Worker) i.next();
try {
handler.cancel(wr.getWorkerTask());
}
catch (Exception e) {
logger.warn("Failed to cancel queued worker task " + wr.getWorkerTask(), e);
}
}
}
}
catch (InterruptedException e) {
logger.warn("Interrupted", e);
}
}
private void startInfoThread() {
new Thread() {
{
setDaemon(true);
}
public void run() {
while (true) {
try {
Thread.sleep(20000);
synchronized (WorkerManager.this) {
logger.info("Current workers: " + currentWorkers);
logger.info("Ready: " + ready);
logger.info("Busy: " + busy);
logger.info("Requested: " + requested);
logger.info("Starting: " + startingTasks);
logger.info("Ids: " + ids);
}
synchronized (allocationRequests) {
logger.info("AllocationR: " + allocationRequests);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
}
| avoid concurrent modification exceptions
git-svn-id: 093fa4c7fa7b11ddcea9103fc581483144c30c11@2381 5b74d2a0-fa0e-0410-85ed-ffba77ec0bde
| src/cog/modules/provider-coaster/src/org/globus/cog/abstraction/coaster/service/job/manager/WorkerManager.java | avoid concurrent modification exceptions | <ide><path>rc/cog/modules/provider-coaster/src/org/globus/cog/abstraction/coaster/service/job/manager/WorkerManager.java
<ide> synchronized (this) {
<ide> Iterator i;
<ide> List callbacks = new ArrayList();
<del> i = ready.values().iterator();
<add> //wr.shutdown removes the worker from this manager, which messes
<add> //up with the iteration
<add> i = new ArrayList(ready.values()).iterator();
<ide> while (i.hasNext()) {
<ide> Worker wr = (Worker) i.next();
<ide> callbacks.add(wr.shutdown()); |
|
Java | apache-2.0 | ca27e22cce53858599e6165d214768d5bd16b626 | 0 | lefou/AsciidocFX,asciidocfx/AsciidocFX,lefou/AsciidocFX,LightGuard/AsciidocFX,jaredmorgs/AsciidocFX,asciidocfx/AsciidocFX,jaredmorgs/AsciidocFX,asciidocfx/AsciidocFX,asciidocfx/AsciidocFX,gastaldi/AsciidocFX,gastaldi/AsciidocFX,jaredmorgs/AsciidocFX,LightGuard/AsciidocFX,LightGuard/AsciidocFX,gastaldi/AsciidocFX | package com.kodcu.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.install4j.api.launcher.ApplicationLauncher;
import com.kodcu.bean.Config;
import com.kodcu.bean.RecentFiles;
import com.kodcu.component.*;
import com.kodcu.logging.MyLog;
import com.kodcu.logging.TableViewLogAppender;
import com.kodcu.other.*;
import com.kodcu.outline.Section;
import com.kodcu.service.*;
import com.kodcu.service.config.YamlService;
import com.kodcu.service.convert.GitbookToAsciibookService;
import com.kodcu.service.convert.docbook.DocBookConverter;
import com.kodcu.service.convert.ebook.EpubConverter;
import com.kodcu.service.convert.ebook.MobiConverter;
import com.kodcu.service.convert.html.HtmlBookConverter;
import com.kodcu.service.convert.markdown.MarkdownService;
import com.kodcu.service.convert.odf.ODFConverter;
import com.kodcu.service.convert.pdf.AbstractPdfConverter;
import com.kodcu.service.convert.slide.SlideConverter;
import com.kodcu.service.extension.MathJaxService;
import com.kodcu.service.extension.PlantUmlService;
import com.kodcu.service.extension.TreeService;
import com.kodcu.service.extension.chart.ChartProvider;
import com.kodcu.service.shortcut.ShortcutProvider;
import com.kodcu.service.table.AsciidocTableController;
import com.kodcu.service.ui.*;
import com.sun.javafx.application.HostServicesDelegate;
import com.sun.webkit.dom.DocumentFragmentImpl;
import de.jensd.fx.fontawesome.AwesomeDude;
import de.jensd.fx.fontawesome.AwesomeIcon;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTreeCell;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebHistory;
import javafx.scene.web.WebView;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.CodeSource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static java.nio.file.StandardOpenOption.*;
@Component
public class ApplicationController extends TextWebSocketHandler implements Initializable {
public TabPane previewTabPane;
@Autowired
public HtmlPane htmlPane;
public Label odfPro;
public VBox logVBox;
public Label statusText;
public SplitPane editorSplitPane;
public Label statusMessage;
public Label showHideLogs;
public Tab outlineTab;
public MenuItem newFolder;
public MenuItem newSlide;
public Menu newMenu;
private Logger logger = LoggerFactory.getLogger(ApplicationController.class);
private Path userHome = Paths.get(System.getProperty("user.home"));
private TreeSet<Section> outlineList = new TreeSet<>();
private ObservableList<DocumentMode> modeList = FXCollections.observableArrayList();
private final Pattern bookArticleHeaderRegex =
Pattern.compile("^:doctype:.*(book|article)", Pattern.MULTILINE);
private final Pattern forceIncludeRegex =
Pattern.compile("^:forceinclude:", Pattern.MULTILINE);
public CheckMenuItem hidePreviewPanel;
public MenuItem hideFileBrowser;
public MenuButton panelShowHideMenuButton;
public MenuItem renameFile;
public MenuItem newFile;
public TabPane tabPane;
public SplitPane splitPane;
public SplitPane splitPaneVertical;
public TreeView<Item> treeView;
public Label workingDirButton;
public Label goUpLabel;
public Label goHomeLabel;
public Label refreshLabel;
public AnchorPane rootAnchor;
public ProgressIndicator indikator;
public ListView<String> recentListView;
public MenuItem openFileTreeItem;
public MenuItem deletePathItem;
public MenuItem openFolderTreeItem;
public MenuItem openFileListItem;
public MenuItem openFolderListItem;
public MenuItem copyPathTreeItem;
public MenuItem copyPathListItem;
public MenuItem copyTreeItem;
public MenuItem copyListItem;
public MenuButton leftButton;
private WebView mathjaxView;
public Label htmlPro;
public Label pdfPro;
public Label ebookPro;
public Label docbookPro;
public Label browserPro;
private AnchorPane markdownTableAnchor;
private Stage markdownTableStage;
private TreeView<Section> sectionTreeView;
private AtomicBoolean includeAsciidocResource = new AtomicBoolean(false);
private static ObservableList<MyLog> logList = FXCollections.synchronizedObservableList(FXCollections.observableArrayList());
@Autowired
private ApplicationContext applicationContext;
@Autowired
private AsciidocTableController asciidocTableController;
@Autowired
private GitbookToAsciibookService gitbookToAsciibook;
@Autowired
private PathOrderService pathOrder;
@Autowired
private TreeService treeService;
@Autowired
private TooltipTimeFixService tooltipTimeFixService;
@Autowired
private TabService tabService;
@Autowired
private ODFConverter odfConverter;
@Autowired
private PathResolverService pathResolver;
@Autowired
private PlantUmlService plantUmlService;
@Autowired
private EditorService editorService;
@Autowired
private MathJaxService mathJaxService;
@Autowired
private YamlService yamlService;
@Autowired
private WebviewService webviewService;
@Autowired
private DocBookConverter docBookConverter;
@Autowired
private HtmlBookConverter htmlBookService;
@Autowired
@Qualifier("pdfBookConverter")
private AbstractPdfConverter pdfBookConverter;
@Autowired
private EpubConverter epubConverter;
@Autowired
private Current current;
@Autowired
private FileBrowseService fileBrowser;
@Autowired
private IndikatorService indikatorService;
@Autowired
private MobiConverter mobiConverter;
@Autowired
private SampleBookService sampleBookService;
@Autowired
private EmbeddedWebApplicationContext server;
@Autowired
private ParserService parserService;
@Autowired
private AwesomeService awesomeService;
@Autowired
private DirectoryService directoryService;
@Autowired
private ThreadService threadService;
@Autowired
private DocumentService documentService;
@Autowired
private EpubController epubController;
@Autowired
private ShortcutProvider shortcutProvider;
@Autowired
private RestTemplate restTemplate;
@Autowired
private Base64.Encoder base64Encoder;
@Autowired
private ChartProvider chartProvider;
@Autowired
private MarkdownService markdownService;
private Stage stage;
private StringProperty lastRendered = new SimpleStringProperty();
private List<WebSocketSession> sessionList = new ArrayList<>();
private Scene scene;
private AnchorPane asciidocTableAnchor;
private Stage asciidocTableStage;
private final Clipboard clipboard = Clipboard.getSystemClipboard();
private final ObservableList<String> recentFilesList = FXCollections.synchronizedObservableList(FXCollections.observableArrayList());
private AnchorPane configAnchor;
private Stage configStage;
private int port = 8080;
private HostServicesDelegate hostServices;
private Path configPath;
private Config config;
private BooleanProperty fileBrowserVisibility = new SimpleBooleanProperty(false);
private BooleanProperty previewPanelVisibility = new SimpleBooleanProperty(false);
private final List<String> bookNames = Arrays.asList("book.asc", "book.txt", "book.asciidoc", "book.adoc", "book.ad");
private Map<String, String> shortCuts;
private RecentFiles recentFiles;
private final ChangeListener<String> lastRenderedChangeListener = (observableValue, old, nev) -> {
if (Objects.isNull(nev))
return;
threadService.runActionLater(() -> {
htmlPane.refreshUI(nev);
});
sessionList.stream().filter(e -> e.isOpen()).forEach(e -> {
try {
e.sendMessage(new TextMessage(nev));
} catch (Exception ex) {
logger.error("Problem occured while sending content over WebSocket", ex);
}
});
};
@Value("${application.version}")
private String version;
@Autowired
private SlideConverter slideConverter;
@Autowired
private SlidePane slidePane;
private Path installationPath;
private Path logPath;
@Autowired
private LiveReloadPane liveReloadPane;
private List<String> supportedModes;
@Autowired
private FileWatchService fileWatchService;
private PreviewTab previewTab;
public void createAsciidocTable() {
asciidocTableStage.showAndWait();
}
public void createMarkdownTable() {
markdownTableStage.showAndWait();
}
@FXML
private void openConfig(ActionEvent event) {
configStage.show();
}
@FXML
private void fullScreen(ActionEvent event) {
getStage().setFullScreen(!getStage().isFullScreen());
}
@FXML
private void directoryView(ActionEvent event) {
splitPane.setDividerPositions(0.1610294117647059, 0.5823529411764706);
}
private void generatePdf() {
this.generatePdf(false);
}
private void generatePdf(boolean askPath) {
if (!current.currentPath().isPresent())
saveDoc();
threadService.runTaskLater(() -> {
pdfBookConverter.convert(askPath);
});
}
@FXML
private void generateSampleBook(ActionEvent event) {
DirectoryChooser directoryChooser = directoryService.newDirectoryChooser("Select a New Directory for sample book");
File file = directoryChooser.showDialog(null);
threadService.runTaskLater(() -> {
sampleBookService.produceSampleBook(configPath, file.toPath());
directoryService.setWorkingDirectory(Optional.of(file.toPath()));
fileBrowser.browse(treeView, file.toPath());
threadService.runActionLater(() -> {
directoryView(null);
tabService.addTab(file.toPath().resolve("book.asc"));
});
});
}
public void convertDocbook() {
convertDocbook(false);
}
public void convertDocbook(boolean askPath) {
threadService.runTaskLater(() -> {
if (!current.currentPath().isPresent())
saveDoc();
threadService.runActionLater(() -> {
Path currentTabPath = current.currentPath().get();
Path currentTabPathDir = currentTabPath.getParent();
String tabText = current.getCurrentTabText().replace("*", "").trim();
Path docbookPath;
if (askPath) {
FileChooser fileChooser = directoryService.newFileChooser("Save Docbook file");
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Docbook", "*.xml"));
docbookPath = fileChooser.showSaveDialog(null).toPath();
} else
docbookPath = currentTabPathDir.resolve(tabText + ".xml");
Consumer<String> step = docbook -> {
final String finalDocbook = docbook;
threadService.runTaskLater(() -> {
IOHelper.writeToFile(docbookPath, finalDocbook, CREATE, TRUNCATE_EXISTING, WRITE);
});
threadService.runActionLater(() -> {
getRecentFilesList().remove(docbookPath.toString());
getRecentFilesList().add(0, docbookPath.toString());
});
};
docBookConverter.convert(false, step);
});
});
}
private void convertEpub() {
convertEpub(false);
}
private void convertEpub(boolean askPath) {
epubConverter.produceEpub3(askPath);
}
public void appendFormula(String fileName, String formula) {
mathJaxService.appendFormula(fileName, formula);
}
public void svgToPng(String fileName, String svg, String formula, float width, float height) {
threadService.runTaskLater(() -> {
mathJaxService.svgToPng(fileName, svg, formula, width, height);
});
}
private void convertMobi() {
convertMobi(false);
}
private void convertMobi(boolean askPath) {
if (Objects.nonNull(config.getKindlegenDir())) {
if (!Files.exists(Paths.get(config.getKindlegenDir()))) {
config.setKindlegenDir(null);
}
}
if (Objects.isNull(config.getKindlegenDir())) {
FileChooser fileChooser = directoryService.newFileChooser("Select 'kindlegen' executable");
File kindlegenFile = fileChooser.showOpenDialog(null);
if (Objects.isNull(kindlegenFile))
return;
config.setKindlegenDir(kindlegenFile.toPath().getParent().toString());
}
threadService.runTaskLater(() -> {
mobiConverter.convert(askPath);
});
}
private void generateHtml() {
this.generateHtml(false);
}
private void generateHtml(boolean askPath) {
if (!current.currentPath().isPresent())
this.saveDoc();
threadService.runTaskLater(() -> {
htmlBookService.convert(askPath);
});
}
public void createFileTree(String tree, String type, String fileName, String width, String height) {
threadService.runTaskLater(() -> {
treeService.createFileTree(tree, type, fileName, width, height);
});
}
public void createHighlightFileTree(String tree, String type, String fileName, String width, String height) {
threadService.runTaskLater(() -> {
treeService.createHighlightFileTree(tree, type, fileName, width, height);
});
}
@FXML
public void goUp() {
directoryService.goUp();
}
@FXML
public void refreshWorkingDir() {
current.currentPath().map(Path::getParent).ifPresent(directoryService::changeWorkigDir);
}
@FXML
public void goHome() {
directoryService.changeWorkigDir(userHome);
}
@WebkitCall
public void imageToBase64Url(final String url, final int index) {
threadService.runTaskLater(() -> {
try {
byte[] imageBuffer = restTemplate.getForObject(url, byte[].class);
String imageBase64 = base64Encoder.encodeToString(imageBuffer);
threadService.runActionLater(() -> {
htmlPane.updateBase64Url(index, imageBase64);
});
} catch (Exception e) {
logger.error("Problem occured while converting image to base64 for {}", url);
}
});
}
@Override
public void initialize(URL url, ResourceBundle rb) {
port = server.getEmbeddedServletContainer().getPort();
this.previewTab = new PreviewTab("Preview", htmlPane);
this.previewTab.setClosable(false);
threadService.runActionLater(() -> {
previewTabPane.getTabs().add(previewTab);
});
// Hide tab if one in tabpane
previewTabPane.getTabs().addListener((ListChangeListener) change -> {
final StackPane header = (StackPane) previewTabPane.lookup(".tab-header-area");
if (header != null) {
if (previewTabPane.getTabs().size() == 1)
header.setPrefHeight(0);
else
header.setPrefHeight(-1);
}
});
previewTabPane.setRotateGraphic(true);
outlineTab.getTabPane()
.getSelectionModel()
.selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
if (newValue == outlineTab) {
current.currentEditor().rerender();
}
});
initializePaths();
initializeLogViewer();
initializeDoctypes();
previewTabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS);
previewTabPane.setSide(Side.RIGHT);
tooltipTimeFixService.fix();
// Convert menu label icons
AwesomeDude.setIcon(htmlPro, AwesomeIcon.HTML5);
AwesomeDude.setIcon(pdfPro, AwesomeIcon.FILE_PDF_ALT);
AwesomeDude.setIcon(ebookPro, AwesomeIcon.BOOK);
AwesomeDude.setIcon(docbookPro, AwesomeIcon.CODE);
AwesomeDude.setIcon(odfPro, AwesomeIcon.FILE_WORD_ALT);
AwesomeDude.setIcon(browserPro, AwesomeIcon.FLASH);
// Left menu label icons
AwesomeDude.setIcon(workingDirButton, AwesomeIcon.FOLDER_ALT, "14.0");
AwesomeDude.setIcon(panelShowHideMenuButton, AwesomeIcon.COLUMNS, "14.0");
AwesomeDude.setIcon(refreshLabel, AwesomeIcon.REFRESH, "14.0");
AwesomeDude.setIcon(goUpLabel, AwesomeIcon.LEVEL_UP, "14.0");
AwesomeDude.setIcon(goHomeLabel, AwesomeIcon.HOME, "14.0");
leftButton.setGraphic(AwesomeDude.createIconLabel(AwesomeIcon.ELLIPSIS_H, "14.0"));
leftButton.getItems().get(leftButton.getItems().size() - 1).setText(String.join(" ", "Version", version));
ContextMenu htmlProMenu = new ContextMenu();
htmlProMenu.getStyleClass().add("build-menu");
htmlPro.setContextMenu(htmlProMenu);
htmlPro.setOnMouseClicked(event -> {
htmlProMenu.show(htmlPro, event.getScreenX(), 50);
});
htmlProMenu.getItems().add(MenuItemBuilt.item("Save").click(event -> {
this.generateHtml();
}));
htmlProMenu.getItems().add(MenuItemBuilt.item("Save as").click(event -> {
this.generateHtml(true);
}));
htmlProMenu.getItems().add(MenuItemBuilt.item("Copy source").tip("Copy HTML source").click(event -> {
this.cutCopy(lastRendered.getValue());
}));
htmlProMenu.getItems().add(MenuItemBuilt.item("Clone source").tip("Copy HTML source (Embedded images)").click(event -> {
htmlPane.call("imageToBase64Url", new Object[]{});
}));
ContextMenu pdfProMenu = new ContextMenu();
pdfProMenu.getStyleClass().add("build-menu");
pdfProMenu.getItems().add(MenuItemBuilt.item("Save").click(event -> {
this.generatePdf();
}));
pdfProMenu.getItems().add(MenuItemBuilt.item("Save as").click(event -> {
this.generatePdf(true);
}));
pdfPro.setContextMenu(pdfProMenu);
pdfPro.setOnMouseClicked(event -> {
pdfProMenu.show(pdfPro, event.getScreenX(), 50);
});
ContextMenu docbookProMenu = new ContextMenu();
docbookProMenu.getStyleClass().add("build-menu");
docbookProMenu.getItems().add(MenuItemBuilt.item("Save").click(event -> {
this.convertDocbook();
}));
docbookProMenu.getItems().add(MenuItemBuilt.item("Save as").click(event -> {
this.convertDocbook(true);
}));
docbookPro.setContextMenu(docbookProMenu);
docbookPro.setOnMouseClicked(event -> {
docbookProMenu.show(docbookPro, event.getScreenX(), 50);
});
ContextMenu ebookProMenu = new ContextMenu();
ebookProMenu.getStyleClass().add("build-menu");
ebookProMenu.getItems().add(MenuBuilt.name("Mobi")
.add(MenuItemBuilt.item("Save").click(event -> {
this.convertMobi();
}))
.add(MenuItemBuilt.item("Save as").click(event -> {
this.convertMobi(true);
})).build());
ebookProMenu.getItems().add(MenuBuilt.name("Epub")
.add(MenuItemBuilt.item("Save").click(event -> {
this.convertEpub();
}))
.add(MenuItemBuilt.item("Save as").click(event -> {
this.convertEpub(true);
})).build());
ebookPro.setOnMouseClicked(event -> {
ebookProMenu.show(ebookPro, event.getScreenX(), 50);
});
ebookPro.setContextMenu(ebookProMenu);
ContextMenu odfProMenu = new ContextMenu();
odfProMenu.getStyleClass().add("build-menu");
odfProMenu.setAutoHide(true);
odfProMenu.getItems().add(MenuItemBuilt.item("Save").click(event -> {
odfProMenu.hide();
this.generateODFDocument();
}));
odfProMenu.getItems().add(MenuItemBuilt.item("Save as").click(event -> {
odfProMenu.hide();
this.generateODFDocument(true);
}));
odfPro.setContextMenu(odfProMenu);
odfPro.setOnMouseClicked(event -> {
odfProMenu.show(odfPro, event.getScreenX(), 50);
});
browserPro.setOnMouseClicked(event -> {
if (event.getButton() == MouseButton.PRIMARY)
this.externalBrowse();
});
loadConfigurations();
loadRecentFileList();
loadShortCuts();
recentListView.setItems(recentFilesList);
recentFilesList.addListener((ListChangeListener<String>) c -> {
recentListView.visibleProperty().setValue(c.getList().size() > 0);
recentListView.getSelectionModel().selectFirst();
});
recentListView.setOnMouseClicked(event -> {
if (event.getClickCount() > 1) {
openRecentListFile(event);
}
});
treeView.setCellFactory(param -> {
TreeCell<Item> cell = new TextFieldTreeCell<Item>();
cell.setOnDragDetected(event -> {
Dragboard db = cell.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
content.putFiles(Arrays.asList(cell.getTreeItem().getValue().getPath().toFile()));
db.setContent(content);
});
return cell;
});
lastRendered.addListener(lastRenderedChangeListener);
// MathJax
mathjaxView = new WebView();
mathjaxView.setVisible(false);
rootAnchor.getChildren().add(mathjaxView);
WebEngine mathjaxEngine = mathjaxView.getEngine();
mathjaxEngine.getLoadWorker().stateProperty().addListener((observableValue1, state, state2) -> {
JSObject window = (JSObject) mathjaxEngine.executeScript("window");
if (window.getMember("afx").equals("undefined"))
window.setMember("afx", this);
});
threadService.runActionLater(() -> {
mathjaxEngine.load(String.format("http://localhost:%d/mathjax.html", port));
});
htmlPane.load(String.format("http://localhost:%d/preview.html", port));
/// Treeview
if (Objects.nonNull(recentFiles.getWorkingDirectory())) {
Path path = Paths.get(recentFiles.getWorkingDirectory());
Optional<Path> optional = Files.notExists(path) ? Optional.empty() : Optional.of(path);
directoryService.setWorkingDirectory(optional);
}
Path workDir = directoryService.getWorkingDirectory().orElse(userHome);
fileBrowser.browse(treeView, workDir);
openFileTreeItem.setOnAction(event -> {
ObservableList<TreeItem<Item>> selectedItems = treeView.getSelectionModel().getSelectedItems();
selectedItems.stream()
.map(e -> e.getValue())
.map(e -> e.getPath())
.filter(path -> {
if (selectedItems.size() == 1)
return true;
return !Files.isDirectory(path);
})
.forEach(directoryService.getOpenFileConsumer()::accept);
});
deletePathItem.setOnAction(event -> {
ObservableList<TreeItem<Item>> selectedItems = treeView.getSelectionModel().getSelectedItems();
AlertHelper.deleteAlert().ifPresent(btn -> {
if (btn == ButtonType.YES)
selectedItems.stream()
.map(e -> e.getValue())
.map(e -> e.getPath())
.forEach(path -> threadService.runTaskLater(() -> {
if (Files.isDirectory(path)) {
IOHelper.deleteDirectory(path);
} else {
IOHelper.deleteIfExists(path);
}
}));
});
});
openFolderTreeItem.setOnAction(event -> {
Path path = tabService.getSelectedTabPath();
path = Files.isDirectory(path) ? path : path.getParent();
if (Objects.nonNull(path))
getHostServices().showDocument(path.toString());
});
openFolderListItem.setOnAction(event -> {
Path path = Paths.get(recentListView.getSelectionModel().getSelectedItem());
path = Files.isDirectory(path) ? path : path.getParent();
if (Objects.nonNull(path))
getHostServices().showDocument(path.toString());
});
openFileListItem.setOnAction(this::openRecentListFile);
copyPathTreeItem.setOnAction(event -> {
Path path = tabService.getSelectedTabPath();
this.cutCopy(path.toString());
});
copyPathListItem.setOnAction(event -> {
this.cutCopy(recentListView.getSelectionModel().getSelectedItem());
});
copyTreeItem.setOnAction(event -> {
Path path = tabService.getSelectedTabPath();
this.copyFile(path);
});
copyListItem.setOnAction(event -> {
Path path = Paths.get(recentListView.getSelectionModel().getSelectedItem());
this.copyFile(path);
});
treeView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
treeView.setOnMouseClicked(event -> {
TreeItem<Item> selectedItem = treeView.getSelectionModel().getSelectedItem();
if (Objects.isNull(selectedItem))
return;
Path selectedPath = selectedItem.getValue().getPath();
if (event.getButton() == MouseButton.PRIMARY)
if (event.getClickCount() == 2)
directoryService.getOpenFileConsumer().accept(selectedPath);
});
treeView.getSelectionModel().getSelectedIndices().addListener((ListChangeListener<? super Integer>) p -> {
ObservableList<TreeItem<Item>> selectedItems = treeView.getSelectionModel().getSelectedItems();
if (selectedItems.size() > 1) {
renameFile.setVisible(false);
newMenu.setVisible(false);
} else if (selectedItems.size() == 1) {
Path path = selectedItems.get(0).getValue().getPath();
boolean isDirectory = Files.isDirectory(path);
newMenu.setVisible(isDirectory);
renameFile.setVisible(!isDirectory);
}
});
htmlPane.webEngine().setOnAlert(event -> {
if ("PREVIEW_LOADED".equals(event.getData())) {
if (htmlPane.getMember("afx").equals("undefined")) {
htmlPane.setMember("afx", this);
}
if (Objects.nonNull(lastRendered.getValue()))
lastRenderedChangeListener.changed(null, null, lastRendered.getValue());
}
});
ContextMenu previewContextMenu = new ContextMenu(
MenuItemBuilt.item("Go back").click(event -> {
WebHistory history = htmlPane.webEngine().getHistory();
if (history.getCurrentIndex() != 0)
history.go(-1);
}),
MenuItemBuilt.item("Go forward").click(event -> {
WebHistory history = htmlPane.webEngine().getHistory();
if (history.getCurrentIndex() + 1 != history.getEntries().size())
history.go(+1);
}),
new SeparatorMenuItem(),
MenuItemBuilt.item("Copy Html").click(event -> {
DocumentFragmentImpl selectionDom = (DocumentFragmentImpl) htmlPane.webEngine().executeScript("window.getSelection().getRangeAt(0).cloneContents()");
ClipboardContent content = new ClipboardContent();
content.putHtml(XMLHelper.nodeToString(selectionDom, true));
clipboard.setContent(content);
}),
MenuItemBuilt.item("Copy Text").click(event -> {
String selection = (String) htmlPane.webEngine().executeScript("window.getSelection().toString()");
ClipboardContent content = new ClipboardContent();
content.putString(selection);
clipboard.setContent(content);
}),
MenuItemBuilt.item("Copy Source").click(event -> {
DocumentFragmentImpl selectionDom = (DocumentFragmentImpl) htmlPane.webEngine().executeScript("window.getSelection().getRangeAt(0).cloneContents()");
ClipboardContent content = new ClipboardContent();
content.putString(XMLHelper.nodeToString(selectionDom, true));
clipboard.setContent(content);
}),
new SeparatorMenuItem(),
MenuItemBuilt.item("Refresh").click(event -> {
htmlPane.webEngine().executeScript("clearImageCache()");
}),
MenuItemBuilt.item("Reload").click(event -> {
htmlPane.webEngine().reload();
})
);
previewContextMenu.setAutoHide(true);
htmlPane.getWebView().setOnMouseClicked(event -> {
if (event.getButton() == MouseButton.SECONDARY) {
previewContextMenu.show(htmlPane.getWebView(), event.getScreenX(), event.getScreenY());
} else {
previewContextMenu.hide();
}
});
tabService.initializeTabChangeListener(tabPane);
newDoc(null);
Platform.runLater(() -> {
// editorSplitPane.setDividerPositions(1);
// splitPane.setDividerPositions();
});
threadService.runTaskLater(() -> {
checkNewVersion();
});
}
private void checkNewVersion() {
try {
ApplicationLauncher.launchApplication("504", null, false, new ApplicationLauncher.Callback() {
public void exited(int exitValue) {
//TODO add your code here (not invoked on event dispatch thread)
}
public void prepareShutdown() {
//TODO add your code here (not invoked on event dispatch thread)
}
}
);
} catch (IOException e) {
// logger.error("Problem occured while checking new version", e);
}
}
private void generateODFDocument(boolean askPath) {
if (!current.currentPath().isPresent())
this.saveDoc();
odfConverter.generateODFDocument(askPath);
}
private void generateODFDocument() {
this.generateODFDocument(false);
}
private void initializeDoctypes() {
try {
ObjectMapper mapper = new ObjectMapper();
Object readValue = mapper.readValue(configPath.resolve("doctypes.json").toFile(), new TypeReference<List<DocumentMode>>() {
});
modeList.addAll((Collection) readValue);
supportedModes = modeList.stream()
.map(d -> d.getExtensions())
.filter(Objects::nonNull)
.flatMap(d -> Arrays.asList(d.split("\\|")).stream())
.collect(Collectors.toList());
} catch (Exception e) {
e.printStackTrace();
logger.error("Problem occured while loading document types", e);
}
}
private void initializePaths() {
try {
CodeSource codeSource = ApplicationController.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
installationPath = jarFile.toPath().getParent().getParent();
configPath = installationPath.resolve("conf");
logPath = installationPath.resolve("log");
} catch (URISyntaxException e) {
logger.error("Problem occured while resolving conf and log paths", e);
}
}
@WebkitCall
public void updateStatusBox(long row, long column, long linecount, long wordcount) {
threadService.runTaskLater(() -> {
threadService.runActionLater(() -> {
statusText.setText(String.format("(Characters: %d) (Lines: %d) (%d:%d)", wordcount, linecount, row, column));
});
});
}
private void initializeLogViewer() {
TableView<MyLog> logViewer = new TableView<>();
logViewer.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
ContextMenu logViewerContextMenu = new ContextMenu();
logViewerContextMenu.getItems().add(MenuItemBuilt.item("Copy").click(e -> {
ObservableList<MyLog> rowList = (ObservableList) logViewer.getSelectionModel().getSelectedItems();
StringBuilder clipboardString = new StringBuilder();
for (MyLog rowLog : rowList) {
clipboardString.append(String.format("%s => %s", rowLog.getLevel(), rowLog.getMessage()));
clipboardString.append("\n\n");
}
ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putString(clipboardString.toString());
clipboard.setContent(clipboardContent);
}));
logViewer.setContextMenu(logViewerContextMenu);
logViewer.getStyleClass().add("log-viewer");
FilteredList<MyLog> logFilteredList = new FilteredList<MyLog>(logList, log -> true);
logViewer.setItems(logFilteredList);
// logViewer.setColumnResizePolicy((param) -> true);
logViewer.getItems().addListener((ListChangeListener<MyLog>) c -> {
c.next();
final int size = logViewer.getItems().size();
if (size > 0) {
logViewer.scrollTo(size - 1);
}
});
TableColumn<MyLog, String> levelColumn = new TableColumn<>("Level");
levelColumn.getStyleClass().add("level-column");
TableColumn<MyLog, String> messageColumn = new TableColumn<>("Message");
levelColumn.setCellValueFactory(new PropertyValueFactory<MyLog, String>("level"));
messageColumn.setCellValueFactory(new PropertyValueFactory<MyLog, String>("message"));
messageColumn.prefWidthProperty().bind(logViewer.widthProperty().subtract(levelColumn.widthProperty()).subtract(5));
logViewer.setRowFactory(param -> new TableRow<MyLog>() {
@Override
protected void updateItem(MyLog item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
getStyleClass().removeAll("DEBUG", "INFO", "WARN", "ERROR");
getStyleClass().add(item.getLevel());
}
}
});
messageColumn.setCellFactory(param -> new TableCell<MyLog, String>() {
@Override
protected void updateItem(String item, boolean empty) {
if (item == getItem())
return;
super.updateItem(item, empty);
if (item == null) {
super.setText(null);
super.setGraphic(null);
} else {
Text text = new Text(item);
super.setGraphic(text);
text.wrappingWidthProperty().bind(messageColumn.widthProperty().subtract(0));
}
}
});
logViewer.getColumns().addAll(levelColumn, messageColumn);
logViewer.setEditable(true);
TableViewLogAppender.setLogList(logList);
TableViewLogAppender.setLogShortMessage(statusMessage);
TableViewLogAppender.setLogViewer(logViewer);
final EventHandler<ActionEvent> filterByLogLevel = event -> {
ToggleButton logLevelItem = (ToggleButton) event.getTarget();
if (Objects.nonNull(logLevelItem)) {
logFilteredList.setPredicate(myLog -> {
String text = logLevelItem.getText();
return text.equals("All") || text.equalsIgnoreCase(myLog.getLevel());
});
}
};
ToggleGroup toggleGroup = new ToggleGroup();
ToggleButton allToggle = ToggleButtonBuilt.item("All").tip("Show all").click(filterByLogLevel);
ToggleButton errorToggle = ToggleButtonBuilt.item("Error").tip("Filter by Error").click(filterByLogLevel);
ToggleButton warnToggle = ToggleButtonBuilt.item("Warn").tip("Filter by Warn").click(filterByLogLevel);
ToggleButton infoToggle = ToggleButtonBuilt.item("Info").tip("Filter by Info").click(filterByLogLevel);
ToggleButton debugToggle = ToggleButtonBuilt.item("Debug").tip("Filter by Debug").click(filterByLogLevel);
toggleGroup.getToggles().addAll(
allToggle,
errorToggle,
warnToggle,
infoToggle,
debugToggle
);
toggleGroup.selectToggle(allToggle);
Button clearLogsButton = new Button("Clear");
clearLogsButton.setOnAction(e -> {
statusMessage.setText("");
logList.clear();
});
Button browseLogsButton = new Button("Browse");
browseLogsButton.setOnAction(e -> {
getHostServices().showDocument(logPath.toUri().toString());
});
TextField searchLogField = new TextField();
searchLogField.setPromptText("Search in logs..");
searchLogField.textProperty().addListener((observable, oldValue, newValue) -> {
if (Objects.isNull(newValue)) {
return;
}
if (newValue.isEmpty()) {
logFilteredList.setPredicate(myLog -> true);
}
logFilteredList.setPredicate(myLog -> {
final AtomicBoolean result = new AtomicBoolean(false);
String message = myLog.getMessage();
if (Objects.nonNull(message)) {
if (!result.get())
result.set(message.toLowerCase().contains(newValue.toLowerCase()));
}
String level = myLog.getLevel();
String toggleText = ((ToggleButton) toggleGroup.getSelectedToggle()).getText();
boolean inputContains = level.toLowerCase().contains(newValue.toLowerCase());
if (Objects.nonNull(level)) {
if (!result.get()) {
result.set(inputContains);
}
}
boolean levelContains = toggleText.toLowerCase().equalsIgnoreCase(level);
if (!toggleText.equals("All") && !levelContains) {
result.set(false);
}
return result.get();
});
});
List<Control> controls = Arrays.asList(allToggle,
errorToggle, warnToggle, infoToggle, debugToggle,
searchLogField, clearLogsButton, browseLogsButton);
HBox logHBox = new HBox();
for (Control control : controls) {
logHBox.getChildren().add(control);
HBox.setMargin(control, new Insets(3));
control.prefHeightProperty().bind(searchLogField.heightProperty());
}
AwesomeDude.setIcon(showHideLogs, AwesomeIcon.CHEVRON_CIRCLE_UP, "14.0");
HBox.setMargin(showHideLogs, new Insets(0, 0, 0, 3));
HBox.setMargin(statusText, new Insets(0, 3, 0, 0));
showHideLogs.setOnMouseClicked(event -> {
showHideLogs.setRotate(showHideLogs.getRotate() + 180);
if (showHideLogs.getRotate() % 360 == 0)
editorSplitPane.setDividerPositions(1);
else
editorSplitPane.setDividerPositions(0.5);
});
logVBox.getChildren().addAll(logHBox, logViewer);
VBox.setVgrow(logViewer, Priority.ALWAYS);
}
private void loadShortCuts() {
try {
String yamlC = IOHelper.readFile(configPath.resolve("shortcuts.yml"));
Yaml yaml = new Yaml();
this.shortCuts = yaml.loadAs(yamlC, Map.class);
} catch (Exception e) {
logger.error("Problem occured while loading shortcuts.yml file", e);
}
}
private void openRecentListFile(Event event) {
Path path = Paths.get(recentListView.getSelectionModel().getSelectedItem());
directoryService.getOpenFileConsumer().accept(path);
}
private void loadConfigurations() {
try {
String yamlContent = IOHelper.readFile(configPath.resolve("config.yml"));
Yaml yaml = new Yaml();
config = yaml.loadAs(yamlContent, Config.class);
} catch (Exception e) {
logger.error("Problem occured while loading config.yml file", e);
}
if (!config.getDirectoryPanel())
threadService.runActionLater(() -> {
splitPane.setDividerPositions(0, 0.51);
});
}
private void loadRecentFileList() {
try {
String yamlContent = IOHelper.readFile(configPath.resolve("recentFiles.yml"));
Yaml yaml = new Yaml();
recentFiles = yaml.loadAs(yamlContent, RecentFiles.class);
recentFilesList.addAll(recentFiles.getFiles());
} catch (Exception e) {
logger.error("Problem occured while loading recent file list", e);
}
}
public void externalBrowse() {
ObservableList<Tab> tabs = previewTabPane.getTabs();
for (Tab tab : tabs) {
if (tab.isSelected()) {
Node content = tab.getContent();
if (Objects.nonNull(content))
((ViewPanel) content).browse();
}
}
}
@WebkitCall(from = "index")
public void fillOutlines(JSObject doc) {
if (outlineTab.isSelected())
threadService.runActionLater(() -> {
htmlPane.fillOutlines(doc);
});
}
@WebkitCall(from = "index")
public void clearOutline() {
outlineList = new TreeSet<>();
}
@WebkitCall(from = "index")
public void finishOutline() {
threadService.runTaskLater(() -> {
if (Objects.isNull(sectionTreeView)) {
sectionTreeView = new TreeView<Section>();
TreeItem<Section> rootItem = new TreeItem<>();
rootItem.setExpanded(true);
Section rootSection = new Section();
rootSection.setLevel(-1);
String outlineTitle = "Outline";
rootSection.setTitle(outlineTitle);
rootItem.setValue(rootSection);
sectionTreeView.setRoot(rootItem);
sectionTreeView.setOnMouseClicked(event -> {
try {
TreeItem<Section> item = sectionTreeView.getSelectionModel().getSelectedItem();
EditorPane editorPane = current.currentEditor();
editorPane.moveCursorTo(item.getValue().getLineno());
} catch (Exception e) {
logger.error("Problem occured while jumping from outline");
}
});
}
sectionTreeView.getRoot().getChildren().clear();
for (Section section : outlineList) {
TreeItem<Section> sectionItem = new TreeItem<>(section);
sectionTreeView.getRoot().getChildren().add(sectionItem);
TreeSet<Section> subsections = section.getSubsections();
for (Section subsection : subsections) {
TreeItem<Section> subItem = new TreeItem<>(subsection);
sectionItem.getChildren().add(subItem);
this.addSubSections(subItem, subsection.getSubsections());
}
}
if (Objects.isNull(outlineTab.getContent()))
threadService.runActionLater(() -> {
outlineTab.setContent(sectionTreeView);
});
});
}
private void addSubSections(TreeItem<Section> subItem, TreeSet<Section> outlineList) {
for (Section section : outlineList) {
TreeItem<Section> sectionItem = new TreeItem<>(section);
subItem.getChildren().add(sectionItem);
TreeSet<Section> subsections = section.getSubsections();
for (Section subsection : subsections) {
TreeItem<Section> item = new TreeItem<>(subsection);
sectionItem.getChildren().add(item);
this.addSubSections(item, subsection.getSubsections());
}
}
}
@WebkitCall(from = "index")
public void fillOutline(String parentLineNo, String level, String title, String lineno, String id) {
Section section = new Section();
section.setLevel(Integer.valueOf(level));
section.setTitle(title);
section.setLineno(Integer.valueOf(lineno));
section.setId(id);
if (Objects.isNull(parentLineNo))
outlineList.add(section);
else {
Integer parentLine = Integer.valueOf(parentLineNo);
Optional<Section> parentSection = outlineList.stream()
.filter(e -> e.getLineno().equals(parentLine))
.findFirst();
if (parentSection.isPresent())
parentSection.get().getSubsections().add(section);
else {
this.traverseEachSubSection(outlineList, parentLine, section);
}
}
}
private void traverseEachSubSection(TreeSet<Section> sections, Integer parentLine, Section section) {
sections.stream().forEach(s -> {
Optional<Section> subs = s.getSubsections().stream()
.filter(e -> e.getLineno().equals(parentLine))
.findFirst();
if (subs.isPresent())
subs.get().getSubsections().add(section);
else
this.traverseEachSubSection(s.getSubsections(), parentLine, section);
});
}
@FXML
public void changeWorkingDir(Event actionEvent) {
directoryService.changeWorkigDir();
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessionList.add(session);
String value = lastRendered.getValue();
if (Objects.nonNull(value))
session.sendMessage(new TextMessage(value));
}
@FXML
public void closeApp(ActionEvent event) {
try {
yamlService.persist();
} catch (Exception e) {
logger.error("Error while closing app", e);
}
}
@FXML
public void openDoc(Event event) {
documentService.openDoc();
}
@FXML
public void newDoc(Event event) {
threadService.runActionLater(() -> {
documentService.newDoc();
});
}
@WebkitCall(from = "editor")
public boolean isLiveReloadPane() {
return previewTab.getContent() == liveReloadPane;
}
@WebkitCall(from = "editor")
public void onscroll(Object pos, Object max) {
Node content = previewTab.getContent();
if (Objects.nonNull(content)) {
((ViewPanel) content).onscroll(pos, max);
}
}
@WebkitCall(from = "editor")
public void scrollToCurrentLine(String text) {
if (previewTab.getContent() == slidePane) {
slidePane.flipThePage(htmlPane.findRenderedSelection(text)); // slide
}
if (previewTab.getContent() == htmlPane) {
threadService.runActionLater(() -> {
try {
htmlPane.call("runScroller", text);
} catch (Exception e) {
logger.debug(e.getMessage(), e);
}
});
}
}
public void plantUml(String uml, String type, String fileName) throws IOException {
threadService.runTaskLater(() -> {
plantUmlService.plantUml(uml, type, fileName);
});
}
public void chartBuildFromCsv(String csvFile, String fileName, String chartType, String options) {
if (Objects.isNull(fileName) || Objects.isNull(chartType))
return;
getCurrent().currentPath().map(Path::getParent).ifPresent(root -> {
threadService.runTaskLater(() -> {
String csvContent = IOHelper.readFile(root.resolve(csvFile));
threadService.runActionLater(() -> {
try {
Map<String, String> optMap = parseChartOptions(options);
optMap.put("csv-file", csvFile);
chartProvider.getProvider(chartType).chartBuild(csvContent, fileName, optMap);
} catch (Exception e) {
logger.info(e.getMessage(), e);
}
});
});
});
}
public void chartBuild(String chartContent, String fileName, String chartType, String options) {
if (Objects.isNull(fileName) || Objects.isNull(chartType))
return;
threadService.runActionLater(() -> {
try {
Map<String, String> optMap = parseChartOptions(options);
chartProvider.getProvider(chartType).chartBuild(chartContent, fileName, optMap);
} catch (Exception e) {
logger.info(e.getMessage(), e);
}
});
}
private Map<String, String> parseChartOptions(String options) {
Map<String, String> optMap = new HashMap<>();
if (Objects.nonNull(options)) {
String[] optPart = options.split(",");
for (String opt : optPart) {
String[] keyVal = opt.split("=");
if (keyVal.length != 2)
continue;
optMap.put(keyVal[0], keyVal[1]);
}
}
return optMap;
}
@WebkitCall(from = "editor")
public void appendWildcard() {
String currentTabText = current.getCurrentTabText();
if (!currentTabText.contains(" *"))
current.setCurrentTabText(currentTabText + " *");
}
@WebkitCall(from = "editor")
public void textListener(String text, String mode) {
threadService.runTaskLater(() -> {
boolean bookArticleHeader = this.bookArticleHeaderRegex.matcher(text).find();
boolean forceInclude = this.forceIncludeRegex.matcher(text).find();
threadService.runActionLater(() -> {
try {
if ("asciidoc".equalsIgnoreCase(mode)) {
if (bookArticleHeader && !forceInclude)
setIncludeAsciidocResource(true);
ConverterResult result = htmlPane.convertAsciidoc(text);
setIncludeAsciidocResource(false);
if (result.isBackend("html5")) {
lastRendered.setValue(result.getRendered());
previewTab.setContent(htmlPane);
}
if (result.isBackend("revealjs") || result.isBackend("deckjs")) {
slidePane.setBackend(result.getBackend());
slideConverter.convert(result.getRendered());
}
} else if ("html".equalsIgnoreCase(mode)) {
if (previewTab.getContent() != liveReloadPane) {
liveReloadPane.setOnSuccess(() -> {
liveReloadPane.setMember("afx", this);
liveReloadPane.initializeDiffReplacer();
});
liveReloadPane.load(String.format("http://localhost:%d/livereload/index.reload", port));
} else {
liveReloadPane.updateDomdom();
}
previewTab.setContent(liveReloadPane);
} else if ("markdown".equalsIgnoreCase(mode)) {
markdownService.convertToAsciidoc(text, asciidoc -> {
threadService.runActionLater(() -> {
ConverterResult result = htmlPane.convertAsciidoc(asciidoc);
result.afterRender(lastRendered::setValue);
});
});
previewTab.setContent(htmlPane);
}
} catch (Exception e) {
setIncludeAsciidocResource(false);
logger.error("Problem occured while rendering content", e);
}
});
});
}
@WebkitCall(from = "asciidoctor-odf.js")
public void convertToOdf(String name, Object obj) throws Exception {
JSObject jObj = (JSObject) obj;
odfConverter.buildDocument(name, jObj);
}
@WebkitCall
public String getTemplate(String templateName, String templateDir) throws IOException {
return htmlPane.getTemplate(templateName, templateDir);
}
public void cutCopy(String data) {
ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putString(data);
clipboard.setContent(clipboardContent);
}
public void copyFile(Path path) {
ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putFiles(Arrays.asList(path.toFile()));
clipboard.setContent(clipboardContent);
}
@WebkitCall(from = "asciidoctor")
public String readAsciidoctorResource(String uri, Integer parent) {
if (uri.matches(".*?\\.(asc|adoc|ad|asciidoc|md|markdown)") && getIncludeAsciidocResource())
return String.format("link:%s[]", uri);
final CompletableFuture<String> completableFuture = new CompletableFuture();
completableFuture.runAsync(() -> {
threadService.runTaskLater(() -> {
PathFinderService fileReader = applicationContext.getBean("pathFinder", PathFinderService.class);
Path path = fileReader.findPath(uri, parent);
if (!Files.exists(path))
completableFuture.complete("404");
completableFuture.complete(IOHelper.readFile(path));
});
});
return completableFuture.join();
}
@WebkitCall
public String clipboardValue() {
return clipboard.getString();
}
@WebkitCall
public void pasteRaw() {
JSObject editor = (JSObject) current.currentEngine().executeScript("editor");
if (clipboard.hasFiles()) {
Optional<String> block = parserService.toImageBlock(clipboard.getFiles());
if (block.isPresent()) {
editor.call("insert", block.get());
return;
}
}
editor.call("insert", clipboard.getString());
}
@WebkitCall
public void paste() {
JSObject window = (JSObject) htmlPane.webEngine().executeScript("window");
JSObject editor = (JSObject) current.currentEngine().executeScript("editor");
if (clipboard.hasFiles()) {
Optional<String> block = parserService.toImageBlock(clipboard.getFiles());
if (block.isPresent()) {
editor.call("insert", block.get());
return;
}
}
try {
if (clipboard.hasHtml() || (Boolean) window.call("isHtml", clipboard.getString())) {
String content = Optional.ofNullable(clipboard.getHtml()).orElse(clipboard.getString());
if (current.currentTab().isAsciidoc() || current.currentTab().isMarkdown())
content = (String) window.call(current.currentTab().htmlToMarkupFunction(), content);
editor.call("insert", content);
return;
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
editor.call("insert", clipboard.getString());
}
public void adjustSplitPane() {
if (splitPane.getDividerPositions()[0] > 0.1) {
hideFileAndPreviewPanels(null);
} else {
showFileBrowser();
showPreviewPanel();
}
}
@WebkitCall
public void debug(String message) {
logger.debug(message);
}
@WebkitCall
public void error(String message) {
logger.error(message);
}
@WebkitCall
public void info(String message) {
logger.info(message);
}
@WebkitCall
public void warn(String message) {
logger.warn(message);
}
public void saveDoc() {
documentService.saveDoc();
}
@FXML
public void saveDoc(Event actionEvent) {
documentService.saveDoc();
}
public void fitToParent(Node node) {
AnchorPane.setTopAnchor(node, 0.0);
AnchorPane.setBottomAnchor(node, 0.0);
AnchorPane.setLeftAnchor(node, 0.0);
AnchorPane.setRightAnchor(node, 0.0);
}
public void saveAndCloseCurrentTab() {
this.saveDoc();
threadService.runActionLater(current.currentTab()::close);
}
public ProgressIndicator getIndikator() {
return indikator;
}
public void setStage(Stage stage) {
this.stage = stage;
}
public Stage getStage() {
return stage;
}
public void setScene(Scene scene) {
this.scene = scene;
}
public Scene getScene() {
return scene;
}
public void setAsciidocTableAnchor(AnchorPane asciidocTableAnchor) {
this.asciidocTableAnchor = asciidocTableAnchor;
}
public AnchorPane getAsciidocTableAnchor() {
return asciidocTableAnchor;
}
public void setAsciidocTableStage(Stage asciidocTableStage) {
this.asciidocTableStage = asciidocTableStage;
}
public Stage getAsciidocTableStage() {
return asciidocTableStage;
}
public void setConfigAnchor(AnchorPane configAnchor) {
this.configAnchor = configAnchor;
}
public AnchorPane getConfigAnchor() {
return configAnchor;
}
public void setConfigStage(Stage configStage) {
this.configStage = configStage;
}
public Stage getConfigStage() {
return configStage;
}
public SplitPane getSplitPane() {
return splitPane;
}
public TreeView<Item> getTreeView() {
return treeView;
}
public void setHostServices(HostServicesDelegate hostServices) {
this.hostServices = hostServices;
}
public HostServicesDelegate getHostServices() {
return hostServices;
}
public Config getConfig() {
return config;
}
public AsciidocTableController getAsciidocTableController() {
return asciidocTableController;
}
public StringProperty getLastRendered() {
return lastRendered;
}
public ObservableList<String> getRecentFilesList() {
return recentFilesList;
}
public TabPane getTabPane() {
return tabPane;
}
public WebView getMathjaxView() {
return mathjaxView;
}
public ChangeListener<String> getLastRenderedChangeListener() {
return lastRenderedChangeListener;
}
public AnchorPane getRootAnchor() {
return rootAnchor;
}
public int getPort() {
return port;
}
public Path getConfigPath() {
return configPath;
}
public Current getCurrent() {
return current;
}
public Map<String, String> getShortCuts() {
if (Objects.isNull(shortCuts))
shortCuts = new HashMap<>();
return shortCuts;
}
@FXML
private void bugReport(ActionEvent actionEvent) {
getHostServices().showDocument("https://github.com/asciidocfx/AsciidocFX/issues");
}
@FXML
private void openCommunityForum(ActionEvent actionEvent) {
getHostServices().showDocument("https://groups.google.com/d/forum/asciidocfx-discuss");
}
@FXML
private void openGitterChat(ActionEvent actionEvent) {
getHostServices().showDocument("https://gitter.im/asciidocfx/AsciidocFX");
}
@FXML
private void openGithubPage(ActionEvent actionEvent) {
getHostServices().showDocument("https://github.com/asciidocfx/AsciidocFX");
}
@FXML
public void generateCheatSheet(ActionEvent actionEvent) {
Path cheatsheetPath = configPath.resolve("cheatsheet/cheatsheet.asc");
tabService.addTab(cheatsheetPath);
}
public void setMarkdownTableAnchor(AnchorPane markdownTableAnchor) {
this.markdownTableAnchor = markdownTableAnchor;
}
public AnchorPane getMarkdownTableAnchor() {
return markdownTableAnchor;
}
public void setMarkdownTableStage(Stage markdownTableStage) {
this.markdownTableStage = markdownTableStage;
}
public Stage getMarkdownTableStage() {
return markdownTableStage;
}
public ShortcutProvider getShortcutProvider() {
return shortcutProvider;
}
@FXML
public void createFolder(ActionEvent actionEvent) {
DialogBuilder dialog = DialogBuilder.newFolderDialog();
Consumer<String> consumer = result -> {
if (dialog.isShowing())
dialog.hide();
if (result.matches(DialogBuilder.FOLDER_NAME_REGEX)) {
Path path = treeView.getSelectionModel().getSelectedItem()
.getValue().getPath();
Path folderPath = path.resolve(result);
threadService.runTaskLater(() -> {
IOHelper.createDirectory(folderPath);
directoryService.changeWorkigDir(folderPath);
});
}
};
dialog.getEditor().setOnAction(event -> {
consumer.accept(dialog.getEditor().getText());
});
dialog.showAndWait().ifPresent(consumer);
}
@FXML
public void createFile(ActionEvent actionEvent) {
DialogBuilder dialog = DialogBuilder.newFileDialog();
Consumer<String> consumer = result -> {
if (dialog.isShowing())
dialog.hide();
if (result.matches(DialogBuilder.FILE_NAME_REGEX)) {
Path path = treeView.getSelectionModel().getSelectedItem()
.getValue().getPath();
IOHelper.writeToFile(path.resolve(result), "");
tabService.addTab(path.resolve(result));
threadService.runActionLater(() -> {
directoryService.changeWorkigDir(path);
});
}
};
dialog.getEditor().setOnAction(event -> {
consumer.accept(dialog.getEditor().getText());
});
dialog.showAndWait().ifPresent(consumer);
}
@FXML
public void renameFile(ActionEvent actionEvent) {
RenameDialog dialog = RenameDialog.create();
Path path = treeView.getSelectionModel().getSelectedItem()
.getValue().getPath();
dialog.getEditor().setText(path.getFileName().toString());
Consumer<String> consumer = result -> {
if (dialog.isShowing())
dialog.hide();
if (result.trim().matches("^[^\\\\/:?*\"<>|]+$"))
IOHelper.move(path, path.getParent().resolve(result.trim()));
};
dialog.getEditor().setOnAction(event -> {
consumer.accept(dialog.getEditor().getText());
});
dialog.showAndWait().ifPresent(consumer);
}
@FXML
public void gitbookToAsciibook(ActionEvent actionEvent) {
File gitbookRoot = null;
File asciibookRoot = null;
BiPredicate<File, File> nullPathPredicate = (p1, p2)
-> Objects.isNull(p1)
|| Objects.isNull(p2);
DirectoryChooser gitbookChooser = new DirectoryChooser();
gitbookChooser.setTitle("Select Gitbook Root Directory");
gitbookRoot = gitbookChooser.showDialog(null);
DirectoryChooser asciibookChooser = new DirectoryChooser();
asciibookChooser.setTitle("Select Blank Asciibook Root Directory");
asciibookRoot = asciibookChooser.showDialog(null);
if (nullPathPredicate.test(gitbookRoot, asciibookRoot)) {
AlertHelper.nullDirectoryAlert();
return;
}
final File finalGitbookRoot = gitbookRoot;
final File finalAsciibookRoot = asciibookRoot;
threadService.runTaskLater(() -> {
logger.debug("Gitbook to Asciibook conversion started");
indikatorService.startCycle();
gitbookToAsciibook.gitbookToAsciibook(finalGitbookRoot.toPath(), finalAsciibookRoot.toPath());
indikatorService.completeCycle();
logger.debug("Gitbook to Asciibook conversion ended");
});
}
public boolean getFileBrowserVisibility() {
return fileBrowserVisibility.get();
}
public BooleanProperty fileBrowserVisibilityProperty() {
return fileBrowserVisibility;
}
public boolean getPreviewPanelVisibility() {
return previewPanelVisibility.get();
}
public BooleanProperty previewPanelVisibilityProperty() {
return previewPanelVisibility;
}
@FXML
public void hideFileBrowser(ActionEvent actionEvent) {
splitPane.setDividerPosition(0, 0);
fileBrowserVisibility.setValue(true);
}
public void showFileBrowser() {
splitPane.setDividerPositions(0.195, splitPane.getDividerPositions()[1]);
fileBrowserVisibility.setValue(false);
}
public void hidePreviewPanel() {
splitPane.setDividerPosition(1, 1);
previewPanelVisibility.setValue(true);
}
@FXML
public void togglePreviewPanel(ActionEvent actionEvent) {
if (hidePreviewPanel.isSelected()) {
hidePreviewPanel();
} else {
showPreviewPanel();
}
}
public void showPreviewPanel() {
splitPane.setDividerPosition(1, 0.6);
previewPanelVisibility.setValue(false);
hidePreviewPanel.setSelected(false);
}
@FXML
public void hideFileAndPreviewPanels(ActionEvent actionEvent) {
hidePreviewPanel.setSelected(true);
togglePreviewPanel(actionEvent);
hideFileBrowser(actionEvent);
}
/*
@WebkitCall
public void fillModeList(String mode) {
threadService.runActionLater(() -> {
modeList.add(mode);
});
}*/
public RecentFiles getRecentFiles() {
return recentFiles;
}
public void clearImageCache() {
htmlPane.webEngine().executeScript("clearImageCache()");
}
public ObservableList<DocumentMode> getModeList() {
return modeList;
}
public List<String> getSupportedModes() {
return supportedModes;
}
public boolean getIncludeAsciidocResource() {
return includeAsciidocResource.get();
}
public void setIncludeAsciidocResource(boolean includeAsciidocResource) {
this.includeAsciidocResource.set(includeAsciidocResource);
}
public void removeChildElement(Node node) {
getRootAnchor().getChildren().remove(node);
}
@FXML
public void switchSlideView(ActionEvent actionEvent) {
splitPane.setDividerPositions(0, 0.45);
fileBrowserVisibility.setValue(true);
}
public TabPane getPreviewTabPane() {
return previewTabPane;
}
public PreviewTab getPreviewTab() {
return previewTab;
}
@FXML
public void newSlide(ActionEvent actionEvent) {
DialogBuilder dialog = DialogBuilder.newFolderDialog();
dialog.showAndWait().ifPresent(folderName -> {
if (dialog.isShowing())
dialog.hide();
if (folderName.matches(DialogBuilder.FOLDER_NAME_REGEX)) {
Path path = treeView.getSelectionModel().getSelectedItem()
.getValue().getPath();
Path folderPath = path.resolve(folderName);
// it needs to invalidate file watchservice
fileWatchService.invalidate();
threadService.runTaskLater(() -> {
IOHelper.createDirectory(folderPath);
htmlPane.startProgressBar();
IOHelper.copyDirectory(configPath.resolve("slide/frameworks"), folderPath);
htmlPane.stopProgressBar();
directoryService.changeWorkigDir(folderPath);
threadService.runActionLater(() -> {
tabService.addTab(folderPath.resolve("slide.adoc"));
this.switchSlideView(actionEvent);
});
});
}
});
}
} | src/main/java/com/kodcu/controller/ApplicationController.java | package com.kodcu.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.install4j.api.launcher.ApplicationLauncher;
import com.kodcu.bean.Config;
import com.kodcu.bean.RecentFiles;
import com.kodcu.component.*;
import com.kodcu.logging.MyLog;
import com.kodcu.logging.TableViewLogAppender;
import com.kodcu.other.*;
import com.kodcu.outline.Section;
import com.kodcu.service.*;
import com.kodcu.service.config.YamlService;
import com.kodcu.service.convert.GitbookToAsciibookService;
import com.kodcu.service.convert.docbook.DocBookConverter;
import com.kodcu.service.convert.ebook.EpubConverter;
import com.kodcu.service.convert.ebook.MobiConverter;
import com.kodcu.service.convert.html.HtmlBookConverter;
import com.kodcu.service.convert.markdown.MarkdownService;
import com.kodcu.service.convert.odf.ODFConverter;
import com.kodcu.service.convert.pdf.AbstractPdfConverter;
import com.kodcu.service.convert.slide.SlideConverter;
import com.kodcu.service.extension.MathJaxService;
import com.kodcu.service.extension.PlantUmlService;
import com.kodcu.service.extension.TreeService;
import com.kodcu.service.extension.chart.ChartProvider;
import com.kodcu.service.shortcut.ShortcutProvider;
import com.kodcu.service.table.AsciidocTableController;
import com.kodcu.service.ui.*;
import com.sun.javafx.application.HostServicesDelegate;
import com.sun.webkit.dom.DocumentFragmentImpl;
import de.jensd.fx.fontawesome.AwesomeDude;
import de.jensd.fx.fontawesome.AwesomeIcon;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTreeCell;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebHistory;
import javafx.scene.web.WebView;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.CodeSource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static java.nio.file.StandardOpenOption.*;
@Component
public class ApplicationController extends TextWebSocketHandler implements Initializable {
public TabPane previewTabPane;
@Autowired
public HtmlPane htmlPane;
public Label odfPro;
public VBox logVBox;
public Label statusText;
public SplitPane editorSplitPane;
public Label statusMessage;
public Label showHideLogs;
public Tab outlineTab;
public MenuItem newFolder;
public MenuItem newSlide;
public Menu newMenu;
private Logger logger = LoggerFactory.getLogger(ApplicationController.class);
private Path userHome = Paths.get(System.getProperty("user.home"));
private TreeSet<Section> outlineList = new TreeSet<>();
private ObservableList<DocumentMode> modeList = FXCollections.observableArrayList();
private final Pattern bookArticleHeaderRegex =
Pattern.compile("^:doctype:.*(book|article)", Pattern.MULTILINE);
private final Pattern forceIncludeRegex =
Pattern.compile("^:forceinclude:", Pattern.MULTILINE);
public CheckMenuItem hidePreviewPanel;
public MenuItem hideFileBrowser;
public MenuButton panelShowHideMenuButton;
public MenuItem renameFile;
public MenuItem newFile;
public TabPane tabPane;
public SplitPane splitPane;
public SplitPane splitPaneVertical;
public TreeView<Item> treeView;
public Label workingDirButton;
public Label goUpLabel;
public Label goHomeLabel;
public Label refreshLabel;
public AnchorPane rootAnchor;
public ProgressIndicator indikator;
public ListView<String> recentListView;
public MenuItem openFileTreeItem;
public MenuItem deletePathItem;
public MenuItem openFolderTreeItem;
public MenuItem openFileListItem;
public MenuItem openFolderListItem;
public MenuItem copyPathTreeItem;
public MenuItem copyPathListItem;
public MenuItem copyTreeItem;
public MenuItem copyListItem;
public MenuButton leftButton;
private WebView mathjaxView;
public Label htmlPro;
public Label pdfPro;
public Label ebookPro;
public Label docbookPro;
public Label browserPro;
private AnchorPane markdownTableAnchor;
private Stage markdownTableStage;
private TreeView<Section> sectionTreeView;
private AtomicBoolean includeAsciidocResource = new AtomicBoolean(false);
private static ObservableList<MyLog> logList = FXCollections.synchronizedObservableList(FXCollections.observableArrayList());
@Autowired
private ApplicationContext applicationContext;
@Autowired
private AsciidocTableController asciidocTableController;
@Autowired
private GitbookToAsciibookService gitbookToAsciibook;
@Autowired
private PathOrderService pathOrder;
@Autowired
private TreeService treeService;
@Autowired
private TooltipTimeFixService tooltipTimeFixService;
@Autowired
private TabService tabService;
@Autowired
private ODFConverter odfConverter;
@Autowired
private PathResolverService pathResolver;
@Autowired
private PlantUmlService plantUmlService;
@Autowired
private EditorService editorService;
@Autowired
private MathJaxService mathJaxService;
@Autowired
private YamlService yamlService;
@Autowired
private WebviewService webviewService;
@Autowired
private DocBookConverter docBookConverter;
@Autowired
private HtmlBookConverter htmlBookService;
@Autowired
@Qualifier("pdfBookConverter")
private AbstractPdfConverter pdfBookConverter;
@Autowired
private EpubConverter epubConverter;
@Autowired
private Current current;
@Autowired
private FileBrowseService fileBrowser;
@Autowired
private IndikatorService indikatorService;
@Autowired
private MobiConverter mobiConverter;
@Autowired
private SampleBookService sampleBookService;
@Autowired
private EmbeddedWebApplicationContext server;
@Autowired
private ParserService parserService;
@Autowired
private AwesomeService awesomeService;
@Autowired
private DirectoryService directoryService;
@Autowired
private ThreadService threadService;
@Autowired
private DocumentService documentService;
@Autowired
private EpubController epubController;
@Autowired
private ShortcutProvider shortcutProvider;
@Autowired
private RestTemplate restTemplate;
@Autowired
private Base64.Encoder base64Encoder;
@Autowired
private ChartProvider chartProvider;
@Autowired
private MarkdownService markdownService;
private Stage stage;
private StringProperty lastRendered = new SimpleStringProperty();
private List<WebSocketSession> sessionList = new ArrayList<>();
private Scene scene;
private AnchorPane asciidocTableAnchor;
private Stage asciidocTableStage;
private final Clipboard clipboard = Clipboard.getSystemClipboard();
private final ObservableList<String> recentFilesList = FXCollections.synchronizedObservableList(FXCollections.observableArrayList());
private AnchorPane configAnchor;
private Stage configStage;
private int port = 8080;
private HostServicesDelegate hostServices;
private Path configPath;
private Config config;
private BooleanProperty fileBrowserVisibility = new SimpleBooleanProperty(false);
private BooleanProperty previewPanelVisibility = new SimpleBooleanProperty(false);
private final List<String> bookNames = Arrays.asList("book.asc", "book.txt", "book.asciidoc", "book.adoc", "book.ad");
private Map<String, String> shortCuts;
private RecentFiles recentFiles;
private final ChangeListener<String> lastRenderedChangeListener = (observableValue, old, nev) -> {
if (Objects.isNull(nev))
return;
threadService.runActionLater(() -> {
htmlPane.refreshUI(nev);
});
sessionList.stream().filter(e -> e.isOpen()).forEach(e -> {
try {
e.sendMessage(new TextMessage(nev));
} catch (Exception ex) {
logger.error("Problem occured while sending content over WebSocket", ex);
}
});
};
@Value("${application.version}")
private String version;
@Autowired
private SlideConverter slideConverter;
@Autowired
private SlidePane slidePane;
private Path installationPath;
private Path logPath;
@Autowired
private LiveReloadPane liveReloadPane;
private List<String> supportedModes;
@Autowired
private FileWatchService fileWatchService;
private PreviewTab previewTab;
public void createAsciidocTable() {
asciidocTableStage.showAndWait();
}
public void createMarkdownTable() {
markdownTableStage.showAndWait();
}
@FXML
private void openConfig(ActionEvent event) {
configStage.show();
}
@FXML
private void fullScreen(ActionEvent event) {
getStage().setFullScreen(!getStage().isFullScreen());
}
@FXML
private void directoryView(ActionEvent event) {
splitPane.setDividerPositions(0.1610294117647059, 0.5823529411764706);
}
private void generatePdf() {
this.generatePdf(false);
}
private void generatePdf(boolean askPath) {
if (!current.currentPath().isPresent())
saveDoc();
threadService.runTaskLater(() -> {
pdfBookConverter.convert(askPath);
});
}
@FXML
private void generateSampleBook(ActionEvent event) {
DirectoryChooser directoryChooser = directoryService.newDirectoryChooser("Select a New Directory for sample book");
File file = directoryChooser.showDialog(null);
threadService.runTaskLater(() -> {
sampleBookService.produceSampleBook(configPath, file.toPath());
directoryService.setWorkingDirectory(Optional.of(file.toPath()));
fileBrowser.browse(treeView, file.toPath());
threadService.runActionLater(() -> {
directoryView(null);
tabService.addTab(file.toPath().resolve("book.asc"));
});
});
}
public void convertDocbook() {
convertDocbook(false);
}
public void convertDocbook(boolean askPath) {
threadService.runTaskLater(() -> {
if (!current.currentPath().isPresent())
saveDoc();
threadService.runActionLater(() -> {
Path currentTabPath = current.currentPath().get();
Path currentTabPathDir = currentTabPath.getParent();
String tabText = current.getCurrentTabText().replace("*", "").trim();
Path docbookPath;
if (askPath) {
FileChooser fileChooser = directoryService.newFileChooser("Save Docbook file");
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Docbook", "*.xml"));
docbookPath = fileChooser.showSaveDialog(null).toPath();
} else
docbookPath = currentTabPathDir.resolve(tabText + ".xml");
Consumer<String> step = docbook -> {
final String finalDocbook = docbook;
threadService.runTaskLater(() -> {
IOHelper.writeToFile(docbookPath, finalDocbook, CREATE, TRUNCATE_EXISTING, WRITE);
});
threadService.runActionLater(() -> {
getRecentFilesList().remove(docbookPath.toString());
getRecentFilesList().add(0, docbookPath.toString());
});
};
docBookConverter.convert(false, step);
});
});
}
private void convertEpub() {
convertEpub(false);
}
private void convertEpub(boolean askPath) {
epubConverter.produceEpub3(askPath);
}
public void appendFormula(String fileName, String formula) {
mathJaxService.appendFormula(fileName, formula);
}
public void svgToPng(String fileName, String svg, String formula, float width, float height) {
threadService.runTaskLater(() -> {
mathJaxService.svgToPng(fileName, svg, formula, width, height);
});
}
private void convertMobi() {
convertMobi(false);
}
private void convertMobi(boolean askPath) {
if (Objects.nonNull(config.getKindlegenDir())) {
if (!Files.exists(Paths.get(config.getKindlegenDir()))) {
config.setKindlegenDir(null);
}
}
if (Objects.isNull(config.getKindlegenDir())) {
FileChooser fileChooser = directoryService.newFileChooser("Select 'kindlegen' executable");
File kindlegenFile = fileChooser.showOpenDialog(null);
if (Objects.isNull(kindlegenFile))
return;
config.setKindlegenDir(kindlegenFile.toPath().getParent().toString());
}
threadService.runTaskLater(() -> {
mobiConverter.convert(askPath);
});
}
private void generateHtml() {
this.generateHtml(false);
}
private void generateHtml(boolean askPath) {
if (!current.currentPath().isPresent())
this.saveDoc();
threadService.runTaskLater(() -> {
htmlBookService.convert(askPath);
});
}
public void createFileTree(String tree, String type, String fileName, String width, String height) {
threadService.runTaskLater(() -> {
treeService.createFileTree(tree, type, fileName, width, height);
});
}
public void createHighlightFileTree(String tree, String type, String fileName, String width, String height) {
threadService.runTaskLater(() -> {
treeService.createHighlightFileTree(tree, type, fileName, width, height);
});
}
@FXML
public void goUp() {
directoryService.goUp();
}
@FXML
public void refreshWorkingDir() {
current.currentPath().map(Path::getParent).ifPresent(directoryService::changeWorkigDir);
}
@FXML
public void goHome() {
directoryService.changeWorkigDir(userHome);
}
@WebkitCall
public void imageToBase64Url(final String url, final int index) {
threadService.runTaskLater(() -> {
try {
byte[] imageBuffer = restTemplate.getForObject(url, byte[].class);
String imageBase64 = base64Encoder.encodeToString(imageBuffer);
threadService.runActionLater(() -> {
htmlPane.updateBase64Url(index, imageBase64);
});
} catch (Exception e) {
logger.error("Problem occured while converting image to base64 for {}", url);
}
});
}
@Override
public void initialize(URL url, ResourceBundle rb) {
port = server.getEmbeddedServletContainer().getPort();
this.previewTab = new PreviewTab("Preview", htmlPane);
this.previewTab.setClosable(false);
threadService.runActionLater(() -> {
previewTabPane.getTabs().add(previewTab);
});
// Hide tab if one in tabpane
previewTabPane.getTabs().addListener((ListChangeListener) change -> {
final StackPane header = (StackPane) previewTabPane.lookup(".tab-header-area");
if (header != null) {
if (previewTabPane.getTabs().size() == 1)
header.setPrefHeight(0);
else
header.setPrefHeight(-1);
}
});
previewTabPane.setRotateGraphic(true);
outlineTab.getTabPane()
.getSelectionModel()
.selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
if (newValue == outlineTab) {
current.currentEditor().rerender();
}
});
initializePaths();
initializeLogViewer();
initializeDoctypes();
previewTabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS);
previewTabPane.setSide(Side.RIGHT);
tooltipTimeFixService.fix();
// Convert menu label icons
AwesomeDude.setIcon(htmlPro, AwesomeIcon.HTML5);
AwesomeDude.setIcon(pdfPro, AwesomeIcon.FILE_PDF_ALT);
AwesomeDude.setIcon(ebookPro, AwesomeIcon.BOOK);
AwesomeDude.setIcon(docbookPro, AwesomeIcon.CODE);
AwesomeDude.setIcon(odfPro, AwesomeIcon.FILE_WORD_ALT);
AwesomeDude.setIcon(browserPro, AwesomeIcon.FLASH);
// Left menu label icons
AwesomeDude.setIcon(workingDirButton, AwesomeIcon.FOLDER_ALT, "14.0");
AwesomeDude.setIcon(panelShowHideMenuButton, AwesomeIcon.COLUMNS, "14.0");
AwesomeDude.setIcon(refreshLabel, AwesomeIcon.REFRESH, "14.0");
AwesomeDude.setIcon(goUpLabel, AwesomeIcon.LEVEL_UP, "14.0");
AwesomeDude.setIcon(goHomeLabel, AwesomeIcon.HOME, "14.0");
leftButton.setGraphic(AwesomeDude.createIconLabel(AwesomeIcon.ELLIPSIS_H, "14.0"));
leftButton.getItems().get(leftButton.getItems().size() - 1).setText(String.join(" ", "Version", version));
ContextMenu htmlProMenu = new ContextMenu();
htmlProMenu.getStyleClass().add("build-menu");
htmlPro.setContextMenu(htmlProMenu);
htmlPro.setOnMouseClicked(event -> {
htmlProMenu.show(htmlPro, event.getScreenX(), 50);
});
htmlProMenu.getItems().add(MenuItemBuilt.item("Save").click(event -> {
this.generateHtml();
}));
htmlProMenu.getItems().add(MenuItemBuilt.item("Save as").click(event -> {
this.generateHtml(true);
}));
htmlProMenu.getItems().add(MenuItemBuilt.item("Copy source").tip("Copy HTML source").click(event -> {
this.cutCopy(lastRendered.getValue());
}));
htmlProMenu.getItems().add(MenuItemBuilt.item("Clone source").tip("Copy HTML source (Embedded images)").click(event -> {
htmlPane.call("imageToBase64Url", new Object[]{});
}));
ContextMenu pdfProMenu = new ContextMenu();
pdfProMenu.getStyleClass().add("build-menu");
pdfProMenu.getItems().add(MenuItemBuilt.item("Save").click(event -> {
this.generatePdf();
}));
pdfProMenu.getItems().add(MenuItemBuilt.item("Save as").click(event -> {
this.generatePdf(true);
}));
pdfPro.setContextMenu(pdfProMenu);
pdfPro.setOnMouseClicked(event -> {
pdfProMenu.show(pdfPro, event.getScreenX(), 50);
});
ContextMenu docbookProMenu = new ContextMenu();
docbookProMenu.getStyleClass().add("build-menu");
docbookProMenu.getItems().add(MenuItemBuilt.item("Save").click(event -> {
this.convertDocbook();
}));
docbookProMenu.getItems().add(MenuItemBuilt.item("Save as").click(event -> {
this.convertDocbook(true);
}));
docbookPro.setContextMenu(docbookProMenu);
docbookPro.setOnMouseClicked(event -> {
docbookProMenu.show(docbookPro, event.getScreenX(), 50);
});
ContextMenu ebookProMenu = new ContextMenu();
ebookProMenu.getStyleClass().add("build-menu");
ebookProMenu.getItems().add(MenuBuilt.name("Mobi")
.add(MenuItemBuilt.item("Save").click(event -> {
this.convertMobi();
}))
.add(MenuItemBuilt.item("Save as").click(event -> {
this.convertMobi(true);
})).build());
ebookProMenu.getItems().add(MenuBuilt.name("Epub")
.add(MenuItemBuilt.item("Save").click(event -> {
this.convertEpub();
}))
.add(MenuItemBuilt.item("Save as").click(event -> {
this.convertEpub(true);
})).build());
ebookPro.setOnMouseClicked(event -> {
ebookProMenu.show(ebookPro, event.getScreenX(), 50);
});
ebookPro.setContextMenu(ebookProMenu);
ContextMenu odfProMenu = new ContextMenu();
odfProMenu.getStyleClass().add("build-menu");
odfProMenu.setAutoHide(true);
odfProMenu.getItems().add(MenuItemBuilt.item("Save").click(event -> {
odfProMenu.hide();
this.generateODFDocument();
}));
odfProMenu.getItems().add(MenuItemBuilt.item("Save as").click(event -> {
odfProMenu.hide();
this.generateODFDocument(true);
}));
odfPro.setContextMenu(odfProMenu);
odfPro.setOnMouseClicked(event -> {
odfProMenu.show(odfPro, event.getScreenX(), 50);
});
browserPro.setOnMouseClicked(event -> {
if (event.getButton() == MouseButton.PRIMARY)
this.externalBrowse();
});
loadConfigurations();
loadRecentFileList();
loadShortCuts();
recentListView.setItems(recentFilesList);
recentFilesList.addListener((ListChangeListener<String>) c -> {
recentListView.visibleProperty().setValue(c.getList().size() > 0);
recentListView.getSelectionModel().selectFirst();
});
recentListView.setOnMouseClicked(event -> {
if (event.getClickCount() > 1) {
openRecentListFile(event);
}
});
treeView.setCellFactory(param -> {
TreeCell<Item> cell = new TextFieldTreeCell<Item>();
cell.setOnDragDetected(event -> {
Dragboard db = cell.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
content.putFiles(Arrays.asList(cell.getTreeItem().getValue().getPath().toFile()));
db.setContent(content);
});
return cell;
});
lastRendered.addListener(lastRenderedChangeListener);
// MathJax
mathjaxView = new WebView();
mathjaxView.setVisible(false);
rootAnchor.getChildren().add(mathjaxView);
WebEngine mathjaxEngine = mathjaxView.getEngine();
mathjaxEngine.getLoadWorker().stateProperty().addListener((observableValue1, state, state2) -> {
JSObject window = (JSObject) mathjaxEngine.executeScript("window");
if (window.getMember("afx").equals("undefined"))
window.setMember("afx", this);
});
threadService.runActionLater(() -> {
mathjaxEngine.load(String.format("http://localhost:%d/mathjax.html", port));
});
htmlPane.load(String.format("http://localhost:%d/preview.html", port));
/// Treeview
if (Objects.nonNull(recentFiles.getWorkingDirectory())) {
Path path = Paths.get(recentFiles.getWorkingDirectory());
Optional<Path> optional = Files.notExists(path) ? Optional.empty() : Optional.of(path);
directoryService.setWorkingDirectory(optional);
}
Path workDir = directoryService.getWorkingDirectory().orElse(userHome);
fileBrowser.browse(treeView, workDir);
openFileTreeItem.setOnAction(event -> {
ObservableList<TreeItem<Item>> selectedItems = treeView.getSelectionModel().getSelectedItems();
selectedItems.stream()
.map(e -> e.getValue())
.map(e -> e.getPath())
.filter(path -> {
if (selectedItems.size() == 1)
return true;
return !Files.isDirectory(path);
})
.forEach(directoryService.getOpenFileConsumer()::accept);
});
deletePathItem.setOnAction(event -> {
ObservableList<TreeItem<Item>> selectedItems = treeView.getSelectionModel().getSelectedItems();
AlertHelper.deleteAlert().ifPresent(btn -> {
if (btn == ButtonType.YES)
selectedItems.stream()
.map(e -> e.getValue())
.map(e -> e.getPath())
.forEach(path -> threadService.runTaskLater(() -> {
if (Files.isDirectory(path)) {
IOHelper.deleteDirectory(path);
} else {
IOHelper.deleteIfExists(path);
}
}));
});
});
openFolderTreeItem.setOnAction(event -> {
Path path = tabService.getSelectedTabPath();
path = Files.isDirectory(path) ? path : path.getParent();
if (Objects.nonNull(path))
getHostServices().showDocument(path.toString());
});
openFolderListItem.setOnAction(event -> {
Path path = Paths.get(recentListView.getSelectionModel().getSelectedItem());
path = Files.isDirectory(path) ? path : path.getParent();
if (Objects.nonNull(path))
getHostServices().showDocument(path.toString());
});
openFileListItem.setOnAction(this::openRecentListFile);
copyPathTreeItem.setOnAction(event -> {
Path path = tabService.getSelectedTabPath();
this.cutCopy(path.toString());
});
copyPathListItem.setOnAction(event -> {
this.cutCopy(recentListView.getSelectionModel().getSelectedItem());
});
copyTreeItem.setOnAction(event -> {
Path path = tabService.getSelectedTabPath();
this.copyFile(path);
});
copyListItem.setOnAction(event -> {
Path path = Paths.get(recentListView.getSelectionModel().getSelectedItem());
this.copyFile(path);
});
treeView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
treeView.setOnMouseClicked(event -> {
TreeItem<Item> selectedItem = treeView.getSelectionModel().getSelectedItem();
if (Objects.isNull(selectedItem))
return;
Path selectedPath = selectedItem.getValue().getPath();
if (event.getButton() == MouseButton.PRIMARY)
if (event.getClickCount() == 2)
directoryService.getOpenFileConsumer().accept(selectedPath);
});
treeView.getSelectionModel().getSelectedIndices().addListener((ListChangeListener<? super Integer>) p -> {
ObservableList<TreeItem<Item>> selectedItems = treeView.getSelectionModel().getSelectedItems();
if (selectedItems.size() > 1) {
renameFile.setVisible(false);
newMenu.setVisible(false);
} else if (selectedItems.size() == 1) {
Path path = selectedItems.get(0).getValue().getPath();
boolean isDirectory = Files.isDirectory(path);
newMenu.setVisible(isDirectory);
renameFile.setVisible(!isDirectory);
}
});
htmlPane.webEngine().setOnAlert(event -> {
if ("PREVIEW_LOADED".equals(event.getData())) {
if (htmlPane.getMember("afx").equals("undefined")) {
htmlPane.setMember("afx", this);
}
if (Objects.nonNull(lastRendered.getValue()))
lastRenderedChangeListener.changed(null, null, lastRendered.getValue());
}
});
ContextMenu previewContextMenu = new ContextMenu(
MenuItemBuilt.item("Go back").click(event -> {
WebHistory history = htmlPane.webEngine().getHistory();
if (history.getCurrentIndex() != 0)
history.go(-1);
}),
MenuItemBuilt.item("Go forward").click(event -> {
WebHistory history = htmlPane.webEngine().getHistory();
if (history.getCurrentIndex() + 1 != history.getEntries().size())
history.go(+1);
}),
new SeparatorMenuItem(),
MenuItemBuilt.item("Copy Html").click(event -> {
DocumentFragmentImpl selectionDom = (DocumentFragmentImpl) htmlPane.webEngine().executeScript("window.getSelection().getRangeAt(0).cloneContents()");
ClipboardContent content = new ClipboardContent();
content.putHtml(XMLHelper.nodeToString(selectionDom, true));
clipboard.setContent(content);
}),
MenuItemBuilt.item("Copy Text").click(event -> {
String selection = (String) htmlPane.webEngine().executeScript("window.getSelection().toString()");
ClipboardContent content = new ClipboardContent();
content.putString(selection);
clipboard.setContent(content);
}),
MenuItemBuilt.item("Copy Source").click(event -> {
DocumentFragmentImpl selectionDom = (DocumentFragmentImpl) htmlPane.webEngine().executeScript("window.getSelection().getRangeAt(0).cloneContents()");
ClipboardContent content = new ClipboardContent();
content.putString(XMLHelper.nodeToString(selectionDom, true));
clipboard.setContent(content);
}),
new SeparatorMenuItem(),
MenuItemBuilt.item("Refresh").click(event -> {
htmlPane.webEngine().executeScript("clearImageCache()");
}),
MenuItemBuilt.item("Reload").click(event -> {
htmlPane.webEngine().reload();
})
);
previewContextMenu.setAutoHide(true);
htmlPane.getWebView().setOnMouseClicked(event -> {
if (event.getButton() == MouseButton.SECONDARY) {
previewContextMenu.show(htmlPane.getWebView(), event.getScreenX(), event.getScreenY());
} else {
previewContextMenu.hide();
}
});
tabService.initializeTabChangeListener(tabPane);
newDoc(null);
Platform.runLater(() -> {
// editorSplitPane.setDividerPositions(1);
// splitPane.setDividerPositions();
});
threadService.runTaskLater(() -> {
checkNewVersion();
});
}
private void checkNewVersion() {
try {
ApplicationLauncher.launchApplication("504", null, false, new ApplicationLauncher.Callback() {
public void exited(int exitValue) {
//TODO add your code here (not invoked on event dispatch thread)
}
public void prepareShutdown() {
//TODO add your code here (not invoked on event dispatch thread)
}
}
);
} catch (IOException e) {
logger.error("Problem occured while checking new version", e);
}
}
private void generateODFDocument(boolean askPath) {
if (!current.currentPath().isPresent())
this.saveDoc();
odfConverter.generateODFDocument(askPath);
}
private void generateODFDocument() {
this.generateODFDocument(false);
}
private void initializeDoctypes() {
try {
ObjectMapper mapper = new ObjectMapper();
Object readValue = mapper.readValue(configPath.resolve("doctypes.json").toFile(), new TypeReference<List<DocumentMode>>() {
});
modeList.addAll((Collection) readValue);
supportedModes = modeList.stream()
.map(d -> d.getExtensions())
.filter(Objects::nonNull)
.flatMap(d -> Arrays.asList(d.split("\\|")).stream())
.collect(Collectors.toList());
} catch (Exception e) {
e.printStackTrace();
logger.error("Problem occured while loading document types", e);
}
}
private void initializePaths() {
try {
CodeSource codeSource = ApplicationController.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
installationPath = jarFile.toPath().getParent().getParent();
configPath = installationPath.resolve("conf");
logPath = installationPath.resolve("log");
} catch (URISyntaxException e) {
logger.error("Problem occured while resolving conf and log paths", e);
}
}
@WebkitCall
public void updateStatusBox(long row, long column, long linecount, long wordcount) {
threadService.runTaskLater(() -> {
threadService.runActionLater(() -> {
statusText.setText(String.format("(Characters: %d) (Lines: %d) (%d:%d)", wordcount, linecount, row, column));
});
});
}
private void initializeLogViewer() {
TableView<MyLog> logViewer = new TableView<>();
logViewer.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
ContextMenu logViewerContextMenu = new ContextMenu();
logViewerContextMenu.getItems().add(MenuItemBuilt.item("Copy").click(e -> {
ObservableList<MyLog> rowList = (ObservableList) logViewer.getSelectionModel().getSelectedItems();
StringBuilder clipboardString = new StringBuilder();
for (MyLog rowLog : rowList) {
clipboardString.append(String.format("%s => %s", rowLog.getLevel(), rowLog.getMessage()));
clipboardString.append("\n\n");
}
ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putString(clipboardString.toString());
clipboard.setContent(clipboardContent);
}));
logViewer.setContextMenu(logViewerContextMenu);
logViewer.getStyleClass().add("log-viewer");
FilteredList<MyLog> logFilteredList = new FilteredList<MyLog>(logList, log -> true);
logViewer.setItems(logFilteredList);
// logViewer.setColumnResizePolicy((param) -> true);
logViewer.getItems().addListener((ListChangeListener<MyLog>) c -> {
c.next();
final int size = logViewer.getItems().size();
if (size > 0) {
logViewer.scrollTo(size - 1);
}
});
TableColumn<MyLog, String> levelColumn = new TableColumn<>("Level");
levelColumn.getStyleClass().add("level-column");
TableColumn<MyLog, String> messageColumn = new TableColumn<>("Message");
levelColumn.setCellValueFactory(new PropertyValueFactory<MyLog, String>("level"));
messageColumn.setCellValueFactory(new PropertyValueFactory<MyLog, String>("message"));
messageColumn.prefWidthProperty().bind(logViewer.widthProperty().subtract(levelColumn.widthProperty()).subtract(5));
logViewer.setRowFactory(param -> new TableRow<MyLog>() {
@Override
protected void updateItem(MyLog item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
getStyleClass().removeAll("DEBUG", "INFO", "WARN", "ERROR");
getStyleClass().add(item.getLevel());
}
}
});
messageColumn.setCellFactory(param -> new TableCell<MyLog, String>() {
@Override
protected void updateItem(String item, boolean empty) {
if (item == getItem())
return;
super.updateItem(item, empty);
if (item == null) {
super.setText(null);
super.setGraphic(null);
} else {
Text text = new Text(item);
super.setGraphic(text);
text.wrappingWidthProperty().bind(messageColumn.widthProperty().subtract(0));
}
}
});
logViewer.getColumns().addAll(levelColumn, messageColumn);
logViewer.setEditable(true);
TableViewLogAppender.setLogList(logList);
TableViewLogAppender.setLogShortMessage(statusMessage);
TableViewLogAppender.setLogViewer(logViewer);
final EventHandler<ActionEvent> filterByLogLevel = event -> {
ToggleButton logLevelItem = (ToggleButton) event.getTarget();
if (Objects.nonNull(logLevelItem)) {
logFilteredList.setPredicate(myLog -> {
String text = logLevelItem.getText();
return text.equals("All") || text.equalsIgnoreCase(myLog.getLevel());
});
}
};
ToggleGroup toggleGroup = new ToggleGroup();
ToggleButton allToggle = ToggleButtonBuilt.item("All").tip("Show all").click(filterByLogLevel);
ToggleButton errorToggle = ToggleButtonBuilt.item("Error").tip("Filter by Error").click(filterByLogLevel);
ToggleButton warnToggle = ToggleButtonBuilt.item("Warn").tip("Filter by Warn").click(filterByLogLevel);
ToggleButton infoToggle = ToggleButtonBuilt.item("Info").tip("Filter by Info").click(filterByLogLevel);
ToggleButton debugToggle = ToggleButtonBuilt.item("Debug").tip("Filter by Debug").click(filterByLogLevel);
toggleGroup.getToggles().addAll(
allToggle,
errorToggle,
warnToggle,
infoToggle,
debugToggle
);
toggleGroup.selectToggle(allToggle);
Button clearLogsButton = new Button("Clear");
clearLogsButton.setOnAction(e -> {
statusMessage.setText("");
logList.clear();
});
Button browseLogsButton = new Button("Browse");
browseLogsButton.setOnAction(e -> {
getHostServices().showDocument(logPath.toUri().toString());
});
TextField searchLogField = new TextField();
searchLogField.setPromptText("Search in logs..");
searchLogField.textProperty().addListener((observable, oldValue, newValue) -> {
if (Objects.isNull(newValue)) {
return;
}
if (newValue.isEmpty()) {
logFilteredList.setPredicate(myLog -> true);
}
logFilteredList.setPredicate(myLog -> {
final AtomicBoolean result = new AtomicBoolean(false);
String message = myLog.getMessage();
if (Objects.nonNull(message)) {
if (!result.get())
result.set(message.toLowerCase().contains(newValue.toLowerCase()));
}
String level = myLog.getLevel();
String toggleText = ((ToggleButton) toggleGroup.getSelectedToggle()).getText();
boolean inputContains = level.toLowerCase().contains(newValue.toLowerCase());
if (Objects.nonNull(level)) {
if (!result.get()) {
result.set(inputContains);
}
}
boolean levelContains = toggleText.toLowerCase().equalsIgnoreCase(level);
if (!toggleText.equals("All") && !levelContains) {
result.set(false);
}
return result.get();
});
});
List<Control> controls = Arrays.asList(allToggle,
errorToggle, warnToggle, infoToggle, debugToggle,
searchLogField, clearLogsButton, browseLogsButton);
HBox logHBox = new HBox();
for (Control control : controls) {
logHBox.getChildren().add(control);
HBox.setMargin(control, new Insets(3));
control.prefHeightProperty().bind(searchLogField.heightProperty());
}
AwesomeDude.setIcon(showHideLogs, AwesomeIcon.CHEVRON_CIRCLE_UP, "14.0");
HBox.setMargin(showHideLogs, new Insets(0, 0, 0, 3));
HBox.setMargin(statusText, new Insets(0, 3, 0, 0));
showHideLogs.setOnMouseClicked(event -> {
showHideLogs.setRotate(showHideLogs.getRotate() + 180);
if (showHideLogs.getRotate() % 360 == 0)
editorSplitPane.setDividerPositions(1);
else
editorSplitPane.setDividerPositions(0.5);
});
logVBox.getChildren().addAll(logHBox, logViewer);
VBox.setVgrow(logViewer, Priority.ALWAYS);
}
private void loadShortCuts() {
try {
String yamlC = IOHelper.readFile(configPath.resolve("shortcuts.yml"));
Yaml yaml = new Yaml();
this.shortCuts = yaml.loadAs(yamlC, Map.class);
} catch (Exception e) {
logger.error("Problem occured while loading shortcuts.yml file", e);
}
}
private void openRecentListFile(Event event) {
Path path = Paths.get(recentListView.getSelectionModel().getSelectedItem());
directoryService.getOpenFileConsumer().accept(path);
}
private void loadConfigurations() {
try {
String yamlContent = IOHelper.readFile(configPath.resolve("config.yml"));
Yaml yaml = new Yaml();
config = yaml.loadAs(yamlContent, Config.class);
} catch (Exception e) {
logger.error("Problem occured while loading config.yml file", e);
}
if (!config.getDirectoryPanel())
threadService.runActionLater(() -> {
splitPane.setDividerPositions(0, 0.51);
});
}
private void loadRecentFileList() {
try {
String yamlContent = IOHelper.readFile(configPath.resolve("recentFiles.yml"));
Yaml yaml = new Yaml();
recentFiles = yaml.loadAs(yamlContent, RecentFiles.class);
recentFilesList.addAll(recentFiles.getFiles());
} catch (Exception e) {
logger.error("Problem occured while loading recent file list", e);
}
}
public void externalBrowse() {
ObservableList<Tab> tabs = previewTabPane.getTabs();
for (Tab tab : tabs) {
if (tab.isSelected()) {
Node content = tab.getContent();
if (Objects.nonNull(content))
((ViewPanel) content).browse();
}
}
}
@WebkitCall(from = "index")
public void fillOutlines(JSObject doc) {
if (outlineTab.isSelected())
threadService.runActionLater(() -> {
htmlPane.fillOutlines(doc);
});
}
@WebkitCall(from = "index")
public void clearOutline() {
outlineList = new TreeSet<>();
}
@WebkitCall(from = "index")
public void finishOutline() {
threadService.runTaskLater(() -> {
if (Objects.isNull(sectionTreeView)) {
sectionTreeView = new TreeView<Section>();
TreeItem<Section> rootItem = new TreeItem<>();
rootItem.setExpanded(true);
Section rootSection = new Section();
rootSection.setLevel(-1);
String outlineTitle = "Outline";
rootSection.setTitle(outlineTitle);
rootItem.setValue(rootSection);
sectionTreeView.setRoot(rootItem);
sectionTreeView.setOnMouseClicked(event -> {
try {
TreeItem<Section> item = sectionTreeView.getSelectionModel().getSelectedItem();
EditorPane editorPane = current.currentEditor();
editorPane.moveCursorTo(item.getValue().getLineno());
} catch (Exception e) {
logger.error("Problem occured while jumping from outline");
}
});
}
sectionTreeView.getRoot().getChildren().clear();
for (Section section : outlineList) {
TreeItem<Section> sectionItem = new TreeItem<>(section);
sectionTreeView.getRoot().getChildren().add(sectionItem);
TreeSet<Section> subsections = section.getSubsections();
for (Section subsection : subsections) {
TreeItem<Section> subItem = new TreeItem<>(subsection);
sectionItem.getChildren().add(subItem);
this.addSubSections(subItem, subsection.getSubsections());
}
}
if (Objects.isNull(outlineTab.getContent()))
threadService.runActionLater(() -> {
outlineTab.setContent(sectionTreeView);
});
});
}
private void addSubSections(TreeItem<Section> subItem, TreeSet<Section> outlineList) {
for (Section section : outlineList) {
TreeItem<Section> sectionItem = new TreeItem<>(section);
subItem.getChildren().add(sectionItem);
TreeSet<Section> subsections = section.getSubsections();
for (Section subsection : subsections) {
TreeItem<Section> item = new TreeItem<>(subsection);
sectionItem.getChildren().add(item);
this.addSubSections(item, subsection.getSubsections());
}
}
}
@WebkitCall(from = "index")
public void fillOutline(String parentLineNo, String level, String title, String lineno, String id) {
Section section = new Section();
section.setLevel(Integer.valueOf(level));
section.setTitle(title);
section.setLineno(Integer.valueOf(lineno));
section.setId(id);
if (Objects.isNull(parentLineNo))
outlineList.add(section);
else {
Integer parentLine = Integer.valueOf(parentLineNo);
Optional<Section> parentSection = outlineList.stream()
.filter(e -> e.getLineno().equals(parentLine))
.findFirst();
if (parentSection.isPresent())
parentSection.get().getSubsections().add(section);
else {
this.traverseEachSubSection(outlineList, parentLine, section);
}
}
}
private void traverseEachSubSection(TreeSet<Section> sections, Integer parentLine, Section section) {
sections.stream().forEach(s -> {
Optional<Section> subs = s.getSubsections().stream()
.filter(e -> e.getLineno().equals(parentLine))
.findFirst();
if (subs.isPresent())
subs.get().getSubsections().add(section);
else
this.traverseEachSubSection(s.getSubsections(), parentLine, section);
});
}
@FXML
public void changeWorkingDir(Event actionEvent) {
directoryService.changeWorkigDir();
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessionList.add(session);
String value = lastRendered.getValue();
if (Objects.nonNull(value))
session.sendMessage(new TextMessage(value));
}
@FXML
public void closeApp(ActionEvent event) {
try {
yamlService.persist();
} catch (Exception e) {
logger.error("Error while closing app", e);
}
}
@FXML
public void openDoc(Event event) {
documentService.openDoc();
}
@FXML
public void newDoc(Event event) {
threadService.runActionLater(() -> {
documentService.newDoc();
});
}
@WebkitCall(from = "editor")
public boolean isLiveReloadPane() {
return previewTab.getContent() == liveReloadPane;
}
@WebkitCall(from = "editor")
public void onscroll(Object pos, Object max) {
Node content = previewTab.getContent();
if (Objects.nonNull(content)) {
((ViewPanel) content).onscroll(pos, max);
}
}
@WebkitCall(from = "editor")
public void scrollToCurrentLine(String text) {
if (previewTab.getContent() == slidePane) {
slidePane.flipThePage(htmlPane.findRenderedSelection(text)); // slide
}
if (previewTab.getContent() == htmlPane) {
threadService.runActionLater(() -> {
try {
htmlPane.call("runScroller", text);
} catch (Exception e) {
logger.debug(e.getMessage(), e);
}
});
}
}
public void plantUml(String uml, String type, String fileName) throws IOException {
threadService.runTaskLater(() -> {
plantUmlService.plantUml(uml, type, fileName);
});
}
public void chartBuildFromCsv(String csvFile, String fileName, String chartType, String options) {
if (Objects.isNull(fileName) || Objects.isNull(chartType))
return;
getCurrent().currentPath().map(Path::getParent).ifPresent(root -> {
threadService.runTaskLater(() -> {
String csvContent = IOHelper.readFile(root.resolve(csvFile));
threadService.runActionLater(() -> {
try {
Map<String, String> optMap = parseChartOptions(options);
optMap.put("csv-file", csvFile);
chartProvider.getProvider(chartType).chartBuild(csvContent, fileName, optMap);
} catch (Exception e) {
logger.info(e.getMessage(), e);
}
});
});
});
}
public void chartBuild(String chartContent, String fileName, String chartType, String options) {
if (Objects.isNull(fileName) || Objects.isNull(chartType))
return;
threadService.runActionLater(() -> {
try {
Map<String, String> optMap = parseChartOptions(options);
chartProvider.getProvider(chartType).chartBuild(chartContent, fileName, optMap);
} catch (Exception e) {
logger.info(e.getMessage(), e);
}
});
}
private Map<String, String> parseChartOptions(String options) {
Map<String, String> optMap = new HashMap<>();
if (Objects.nonNull(options)) {
String[] optPart = options.split(",");
for (String opt : optPart) {
String[] keyVal = opt.split("=");
if (keyVal.length != 2)
continue;
optMap.put(keyVal[0], keyVal[1]);
}
}
return optMap;
}
@WebkitCall(from = "editor")
public void appendWildcard() {
String currentTabText = current.getCurrentTabText();
if (!currentTabText.contains(" *"))
current.setCurrentTabText(currentTabText + " *");
}
@WebkitCall(from = "editor")
public void textListener(String text, String mode) {
threadService.runTaskLater(() -> {
boolean bookArticleHeader = this.bookArticleHeaderRegex.matcher(text).find();
boolean forceInclude = this.forceIncludeRegex.matcher(text).find();
threadService.runActionLater(() -> {
try {
if ("asciidoc".equalsIgnoreCase(mode)) {
if (bookArticleHeader && !forceInclude)
setIncludeAsciidocResource(true);
ConverterResult result = htmlPane.convertAsciidoc(text);
setIncludeAsciidocResource(false);
if (result.isBackend("html5")) {
lastRendered.setValue(result.getRendered());
previewTab.setContent(htmlPane);
}
if (result.isBackend("revealjs") || result.isBackend("deckjs")) {
slidePane.setBackend(result.getBackend());
slideConverter.convert(result.getRendered());
}
} else if ("html".equalsIgnoreCase(mode)) {
if (previewTab.getContent() != liveReloadPane) {
liveReloadPane.setOnSuccess(() -> {
liveReloadPane.setMember("afx", this);
liveReloadPane.initializeDiffReplacer();
});
liveReloadPane.load(String.format("http://localhost:%d/livereload/index.reload", port));
} else {
liveReloadPane.updateDomdom();
}
previewTab.setContent(liveReloadPane);
} else if ("markdown".equalsIgnoreCase(mode)) {
markdownService.convertToAsciidoc(text, asciidoc -> {
threadService.runActionLater(() -> {
ConverterResult result = htmlPane.convertAsciidoc(asciidoc);
result.afterRender(lastRendered::setValue);
});
});
previewTab.setContent(htmlPane);
}
} catch (Exception e) {
setIncludeAsciidocResource(false);
logger.error("Problem occured while rendering content", e);
}
});
});
}
@WebkitCall(from = "asciidoctor-odf.js")
public void convertToOdf(String name, Object obj) throws Exception {
JSObject jObj = (JSObject) obj;
odfConverter.buildDocument(name, jObj);
}
@WebkitCall
public String getTemplate(String templateName, String templateDir) throws IOException {
return htmlPane.getTemplate(templateName, templateDir);
}
public void cutCopy(String data) {
ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putString(data);
clipboard.setContent(clipboardContent);
}
public void copyFile(Path path) {
ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putFiles(Arrays.asList(path.toFile()));
clipboard.setContent(clipboardContent);
}
@WebkitCall(from = "asciidoctor")
public String readAsciidoctorResource(String uri, Integer parent) {
if (uri.matches(".*?\\.(asc|adoc|ad|asciidoc|md|markdown)") && getIncludeAsciidocResource())
return String.format("link:%s[]", uri);
final CompletableFuture<String> completableFuture = new CompletableFuture();
completableFuture.runAsync(() -> {
threadService.runTaskLater(() -> {
PathFinderService fileReader = applicationContext.getBean("pathFinder", PathFinderService.class);
Path path = fileReader.findPath(uri, parent);
if (!Files.exists(path))
completableFuture.complete("404");
completableFuture.complete(IOHelper.readFile(path));
});
});
return completableFuture.join();
}
@WebkitCall
public String clipboardValue() {
return clipboard.getString();
}
@WebkitCall
public void pasteRaw() {
JSObject editor = (JSObject) current.currentEngine().executeScript("editor");
if (clipboard.hasFiles()) {
Optional<String> block = parserService.toImageBlock(clipboard.getFiles());
if (block.isPresent()) {
editor.call("insert", block.get());
return;
}
}
editor.call("insert", clipboard.getString());
}
@WebkitCall
public void paste() {
JSObject window = (JSObject) htmlPane.webEngine().executeScript("window");
JSObject editor = (JSObject) current.currentEngine().executeScript("editor");
if (clipboard.hasFiles()) {
Optional<String> block = parserService.toImageBlock(clipboard.getFiles());
if (block.isPresent()) {
editor.call("insert", block.get());
return;
}
}
try {
if (clipboard.hasHtml() || (Boolean) window.call("isHtml", clipboard.getString())) {
String content = Optional.ofNullable(clipboard.getHtml()).orElse(clipboard.getString());
if (current.currentTab().isAsciidoc() || current.currentTab().isMarkdown())
content = (String) window.call(current.currentTab().htmlToMarkupFunction(), content);
editor.call("insert", content);
return;
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
editor.call("insert", clipboard.getString());
}
public void adjustSplitPane() {
if (splitPane.getDividerPositions()[0] > 0.1) {
hideFileAndPreviewPanels(null);
} else {
showFileBrowser();
showPreviewPanel();
}
}
@WebkitCall
public void debug(String message) {
logger.debug(message);
}
@WebkitCall
public void error(String message) {
logger.error(message);
}
@WebkitCall
public void info(String message) {
logger.info(message);
}
@WebkitCall
public void warn(String message) {
logger.warn(message);
}
public void saveDoc() {
documentService.saveDoc();
}
@FXML
public void saveDoc(Event actionEvent) {
documentService.saveDoc();
}
public void fitToParent(Node node) {
AnchorPane.setTopAnchor(node, 0.0);
AnchorPane.setBottomAnchor(node, 0.0);
AnchorPane.setLeftAnchor(node, 0.0);
AnchorPane.setRightAnchor(node, 0.0);
}
public void saveAndCloseCurrentTab() {
this.saveDoc();
threadService.runActionLater(current.currentTab()::close);
}
public ProgressIndicator getIndikator() {
return indikator;
}
public void setStage(Stage stage) {
this.stage = stage;
}
public Stage getStage() {
return stage;
}
public void setScene(Scene scene) {
this.scene = scene;
}
public Scene getScene() {
return scene;
}
public void setAsciidocTableAnchor(AnchorPane asciidocTableAnchor) {
this.asciidocTableAnchor = asciidocTableAnchor;
}
public AnchorPane getAsciidocTableAnchor() {
return asciidocTableAnchor;
}
public void setAsciidocTableStage(Stage asciidocTableStage) {
this.asciidocTableStage = asciidocTableStage;
}
public Stage getAsciidocTableStage() {
return asciidocTableStage;
}
public void setConfigAnchor(AnchorPane configAnchor) {
this.configAnchor = configAnchor;
}
public AnchorPane getConfigAnchor() {
return configAnchor;
}
public void setConfigStage(Stage configStage) {
this.configStage = configStage;
}
public Stage getConfigStage() {
return configStage;
}
public SplitPane getSplitPane() {
return splitPane;
}
public TreeView<Item> getTreeView() {
return treeView;
}
public void setHostServices(HostServicesDelegate hostServices) {
this.hostServices = hostServices;
}
public HostServicesDelegate getHostServices() {
return hostServices;
}
public Config getConfig() {
return config;
}
public AsciidocTableController getAsciidocTableController() {
return asciidocTableController;
}
public StringProperty getLastRendered() {
return lastRendered;
}
public ObservableList<String> getRecentFilesList() {
return recentFilesList;
}
public TabPane getTabPane() {
return tabPane;
}
public WebView getMathjaxView() {
return mathjaxView;
}
public ChangeListener<String> getLastRenderedChangeListener() {
return lastRenderedChangeListener;
}
public AnchorPane getRootAnchor() {
return rootAnchor;
}
public int getPort() {
return port;
}
public Path getConfigPath() {
return configPath;
}
public Current getCurrent() {
return current;
}
public Map<String, String> getShortCuts() {
if (Objects.isNull(shortCuts))
shortCuts = new HashMap<>();
return shortCuts;
}
@FXML
private void bugReport(ActionEvent actionEvent) {
getHostServices().showDocument("https://github.com/asciidocfx/AsciidocFX/issues");
}
@FXML
private void openCommunityForum(ActionEvent actionEvent) {
getHostServices().showDocument("https://groups.google.com/d/forum/asciidocfx-discuss");
}
@FXML
private void openGitterChat(ActionEvent actionEvent) {
getHostServices().showDocument("https://gitter.im/asciidocfx/AsciidocFX");
}
@FXML
private void openGithubPage(ActionEvent actionEvent) {
getHostServices().showDocument("https://github.com/asciidocfx/AsciidocFX");
}
@FXML
public void generateCheatSheet(ActionEvent actionEvent) {
Path cheatsheetPath = configPath.resolve("cheatsheet/cheatsheet.asc");
tabService.addTab(cheatsheetPath);
}
public void setMarkdownTableAnchor(AnchorPane markdownTableAnchor) {
this.markdownTableAnchor = markdownTableAnchor;
}
public AnchorPane getMarkdownTableAnchor() {
return markdownTableAnchor;
}
public void setMarkdownTableStage(Stage markdownTableStage) {
this.markdownTableStage = markdownTableStage;
}
public Stage getMarkdownTableStage() {
return markdownTableStage;
}
public ShortcutProvider getShortcutProvider() {
return shortcutProvider;
}
@FXML
public void createFolder(ActionEvent actionEvent) {
DialogBuilder dialog = DialogBuilder.newFolderDialog();
Consumer<String> consumer = result -> {
if (dialog.isShowing())
dialog.hide();
if (result.matches(DialogBuilder.FOLDER_NAME_REGEX)) {
Path path = treeView.getSelectionModel().getSelectedItem()
.getValue().getPath();
Path folderPath = path.resolve(result);
threadService.runTaskLater(() -> {
IOHelper.createDirectory(folderPath);
directoryService.changeWorkigDir(folderPath);
});
}
};
dialog.getEditor().setOnAction(event -> {
consumer.accept(dialog.getEditor().getText());
});
dialog.showAndWait().ifPresent(consumer);
}
@FXML
public void createFile(ActionEvent actionEvent) {
DialogBuilder dialog = DialogBuilder.newFileDialog();
Consumer<String> consumer = result -> {
if (dialog.isShowing())
dialog.hide();
if (result.matches(DialogBuilder.FILE_NAME_REGEX)) {
Path path = treeView.getSelectionModel().getSelectedItem()
.getValue().getPath();
IOHelper.writeToFile(path.resolve(result), "");
tabService.addTab(path.resolve(result));
threadService.runActionLater(() -> {
directoryService.changeWorkigDir(path);
});
}
};
dialog.getEditor().setOnAction(event -> {
consumer.accept(dialog.getEditor().getText());
});
dialog.showAndWait().ifPresent(consumer);
}
@FXML
public void renameFile(ActionEvent actionEvent) {
RenameDialog dialog = RenameDialog.create();
Path path = treeView.getSelectionModel().getSelectedItem()
.getValue().getPath();
dialog.getEditor().setText(path.getFileName().toString());
Consumer<String> consumer = result -> {
if (dialog.isShowing())
dialog.hide();
if (result.trim().matches("^[^\\\\/:?*\"<>|]+$"))
IOHelper.move(path, path.getParent().resolve(result.trim()));
};
dialog.getEditor().setOnAction(event -> {
consumer.accept(dialog.getEditor().getText());
});
dialog.showAndWait().ifPresent(consumer);
}
@FXML
public void gitbookToAsciibook(ActionEvent actionEvent) {
File gitbookRoot = null;
File asciibookRoot = null;
BiPredicate<File, File> nullPathPredicate = (p1, p2)
-> Objects.isNull(p1)
|| Objects.isNull(p2);
DirectoryChooser gitbookChooser = new DirectoryChooser();
gitbookChooser.setTitle("Select Gitbook Root Directory");
gitbookRoot = gitbookChooser.showDialog(null);
DirectoryChooser asciibookChooser = new DirectoryChooser();
asciibookChooser.setTitle("Select Blank Asciibook Root Directory");
asciibookRoot = asciibookChooser.showDialog(null);
if (nullPathPredicate.test(gitbookRoot, asciibookRoot)) {
AlertHelper.nullDirectoryAlert();
return;
}
final File finalGitbookRoot = gitbookRoot;
final File finalAsciibookRoot = asciibookRoot;
threadService.runTaskLater(() -> {
logger.debug("Gitbook to Asciibook conversion started");
indikatorService.startCycle();
gitbookToAsciibook.gitbookToAsciibook(finalGitbookRoot.toPath(), finalAsciibookRoot.toPath());
indikatorService.completeCycle();
logger.debug("Gitbook to Asciibook conversion ended");
});
}
public boolean getFileBrowserVisibility() {
return fileBrowserVisibility.get();
}
public BooleanProperty fileBrowserVisibilityProperty() {
return fileBrowserVisibility;
}
public boolean getPreviewPanelVisibility() {
return previewPanelVisibility.get();
}
public BooleanProperty previewPanelVisibilityProperty() {
return previewPanelVisibility;
}
@FXML
public void hideFileBrowser(ActionEvent actionEvent) {
splitPane.setDividerPosition(0, 0);
fileBrowserVisibility.setValue(true);
}
public void showFileBrowser() {
splitPane.setDividerPositions(0.195, splitPane.getDividerPositions()[1]);
fileBrowserVisibility.setValue(false);
}
public void hidePreviewPanel() {
splitPane.setDividerPosition(1, 1);
previewPanelVisibility.setValue(true);
}
@FXML
public void togglePreviewPanel(ActionEvent actionEvent) {
if (hidePreviewPanel.isSelected()) {
hidePreviewPanel();
} else {
showPreviewPanel();
}
}
public void showPreviewPanel() {
splitPane.setDividerPosition(1, 0.6);
previewPanelVisibility.setValue(false);
hidePreviewPanel.setSelected(false);
}
@FXML
public void hideFileAndPreviewPanels(ActionEvent actionEvent) {
hidePreviewPanel.setSelected(true);
togglePreviewPanel(actionEvent);
hideFileBrowser(actionEvent);
}
/*
@WebkitCall
public void fillModeList(String mode) {
threadService.runActionLater(() -> {
modeList.add(mode);
});
}*/
public RecentFiles getRecentFiles() {
return recentFiles;
}
public void clearImageCache() {
htmlPane.webEngine().executeScript("clearImageCache()");
}
public ObservableList<DocumentMode> getModeList() {
return modeList;
}
public List<String> getSupportedModes() {
return supportedModes;
}
public boolean getIncludeAsciidocResource() {
return includeAsciidocResource.get();
}
public void setIncludeAsciidocResource(boolean includeAsciidocResource) {
this.includeAsciidocResource.set(includeAsciidocResource);
}
public void removeChildElement(Node node) {
getRootAnchor().getChildren().remove(node);
}
@FXML
public void switchSlideView(ActionEvent actionEvent) {
splitPane.setDividerPositions(0, 0.45);
fileBrowserVisibility.setValue(true);
}
public TabPane getPreviewTabPane() {
return previewTabPane;
}
public PreviewTab getPreviewTab() {
return previewTab;
}
@FXML
public void newSlide(ActionEvent actionEvent) {
DialogBuilder dialog = DialogBuilder.newFolderDialog();
dialog.showAndWait().ifPresent(folderName -> {
if (dialog.isShowing())
dialog.hide();
if (folderName.matches(DialogBuilder.FOLDER_NAME_REGEX)) {
Path path = treeView.getSelectionModel().getSelectedItem()
.getValue().getPath();
Path folderPath = path.resolve(folderName);
// it needs to invalidate file watchservice
fileWatchService.invalidate();
threadService.runTaskLater(() -> {
IOHelper.createDirectory(folderPath);
htmlPane.startProgressBar();
IOHelper.copyDirectory(configPath.resolve("slide/frameworks"), folderPath);
htmlPane.stopProgressBar();
directoryService.changeWorkigDir(folderPath);
threadService.runActionLater(() -> {
tabService.addTab(folderPath.resolve("slide.adoc"));
this.switchSlideView(actionEvent);
});
});
}
});
}
} | - Dont log error when checking new version
| src/main/java/com/kodcu/controller/ApplicationController.java | - Dont log error when checking new version | <ide><path>rc/main/java/com/kodcu/controller/ApplicationController.java
<ide> }
<ide> );
<ide> } catch (IOException e) {
<del> logger.error("Problem occured while checking new version", e);
<add> // logger.error("Problem occured while checking new version", e);
<ide> }
<ide> }
<ide> |
|
JavaScript | apache-2.0 | aa90e9591ade9eb1f8edffedce2ce0f8d1a29b97 | 0 | matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk | /*
Copyright 2018 New Vector Ltd
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.
*/
import Sizer from "../sizer";
import ResizeItem from "../item";
class RoomSizer extends Sizer {
setItemSize(item, size) {
item.style.maxHeight = `${Math.round(size)}px`;
item.classList.add("resized-sized");
}
clearItemSize(item) {
item.style.maxHeight = null;
item.classList.remove("resized-sized");
}
}
class RoomSubListItem extends ResizeItem {
isCollapsed() {
return this.domNode.classList.contains("mx_RoomSubList_hidden");
}
maxSize() {
const header = this.domNode.querySelector(".mx_RoomSubList_labelContainer");
const scrollItem = this.domNode.querySelector(".mx_RoomSubList_scroll");
const headerHeight = this.sizer.getItemSize(header);
return headerHeight + (scrollItem ? scrollItem.scrollHeight : 0);
}
minSize() {
const isNotEmpty = this.domNode.classList.contains("mx_RoomSubList_nonEmpty");
return isNotEmpty ? 74 : 31; //size of header + 1? room tile (see room sub list css)
}
isSized() {
return this.domNode.classList.contains("resized-sized");
}
}
export default class RoomSubListDistributor {
static createItem(resizeHandle, resizer, sizer) {
return new RoomSubListItem(resizeHandle, resizer, sizer);
}
static createSizer(containerElement, vertical, reverse) {
return new RoomSizer(containerElement, vertical, reverse);
}
constructor(item) {
this.item = item;
}
_handleSize() {
return 1;
}
resize(size) {
//console.log("*** starting resize session with size", size);
let item = this.item;
while (item) {
const minSize = item.minSize();
if (item.isCollapsed()) {
item = item.previous();
} else if (size <= minSize) {
//console.log(" - resizing", item.id, "to min size", minSize);
item.setSize(minSize);
const remainder = minSize - size;
item = item.previous();
if (item) {
size = item.size() - remainder - this._handleSize();
}
} else {
const maxSize = item.maxSize();
if (size > maxSize) {
// console.log(" - resizing", item.id, "to maxSize", maxSize);
item.setSize(maxSize);
const remainder = size - maxSize;
item = item.previous();
if (item) {
size = item.size() + remainder; // todo: handle size here?
}
} else {
//console.log(" - resizing", item.id, "to size", size);
item.setSize(size);
item = null;
size = 0;
}
}
}
//console.log("*** ending resize session");
}
resizeFromContainerOffset(containerOffset) {
this.resize(containerOffset - this.item.offset());
}
start() {
// set all max-height props to the actual height.
let item = this.item.first();
while (item) {
if (!item.isCollapsed() && item.isSized()) {
item.setSize(item.size());
}
item = item.next();
}
}
finish() {
}
}
| src/resizer/distributors/roomsublist.js | /*
Copyright 2018 New Vector Ltd
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.
*/
import Sizer from "../sizer";
import ResizeItem from "../item";
class RoomSizer extends Sizer {
setItemSize(item, size) {
item.style.maxHeight = `${Math.round(size)}px`;
item.classList.add("resized-sized");
}
clearItemSize(item) {
item.style.maxHeight = null;
item.classList.remove("resized-sized");
}
}
class RoomSubListItem extends ResizeItem {
isCollapsed() {
return this.domNode.classList.contains("mx_RoomSubList_hidden");
}
maxSize() {
const scrollItem = this.domNode.querySelector(".mx_RoomSubList_scroll");
const header = this.domNode.querySelector(".mx_RoomSubList_labelContainer");
const headerHeight = this.sizer.getItemSize(header);
return headerHeight + scrollItem.scrollHeight;
}
minSize() {
return 74; //size of header + 1 room tile
}
isSized() {
return this.domNode.classList.contains("resized-sized");
}
}
export default class RoomSubListDistributor {
static createItem(resizeHandle, resizer, sizer) {
return new RoomSubListItem(resizeHandle, resizer, sizer);
}
static createSizer(containerElement, vertical, reverse) {
return new RoomSizer(containerElement, vertical, reverse);
}
constructor(item) {
this.item = item;
}
_handleSize() {
return 1;
}
resize(size) {
//console.log("*** starting resize session with size", size);
let item = this.item;
while (item) {
const minSize = item.minSize();
if (item.isCollapsed()) {
item = item.previous();
} else if (size <= minSize) {
//console.log(" - resizing", item.id, "to min size", minSize);
item.setSize(minSize);
const remainder = minSize - size;
item = item.previous();
if (item) {
size = item.size() - remainder - this._handleSize();
}
} else {
const maxSize = item.maxSize();
if (size > maxSize) {
// console.log(" - resizing", item.id, "to maxSize", maxSize);
item.setSize(maxSize);
const remainder = size - maxSize;
item = item.previous();
if (item) {
size = item.size() + remainder; // todo: handle size here?
}
} else {
//console.log(" - resizing", item.id, "to size", size);
item.setSize(size);
item = null;
size = 0;
}
}
}
//console.log("*** ending resize session");
}
resizeFromContainerOffset(containerOffset) {
this.resize(containerOffset - this.item.offset());
}
start() {
// set all max-height props to the actual height.
let item = this.item.first();
while (item) {
if (!item.isCollapsed() && item.isSized()) {
item.setSize(item.size());
}
item = item.next();
}
}
finish() {
}
}
| fix min & max size for empty sublists
| src/resizer/distributors/roomsublist.js | fix min & max size for empty sublists | <ide><path>rc/resizer/distributors/roomsublist.js
<ide> }
<ide>
<ide> maxSize() {
<add> const header = this.domNode.querySelector(".mx_RoomSubList_labelContainer");
<ide> const scrollItem = this.domNode.querySelector(".mx_RoomSubList_scroll");
<del> const header = this.domNode.querySelector(".mx_RoomSubList_labelContainer");
<ide> const headerHeight = this.sizer.getItemSize(header);
<del> return headerHeight + scrollItem.scrollHeight;
<add> return headerHeight + (scrollItem ? scrollItem.scrollHeight : 0);
<ide> }
<ide>
<ide> minSize() {
<del> return 74; //size of header + 1 room tile
<add> const isNotEmpty = this.domNode.classList.contains("mx_RoomSubList_nonEmpty");
<add> return isNotEmpty ? 74 : 31; //size of header + 1? room tile (see room sub list css)
<ide> }
<ide>
<ide> isSized() { |
|
Java | epl-1.0 | 400d97a8d77155c8955474ee18ad1821637f96ab | 0 | R-Brain/codenvy,codenvy/codenvy,R-Brain/codenvy,R-Brain/codenvy,codenvy/codenvy,codenvy/codenvy,codenvy/codenvy,codenvy/codenvy,R-Brain/codenvy,R-Brain/codenvy,R-Brain/codenvy,codenvy/codenvy | /*******************************************************************************
* Copyright (c) 2012-2014 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package com.codenvy.cli.command.builtin;
import com.codenvy.cli.command.builtin.model.UserProjectReference;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
/**
* Allows to create a project
* @author Florent Benoit
*/
@Command(scope = "codenvy", name = "create-project", description = "Create a project")
public class CreateProjectCommand extends AbsCommand {
@Argument(name = "configFile", description = "Configuration file of the project", required = true, index = 0)
private String configurationFile;
@Argument(name = "name", description = "Name of the project", required = true, index = 1)
private String name;
@Option(name = "--workspace", description = "Specify the workspace to use")
private String workspace;
@Option(name = "--remote", description = "Specify the remote to use")
private String remote;
@Option(name = "--open", description = "Open the project once created")
private boolean openProject;
/**
* Execute the command
*/
@Override
protected Object doExecute() throws Exception {
init();
// not logged in
if (!checkifEnabledRemotes()) {
return null;
}
UserProjectReference userProjectReference = getMultiRemoteCodenvy().createProject(name, workspace, remote, configurationFile);
if (userProjectReference != null) {
System.out.println(String.format("Project %s has been created", name));
if (openProject) {
openURL(userProjectReference.getInnerReference().ideUrl());
}
}
return null;
}
}
| command/src/main/java/com/codenvy/cli/command/builtin/CreateProjectCommand.java | /*******************************************************************************
* Copyright (c) 2012-2014 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package com.codenvy.cli.command.builtin;
import com.codenvy.cli.command.builtin.model.UserProjectReference;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.fusesource.jansi.Ansi;
import static org.fusesource.jansi.Ansi.Color.RED;
/**
* Allows to create a project
* @author Florent Benoit
*/
@Command(scope = "codenvy", name = "create-project", description = "Create a project")
public class CreateProjectCommand extends AbsCommand {
@Argument(name = "name", description = "Name of the project", required = true, index = 0)
private String name;
@Option(name = "--workspace", description = "Specify the workspace to use")
private String workspace;
@Option(name = "--remote", description = "Specify the remote to use")
private String remote;
@Option(name = "--type", description = "Specify the type of the project")
private String projectType;
@Option(name = "--open", description = "Open the project once created")
private boolean openProject;
/**
* Execute the command
*/
@Override
protected Object doExecute() throws Exception {
init();
// not logged in
if (!checkifEnabledRemotes()) {
return null;
}
// do we have the project name ?
if (name == null) {
Ansi buffer = Ansi.ansi();
buffer.fg(RED);
buffer.a("No name of the project has been set");
buffer.reset();
System.out.println(buffer.toString());
return null;
}
UserProjectReference userProjectReference = getMultiRemoteCodenvy().createProject(name, workspace, remote, projectType);
if (userProjectReference != null) {
System.out.println(String.format("Project %s has been created", name));
if (openProject) {
openURL(userProjectReference.getInnerReference().ideUrl());
}
}
return null;
}
}
| DSKCLI-303 Use of the new syntax for create project. Now it assumes that configuration for the project is done through the factory 2.0 config file
| command/src/main/java/com/codenvy/cli/command/builtin/CreateProjectCommand.java | DSKCLI-303 Use of the new syntax for create project. Now it assumes that configuration for the project is done through the factory 2.0 config file | <ide><path>ommand/src/main/java/com/codenvy/cli/command/builtin/CreateProjectCommand.java
<ide> import org.apache.karaf.shell.commands.Argument;
<ide> import org.apache.karaf.shell.commands.Command;
<ide> import org.apache.karaf.shell.commands.Option;
<del>import org.fusesource.jansi.Ansi;
<del>
<del>import static org.fusesource.jansi.Ansi.Color.RED;
<ide>
<ide> /**
<ide> * Allows to create a project
<ide> public class CreateProjectCommand extends AbsCommand {
<ide>
<ide>
<del> @Argument(name = "name", description = "Name of the project", required = true, index = 0)
<add> @Argument(name = "configFile", description = "Configuration file of the project", required = true, index = 0)
<add> private String configurationFile;
<add>
<add> @Argument(name = "name", description = "Name of the project", required = true, index = 1)
<ide> private String name;
<ide>
<ide> @Option(name = "--workspace", description = "Specify the workspace to use")
<ide>
<ide> @Option(name = "--remote", description = "Specify the remote to use")
<ide> private String remote;
<del>
<del> @Option(name = "--type", description = "Specify the type of the project")
<del> private String projectType;
<ide>
<ide> @Option(name = "--open", description = "Open the project once created")
<ide> private boolean openProject;
<ide> return null;
<ide> }
<ide>
<del> // do we have the project name ?
<del> if (name == null) {
<del> Ansi buffer = Ansi.ansi();
<del> buffer.fg(RED);
<del> buffer.a("No name of the project has been set");
<del> buffer.reset();
<del> System.out.println(buffer.toString());
<del> return null;
<del> }
<del>
<del>
<del> UserProjectReference userProjectReference = getMultiRemoteCodenvy().createProject(name, workspace, remote, projectType);
<add> UserProjectReference userProjectReference = getMultiRemoteCodenvy().createProject(name, workspace, remote, configurationFile);
<ide>
<ide> if (userProjectReference != null) {
<ide> System.out.println(String.format("Project %s has been created", name)); |
|
Java | apache-2.0 | 2c3476de997309346d77d69ff90740ffeac14878 | 0 | mohanaraosv/commons-jcs,apache/commons-jcs,apache/commons-jcs,apache/commons-jcs,mohanaraosv/commons-jcs,mohanaraosv/commons-jcs | package org.apache.jcs.engine.memory.shrinking;
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import java.util.Map;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.Serializable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jcs.engine.memory.MemoryCache;
import org.apache.jcs.engine.memory.MemoryElementDescriptor;
import org.apache.jcs.engine.control.event.ElementEvent;
import org.apache.jcs.engine.control.event.behavior.IElementEventHandler;
import org.apache.jcs.engine.control.event.behavior.IElementEvent;
import org.apache.jcs.engine.control.event.behavior.IElementEventConstants;
import org.apache.jcs.engine.behavior.ICacheElement;
/**
* A background memory shrinker. Memory problems and concurrent modification
* exception caused by acting directly on an iterator of the underlying memory
* cache should have been solved.
*
*@author <a href="mailto:[email protected]">Aaron Smuts</a>
*@created February 18, 2002
*@version $Id:
*/
public class ShrinkerThread extends Thread
{
private MemoryCache cache;
boolean alive = true;
private final static Log log =
LogFactory.getLog( ShrinkerThread.class );
/**
* Constructor for the ShrinkerThread object. Should take an IMemoryCache
*
*@param cache
*/
public ShrinkerThread( MemoryCache cache )
{
super();
this.cache = cache;
}
/**
* Graceful shutdown after this round of processing.
*/
public void kill()
{
alive = false;
}
/**
* Main processing method for the ShrinkerThread object
*/
public void run()
{
while ( alive )
{
shrink();
try
{
this.sleep( cache.getCacheAttributes()
.getShrinkerIntervalSeconds() * 1000 );
}
catch ( InterruptedException ie )
{
return;
}
}
return;
}
/**
* This method is called when the thread wakes up. A. The method obtains an
* array of keys for the cache region. B. It iterates through the keys and
* tries to get the item from the cache without affecting the last access
* or position of the item. C. Then the item is checked for expiration.
* This expiration check has 3 parts: 1. Has the
* cacheattributes.MaxMemoryIdleTimeSeconds defined for the region been
* exceeded? If so, the item should be move to disk. 2. Has the item
* exceeded MaxLifeSeconds defined in the element atributes? If so, remove
* it. 3. Has the item exceeded IdleTime defined in the element atributes?
* If so, remove it. If there are event listeners registered for the cache
* element, they will be called.
*/
protected void shrink()
{
if ( log.isDebugEnabled() )
{
log.debug( "Shrinking" );
}
try
{
Object[] keys = cache.getKeyArray();
int size = keys.length;
for ( int i = 0; i < size; i++ )
{
Serializable key = ( Serializable ) keys[i];
ICacheElement ce = cache.getQuiet( key );
if ( ce != null )
{
boolean ok = true;
long now = System.currentTimeMillis();
if ( log.isDebugEnabled() )
{
log.debug( "now = " + now );
log.debug( "!ce.getElementAttributes().getIsEternal() = " + !ce.getElementAttributes().getIsEternal() );
log.debug( "ce.getElementAttributes().getMaxLifeSeconds() = " + ce.getElementAttributes().getMaxLifeSeconds() );
log.debug( "now - ce.getElementAttributes().getCreateTime() = " + String.valueOf( now - ce.getElementAttributes().getCreateTime() ) );
log.debug( "ce.getElementAttributes().getMaxLifeSeconds() * 1000 = " + ce.getElementAttributes().getMaxLifeSeconds() * 1000 );
}
////////////////////////////////////////////////
if ( !ce.getElementAttributes().getIsEternal() )
{
// Exceeded maxLifeSeconds
if ( ( ce.getElementAttributes().getMaxLifeSeconds() != -1 ) && ( now - ce.getElementAttributes().getCreateTime() ) > ( ce.getElementAttributes().getMaxLifeSeconds() * 1000 ) )
{
if ( log.isInfoEnabled() )
{
log.info( "Exceeded maxLifeSeconds -- " + ce.getKey() );
}
// handle event, might move to a new method
ArrayList eventHandlers = ce.getElementAttributes().getElementEventHandlers();
if ( eventHandlers != null )
{
if ( log.isDebugEnabled() )
{
log.debug( "Handlers are registered. Event -- ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND" );
}
IElementEvent event = new ElementEvent( ce, IElementEventConstants.ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND );
Iterator hIt = eventHandlers.iterator();
while ( hIt.hasNext() )
{
IElementEventHandler hand = ( IElementEventHandler ) hIt.next();
hand.handleElementEvent( event );
}
}
ok = false;
cache.remove( ce.getKey() );
}
else
// Exceeded maxIdleTime, removal
if ( ( ce.getElementAttributes().getIdleTime() != -1 ) && ( now - ce.getElementAttributes().getLastAccessTime() ) > ( ce.getElementAttributes().getIdleTime() * 1000 ) )
{
if ( log.isInfoEnabled() )
{
log.info( "Exceeded maxIdleTime [ ce.getElementAttributes().getIdleTime() = " + ce.getElementAttributes().getIdleTime() + " ]-- " + ce.getKey() );
}
// handle event, might move to a new method
ArrayList eventHandlers = ce.getElementAttributes().getElementEventHandlers();
if ( eventHandlers != null )
{
if ( log.isDebugEnabled() )
{
log.debug( "Handlers are registered. Event -- ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND" );
}
IElementEvent event = new ElementEvent( ce, IElementEventConstants.ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND );
Iterator hIt = eventHandlers.iterator();
while ( hIt.hasNext() )
{
IElementEventHandler hand = ( IElementEventHandler ) hIt.next();
hand.handleElementEvent( event );
}
}
ok = false;
cache.remove( ce.getKey() );
}
}// end if not eternal
// This should be last, since we wouldn't want to wast time
// spooling if the item is removed.
// Memory idle, to disk shrinkage
if ( ok && ( cache.getCacheAttributes().getMaxMemoryIdleTimeSeconds() != -1 ) )
{
long deadAt = ce.getElementAttributes().getLastAccessTime() + ( cache.getCacheAttributes().getMaxMemoryIdleTimeSeconds() * 1000 );
if ( ( deadAt - now ) < 0 )
{
if ( log.isInfoEnabled() )
{
log.info( "Exceeded memory idle time, Pushing item to disk -- " + ce.getKey() + " over by = " + String.valueOf( deadAt - now ) + " ms." );
}
cache.remove( ce.getKey() );
cache.waterfal( ce );
}
}
}// end if ce != null
}// end for
}
catch ( Throwable t )
{
log.info( "Unexpected trouble in shrink cycle", t );
// concurrent modifications should no longer be a problem
// It is up to the IMemoryCache to return an array of keys
//stop for now
return;
}
}
}
| src/java/org/apache/jcs/engine/memory/shrinking/ShrinkerThread.java | package org.apache.jcs.engine.memory.shrinking;
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import java.util.Map;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.Serializable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jcs.engine.memory.MemoryCache;
import org.apache.jcs.engine.memory.MemoryElementDescriptor;
import org.apache.jcs.engine.control.event.ElementEvent;
import org.apache.jcs.engine.control.event.behavior.IElementEventHandler;
import org.apache.jcs.engine.control.event.behavior.IElementEvent;
import org.apache.jcs.engine.control.event.behavior.IElementEventConstants;
import org.apache.jcs.engine.behavior.ICacheElement;
/**
* A background memory shrinker. Memory problems and concurrent modification
* exception caused by acting directly on an iterator of the underlying memory
* cache should have been solved.
*
*@author <a href="mailto:[email protected]">Aaron Smuts</a>
*@created February 18, 2002
*@version $Id:
*/
public class ShrinkerThread extends Thread
{
private MemoryCache cache;
boolean alive = true;
private final static Log log =
LogFactory.getLog( ShrinkerThread.class );
/**
* Constructor for the ShrinkerThread object. Should take an IMemoryCache
*
*@param cache
*/
public ShrinkerThread( MemoryCache cache )
{
super();
this.cache = cache;
}
/**
* Graceful shutdown after this round of processing.
*/
public void kill()
{
alive = false;
}
/**
* Main processing method for the ShrinkerThread object
*/
public void run()
{
while ( alive )
{
shrink();
try
{
this.sleep( cache.getCacheAttributes()
.getShrinkerIntervalSeconds() * 1000 );
}
catch ( InterruptedException ie )
{
return;
}
}
return;
}
/**
* This method is called when the thread wakes up. A. The method obtains an
* array of keys for the cache region. B. It iterates through the keys and
* tries to get the item from the cache without affecting the last access
* or position of the item. C. Then the item is checked for expiration.
* This expiration check has 3 parts: 1. Has the
* cacheattributes.MaxMemoryIdleTimeSeconds defined for the region been
* exceeded? If so, the item should be move to disk. 2. Has the item
* exceeded MaxLifeSeconds defined in the element atributes? If so, remove
* it. 3. Has the item exceeded IdleTime defined in the element atributes?
* If so, remove it. If there are event listeners registered for the cache
* element, they will be called.
*/
protected void shrink()
{
if ( log.isDebugEnabled() )
{
log.debug( "Shrinking" );
}
try
{
Object[] keys = cache.getKeyArray();
int size = keys.length;
for ( int i = 0; i < size; i++ )
{
Serializable key = ( Serializable ) keys[i];
ICacheElement ce = cache.getQuiet( key );
if ( ce != null )
{
long now = System.currentTimeMillis();
if ( log.isDebugEnabled() )
{
log.debug( "now = " + now );
log.debug( "!ce.getElementAttributes().getIsEternal() = " + !ce.getElementAttributes().getIsEternal() );
log.debug( "ce.getElementAttributes().getMaxLifeSeconds() = " + ce.getElementAttributes().getMaxLifeSeconds() );
log.debug( "now - ce.getElementAttributes().getCreateTime() = " + String.valueOf( now - ce.getElementAttributes().getCreateTime() ) );
log.debug( "ce.getElementAttributes().getMaxLifeSeconds() * 1000 = " + ce.getElementAttributes().getMaxLifeSeconds() * 1000 );
}
// Memory idle, to disk shrinkage
if ( cache.getCacheAttributes().getMaxMemoryIdleTimeSeconds() != -1 )
{
long deadAt = ce.getElementAttributes().getLastAccessTime() + ( cache.getCacheAttributes().getMaxMemoryIdleTimeSeconds() * 1000 );
if ( ( deadAt - now ) < 0 )
{
if ( log.isInfoEnabled() )
{
log.info( "Exceeded memory idle time, Pushing item to disk -- " + ce.getKey() + " over by = " + String.valueOf( deadAt - now ) + " ms." );
}
cache.remove( ce.getKey() );
cache.waterfal( ce );
}
}
////////////////////////////////////////////////
if ( !ce.getElementAttributes().getIsEternal() )
{
// Exceeded maxLifeSeconds
if ( ( ce.getElementAttributes().getMaxLifeSeconds() != -1 ) && ( now - ce.getElementAttributes().getCreateTime() ) > ( ce.getElementAttributes().getMaxLifeSeconds() * 1000 ) )
{
if ( log.isInfoEnabled() )
{
log.info( "Exceeded maxLifeSeconds -- " + ce.getKey() );
}
// handle event, might move to a new method
ArrayList eventHandlers = ce.getElementAttributes().getElementEventHandlers();
if ( eventHandlers != null )
{
if ( log.isDebugEnabled() )
{
log.debug( "Handlers are registered. Event -- ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND" );
}
IElementEvent event = new ElementEvent( ce, IElementEventConstants.ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND );
Iterator hIt = eventHandlers.iterator();
while ( hIt.hasNext() )
{
IElementEventHandler hand = ( IElementEventHandler ) hIt.next();
hand.handleElementEvent( event );
}
}
cache.remove( ce.getKey() );
}
else
// Exceeded maxIdleTime, removal
if ( ( ce.getElementAttributes().getIdleTime() != -1 ) && ( now - ce.getElementAttributes().getLastAccessTime() ) > ( ce.getElementAttributes().getIdleTime() * 1000 ) )
{
if ( log.isInfoEnabled() )
{
log.info( "Exceeded maxIdleTime [ ce.getElementAttributes().getIdleTime() = " + ce.getElementAttributes().getIdleTime() + " ]-- " + ce.getKey() );
}
// handle event, might move to a new method
ArrayList eventHandlers = ce.getElementAttributes().getElementEventHandlers();
if ( eventHandlers != null )
{
if ( log.isDebugEnabled() )
{
log.debug( "Handlers are registered. Event -- ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND" );
}
IElementEvent event = new ElementEvent( ce, IElementEventConstants.ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND );
Iterator hIt = eventHandlers.iterator();
while ( hIt.hasNext() )
{
IElementEventHandler hand = ( IElementEventHandler ) hIt.next();
hand.handleElementEvent( event );
}
}
cache.remove( ce.getKey() );
}
}// end if not eternal
}// end if ce != null
}// end for
}
catch ( Throwable t )
{
log.info( "Unexpected trouble in shrink cycle", t );
// concurrent modifications should no longer be a problem
// It is up to the IMemoryCache to return an array of keys
//stop for now
return;
}
}
}
| Changed order. Avoid spooling if expired.
git-svn-id: fb05bfbd7e12d1dc22225677a916a89c73eee8a2@223942 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/jcs/engine/memory/shrinking/ShrinkerThread.java | Changed order. Avoid spooling if expired. | <ide><path>rc/java/org/apache/jcs/engine/memory/shrinking/ShrinkerThread.java
<ide> if ( ce != null )
<ide> {
<ide>
<add> boolean ok = true;
<add>
<ide> long now = System.currentTimeMillis();
<ide>
<ide> if ( log.isDebugEnabled() )
<ide> log.debug( "ce.getElementAttributes().getMaxLifeSeconds() * 1000 = " + ce.getElementAttributes().getMaxLifeSeconds() * 1000 );
<ide> }
<ide>
<del> // Memory idle, to disk shrinkage
<del> if ( cache.getCacheAttributes().getMaxMemoryIdleTimeSeconds() != -1 )
<del> {
<del> long deadAt = ce.getElementAttributes().getLastAccessTime() + ( cache.getCacheAttributes().getMaxMemoryIdleTimeSeconds() * 1000 );
<del> if ( ( deadAt - now ) < 0 )
<del> {
<del> if ( log.isInfoEnabled() )
<del> {
<del> log.info( "Exceeded memory idle time, Pushing item to disk -- " + ce.getKey() + " over by = " + String.valueOf( deadAt - now ) + " ms." );
<del> }
<del>
<del> cache.remove( ce.getKey() );
<del>
<del> cache.waterfal( ce );
<del> }
<del> }
<del>
<ide> ////////////////////////////////////////////////
<ide> if ( !ce.getElementAttributes().getIsEternal() )
<ide> {
<ide> }
<ide> }
<ide>
<add> ok = false;
<ide> cache.remove( ce.getKey() );
<ide> }
<ide> else
<ide> }
<ide> }
<ide>
<add> ok = false;
<ide> cache.remove( ce.getKey() );
<ide> }
<ide>
<ide> }// end if not eternal
<ide>
<add> // This should be last, since we wouldn't want to wast time
<add> // spooling if the item is removed.
<add> // Memory idle, to disk shrinkage
<add> if ( ok && ( cache.getCacheAttributes().getMaxMemoryIdleTimeSeconds() != -1 ) )
<add> {
<add> long deadAt = ce.getElementAttributes().getLastAccessTime() + ( cache.getCacheAttributes().getMaxMemoryIdleTimeSeconds() * 1000 );
<add> if ( ( deadAt - now ) < 0 )
<add> {
<add> if ( log.isInfoEnabled() )
<add> {
<add> log.info( "Exceeded memory idle time, Pushing item to disk -- " + ce.getKey() + " over by = " + String.valueOf( deadAt - now ) + " ms." );
<add> }
<add>
<add> cache.remove( ce.getKey() );
<add>
<add> cache.waterfal( ce );
<add> }
<add> }
<add>
<ide> }// end if ce != null
<ide>
<ide> }// end for |
|
Java | apache-2.0 | 9c631796b0a4be48b36e34ce14e4262a659a0ea3 | 0 | gouessej/libgdx,jberberick/libgdx,kotcrab/libgdx,tommycli/libgdx,sjosegarcia/libgdx,snovak/libgdx,fwolff/libgdx,del-sol/libgdx,copystudy/libgdx,309746069/libgdx,MikkelTAndersen/libgdx,Deftwun/libgdx,Zonglin-Li6565/libgdx,GreenLightning/libgdx,stinsonga/libgdx,FredGithub/libgdx,Deftwun/libgdx,copystudy/libgdx,GreenLightning/libgdx,curtiszimmerman/libgdx,zhimaijoy/libgdx,PedroRomanoBarbosa/libgdx,titovmaxim/libgdx,Zonglin-Li6565/libgdx,ztv/libgdx,kotcrab/libgdx,nudelchef/libgdx,tommycli/libgdx,ninoalma/libgdx,codepoke/libgdx,sjosegarcia/libgdx,MikkelTAndersen/libgdx,mumer92/libgdx,anserran/libgdx,1yvT0s/libgdx,revo09/libgdx,samskivert/libgdx,stickyd/libgdx,nudelchef/libgdx,antag99/libgdx,yangweigbh/libgdx,srwonka/libGdx,SidneyXu/libgdx,designcrumble/libgdx,FyiurAmron/libgdx,Heart2009/libgdx,copystudy/libgdx,sarkanyi/libgdx,youprofit/libgdx,jsjolund/libgdx,revo09/libgdx,xpenatan/libgdx-LWJGL3,alex-dorokhov/libgdx,shiweihappy/libgdx,Thotep/libgdx,TheAks999/libgdx,jsjolund/libgdx,xoppa/libgdx,MetSystem/libgdx,xpenatan/libgdx-LWJGL3,firefly2442/libgdx,SidneyXu/libgdx,petugez/libgdx,luischavez/libgdx,tommyettinger/libgdx,antag99/libgdx,fwolff/libgdx,Heart2009/libgdx,nrallakis/libgdx,bgroenks96/libgdx,andyvand/libgdx,nave966/libgdx,jasonwee/libgdx,gf11speed/libgdx,bgroenks96/libgdx,alex-dorokhov/libgdx,MadcowD/libgdx,UnluckyNinja/libgdx,jasonwee/libgdx,PedroRomanoBarbosa/libgdx,MikkelTAndersen/libgdx,ThiagoGarciaAlves/libgdx,Senth/libgdx,collinsmith/libgdx,cypherdare/libgdx,alex-dorokhov/libgdx,djom20/libgdx,jberberick/libgdx,realitix/libgdx,tommycli/libgdx,NathanSweet/libgdx,yangweigbh/libgdx,KrisLee/libgdx,copystudy/libgdx,ya7lelkom/libgdx,andyvand/libgdx,bgroenks96/libgdx,yangweigbh/libgdx,fwolff/libgdx,alex-dorokhov/libgdx,firefly2442/libgdx,fwolff/libgdx,libgdx/libgdx,gouessej/libgdx,gdos/libgdx,JDReutt/libgdx,youprofit/libgdx,MetSystem/libgdx,saqsun/libgdx,xpenatan/libgdx-LWJGL3,fiesensee/libgdx,ninoalma/libgdx,xoppa/libgdx,jberberick/libgdx,yangweigbh/libgdx,Badazdz/libgdx,antag99/libgdx,tell10glu/libgdx,xoppa/libgdx,alex-dorokhov/libgdx,jberberick/libgdx,jasonwee/libgdx,Wisienkas/libgdx,xpenatan/libgdx-LWJGL3,MadcowD/libgdx,Deftwun/libgdx,revo09/libgdx,kotcrab/libgdx,MetSystem/libgdx,Dzamir/libgdx,nrallakis/libgdx,Zomby2D/libgdx,firefly2442/libgdx,tell10glu/libgdx,snovak/libgdx,Zonglin-Li6565/libgdx,tommycli/libgdx,collinsmith/libgdx,Senth/libgdx,TheAks999/libgdx,JFixby/libgdx,sjosegarcia/libgdx,zhimaijoy/libgdx,tell10glu/libgdx,FredGithub/libgdx,shiweihappy/libgdx,gouessej/libgdx,fiesensee/libgdx,Deftwun/libgdx,yangweigbh/libgdx,josephknight/libgdx,zommuter/libgdx,MikkelTAndersen/libgdx,MetSystem/libgdx,ThiagoGarciaAlves/libgdx,JFixby/libgdx,ztv/libgdx,mumer92/libgdx,saqsun/libgdx,jsjolund/libgdx,thepullman/libgdx,tell10glu/libgdx,kotcrab/libgdx,Wisienkas/libgdx,ztv/libgdx,nrallakis/libgdx,noelsison2/libgdx,EsikAntony/libgdx,js78/libgdx,youprofit/libgdx,jsjolund/libgdx,MovingBlocks/libgdx,TheAks999/libgdx,JDReutt/libgdx,Xhanim/libgdx,cypherdare/libgdx,TheAks999/libgdx,thepullman/libgdx,kagehak/libgdx,fiesensee/libgdx,luischavez/libgdx,josephknight/libgdx,curtiszimmerman/libgdx,haedri/libgdx-1,thepullman/libgdx,gdos/libgdx,NathanSweet/libgdx,stinsonga/libgdx,KrisLee/libgdx,srwonka/libGdx,libgdx/libgdx,czyzby/libgdx,youprofit/libgdx,sarkanyi/libgdx,nave966/libgdx,ztv/libgdx,mumer92/libgdx,FredGithub/libgdx,bgroenks96/libgdx,309746069/libgdx,libgdx/libgdx,Senth/libgdx,katiepino/libgdx,GreenLightning/libgdx,Gliby/libgdx,JDReutt/libgdx,zommuter/libgdx,youprofit/libgdx,Wisienkas/libgdx,firefly2442/libgdx,ricardorigodon/libgdx,JDReutt/libgdx,MovingBlocks/libgdx,czyzby/libgdx,xpenatan/libgdx-LWJGL3,shiweihappy/libgdx,MetSystem/libgdx,bladecoder/libgdx,realitix/libgdx,revo09/libgdx,shiweihappy/libgdx,tommycli/libgdx,snovak/libgdx,sjosegarcia/libgdx,zommuter/libgdx,JFixby/libgdx,hyvas/libgdx,thepullman/libgdx,petugez/libgdx,realitix/libgdx,junkdog/libgdx,gf11speed/libgdx,jasonwee/libgdx,samskivert/libgdx,saqsun/libgdx,KrisLee/libgdx,kagehak/libgdx,snovak/libgdx,andyvand/libgdx,Badazdz/libgdx,ricardorigodon/libgdx,sjosegarcia/libgdx,katiepino/libgdx,EsikAntony/libgdx,xoppa/libgdx,GreenLightning/libgdx,djom20/libgdx,hyvas/libgdx,czyzby/libgdx,ttencate/libgdx,Zonglin-Li6565/libgdx,kagehak/libgdx,katiepino/libgdx,Badazdz/libgdx,anserran/libgdx,JFixby/libgdx,ztv/libgdx,MetSystem/libgdx,sjosegarcia/libgdx,UnluckyNinja/libgdx,bladecoder/libgdx,hyvas/libgdx,KrisLee/libgdx,Badazdz/libgdx,MovingBlocks/libgdx,stinsonga/libgdx,xpenatan/libgdx-LWJGL3,titovmaxim/libgdx,1yvT0s/libgdx,1yvT0s/libgdx,ninoalma/libgdx,josephknight/libgdx,firefly2442/libgdx,bgroenks96/libgdx,MadcowD/libgdx,TheAks999/libgdx,haedri/libgdx-1,fiesensee/libgdx,309746069/libgdx,toloudis/libgdx,Heart2009/libgdx,collinsmith/libgdx,ttencate/libgdx,bgroenks96/libgdx,js78/libgdx,kagehak/libgdx,MikkelTAndersen/libgdx,tell10glu/libgdx,billgame/libgdx,samskivert/libgdx,SidneyXu/libgdx,fwolff/libgdx,stickyd/libgdx,Senth/libgdx,ThiagoGarciaAlves/libgdx,JFixby/libgdx,toloudis/libgdx,Heart2009/libgdx,FredGithub/libgdx,anserran/libgdx,kagehak/libgdx,gouessej/libgdx,PedroRomanoBarbosa/libgdx,Xhanim/libgdx,Heart2009/libgdx,flaiker/libgdx,Dzamir/libgdx,NathanSweet/libgdx,luischavez/libgdx,curtiszimmerman/libgdx,bsmr-java/libgdx,haedri/libgdx-1,FyiurAmron/libgdx,ricardorigodon/libgdx,zhimaijoy/libgdx,antag99/libgdx,GreenLightning/libgdx,alireza-hosseini/libgdx,JDReutt/libgdx,FredGithub/libgdx,nrallakis/libgdx,Xhanim/libgdx,alireza-hosseini/libgdx,hyvas/libgdx,gf11speed/libgdx,gdos/libgdx,tommycli/libgdx,xranby/libgdx,noelsison2/libgdx,zommuter/libgdx,SidneyXu/libgdx,FredGithub/libgdx,saltares/libgdx,Dzamir/libgdx,js78/libgdx,thepullman/libgdx,jasonwee/libgdx,309746069/libgdx,stickyd/libgdx,yangweigbh/libgdx,stickyd/libgdx,jberberick/libgdx,Dzamir/libgdx,nudelchef/libgdx,josephknight/libgdx,samskivert/libgdx,josephknight/libgdx,luischavez/libgdx,del-sol/libgdx,srwonka/libGdx,Badazdz/libgdx,codepoke/libgdx,jasonwee/libgdx,curtiszimmerman/libgdx,zhimaijoy/libgdx,cypherdare/libgdx,saltares/libgdx,xranby/libgdx,tommyettinger/libgdx,del-sol/libgdx,petugez/libgdx,MetSystem/libgdx,MadcowD/libgdx,1yvT0s/libgdx,UnluckyNinja/libgdx,Gliby/libgdx,libgdx/libgdx,MadcowD/libgdx,haedri/libgdx-1,gf11speed/libgdx,Thotep/libgdx,nrallakis/libgdx,nave966/libgdx,nave966/libgdx,toa5/libgdx,youprofit/libgdx,toa5/libgdx,haedri/libgdx-1,xranby/libgdx,EsikAntony/libgdx,djom20/libgdx,antag99/libgdx,BlueRiverInteractive/libgdx,bsmr-java/libgdx,antag99/libgdx,Zonglin-Li6565/libgdx,Zonglin-Li6565/libgdx,ttencate/libgdx,petugez/libgdx,Gliby/libgdx,jsjolund/libgdx,gf11speed/libgdx,MovingBlocks/libgdx,ricardorigodon/libgdx,katiepino/libgdx,firefly2442/libgdx,czyzby/libgdx,JFixby/libgdx,katiepino/libgdx,sjosegarcia/libgdx,PedroRomanoBarbosa/libgdx,Thotep/libgdx,bsmr-java/libgdx,kagehak/libgdx,xpenatan/libgdx-LWJGL3,MovingBlocks/libgdx,Senth/libgdx,designcrumble/libgdx,petugez/libgdx,kotcrab/libgdx,collinsmith/libgdx,designcrumble/libgdx,309746069/libgdx,nave966/libgdx,sjosegarcia/libgdx,del-sol/libgdx,nudelchef/libgdx,codepoke/libgdx,titovmaxim/libgdx,PedroRomanoBarbosa/libgdx,kotcrab/libgdx,jasonwee/libgdx,haedri/libgdx-1,katiepino/libgdx,EsikAntony/libgdx,EsikAntony/libgdx,mumer92/libgdx,billgame/libgdx,gouessej/libgdx,mumer92/libgdx,tell10glu/libgdx,noelsison2/libgdx,Gliby/libgdx,hyvas/libgdx,nrallakis/libgdx,1yvT0s/libgdx,ninoalma/libgdx,luischavez/libgdx,samskivert/libgdx,gdos/libgdx,collinsmith/libgdx,andyvand/libgdx,yangweigbh/libgdx,firefly2442/libgdx,Deftwun/libgdx,ninoalma/libgdx,djom20/libgdx,GreenLightning/libgdx,Zomby2D/libgdx,NathanSweet/libgdx,SidneyXu/libgdx,noelsison2/libgdx,bladecoder/libgdx,ThiagoGarciaAlves/libgdx,JFixby/libgdx,Xhanim/libgdx,ztv/libgdx,billgame/libgdx,tommyettinger/libgdx,ttencate/libgdx,toa5/libgdx,alireza-hosseini/libgdx,ttencate/libgdx,Gliby/libgdx,ya7lelkom/libgdx,toloudis/libgdx,petugez/libgdx,curtiszimmerman/libgdx,SidneyXu/libgdx,Wisienkas/libgdx,billgame/libgdx,UnluckyNinja/libgdx,Zomby2D/libgdx,toa5/libgdx,titovmaxim/libgdx,noelsison2/libgdx,EsikAntony/libgdx,xoppa/libgdx,TheAks999/libgdx,zhimaijoy/libgdx,nudelchef/libgdx,codepoke/libgdx,shiweihappy/libgdx,GreenLightning/libgdx,bsmr-java/libgdx,saqsun/libgdx,curtiszimmerman/libgdx,jasonwee/libgdx,PedroRomanoBarbosa/libgdx,fiesensee/libgdx,alex-dorokhov/libgdx,billgame/libgdx,djom20/libgdx,flaiker/libgdx,czyzby/libgdx,ricardorigodon/libgdx,realitix/libgdx,ya7lelkom/libgdx,alex-dorokhov/libgdx,stickyd/libgdx,collinsmith/libgdx,billgame/libgdx,309746069/libgdx,ThiagoGarciaAlves/libgdx,billgame/libgdx,snovak/libgdx,saltares/libgdx,ricardorigodon/libgdx,MikkelTAndersen/libgdx,ninoalma/libgdx,gdos/libgdx,stinsonga/libgdx,cypherdare/libgdx,alireza-hosseini/libgdx,nrallakis/libgdx,SidneyXu/libgdx,toloudis/libgdx,309746069/libgdx,samskivert/libgdx,Wisienkas/libgdx,GreenLightning/libgdx,zhimaijoy/libgdx,josephknight/libgdx,ThiagoGarciaAlves/libgdx,kagehak/libgdx,xoppa/libgdx,ricardorigodon/libgdx,realitix/libgdx,junkdog/libgdx,FyiurAmron/libgdx,anserran/libgdx,saltares/libgdx,djom20/libgdx,ninoalma/libgdx,Badazdz/libgdx,ThiagoGarciaAlves/libgdx,Gliby/libgdx,EsikAntony/libgdx,andyvand/libgdx,del-sol/libgdx,alireza-hosseini/libgdx,Zomby2D/libgdx,srwonka/libGdx,flaiker/libgdx,FyiurAmron/libgdx,SidneyXu/libgdx,Thotep/libgdx,Xhanim/libgdx,katiepino/libgdx,anserran/libgdx,luischavez/libgdx,titovmaxim/libgdx,anserran/libgdx,xranby/libgdx,copystudy/libgdx,tommyettinger/libgdx,gf11speed/libgdx,Wisienkas/libgdx,saltares/libgdx,billgame/libgdx,fwolff/libgdx,srwonka/libGdx,junkdog/libgdx,BlueRiverInteractive/libgdx,BlueRiverInteractive/libgdx,js78/libgdx,antag99/libgdx,Thotep/libgdx,toa5/libgdx,ttencate/libgdx,revo09/libgdx,Gliby/libgdx,designcrumble/libgdx,realitix/libgdx,srwonka/libGdx,gouessej/libgdx,Senth/libgdx,petugez/libgdx,mumer92/libgdx,1yvT0s/libgdx,titovmaxim/libgdx,revo09/libgdx,sarkanyi/libgdx,Gliby/libgdx,alireza-hosseini/libgdx,Thotep/libgdx,curtiszimmerman/libgdx,junkdog/libgdx,ricardorigodon/libgdx,KrisLee/libgdx,jsjolund/libgdx,Senth/libgdx,Deftwun/libgdx,xpenatan/libgdx-LWJGL3,thepullman/libgdx,gouessej/libgdx,josephknight/libgdx,ya7lelkom/libgdx,designcrumble/libgdx,fiesensee/libgdx,JDReutt/libgdx,jberberick/libgdx,bgroenks96/libgdx,zhimaijoy/libgdx,Dzamir/libgdx,tell10glu/libgdx,bsmr-java/libgdx,saqsun/libgdx,Zonglin-Li6565/libgdx,FredGithub/libgdx,BlueRiverInteractive/libgdx,MadcowD/libgdx,youprofit/libgdx,tommyettinger/libgdx,1yvT0s/libgdx,nave966/libgdx,snovak/libgdx,Xhanim/libgdx,designcrumble/libgdx,Heart2009/libgdx,KrisLee/libgdx,flaiker/libgdx,jsjolund/libgdx,codepoke/libgdx,djom20/libgdx,alireza-hosseini/libgdx,flaiker/libgdx,saltares/libgdx,alex-dorokhov/libgdx,junkdog/libgdx,junkdog/libgdx,titovmaxim/libgdx,JDReutt/libgdx,bladecoder/libgdx,bgroenks96/libgdx,xranby/libgdx,tommycli/libgdx,designcrumble/libgdx,antag99/libgdx,toloudis/libgdx,Zonglin-Li6565/libgdx,MovingBlocks/libgdx,MetSystem/libgdx,Deftwun/libgdx,ttencate/libgdx,Zomby2D/libgdx,hyvas/libgdx,js78/libgdx,toloudis/libgdx,sarkanyi/libgdx,toa5/libgdx,haedri/libgdx-1,nave966/libgdx,Badazdz/libgdx,czyzby/libgdx,del-sol/libgdx,nudelchef/libgdx,ya7lelkom/libgdx,JFixby/libgdx,nave966/libgdx,FyiurAmron/libgdx,zommuter/libgdx,hyvas/libgdx,jberberick/libgdx,KrisLee/libgdx,UnluckyNinja/libgdx,zommuter/libgdx,Badazdz/libgdx,stickyd/libgdx,Heart2009/libgdx,tommycli/libgdx,snovak/libgdx,sarkanyi/libgdx,jberberick/libgdx,djom20/libgdx,nudelchef/libgdx,srwonka/libGdx,realitix/libgdx,Thotep/libgdx,MovingBlocks/libgdx,yangweigbh/libgdx,fiesensee/libgdx,codepoke/libgdx,gouessej/libgdx,mumer92/libgdx,UnluckyNinja/libgdx,Dzamir/libgdx,snovak/libgdx,firefly2442/libgdx,saltares/libgdx,revo09/libgdx,czyzby/libgdx,Thotep/libgdx,flaiker/libgdx,copystudy/libgdx,MikkelTAndersen/libgdx,haedri/libgdx-1,bladecoder/libgdx,js78/libgdx,shiweihappy/libgdx,ztv/libgdx,BlueRiverInteractive/libgdx,gdos/libgdx,collinsmith/libgdx,xoppa/libgdx,shiweihappy/libgdx,zommuter/libgdx,FyiurAmron/libgdx,gdos/libgdx,junkdog/libgdx,sarkanyi/libgdx,samskivert/libgdx,jsjolund/libgdx,noelsison2/libgdx,Wisienkas/libgdx,thepullman/libgdx,del-sol/libgdx,FredGithub/libgdx,thepullman/libgdx,stickyd/libgdx,ThiagoGarciaAlves/libgdx,mumer92/libgdx,katiepino/libgdx,MadcowD/libgdx,saqsun/libgdx,anserran/libgdx,toa5/libgdx,andyvand/libgdx,ztv/libgdx,andyvand/libgdx,stickyd/libgdx,sarkanyi/libgdx,Xhanim/libgdx,srwonka/libGdx,js78/libgdx,flaiker/libgdx,JDReutt/libgdx,MovingBlocks/libgdx,UnluckyNinja/libgdx,stinsonga/libgdx,FyiurAmron/libgdx,saqsun/libgdx,czyzby/libgdx,kotcrab/libgdx,bsmr-java/libgdx,zhimaijoy/libgdx,Dzamir/libgdx,realitix/libgdx,bsmr-java/libgdx,UnluckyNinja/libgdx,Wisienkas/libgdx,kagehak/libgdx,noelsison2/libgdx,ya7lelkom/libgdx,FyiurAmron/libgdx,cypherdare/libgdx,MadcowD/libgdx,gf11speed/libgdx,luischavez/libgdx,xranby/libgdx,PedroRomanoBarbosa/libgdx,1yvT0s/libgdx,309746069/libgdx,codepoke/libgdx,bsmr-java/libgdx,libgdx/libgdx,anserran/libgdx,PedroRomanoBarbosa/libgdx,ya7lelkom/libgdx,fwolff/libgdx,js78/libgdx,samskivert/libgdx,Heart2009/libgdx,BlueRiverInteractive/libgdx,toloudis/libgdx,del-sol/libgdx,BlueRiverInteractive/libgdx,josephknight/libgdx,sarkanyi/libgdx,kotcrab/libgdx,noelsison2/libgdx,shiweihappy/libgdx,xoppa/libgdx,gf11speed/libgdx,ya7lelkom/libgdx,luischavez/libgdx,copystudy/libgdx,petugez/libgdx,designcrumble/libgdx,hyvas/libgdx,saltares/libgdx,Deftwun/libgdx,fwolff/libgdx,nudelchef/libgdx,Dzamir/libgdx,youprofit/libgdx,xranby/libgdx,Xhanim/libgdx,tell10glu/libgdx,MikkelTAndersen/libgdx,copystudy/libgdx,ttencate/libgdx,NathanSweet/libgdx,KrisLee/libgdx,toa5/libgdx,codepoke/libgdx,curtiszimmerman/libgdx,BlueRiverInteractive/libgdx,xranby/libgdx,zommuter/libgdx,revo09/libgdx,saqsun/libgdx,collinsmith/libgdx,EsikAntony/libgdx,alireza-hosseini/libgdx,TheAks999/libgdx,gdos/libgdx,TheAks999/libgdx,titovmaxim/libgdx,Senth/libgdx,ninoalma/libgdx,fiesensee/libgdx,andyvand/libgdx,flaiker/libgdx,junkdog/libgdx,nrallakis/libgdx,toloudis/libgdx | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.
******************************************************************************/
package com.badlogic.gdx.utils;
/** A simple linked list that pools its nodes.
* @author mzechner */
public class PooledLinkedList<T> {
static final class Item<T> {
public T payload;
public Item<T> next;
public Item<T> prev;
}
private Item<T> head;
private Item<T> tail;
private Item<T> iter;
private Item<T> curr;
private int size = 0;
private final Pool<Item<T>> pool;
public PooledLinkedList (int maxPoolSize) {
this.pool = new Pool<Item<T>>(16, maxPoolSize) {
protected Item<T> newObject () {
return new Item<T>();
}
};
}
public void add (T object) {
Item<T> item = pool.obtain();
item.payload = object;
item.next = null;
item.prev = null;
if (head == null) {
head = item;
tail = item;
size++;
return;
}
item.prev = tail;
tail.next = item;
tail = item;
size++;
}
/** Starts iterating over the list's items from the head of the list */
public void iter () {
iter = head;
}
/** Starts iterating over the list's items from the tail of the list */
public void iterReverse () {
iter = tail;
}
/** Gets the next item in the list
*
* @return the next item in the list or null if there are no more items */
public T next () {
if (iter == null) return null;
T payload = iter.payload;
curr = iter;
iter = iter.next;
return payload;
}
/** Gets the previous item in the list
*
* @return the previous item in the list or null if there are no more items */
public T previous () {
if (iter == null) return null;
T payload = iter.payload;
curr = iter;
iter = iter.prev;
return payload;
}
/** Removes the current list item based on the iterator position. */
public void remove () {
if (curr == null) return;
size--;
pool.free(curr);
Item<T> c = curr;
Item<T> n = curr.next;
Item<T> p = curr.prev;
curr = null;
if (size == 0) {
head = null;
tail = null;
return;
}
if (c == head) {
n.prev = null;
head = n;
return;
}
if (c == tail) {
p.next = null;
tail = p;
return;
}
p.next = n;
n.prev = p;
}
// public static void main (String[] argv) {
// PooledLinkedList<Integer> list = new PooledLinkedList<Integer>(10);
//
// list.add(1);
// list.add(2);
// list.add(3);
// list.add(4);
// list.iter();
// list.next();
// list.next();
// list.remove();
// list.next();
// list.next();
// list.remove();
//
// list.iter();
// Integer v = null;
// while ((v = list.next()) != null)
// System.out.println(v);
//
// list.iter();
// list.next();
// list.next();
// list.remove();
//
// list.iter();
// list.next();
// list.remove();
// }
public void clear () {
iter();
T v = null;
while ((v = next()) != null)
remove();
}
}
| gdx/src/com/badlogic/gdx/utils/PooledLinkedList.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.
******************************************************************************/
package com.badlogic.gdx.utils;
/** A simple linked list that pools its nodes.
* @author mzechner */
public class PooledLinkedList<T> {
static final class Item<T> {
public T payload;
public Item<T> next;
public Item<T> prev;
}
private Item<T> head;
private Item<T> tail;
private Item<T> iter;
private Item<T> curr;
private int size = 0;
private final Pool<Item<T>> pool;
public PooledLinkedList (int maxPoolSize) {
this.pool = new Pool<Item<T>>(16, maxPoolSize) {
protected Item<T> newObject () {
return new Item<T>();
}
};
}
public void add (T object) {
Item<T> item = pool.obtain();
item.payload = object;
item.next = null;
item.prev = null;
if (head == null) {
head = item;
tail = item;
size++;
return;
}
item.prev = tail;
tail.next = item;
tail = item;
size++;
}
/** Starts iterating over the lists items */
public void iter () {
iter = head;
}
/** Gets the next item in the list
*
* @return the next item in the list or null if there are no more items */
public T next () {
if (iter == null) return null;
T payload = iter.payload;
curr = iter;
iter = iter.next;
return payload;
}
/** Removes the current list item based on the iterator position. */
public void remove () {
if (curr == null) return;
size--;
pool.free(curr);
Item<T> c = curr;
Item<T> n = curr.next;
Item<T> p = curr.prev;
curr = null;
if (size == 0) {
head = null;
tail = null;
return;
}
if (c == head) {
n.prev = null;
head = n;
return;
}
if (c == tail) {
p.next = null;
tail = p;
return;
}
p.next = n;
n.prev = p;
}
// public static void main (String[] argv) {
// PooledLinkedList<Integer> list = new PooledLinkedList<Integer>(10);
//
// list.add(1);
// list.add(2);
// list.add(3);
// list.add(4);
// list.iter();
// list.next();
// list.next();
// list.remove();
// list.next();
// list.next();
// list.remove();
//
// list.iter();
// Integer v = null;
// while ((v = list.next()) != null)
// System.out.println(v);
//
// list.iter();
// list.next();
// list.next();
// list.remove();
//
// list.iter();
// list.next();
// list.remove();
// }
public void clear () {
iter();
T v = null;
while ((v = next()) != null)
remove();
}
}
| Added reverse iteration from tail of PooledLinkedList | gdx/src/com/badlogic/gdx/utils/PooledLinkedList.java | Added reverse iteration from tail of PooledLinkedList | <ide><path>dx/src/com/badlogic/gdx/utils/PooledLinkedList.java
<ide> size++;
<ide> }
<ide>
<del> /** Starts iterating over the lists items */
<add> /** Starts iterating over the list's items from the head of the list */
<ide> public void iter () {
<ide> iter = head;
<add> }
<add>
<add> /** Starts iterating over the list's items from the tail of the list */
<add> public void iterReverse () {
<add> iter = tail;
<ide> }
<ide>
<ide> /** Gets the next item in the list
<ide> T payload = iter.payload;
<ide> curr = iter;
<ide> iter = iter.next;
<add> return payload;
<add> }
<add>
<add> /** Gets the previous item in the list
<add> *
<add> * @return the previous item in the list or null if there are no more items */
<add> public T previous () {
<add> if (iter == null) return null;
<add>
<add> T payload = iter.payload;
<add> curr = iter;
<add> iter = iter.prev;
<ide> return payload;
<ide> }
<ide> |
|
Java | apache-2.0 | cf9dd1f3a3df09c4abb3f7b8cbbdde6e000a8df3 | 0 | HKMOpen/android-DecoView-charting,Juneor/android-DecoView-charting,honeyflyfish/android-DecoView-charting,tieusangaka/android-DecoView-charting,SilverFoxA/android-DecoView-charting,letanloc/android-DecoView-charting,tsdl2013/android-DecoView-charting,WeRockStar/android-DecoView-charting,hzw1199/android-DecoView-charting,zhangswings/android-DecoView-charting,simple88/android-DecoView-charting,aaaliua/android-DecoView-charting,dxiaogang/android-DecoView-charting,jiyuren/android-DecoView-charting,Learn-Android-app/android-DecoView-charting,taimur97/android-DecoView-charting,SmarkSeven/android-DecoView-charting,datalink747/android-DecoView-charting,MaTriXy/android-DecoView-charting,MilanNz/android-DecoView-charting,bmarrdev/android-DecoView-charting,DuongNTdev/android-DecoView-charting,saady/android-DecoView-charting,pranavlathigara/android-DecoView-charting,leasual/android-DecoView-charting,mkodekar/android-DecoView-charting,luwei2012/android-DecoView-charting,bayan1987/android-DecoView-charting,0359xiaodong/android-DecoView-charting,khalidkhan433/android-DecoView-charting,nguyenhongson03/android-DecoView-charting | /*
* Copyright (C) 2015 Brent Marriott
*
* 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.
*/
package com.hookedonplay.decoviewlib.events;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.animation.AlphaAnimation;
import com.hookedonplay.decoviewlib.charts.DecoDrawEffect;
/**
* Event manager for processing {@link DecoEvent} at the scheduled time (or immediately if no
* delay is set). This class is also responsible for processing the hide/show fade effects of linked
* views.
*/
public class DecoEventManager {
/**
* Handler to manage firing events at given delays
*/
private final Handler mHandler = new Handler();
private ArcEventManagerListener mListener;
public DecoEventManager(@NonNull ArcEventManagerListener listener) {//DynamicArcView arcView) {
mListener = listener;
}
/**
* Add a {@link DecoEvent} to the schedule to be processed at the required time
* @param event
*/
public void add(@NonNull final DecoEvent event) {
final boolean show = (event.getEventType() == DecoEvent.EventType.EVENT_SHOW) ||
(event.getEffectType() == DecoDrawEffect.EffectType.EFFECT_SPIRAL_OUT) ||
(event.getEffectType() == DecoDrawEffect.EffectType.EFFECT_SPIRAL_OUT_FILL);
final boolean ignore = (event.getEventType() == DecoEvent.EventType.EVENT_MOVE);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (show) {
if (event.getLinkedViews() != null) {
for (View view : event.getLinkedViews()) {
view.setVisibility(View.VISIBLE);
}
}
}
if (!ignore && event.getLinkedViews() != null) {
for (View view : event.getLinkedViews()) {
AlphaAnimation anim = new AlphaAnimation(show ? 0.0f : 1.0f, show ? 1.0f : 0.0f);
anim.setDuration(event.getFadeDuration());
anim.setFillAfter(true);
view.startAnimation(anim);
}
}
if (mListener != null) {
mListener.onExecuteEventStart(event);
}
}
}, event.getDelay());
}
/**
* Remove any existing delayed messages from the handler
*/
public void resetEvents() {
mHandler.removeCallbacksAndMessages(null);
}
/**
* Callback interface for notification of event to be processed
*/
public interface ArcEventManagerListener {
void onExecuteEventStart(@NonNull DecoEvent event);
}
} | decoviewlib/src/main/java/com/hookedonplay/decoviewlib/events/DecoEventManager.java | /*
* Copyright (C) 2015 Brent Marriott
*
* 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.
*/
package com.hookedonplay.decoviewlib.events;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.animation.AlphaAnimation;
import com.hookedonplay.decoviewlib.charts.DecoDrawEffect;
public class DecoEventManager {
/**
* Handler to manage firing events at given delays
*/
private final Handler mHandler = new Handler();
private ArcEventManagerListener mListener;
public DecoEventManager(@NonNull ArcEventManagerListener listener) {//DynamicArcView arcView) {
mListener = listener;
}
public void add(@NonNull final DecoEvent event) {
final boolean show = (event.getEventType() == DecoEvent.EventType.EVENT_SHOW) ||
(event.getEffectType() == DecoDrawEffect.EffectType.EFFECT_SPIRAL_OUT) ||
(event.getEffectType() == DecoDrawEffect.EffectType.EFFECT_SPIRAL_OUT_FILL);
final boolean ignore = (event.getEventType() == DecoEvent.EventType.EVENT_MOVE);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (show) {
if (event.getLinkedViews() != null) {
for (View view : event.getLinkedViews()) {
view.setVisibility(View.VISIBLE);
}
}
}
if (!ignore && event.getLinkedViews() != null) {
for (View view : event.getLinkedViews()) {
AlphaAnimation anim = new AlphaAnimation(show ? 0.0f : 1.0f, show ? 1.0f : 0.0f);
anim.setDuration(event.getFadeDuration());
anim.setFillAfter(true);
view.startAnimation(anim);
}
}
if (mListener != null) {
mListener.onExecuteEventStart(event);
}
}
}, event.getDelay());
}
/**
* Remove any existing delayed messages from the handler
*/
public void resetEvents() {
mHandler.removeCallbacksAndMessages(null);
}
/**
* Callback interface for notification of event to be processed
*/
public interface ArcEventManagerListener {
void onExecuteEventStart(@NonNull DecoEvent event);
}
}
| Update javadoc
| decoviewlib/src/main/java/com/hookedonplay/decoviewlib/events/DecoEventManager.java | Update javadoc | <ide><path>ecoviewlib/src/main/java/com/hookedonplay/decoviewlib/events/DecoEventManager.java
<ide>
<ide> import com.hookedonplay.decoviewlib.charts.DecoDrawEffect;
<ide>
<add>/**
<add> * Event manager for processing {@link DecoEvent} at the scheduled time (or immediately if no
<add> * delay is set). This class is also responsible for processing the hide/show fade effects of linked
<add> * views.
<add> */
<ide> public class DecoEventManager {
<ide>
<ide> /**
<ide> mListener = listener;
<ide> }
<ide>
<add> /**
<add> * Add a {@link DecoEvent} to the schedule to be processed at the required time
<add> * @param event
<add> */
<ide> public void add(@NonNull final DecoEvent event) {
<ide> final boolean show = (event.getEventType() == DecoEvent.EventType.EVENT_SHOW) ||
<ide> (event.getEffectType() == DecoDrawEffect.EffectType.EFFECT_SPIRAL_OUT) || |
|
JavaScript | mit | 4b981cd69989eb543beb5083c06e86c784c2c651 | 0 | quri/raml2html | #!/usr/bin/env node
var raml = require('raml-parser');
var handlebars = require('handlebars');
var fs = require('fs');
var util = require('util');
var template = require('./template.handlebars');
var resourceTemplate = require('./resource.handlebars');
function parseBaseUri(ramlObj) {
// I have no clue what kind of variables the RAML spec allows in the baseUri.
// For now keep it super super simple.
if (ramlObj.baseUri){
ramlObj.baseUri = ramlObj.baseUri.replace('{version}', ramlObj.version);
}
return ramlObj;
}
function makeUniqueId(resource) {
var fullUrl = resource.parentUrl + resource.relativeUri;
return slugify(fullUrl);
}
function slugify(str) {
return str.replace(/[\{\}\/}]/g, '_');
}
function addParentUrls(ramlObj, parentUrl, rootId) {
var resource, index;
for (index in ramlObj.resources) {
resource = ramlObj.resources[index];
resource.parentUrl = parentUrl;
resource.uniqueId = makeUniqueId(resource);
if (!rootId.length) {
resource.rootId = slugify(resource.relativeUri);
} else {
resource.rootId = rootId;
}
addParentUrls(resource, resource.parentUrl + resource.relativeUri, resource.rootId);
}
return ramlObj;
}
function parse(source) {
raml.loadFile(source).then(function(ramlObj) {
ramlObj = parseBaseUri(ramlObj);
ramlObj = addParentUrls(ramlObj, '', '');
//console.log(util.inspect(ramlObj, false, null));
//process.exit(0);
handlebars.registerPartial('resource', resourceTemplate);
var result = template(ramlObj);
// For now simply output to console
process.stdout.write(result);
process.exit(0);
}, function(error) {
console.log('Error parsing: ' + error);
process.exit(1);
});
}
function parseWithStream(source, stream, callback) {
parseAndReturn(source, function(html) {
stream.write(html);
callback(stream);
});
}
function parseAndReturn(source, callback) {
raml.loadFile(source).then(function(ramlObj) {
ramlObj = parseBaseUri(ramlObj);
ramlObj = addParentUrls(ramlObj, '', '');
handlebars.registerPartial('resource', resourceTemplate);
var result = template(ramlObj);
callback(result);
}, function(error) {
console.log('Error parsing: ' + error);
});
}
exports.parseWithStream = parseWithStream;
exports.parseAndReturn = parseAndReturn;
| lib/raml2html.js | #!/usr/bin/env node
var raml = require('raml-parser');
var handlebars = require('handlebars');
var fs = require('fs');
var util = require('util');
var template = require('./template.handlebars');
var resourceTemplate = require('./resource.handlebars');
function parseBaseUri(ramlObj) {
// I have no clue what kind of variables the RAML spec allows in the baseUri.
// For now keep it super super simple.
if (ramlObj.baseUri){
ramlObj.baseUri = ramlObj.baseUri.replace('{version}', ramlObj.version);
}
return ramlObj;
}
function makeUniqueId(resource) {
var fullUrl = resource.parentUrl + resource.relativeUri;
return slugify(fullUrl);
}
function slugify(str) {
return str.replace(/[\{\}\/}]/g, '_');
}
function addParentUrls(ramlObj, parentUrl, rootId) {
var resource, index;
for (index in ramlObj.resources) {
resource = ramlObj.resources[index];
resource.parentUrl = parentUrl;
resource.uniqueId = makeUniqueId(resource);
if (!rootId.length) {
resource.rootId = slugify(resource.relativeUri);
} else {
resource.rootId = rootId;
}
addParentUrls(resource, resource.parentUrl + resource.relativeUri, resource.rootId);
}
return ramlObj;
}
function parse(source) {
raml.loadFile(source).then(function(ramlObj) {
ramlObj = parseBaseUri(ramlObj);
ramlObj = addParentUrls(ramlObj, '', '');
//console.log(util.inspect(ramlObj, false, null));
//process.exit(0);
handlebars.registerPartial('resource', resourceTemplate);
var result = template(ramlObj);
// For now simply output to console
process.stdout.write(result);
process.exit(0);
}, function(error) {
console.log('Error parsing: ' + error);
process.exit(1);
});
}
function parseWithStream(source, stream, callback) {
raml.loadFile(source).then(function(ramlObj) {
ramlObj = parseBaseUri(ramlObj);
ramlObj = addParentUrls(ramlObj, '', '');
handlebars.registerPartial('resource', resourceTemplate);
var result = template(ramlObj);
stream.write(result);
callback(stream);
}, function(error) {
console.log('Error parsing: ' + error);
});
}
exports.parseWithStream = parseWithStream;
| Add parseAndReturn (more generic)
| lib/raml2html.js | Add parseAndReturn (more generic) | <ide><path>ib/raml2html.js
<ide> }
<ide>
<ide> function parseWithStream(source, stream, callback) {
<add> parseAndReturn(source, function(html) {
<add> stream.write(html);
<add> callback(stream);
<add> });
<add>}
<add>
<add>function parseAndReturn(source, callback) {
<ide> raml.loadFile(source).then(function(ramlObj) {
<ide> ramlObj = parseBaseUri(ramlObj);
<ide> ramlObj = addParentUrls(ramlObj, '', '');
<ide> handlebars.registerPartial('resource', resourceTemplate);
<ide> var result = template(ramlObj);
<ide>
<del> stream.write(result);
<del> callback(stream);
<add> callback(result);
<ide> }, function(error) {
<ide> console.log('Error parsing: ' + error);
<ide> });
<ide> }
<ide>
<ide> exports.parseWithStream = parseWithStream;
<add>exports.parseAndReturn = parseAndReturn; |
|
JavaScript | mit | 96d25e39ac57e683248ec3d4daa5a8e5bc3352f6 | 0 | gayancliyanage/handsontable,toresenneseth/handsontable,fjvalencian/handsontable,IntexSoft/handsontable,billdc/handsontable,Cropster/handsontable,IntexSoft/handsontable,MultivitaminLLC/handsontable,TGOlson/handsontable,Arteaga2k/handsontable,peerlibrary/handsontable,fashionsun/handsontable,RobertoMalatesta/handsontable,diycp/handsontable,jmptrader/handsontable,RobertoMalatesta/handsontable,SecureCloud-biz/handsontable,bjorkegeek/handsontable,PaulZadorozhniy/handsontable,Arteaga2k/handsontable,fashionsun/handsontable,bjorkegeek/handsontable,deenairn/handsontable,littleforeastli/handsontable,robksawyer/handsontable,ibm-et/handsontable,Jazzo/handsontable,deenairn/handsontable,zhouxiaoping/handsontable,kirubz/handsontable,VladimirGavrilov/handsontable,dataiku/handsontable,adlenafane/handsontable,pingyuanChen/handsontable,overcastsoftware/handsontable,thesgc/handsontable,ericyang89/handsontable,LeeKyoungIl/handsontable,peerlibrary/handsontable,rjansen72/handsontable,portons/handsontable,PaulZadorozhniy/handsontable,bjorkegeek/handsontable,LeeKyoungIl/handsontable,iamjakob/handsontable,robksawyer/handsontable,ledt/jquery-handsontable,surfncode/handsontable,GerHobbelt/jquery-handsontable,SecureCloud-biz/handsontable,Growmies/handsontable,avct/handsontable,floribon/handsontable,peaceboy/handsontable,jmptrader/handsontable,compstak/handsontable,Growmies/handsontable,Cropster/handsontable,fashionsun/handsontable,napramirez/handsontable,machinelearningdeveloper/handsontable,vo-va/handsontable,fjvalencian/handsontable,gayancliyanage/handsontable,ericyang89/handsontable,cyancdesign/handsontable,andrewlin12/handsontable,ilovezy/handsontable,beealone/handsontable,peaceboy/handsontable,2947721120/handsontable,MultivitaminLLC/handsontable,adlenafane/handsontable,j6er8er/jquery-handsontable,toresenneseth/handsontable,ibm-et/handsontable,LeeKyoungIl/handsontable,richtier/handsontable,SecureCloud-biz/handsontable,shelsonjava/handsontable,2947721120/handsontable,kylelynch/handsontable,adlenafane/handsontable,richtier/handsontable,cjc343/jquery-handsontable,peerlibrary/handsontable,ilovezy/handsontable,pingyuanChen/handsontable,anandmehrotra/handsontable,winniefox/jquery-handsontable,surfncode/handsontable,cyancdesign/handsontable,floribon/handsontable,littleforeastli/handsontable,ibm-et/handsontable,TGOlson/handsontable,ledt/jquery-handsontable,VladimirGavrilov/handsontable,thesgc/handsontable,ilovezy/handsontable,diycp/handsontable,littleforeastli/handsontable,avct/handsontable,kirubz/handsontable,richtier/handsontable,PaulZadorozhniy/handsontable,zhouxiaoping/handsontable,floribon/handsontable,vo-va/handsontable,Jazzo/handsontable,rjansen72/handsontable,Cropster/handsontable,MultivitaminLLC/handsontable,zhouxiaoping/handsontable,IntexSoft/handsontable,peaceboy/handsontable,compstak/handsontable,diycp/handsontable,Jazzo/handsontable,Arteaga2k/handsontable,overcastsoftware/handsontable,RobertoMalatesta/handsontable,plotly/handsontable,beealone/handsontable,portons/handsontable,dataiku/handsontable,beealone/handsontable,kirubz/handsontable,GerHobbelt/jquery-handsontable,kylelynch/handsontable,cjc343/jquery-handsontable,pingyuanChen/handsontable,machinelearningdeveloper/handsontable,j6er8er/jquery-handsontable,napramirez/handsontable,ericyang89/handsontable,billdc/handsontable,napramirez/handsontable,vo-va/handsontable,toresenneseth/handsontable,thesgc/handsontable,andrewlin12/handsontable,andrewlin12/handsontable,deenairn/handsontable,robksawyer/handsontable,Growmies/handsontable,kylelynch/handsontable,gayancliyanage/handsontable,overcastsoftware/handsontable,dataiku/handsontable,anandmehrotra/handsontable,billdc/handsontable,iamjakob/handsontable,winniefox/jquery-handsontable,compstak/handsontable,iamjakob/handsontable,shelsonjava/handsontable,2947721120/handsontable,anandmehrotra/handsontable,cyancdesign/handsontable,avct/handsontable,shelsonjava/handsontable,plotly/handsontable,cjc343/jquery-handsontable,jmptrader/handsontable,fjvalencian/handsontable,GerHobbelt/jquery-handsontable,TGOlson/handsontable,VladimirGavrilov/handsontable,portons/handsontable,machinelearningdeveloper/handsontable | var spec = function () {
return jasmine.getEnv().currentSpec;
};
var handsontable = function (options) {
var currentSpec = spec();
currentSpec.$container.handsontable(options);
currentSpec.$container[0].focus(); //otherwise TextEditor tests do not pass in IE8
return currentSpec.$container.data('handsontable');
};
var countRows = function () {
return spec().$container.find('.htCore tbody tr').length;
};
var countCols = function () {
return spec().$container.find('.htCore tbody tr:eq(0) td').length;
};
var countCells = function () {
return spec().$container.find('.htCore tbody td').length;
};
var isEditorVisible = function () {
return !!(keyProxy().is(':visible') && keyProxy().parent().is(':visible') && !keyProxy().parent().is('.htHidden'));
};
var isFillHandleVisible = function () {
return !!spec().$container.find('.wtBorder.corner:visible').length;
};
var isAutocompleteVisible = function () {
return !!(autocompleteEditor() && autocompleteEditor().data("typeahead") && autocompleteEditor().data("typeahead").$menu.is(":visible"));
};
/**
* Shows context menu
*/
var contextMenu = function () {
var ev = $.Event('contextmenu');
ev.button = 2;
var instance = spec().$container.data('handsontable');
var selector = "#" + instance.rootElement.attr('id') + ' table, #' + instance.rootElement.attr('id') + ' div';
$(selector).trigger(ev);
};
/**
* Returns a function that triggers a mouse event
* @param {String} type Event type
* @return {Function}
*/
var handsontableMouseTriggerFactory = function (type) {
return function (element) {
if(!(element instanceof jQuery)){
element = $(element);
}
var ev = $.Event(type);
ev.which = 1; //left mouse button
element.trigger(ev);
}
};
var mouseDown = handsontableMouseTriggerFactory('mousedown');
var mouseUp = handsontableMouseTriggerFactory('mouseup');
/**
* Returns a function that triggers a key event
* @param {String} type Event type
* @return {Function}
*/
var handsontableKeyTriggerFactory = function (type) {
return function (key, extend) {
var ev = $.Event(type);
if (typeof key === 'string') {
if (key.indexOf('shift+') > -1) {
key = key.substring(6);
ev.shiftKey = true;
}
switch (key) {
case 'tab':
ev.keyCode = 9;
break;
case 'enter':
ev.keyCode = 13;
break;
case 'esc':
ev.keyCode = 27;
break;
case 'f2':
ev.keyCode = 113;
break;
case 'arrow_left':
ev.keyCode = 37;
break;
case 'arrow_up':
ev.keyCode = 38;
break;
case 'arrow_right':
ev.keyCode = 39;
break;
case 'arrow_down':
ev.keyCode = 40;
break;
case 'ctrl':
ev.keyCode = 17;
break;
case 'shift':
ev.keyCode = 16;
break;
case 'backspace':
ev.keyCode = 8;
break;
case 'space':
ev.keyCode = 32;
break;
default:
throw new Error('Unrecognised key name: ' + key);
}
}
else if (typeof key === 'number') {
ev.keyCode = key;
}
ev.originalEvent = {}; //needed as long Handsontable searches for event.originalEvent
$.extend(ev, extend);
$(document.activeElement).trigger(ev);
}
};
var keyDown = handsontableKeyTriggerFactory('keydown');
var keyUp = handsontableKeyTriggerFactory('keyup');
/**
* Presses keyDown, then keyUp
*/
var keyDownUp = function (key, extend) {
if (typeof key === 'string' && key.indexOf('shift+') > -1) {
keyDown('shift');
}
keyDown(key, extend);
keyUp(key, extend);
if (typeof key === 'string' && key.indexOf('shift+') > -1) {
keyUp('shift');
}
};
/**
* Returns current value of the keyboard proxy textarea
* @return {String}
*/
var keyProxy = function () {
return spec().$container.find('textarea.handsontableInput');
};
var autocompleteEditor = function () {
return spec().$container.data('handsontable').autocompleteEditor.$textarea;
};
/**
* Sets text cursor inside keyboard proxy
*/
var setCaretPosition = function (pos) {
var el = keyProxy()[0];
if (el.setSelectionRange) {
el.focus();
el.setSelectionRange(pos, pos);
}
else if (el.createTextRange) {
var range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
};
/**
* Returns autocomplete instance
*/
var autocomplete = function () {
return spec().$container.find('.handsontableInput').data("typeahead");
};
/**
* Triggers paste string on current selection
*/
var triggerPaste = function (str) {
spec().$container.data('handsontable').copyPaste.triggerPaste(null, str);
};
/**
* Calls a method in current Handsontable instance, returns its output
* @param method
* @return {Function}
*/
var handsontableMethodFactory = function (method) {
return function () {
var instance = spec().$container.handsontable('getInstance');
if (!instance) {
if (method === 'destroy') {
return; //we can forgive this... maybe it was destroyed in the test
}
throw new Error('Something wrong with the test spec: Handsontable instance not found');
}
return instance[method].apply(instance, arguments);
}
};
var getInstance = handsontableMethodFactory('getInstance');
var selectCell = handsontableMethodFactory('selectCell');
var deselectCell = handsontableMethodFactory('deselectCell');
var getSelected = handsontableMethodFactory('getSelected');
var setDataAtCell = handsontableMethodFactory('setDataAtCell');
var getCell = handsontableMethodFactory('getCell');
var getCellMeta = handsontableMethodFactory('getCellMeta');
var getData = handsontableMethodFactory('getData');
var getDataAtCell = handsontableMethodFactory('getDataAtCell');
var getDataAtRow = handsontableMethodFactory('getDataAtRow');
var getDataAtCol = handsontableMethodFactory('getDataAtCol');
var getRowHeader = handsontableMethodFactory('getRowHeader');
var getColHeader = handsontableMethodFactory('getColHeader');
var alter = handsontableMethodFactory('alter');
var spliceCol = handsontableMethodFactory('spliceCol');
var spliceRow = handsontableMethodFactory('spliceRow');
var populateFromArray = handsontableMethodFactory('populateFromArray');
var loadData = handsontableMethodFactory('loadData');
var destroyEditor = handsontableMethodFactory('destroyEditor');
var render = handsontableMethodFactory('render');
var updateSettings = handsontableMethodFactory('updateSettings');
var destroy = handsontableMethodFactory('destroy');
/**
* Creates 2D array of Excel-like values "A0", "A1", ...
* @param rowCount
* @param colCount
* @returns {Array}
*/
function createSpreadsheetData(rowCount, colCount) {
rowCount = typeof rowCount === 'number' ? rowCount : 100;
colCount = typeof colCount === 'number' ? colCount : 4;
var rows = []
, i
, j;
for (i = 0; i < rowCount; i++) {
var row = [];
for (j = 0; j < colCount; j++) {
row.push(Handsontable.helper.spreadsheetColumnLabel(j) + i);
}
rows.push(row);
}
return rows;
}
/**
* Returns column width for HOT container
* @param $elem
* @param col
* @returns {Number}
*/
function colWidth($elem, col) {
var TD = $elem[0].querySelector('TR').querySelectorAll('TD')[col];
if (!TD) {
throw new Error("Cannot find table column of index '" + col + "'");
}
return TD.offsetWidth;
} | test/jasmine/spec/SpecHelper.js | var spec = function () {
return jasmine.getEnv().currentSpec;
};
var handsontable = function (options) {
var currentSpec = spec();
currentSpec.$container.handsontable(options);
currentSpec.$container[0].focus(); //otherwise TextEditor tests do not pass in IE8
return currentSpec.$container.data('handsontable');
};
var countRows = function () {
return spec().$container.find('.htCore tbody tr').length;
};
var countCols = function () {
return spec().$container.find('.htCore tbody tr:eq(0) td').length;
};
var countCells = function () {
return spec().$container.find('.htCore tbody td').length;
};
var isEditorVisible = function () {
return !!(keyProxy().is(':visible') && keyProxy().parent().is(':visible') && !keyProxy().parent().is('.htHidden'));
};
var isFillHandleVisible = function () {
return !!spec().$container.find('.wtBorder.corner:visible').length;
};
var isAutocompleteVisible = function () {
return !!(autocompleteEditor() && autocompleteEditor().data("typeahead") && autocompleteEditor().data("typeahead").$menu.is(":visible"));
};
/**
* Shows context menu
*/
var contextMenu = function () {
var ev = $.Event('contextmenu');
ev.button = 2;
var instance = spec().$container.data('handsontable');
var selector = "#" + instance.rootElement.attr('id') + ' table, #' + instance.rootElement.attr('id') + ' div';
$(selector).trigger(ev);
};
/**
* Returns a function that triggers a mouse event
* @param {String} type Event type
* @return {Function}
*/
var handsontableMouseTriggerFactory = function (type) {
return function (element) {
var ev = $.Event(type);
ev.which = 1; //left mouse button
element.trigger(ev);
}
};
var mouseDown = handsontableMouseTriggerFactory('mousedown');
var mouseUp = handsontableMouseTriggerFactory('mouseup');
/**
* Returns a function that triggers a key event
* @param {String} type Event type
* @return {Function}
*/
var handsontableKeyTriggerFactory = function (type) {
return function (key, extend) {
var ev = $.Event(type);
if (typeof key === 'string') {
if (key.indexOf('shift+') > -1) {
key = key.substring(6);
ev.shiftKey = true;
}
switch (key) {
case 'tab':
ev.keyCode = 9;
break;
case 'enter':
ev.keyCode = 13;
break;
case 'esc':
ev.keyCode = 27;
break;
case 'f2':
ev.keyCode = 113;
break;
case 'arrow_left':
ev.keyCode = 37;
break;
case 'arrow_up':
ev.keyCode = 38;
break;
case 'arrow_right':
ev.keyCode = 39;
break;
case 'arrow_down':
ev.keyCode = 40;
break;
case 'ctrl':
ev.keyCode = 17;
break;
case 'shift':
ev.keyCode = 16;
break;
case 'backspace':
ev.keyCode = 8;
break;
case 'space':
ev.keyCode = 32;
break;
default:
throw new Error('Unrecognised key name: ' + key);
}
}
else if (typeof key === 'number') {
ev.keyCode = key;
}
ev.originalEvent = {}; //needed as long Handsontable searches for event.originalEvent
$.extend(ev, extend);
$(document.activeElement).trigger(ev);
}
};
var keyDown = handsontableKeyTriggerFactory('keydown');
var keyUp = handsontableKeyTriggerFactory('keyup');
/**
* Presses keyDown, then keyUp
*/
var keyDownUp = function (key, extend) {
if (typeof key === 'string' && key.indexOf('shift+') > -1) {
keyDown('shift');
}
keyDown(key, extend);
keyUp(key, extend);
if (typeof key === 'string' && key.indexOf('shift+') > -1) {
keyUp('shift');
}
};
/**
* Returns current value of the keyboard proxy textarea
* @return {String}
*/
var keyProxy = function () {
return spec().$container.find('textarea.handsontableInput');
};
var autocompleteEditor = function () {
return spec().$container.data('handsontable').autocompleteEditor.$textarea;
};
/**
* Sets text cursor inside keyboard proxy
*/
var setCaretPosition = function (pos) {
var el = keyProxy()[0];
if (el.setSelectionRange) {
el.focus();
el.setSelectionRange(pos, pos);
}
else if (el.createTextRange) {
var range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
};
/**
* Returns autocomplete instance
*/
var autocomplete = function () {
return spec().$container.find('.handsontableInput').data("typeahead");
};
/**
* Triggers paste string on current selection
*/
var triggerPaste = function (str) {
spec().$container.data('handsontable').copyPaste.triggerPaste(null, str);
};
/**
* Calls a method in current Handsontable instance, returns its output
* @param method
* @return {Function}
*/
var handsontableMethodFactory = function (method) {
return function () {
var instance = spec().$container.handsontable('getInstance');
if (!instance) {
if (method === 'destroy') {
return; //we can forgive this... maybe it was destroyed in the test
}
throw new Error('Something wrong with the test spec: Handsontable instance not found');
}
return instance[method].apply(instance, arguments);
}
};
var getInstance = handsontableMethodFactory('getInstance');
var selectCell = handsontableMethodFactory('selectCell');
var deselectCell = handsontableMethodFactory('deselectCell');
var getSelected = handsontableMethodFactory('getSelected');
var setDataAtCell = handsontableMethodFactory('setDataAtCell');
var getCell = handsontableMethodFactory('getCell');
var getCellMeta = handsontableMethodFactory('getCellMeta');
var getData = handsontableMethodFactory('getData');
var getDataAtCell = handsontableMethodFactory('getDataAtCell');
var getDataAtRow = handsontableMethodFactory('getDataAtRow');
var getDataAtCol = handsontableMethodFactory('getDataAtCol');
var getRowHeader = handsontableMethodFactory('getRowHeader');
var getColHeader = handsontableMethodFactory('getColHeader');
var alter = handsontableMethodFactory('alter');
var spliceCol = handsontableMethodFactory('spliceCol');
var spliceRow = handsontableMethodFactory('spliceRow');
var populateFromArray = handsontableMethodFactory('populateFromArray');
var loadData = handsontableMethodFactory('loadData');
var destroyEditor = handsontableMethodFactory('destroyEditor');
var render = handsontableMethodFactory('render');
var updateSettings = handsontableMethodFactory('updateSettings');
var destroy = handsontableMethodFactory('destroy');
/**
* Creates 2D array of Excel-like values "A0", "A1", ...
* @param rowCount
* @param colCount
* @returns {Array}
*/
function createSpreadsheetData(rowCount, colCount) {
rowCount = typeof rowCount === 'number' ? rowCount : 100;
colCount = typeof colCount === 'number' ? colCount : 4;
var rows = []
, i
, j;
for (i = 0; i < rowCount; i++) {
var row = [];
for (j = 0; j < colCount; j++) {
row.push(Handsontable.helper.spreadsheetColumnLabel(j) + i);
}
rows.push(row);
}
return rows;
}
/**
* Returns column width for HOT container
* @param $elem
* @param col
* @returns {Number}
*/
function colWidth($elem, col) {
var TD = $elem[0].querySelector('TR').querySelectorAll('TD')[col];
if (!TD) {
throw new Error("Cannot find table column of index '" + col + "'");
}
return TD.offsetWidth;
} | mouseDown and mouseUp spec helpers can now handle plain DOM objects
| test/jasmine/spec/SpecHelper.js | mouseDown and mouseUp spec helpers can now handle plain DOM objects | <ide><path>est/jasmine/spec/SpecHelper.js
<ide> */
<ide> var handsontableMouseTriggerFactory = function (type) {
<ide> return function (element) {
<add> if(!(element instanceof jQuery)){
<add> element = $(element);
<add> }
<ide> var ev = $.Event(type);
<ide> ev.which = 1; //left mouse button
<ide> element.trigger(ev); |
|
Java | apache-2.0 | 1c99f12b42b71a0f1b516e8ebab80c9342b0ba69 | 0 | bjagg/uPortal,apetro/uPortal,groybal/uPortal,doodelicious/uPortal,MichaelVose2/uPortal,jhelmer-unicon/uPortal,jameswennmacher/uPortal,chasegawa/uPortal,EsupPortail/esup-uportal,timlevett/uPortal,phillips1021/uPortal,apetro/uPortal,stalele/uPortal,GIP-RECIA/esup-uportal,jameswennmacher/uPortal,jl1955/uPortal5,jl1955/uPortal5,Jasig/uPortal,kole9273/uPortal,apetro/uPortal,vertein/uPortal,Mines-Albi/esup-uportal,vbonamy/esup-uportal,phillips1021/uPortal,groybal/uPortal,pspaude/uPortal,apetro/uPortal,andrewstuart/uPortal,ASU-Capstone/uPortal,GIP-RECIA/esup-uportal,MichaelVose2/uPortal,joansmith/uPortal,vertein/uPortal,Jasig/SSP-Platform,drewwills/uPortal,GIP-RECIA/esup-uportal,kole9273/uPortal,GIP-RECIA/esco-portail,vbonamy/esup-uportal,andrewstuart/uPortal,ASU-Capstone/uPortal,GIP-RECIA/esco-portail,Jasig/SSP-Platform,pspaude/uPortal,ASU-Capstone/uPortal-Forked,chasegawa/uPortal,andrewstuart/uPortal,bjagg/uPortal,jameswennmacher/uPortal,kole9273/uPortal,cousquer/uPortal,timlevett/uPortal,Mines-Albi/esup-uportal,phillips1021/uPortal,ASU-Capstone/uPortal-Forked,ASU-Capstone/uPortal,Jasig/SSP-Platform,vertein/uPortal,ASU-Capstone/uPortal,vbonamy/esup-uportal,jl1955/uPortal5,Mines-Albi/esup-uportal,jhelmer-unicon/uPortal,EsupPortail/esup-uportal,chasegawa/uPortal,doodelicious/uPortal,EdiaEducationTechnology/uPortal,drewwills/uPortal,jhelmer-unicon/uPortal,ChristianMurphy/uPortal,joansmith/uPortal,MichaelVose2/uPortal,joansmith/uPortal,jonathanmtran/uPortal,jl1955/uPortal5,kole9273/uPortal,mgillian/uPortal,jameswennmacher/uPortal,EsupPortail/esup-uportal,jameswennmacher/uPortal,kole9273/uPortal,phillips1021/uPortal,MichaelVose2/uPortal,ASU-Capstone/uPortal-Forked,EsupPortail/esup-uportal,jl1955/uPortal5,Jasig/SSP-Platform,ChristianMurphy/uPortal,MichaelVose2/uPortal,drewwills/uPortal,timlevett/uPortal,doodelicious/uPortal,vertein/uPortal,GIP-RECIA/esco-portail,jhelmer-unicon/uPortal,EdiaEducationTechnology/uPortal,mgillian/uPortal,chasegawa/uPortal,timlevett/uPortal,Jasig/uPortal,EdiaEducationTechnology/uPortal,ASU-Capstone/uPortal-Forked,vbonamy/esup-uportal,jonathanmtran/uPortal,Mines-Albi/esup-uportal,ASU-Capstone/uPortal,groybal/uPortal,mgillian/uPortal,Mines-Albi/esup-uportal,EsupPortail/esup-uportal,bjagg/uPortal,joansmith/uPortal,GIP-RECIA/esup-uportal,pspaude/uPortal,stalele/uPortal,groybal/uPortal,doodelicious/uPortal,EdiaEducationTechnology/uPortal,apetro/uPortal,chasegawa/uPortal,stalele/uPortal,GIP-RECIA/esup-uportal,ChristianMurphy/uPortal,andrewstuart/uPortal,jonathanmtran/uPortal,Jasig/SSP-Platform,drewwills/uPortal,jhelmer-unicon/uPortal,stalele/uPortal,joansmith/uPortal,Jasig/uPortal-start,ASU-Capstone/uPortal-Forked,cousquer/uPortal,stalele/uPortal,vbonamy/esup-uportal,Jasig/uPortal,cousquer/uPortal,Jasig/uPortal-start,pspaude/uPortal,andrewstuart/uPortal,groybal/uPortal,doodelicious/uPortal,phillips1021/uPortal | /* Copyright 2003 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package org.jasig.portal;
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
import javax.servlet.*;
import javax.servlet.http.*;
import org.jasig.portal.properties.PropertiesManager;
import org.jasig.portal.services.HttpClientManager;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Proxy embedded content such as images for portal sessions.
* When portal is running over ssl, HttpProxyServlet can be used
* to deliver insecure content such as images over ssl to avoid
* mixed content in the browser window.
*
* @author Drew Mazurek ([email protected])
* @author Susan Bramhall ([email protected])
* @version 1.0
* @since uPortal 2.2
*/
public class HttpProxyServlet extends HttpServlet {
private static final Log log = LogFactory.getLog(HttpProxyServlet.class);
/**
* Returns content retreived from location following context (Path Info)
* If no content found returns 404
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// check referrer property - return 404 if incorrect.
final String checkReferer = PropertiesManager.getProperty(HttpProxyServlet.class.getName()
+ ".checkReferer", null);
String target;
// if checking referer then only supply proxied content for specific referer
// Ensures requests come from pages in the portal
if (null!=checkReferer && !checkReferer.equals("")){
StringTokenizer checkedReferers = new StringTokenizer (checkReferer, " ");
boolean refOK = false;
String referer = request.getHeader("Referer");
if (log.isDebugEnabled()) {
log.debug("HttpProxyServlet: HTTP Referer: " + referer);
}
if (null!=referer) {
while (checkedReferers.hasMoreTokens()) {
String goodRef = checkedReferers.nextToken();
if (log.isDebugEnabled()) {
log.debug("HttpProxyServlet: checking for "+goodRef);
}
if (referer.startsWith(goodRef)) {
refOK = true;
if (log.isDebugEnabled()) {
log.debug("HttpProxyServlet: referer accepted "+goodRef);
}
break;
}
}
if (!refOK) {
if (log.isWarnEnabled()) {
log.warn("HttpProxyServlet: bad Referer: " + referer);
}
response.setStatus(404);
return;
}
}
else /* referer is null so don't return element */{
if (log.isWarnEnabled()) {
log.warn("HttpProxyServlet: bad Referer: " + referer);
}
response.setStatus(404);
return;
}
}
if (request.getSession(false)==null) {
if (log.isWarnEnabled())
log.warn("HttpProxyServlet: no session");
response.setStatus(404);
return;
}
// pathinfo is "/host/url"
if(request.getPathInfo() != null && !request.getPathInfo().equals("")) {
target = "http:/" + request.getPathInfo();
String qs = request.getQueryString();
if (qs != null) {
target +="?"+request.getQueryString();
}
} else {
response.setStatus(404);
log.warn("HttpProxyServlet: getPathInfo is empty");
return;
}
try {
final HttpClient client = HttpClientManager.getNewHTTPClient();
final GetMethod get = new GetMethod(target);
final int rc = client.executeMethod(get);
if (rc != 200) {
response.setStatus(404);
log.info("httpProxyServlet returning response 404 after receiving response code: "+rc+" from url: "+"target");
}
final Header contentType = get.getResponseHeader("content-type");
if (log.isDebugEnabled())
log.debug("httpProxyServlet examining element with content type = "+contentType);
if (!contentType.getValue().startsWith("image")){
response.setStatus(404);
log.info("httpProxyServlet returning response 404 after receiving element with contentType ="+contentType);
} response.setContentType(contentType.getValue());
final ServletOutputStream out = response.getOutputStream();
try {
final InputStream is = get.getResponseBodyAsStream();
try {
final byte[] buf = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
}
} finally {
is.close();
}
} finally {
out.close();
}
} catch (MalformedURLException e) {
response.setStatus(404);
log.warn("HttpProxyServlet: target=" + target.toString(), e);
} catch (IOException e) {
response.setStatus(404);
log.warn(e, e);
}
}
}
| uportal-impl/src/main/java/org/jasig/portal/HttpProxyServlet.java | /* Copyright 2003 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package org.jasig.portal;
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
import javax.servlet.*;
import javax.servlet.http.*;
import org.jasig.portal.properties.PropertiesManager;
import org.jasig.portal.services.HttpClientManager;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Proxy embedded content such as images for portal sessions.
* When portal is running over ssl, HttpProxyServlet can be used
* to deliver insecure content such as images over ssl to avoid
* mixed content in the browser window.
*
* @author Drew Mazurek ([email protected])
* @author Susan Bramhall ([email protected])
* @version 1.0
* @since uPortal 2.2
*/
public class HttpProxyServlet extends HttpServlet {
private static final Log log = LogFactory.getLog(HttpProxyServlet.class);
/**
* Returns content retreived from location following context (Path Info)
* If no content found returns 404
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// check referrer property - return 404 if incorrect.
final String checkReferer = PropertiesManager.getProperty(HttpProxyServlet.class.getName()
+ ".checkReferer", null);
String target;
// if checking referer then only supply proxied content for specific referer
// Ensures requests come from pages in the portal
if (null!=checkReferer && !checkReferer.equals("")){
StringTokenizer checkedReferers = new StringTokenizer (checkReferer, " ");
boolean refOK = false;
String referer = request.getHeader("Referer");
if (log.isDebugEnabled()) {
log.debug("HttpProxyServlet: HTTP Referer: " + referer);
}
if (null!=referer) {
while (checkedReferers.hasMoreTokens()) {
String goodRef = checkedReferers.nextToken();
if (log.isDebugEnabled()) {
log.debug("HttpProxyServlet: checking for "+goodRef);
}
if (referer.startsWith(goodRef)) {
refOK = true;
if (log.isDebugEnabled()) {
log.debug("HttpProxyServlet: referer accepted "+goodRef);
}
break;
}
}
if (!refOK) {
if (log.isWarnEnabled()) {
log.warn("HttpProxyServlet: bad Referer: " + referer);
}
response.setStatus(404);
return;
}
}
}
if (request.getSession(false)==null) {
if (log.isWarnEnabled())
log.warn("HttpProxyServlet: no session");
response.setStatus(404);
return;
}
// pathinfo is "/host/url"
if(request.getPathInfo() != null && !request.getPathInfo().equals("")) {
target = "http:/" + request.getPathInfo();
String qs = request.getQueryString();
if (qs != null) {
target +="?"+request.getQueryString();
}
} else {
response.setStatus(404);
log.warn("HttpProxyServlet: getPathInfo is empty");
return;
}
try {
final HttpClient client = HttpClientManager.getNewHTTPClient();
final GetMethod get = new GetMethod(target);
final int rc = client.executeMethod(get);
if (rc != 200) {
response.setStatus(404);
log.info("httpProxyServlet returning response 404 after receiving response code: "+rc+" from url: "+"target");
}
final Header contentType = get.getResponseHeader("content-type");
if (log.isDebugEnabled())
log.debug("httpProxyServlet examining element with content type = "+contentType);
if (!contentType.getValue().startsWith("image")){
response.setStatus(404);
log.info("httpProxyServlet returning response 404 after receiving element with contentType ="+contentType);
} response.setContentType(contentType.getValue());
final ServletOutputStream out = response.getOutputStream();
try {
final InputStream is = get.getResponseBodyAsStream();
try {
final byte[] buf = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
}
} finally {
is.close();
}
} finally {
out.close();
}
} catch (MalformedURLException e) {
response.setStatus(404);
log.warn("HttpProxyServlet: target=" + target.toString(), e);
} catch (IOException e) {
response.setStatus(404);
log.warn(e, e);
}
}
}
| UP-1836 Fix null referrer check
git-svn-id: 2f1ee6cafdaf9f6d2a43037ff9da8a267f1ed5b7@14576 f5dbab47-78f9-eb45-b975-e544023573eb
| uportal-impl/src/main/java/org/jasig/portal/HttpProxyServlet.java | UP-1836 Fix null referrer check | <ide><path>portal-impl/src/main/java/org/jasig/portal/HttpProxyServlet.java
<ide> response.setStatus(404);
<ide> return;
<ide> }
<del>
<add> }
<add> else /* referer is null so don't return element */{
<add> if (log.isWarnEnabled()) {
<add> log.warn("HttpProxyServlet: bad Referer: " + referer);
<add> }
<add> response.setStatus(404);
<add> return;
<ide> }
<ide> }
<ide> |
|
JavaScript | apache-2.0 | ed6d19b108d15ca205a55603c65aaa70f49e1118 | 0 | BrianH2/Intercom-Chrome-Extension,BrianH2/Intercom-Chrome-Extension | function concat_collection(obj1, obj2) {
var i;
var arr = new Array();
var len1 = obj1.length;
var len2 = obj2.length;
for (i=0; i<len1; i++) {
arr.push(obj1[i]);
}
for (i=0; i<len2; i++) {
arr.push(obj2[i]);
}
return arr;
}
var password = "";
var username = "";
var dataToReturn = "";
var return_Custom = "";
var dataPresentation = "";
var extraClassToCheck = "";
var allEmailsOnPage;
var IntChrClassName = "IntercomChrExtBH";
var timeNow = Math.floor(new Date().getTime() / 1000);
chrome.storage.local.get('password', function (result) {password = result.password;});
chrome.storage.local.get('username', function (result) {username = result.username;});
chrome.storage.local.get('dataToReturn', function (result) {dataToReturn = result.dataToReturn;});
chrome.storage.local.get('return_Custom', function (result) {return_Custom = result.return_Custom;});
chrome.storage.local.get('dataPresentation', function (result) {dataPresentation = result.dataPresentation;});
chrome.storage.local.get('extraClassToCheck', function (result) {extraClassToCheck = result.extraClassToCheck;});
// remove all existing elements from extension on page
var existingExtensionElements = document.querySelectorAll("."+IntChrClassName);
// console.log(existingExtensionElements);
for (var i = existingExtensionElements.length - 1; i >= 0; i--) {
existingExtensionElements[i].parentNode.removeChild(existingExtensionElements[i]);
}
setTimeout(function(){
allEmailsOnPage = document.querySelectorAll('a[href^="mailto:"]');
salesForceEmailsOnPage = document.querySelectorAll('.uiOutputEmail');
allEmailsOnPage = concat_collection(allEmailsOnPage, salesForceEmailsOnPage);
if (extraClassToCheck.length > 1) {
var allOtherEmailsOnPage = document.querySelectorAll('.'+extraClassToCheck);
allEmailsOnPage = concat_collection(allEmailsOnPage,allOtherEmailsOnPage);
}
// console.log(allEmailsOnPage);
var currentDomain = document.location.hostname;
currentDomain = currentDomain.replace("www.","");
if (allEmailsOnPage.length == 0 ) {
chrome.runtime.sendMessage({
completedScan: "true",
numberEmailsChecked: allEmailsOnPage.length,
numberEmailsFound: 0,
currentDomain: currentDomain
},function(response) {});
} else {
addIntercomData();
}
}, 100);
var numberEmailsFound = 0;
var currentEmailChecking = 0;
function addIntercomData() {
var searchIntercomUrl = "https://app.intercom.io/apps/"+username+"/users?search=";
var currentDomain = document.location.hostname;
currentDomain = currentDomain.replace("www.","");
chrome.runtime.sendMessage({
currentDomain: currentDomain
},
function(response) {});
jQuery.each(allEmailsOnPage, function (i, item) {
var infoSpan = document.createElement('span');
if (item.hasAttribute("href")) {
var email = item.href;
email = email.match(/mailto:([^\?]*)/);
email = email[1]?email[1]:false;
} else {
var emailRegex = /(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/gm
email = (item.innerHTML).match(emailRegex)[0];
}
item.style.color='blue';
item.style.background='yellow';
jQuery.ajax({
url: "https://api.intercom.io/users?email="+encodeURIComponent(email),
type: "GET",
beforeSend: function(request){
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
},
error:function (xhr, ajaxOptions, thrownError){
currentEmailChecking = currentEmailChecking + 1;
if(xhr.status==404) {
iconImage = "<img style='width:20px; -webkit-filter: grayscale(100%);' src='"+chrome.extension.getURL('images/logo.png')+"' alt='Intercom Chrome Extension'>";
if (dataPresentation == "show_Visible") {
infoSpan.innerHTML = " " + iconImage + " not found";
} else {
infoSpan.innerHTML = "<span class='tooltip'>" + iconImage + "<span class='tooltiptext'>Not found</span></span></span>";
}
infoSpan.setAttribute('title', "No user found matching "+email);
infoSpan.setAttribute('class', IntChrClassName);
allEmailsOnPage[i].parentNode.insertBefore(infoSpan, allEmailsOnPage[i].nextSibling);
}
if (currentEmailChecking == allEmailsOnPage.length) {
chrome.runtime.sendMessage({
completedScan: "true",
numberEmailsChecked: allEmailsOnPage.length,
numberEmailsFound: numberEmailsFound,
currentDomain: currentDomain
},function(response) {});
} else {
chrome.runtime.sendMessage({
completedScan: "scanning page"
},function(response) {});
}
}
// cache: false
}).done(function (result) {
// console.log(result);
numberEmailsFound = numberEmailsFound + 1;
currentEmailChecking = currentEmailChecking + 1;
// console.log(numberEmailsFound);
var emailIntercom = result["email"];
var webSessions = result["session_count"];
var location = result["location_data"]["city_name"] + ", " + result["location_data"]["region_name"] + ", " + result["location_data"]["country_name"]
var signed_up_at = result["signed_up_at"];
var name = result["name"];
var minsInDay = 24*60*60;
var daysSinceSignup = Math.floor( (timeNow - signed_up_at) / minsInDay);
iconImage = "<img style='width:20px;' src='"+chrome.extension.getURL('images/logo.png')+"' alt='Intercom Chrome Extension'>";
if (dataPresentation == "show_Visible") {
if (webSessions > 5) {
webSessionsSTYLE = "color:green;";
} else {
webSessionsSTYLE = "color:grey;";
}
if (dataToReturn == "return_WebSessions") {
infoSpan.innerHTML = " <a style='font-weight:bold' href='"+searchIntercomUrl+email+"' target='_blank'> "+iconImage+" <span style='"+webSessionsSTYLE+"'>"+webSessions+" web sessions</span></a>";
} else if(dataToReturn == "return_DaysSignup") {
infoSpan.innerHTML = " <a style='font-weight:bold' href='"+searchIntercomUrl+email+"' target='_blank'> "+iconImage+" "+daysSinceSignup+" days</a>";
} else if(dataToReturn == "return_Location") {
infoSpan.innerHTML = " <a style='font-weight:bold' href='"+searchIntercomUrl+email+"' target='_blank'> "+iconImage+" "+location+"</a>";
} else if(dataToReturn == "return_Name") {
infoSpan.innerHTML = " <a style='font-weight:bold' href='"+searchIntercomUrl+email+"' target='_blank'> "+iconImage+" "+name+"</a>";
} else if(dataToReturn == "return_Custom") {
var custom_attribute = result["custom_attributes"][return_Custom];
if (custom_attribute == null) {custom_attribute = "unknown";}
infoSpan.innerHTML = " <a style='font-weight:bold' href='"+searchIntercomUrl+email+"' target='_blank'> "+iconImage+" "+custom_attribute+"</a>";
}
infoSpan.setAttribute('title', emailIntercom + " | " + name);
} else {
// append CSS
var css = 'a.tooltipIntChrExt::before {content: attr(data-tip);font-size: 13px;position:absolute;z-index: 999;white-space:nowrap;bottom:9999px;left: 50%; background: #DBEEFF;border-radius:2px; color: #000000;border: #4A8EE2 1px solid;padding:4px 10px 7px;opacity: 1; transition:opacity 1s ease-out;} a.tooltipIntChrExt:hover::before {opacity: 1;bottom:-35px;}',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
if (dataToReturn == "return_WebSessions") {
infoSpan.innerHTML = " <a class='tooltipIntChrExt' data-tip='"+webSessions+" web sessions' href='"+searchIntercomUrl+email+"' target='_blank'>"+iconImage+"</a>";
infoSpan.setAttribute('title', webSessions+" web sessions");
} else if(dataToReturn == "return_DaysSignup") {
infoSpan.innerHTML = " <a class='tooltipIntChrExt' data-tip='"+daysSinceSignup+" days since sign up' href='"+searchIntercomUrl+email+"' target='_blank'>"+iconImage+"</a>";
infoSpan.setAttribute('title', daysSinceSignup+" days since sign up");
} else if(dataToReturn == "return_Location") {
infoSpan.innerHTML = " <a class='tooltipIntChrExt' data-tip='"+location+"' href='"+searchIntercomUrl+email+"' target='_blank'>"+iconImage+"</a>";
infoSpan.setAttribute('title', location);
} else if(dataToReturn == "return_Name") {
infoSpan.innerHTML = " <a class='tooltipIntChrExt' data-tip='"+name+"' href='"+searchIntercomUrl+email+"' target='_blank'>"+iconImage+"</a>";
infoSpan.setAttribute('title', name);
} else if(dataToReturn == "return_Custom") {
var custom_attribute = result["custom_attributes"][return_Custom];
if (custom_attribute == null) {custom_attribute = "unknown";}
infoSpan.innerHTML = " <a class='tooltipIntChrExt' data-tip='"+custom_attribute+"' href='"+searchIntercomUrl+email+"' target='_blank'>"+iconImage+"</a>";
infoSpan.setAttribute('title', custom_attribute);
}
}
infoSpan.setAttribute('class', IntChrClassName);
allEmailsOnPage[i].parentNode.insertBefore(infoSpan, allEmailsOnPage[i].nextSibling);
if (currentEmailChecking == allEmailsOnPage.length) {
chrome.runtime.sendMessage({
completedScan: "true",
numberEmailsChecked: allEmailsOnPage.length,
numberEmailsFound: numberEmailsFound,
currentDomain: currentDomain
},function(response) {});
} else {
chrome.runtime.sendMessage({
completedScan: "scanning page",
currentDomain: currentDomain
},function(response) {});
}
});
});
}
| scripts/check_emails.js | function concat_collection(obj1, obj2) {
var i;
var arr = new Array();
var len1 = obj1.length;
var len2 = obj2.length;
for (i=0; i<len1; i++) {
arr.push(obj1[i]);
}
for (i=0; i<len2; i++) {
arr.push(obj2[i]);
}
return arr;
}
var password = "";
var username = "";
var dataToReturn = "";
var return_Custom = "";
var dataPresentation = "";
var extraClassToCheck = "";
var allEmailsOnPage;
var IntChrClassName = "IntercomChrExtBH";
var timeNow = Math.floor(new Date().getTime() / 1000);
chrome.storage.local.get('password', function (result) {password = result.password;});
chrome.storage.local.get('username', function (result) {username = result.username;});
chrome.storage.local.get('dataToReturn', function (result) {dataToReturn = result.dataToReturn;});
chrome.storage.local.get('return_Custom', function (result) {return_Custom = result.return_Custom;});
chrome.storage.local.get('dataPresentation', function (result) {dataPresentation = result.dataPresentation;});
chrome.storage.local.get('extraClassToCheck', function (result) {extraClassToCheck = result.extraClassToCheck;});
// remove all existing elements from extension on page
var existingExtensionElements = document.querySelectorAll("."+IntChrClassName);
// console.log(existingExtensionElements);
for (var i = existingExtensionElements.length - 1; i >= 0; i--) {
existingExtensionElements[i].parentNode.removeChild(existingExtensionElements[i]);
}
setTimeout(function(){
allEmailsOnPage = document.querySelectorAll('a[href^="mailto:"]');
salesForceEmailsOnPage = document.querySelectorAll('.uiOutputEmail');
allEmailsOnPage = concat_collection(allEmailsOnPage, salesForceEmailsOnPage);
if (extraClassToCheck.length > 1) {
var allOtherEmailsOnPage = document.querySelectorAll('.'+extraClassToCheck);
allEmailsOnPage = concat_collection(allEmailsOnPage,allOtherEmailsOnPage);
}
// console.log(allEmailsOnPage);
if (allEmailsOnPage.length == 0 ) {
chrome.runtime.sendMessage({
completedScan: "true",
numberEmailsChecked: allEmailsOnPage.length,
numberEmailsFound: 0
},function(response) {});
} else {
addIntercomData();
}
}, 100);
var numberEmailsFound = 0;
var currentEmailChecking = 0;
function addIntercomData() {
var searchIntercomUrl = "https://app.intercom.io/apps/"+username+"/users?search=";
var currentDomain = document.location.hostname;
currentDomain = currentDomain.replace("www.","");
chrome.runtime.sendMessage({
currentDomain: currentDomain
},
function(response) {});
jQuery.each(allEmailsOnPage, function (i, item) {
var infoSpan = document.createElement('span');
if (item.hasAttribute("href")) {
var email = item.href;
email = email.match(/mailto:([^\?]*)/);
email = email[1]?email[1]:false;
} else {
var emailRegex = /(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/gm
email = (item.innerHTML).match(emailRegex)[0];
}
item.style.color='blue';
item.style.background='yellow';
jQuery.ajax({
url: "https://api.intercom.io/users?email="+encodeURIComponent(email),
type: "GET",
beforeSend: function(request){
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
},
error:function (xhr, ajaxOptions, thrownError){
currentEmailChecking = currentEmailChecking + 1;
if(xhr.status==404) {
iconImage = "<img style='width:20px; -webkit-filter: grayscale(100%);' src='"+chrome.extension.getURL('images/logo.png')+"' alt='Intercom Chrome Extension'>";
if (dataPresentation == "show_Visible") {
infoSpan.innerHTML = " " + iconImage + " not found";
} else {
infoSpan.innerHTML = "<span class='tooltip'>" + iconImage + "<span class='tooltiptext'>Not found</span></span></span>";
}
infoSpan.setAttribute('title', "No user found matching "+email);
infoSpan.setAttribute('class', IntChrClassName);
allEmailsOnPage[i].parentNode.insertBefore(infoSpan, allEmailsOnPage[i].nextSibling);
}
if (currentEmailChecking == allEmailsOnPage.length) {
chrome.runtime.sendMessage({
completedScan: "true",
numberEmailsChecked: allEmailsOnPage.length,
numberEmailsFound: numberEmailsFound
},function(response) {});
} else {
chrome.runtime.sendMessage({
completedScan: "scanning page"
},function(response) {});
}
}
// cache: false
}).done(function (result) {
// console.log(result);
numberEmailsFound = numberEmailsFound + 1;
currentEmailChecking = currentEmailChecking + 1;
// console.log(numberEmailsFound);
var emailIntercom = result["email"];
var webSessions = result["session_count"];
var location = result["location_data"]["city_name"] + ", " + result["location_data"]["region_name"] + ", " + result["location_data"]["country_name"]
var signed_up_at = result["signed_up_at"];
var name = result["name"];
var minsInDay = 24*60*60;
var daysSinceSignup = Math.floor( (timeNow - signed_up_at) / minsInDay);
iconImage = "<img style='width:20px;' src='"+chrome.extension.getURL('images/logo.png')+"' alt='Intercom Chrome Extension'>";
if (dataPresentation == "show_Visible") {
if (webSessions > 5) {
webSessionsSTYLE = "color:green;";
} else {
webSessionsSTYLE = "color:grey;";
}
if (dataToReturn == "return_WebSessions") {
infoSpan.innerHTML = " <a style='font-weight:bold' href='"+searchIntercomUrl+email+"' target='_blank'> "+iconImage+" <span style='"+webSessionsSTYLE+"'>"+webSessions+" web sessions</span></a>";
} else if(dataToReturn == "return_DaysSignup") {
infoSpan.innerHTML = " <a style='font-weight:bold' href='"+searchIntercomUrl+email+"' target='_blank'> "+iconImage+" "+daysSinceSignup+" days</a>";
} else if(dataToReturn == "return_Location") {
infoSpan.innerHTML = " <a style='font-weight:bold' href='"+searchIntercomUrl+email+"' target='_blank'> "+iconImage+" "+location+"</a>";
} else if(dataToReturn == "return_Name") {
infoSpan.innerHTML = " <a style='font-weight:bold' href='"+searchIntercomUrl+email+"' target='_blank'> "+iconImage+" "+name+"</a>";
} else if(dataToReturn == "return_Custom") {
var custom_attribute = result["custom_attributes"][return_Custom];
if (custom_attribute == null) {custom_attribute = "unknown";}
infoSpan.innerHTML = " <a style='font-weight:bold' href='"+searchIntercomUrl+email+"' target='_blank'> "+iconImage+" "+custom_attribute+"</a>";
}
infoSpan.setAttribute('title', emailIntercom + " | " + name);
} else {
// append CSS
var css = 'a.tooltipIntChrExt::before {content: attr(data-tip);font-size: 13px;position:absolute;z-index: 999;white-space:nowrap;bottom:9999px;left: 50%; background: #DBEEFF;border-radius:2px; color: #000000;border: #4A8EE2 1px solid;padding:4px 10px 7px;opacity: 1; transition:opacity 1s ease-out;} a.tooltipIntChrExt:hover::before {opacity: 1;bottom:-35px;}',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
if (dataToReturn == "return_WebSessions") {
infoSpan.innerHTML = " <a class='tooltipIntChrExt' data-tip='"+webSessions+" web sessions' href='"+searchIntercomUrl+email+"' target='_blank'>"+iconImage+"</a>";
infoSpan.setAttribute('title', webSessions+" web sessions");
} else if(dataToReturn == "return_DaysSignup") {
infoSpan.innerHTML = " <a class='tooltipIntChrExt' data-tip='"+daysSinceSignup+" days since sign up' href='"+searchIntercomUrl+email+"' target='_blank'>"+iconImage+"</a>";
infoSpan.setAttribute('title', daysSinceSignup+" days since sign up");
} else if(dataToReturn == "return_Location") {
infoSpan.innerHTML = " <a class='tooltipIntChrExt' data-tip='"+location+"' href='"+searchIntercomUrl+email+"' target='_blank'>"+iconImage+"</a>";
infoSpan.setAttribute('title', location);
} else if(dataToReturn == "return_Name") {
infoSpan.innerHTML = " <a class='tooltipIntChrExt' data-tip='"+name+"' href='"+searchIntercomUrl+email+"' target='_blank'>"+iconImage+"</a>";
infoSpan.setAttribute('title', name);
} else if(dataToReturn == "return_Custom") {
var custom_attribute = result["custom_attributes"][return_Custom];
if (custom_attribute == null) {custom_attribute = "unknown";}
infoSpan.innerHTML = " <a class='tooltipIntChrExt' data-tip='"+custom_attribute+"' href='"+searchIntercomUrl+email+"' target='_blank'>"+iconImage+"</a>";
infoSpan.setAttribute('title', custom_attribute);
}
}
infoSpan.setAttribute('class', IntChrClassName);
allEmailsOnPage[i].parentNode.insertBefore(infoSpan, allEmailsOnPage[i].nextSibling);
if (currentEmailChecking == allEmailsOnPage.length) {
chrome.runtime.sendMessage({
completedScan: "true",
numberEmailsChecked: allEmailsOnPage.length,
numberEmailsFound: numberEmailsFound
},function(response) {});
} else {
chrome.runtime.sendMessage({
completedScan: "scanning page",
currentDomain: currentDomain
},function(response) {});
}
});
});
}
| Fixed message error again! | scripts/check_emails.js | Fixed message error again! | <ide><path>cripts/check_emails.js
<ide> allEmailsOnPage = concat_collection(allEmailsOnPage,allOtherEmailsOnPage);
<ide> }
<ide> // console.log(allEmailsOnPage);
<add> var currentDomain = document.location.hostname;
<add> currentDomain = currentDomain.replace("www.","");
<ide> if (allEmailsOnPage.length == 0 ) {
<ide> chrome.runtime.sendMessage({
<ide> completedScan: "true",
<ide> numberEmailsChecked: allEmailsOnPage.length,
<del> numberEmailsFound: 0
<add> numberEmailsFound: 0,
<add> currentDomain: currentDomain
<ide> },function(response) {});
<ide> } else {
<ide> addIntercomData();
<ide> chrome.runtime.sendMessage({
<ide> completedScan: "true",
<ide> numberEmailsChecked: allEmailsOnPage.length,
<del> numberEmailsFound: numberEmailsFound
<add> numberEmailsFound: numberEmailsFound,
<add> currentDomain: currentDomain
<ide> },function(response) {});
<ide> } else {
<ide> chrome.runtime.sendMessage({
<ide> chrome.runtime.sendMessage({
<ide> completedScan: "true",
<ide> numberEmailsChecked: allEmailsOnPage.length,
<del> numberEmailsFound: numberEmailsFound
<add> numberEmailsFound: numberEmailsFound,
<add> currentDomain: currentDomain
<ide> },function(response) {});
<ide> } else {
<ide> chrome.runtime.sendMessage({ |
|
Java | mit | a9fda4209e2213087c76d78a6329ab9e1ba4a6be | 0 | hgzojer/picturetrainer | package at.hgz.picturetrainer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.commons.io.IOUtils;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import at.hgz.picturetrainer.db.Dictionary;
import at.hgz.picturetrainer.db.Vocable;
import at.hgz.picturetrainer.db.VocableOpenHelper;
import at.hgz.picturetrainer.img.PictureUtil;
import at.hgz.picturetrainer.set.TrainingSet;
import at.hgz.picturetrainer.zip.ZipUtil;
import at.hgz.picturetrainer.zip.ZipUtil.Entity;
public class DictionaryListActivity extends ListActivity {
private static final int EDIT_ACTION = 1;
private static final int CONFIG_ACTION = 2;
private static final int IMPORT_ACTION = 3;
private List<Dictionary> list = new ArrayList<Dictionary>();
private DictionaryArrayAdapter adapter;
private String directionSymbol = "↔";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dictionary_list);
loadConfig();
loadDirectionSymbol();
loadDictionaryList();
adapter = new DictionaryArrayAdapter(this, R.layout.dictionary_list_item, list);
setListAdapter(adapter);
}
@Override
protected void onDestroy() {
saveConfig();
super.onDestroy();
}
@Override
protected void onPause() {
saveConfig();
super.onPause();
}
@Override
protected void onStop() {
saveConfig();
super.onStop();
}
private void loadConfig() {
SharedPreferences settings = DictionaryListActivity.this.getPreferences(MODE_PRIVATE);
int direction = settings.getInt(ConfigActivity.WORD_DIRECTION, TrainingSet.DIRECTION_BIDIRECTIONAL);
TrainingApplication.getState().setDirection(direction);
boolean playSound = settings.getBoolean(ConfigActivity.PLAY_SOUND, true);
TrainingApplication.getState().setPlaySound(playSound);
}
private void saveConfig() {
if (TrainingApplication.getState().hasConfigChanged()) {
SharedPreferences settings = this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(ConfigActivity.WORD_DIRECTION, TrainingApplication.getState().getDirection());
editor.putBoolean(ConfigActivity.PLAY_SOUND, TrainingApplication.getState().isPlaySound());
editor.commit();
TrainingApplication.getState().setConfigChanged(false);
}
}
private boolean isDictionarySelected() {
return TrainingApplication.getState().getDictionary() != null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.dictionary_list_menu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem exportToExternalStorage = menu.findItem(R.id.exportToExternalStorage);
exportToExternalStorage.setVisible(isDictionarySelected());
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addDictionary:
{
PictureUtil util = PictureUtil.getInstance(DictionaryListActivity.this);
byte[] image = util.getDefaultPicture();
TrainingApplication.getState().setDictionary(new Dictionary(-1, image, ""));
List<Vocable> vocables = new ArrayList<Vocable>(5);
vocables.add(new Vocable(-1, -1, image, ""));
vocables.add(new Vocable(-1, -1, image, ""));
vocables.add(new Vocable(-1, -1, image, ""));
vocables.add(new Vocable(-1, -1, image, ""));
vocables.add(new Vocable(-1, -1, image, ""));
TrainingApplication.getState().setVocables(vocables);
Intent intent = new Intent(DictionaryListActivity.this, VocableListActivity.class);
//intent.putExtra("dictionaryId", dictionaryId);
DictionaryListActivity.this.startActivityForResult(intent, EDIT_ACTION);
return true;
}
case R.id.openConfig:
{
Intent intent = new Intent(DictionaryListActivity.this, ConfigActivity.class);
//intent.putExtra("dictionaryId", dictionaryId);
DictionaryListActivity.this.startActivityForResult(intent, CONFIG_ACTION);
return true;
}
case R.id.exportToExternalStorage:
{
exportDictionaryToExternalStorage();
return true;
}
case R.id.importFromExternalStorage:
{
Intent intent = new Intent(DictionaryListActivity.this, ImportActivity.class);
DictionaryListActivity.this.startActivityForResult(intent, IMPORT_ACTION);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
private void exportDictionaryToExternalStorage() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
ZipUtil util = ZipUtil.getInstance();
Dictionary dictionary = TrainingApplication.getState().getDictionary();
List<Vocable> vocables = TrainingApplication.getState().getVocables();
byte[] dictionaryBytes = util.marshall(dictionary, vocables);
File storageDir = getExternalFilesDir(null);
if (!storageDir.exists()) {
if (!storageDir.mkdirs()) {
Log.d("DictionaryListActivity", "failed to create directory");
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
File file;
int i = 1;
do {
file = new File(storageDir, "DICT_"+ timeStamp + (i > 1 ? "_" + i : "") + ".pt");
i++;
} while (file.exists());
try {
OutputStream out = new FileOutputStream(file);
try {
out.write(dictionaryBytes);
out.flush();
} catch (IOException ex) {
} finally {
if (out != null) {
out.close();
}
}
} catch (IOException ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
String text = getResources().getString(R.string.exportedDictionary, file.getName());
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
} else {
String text = getResources().getString(R.string.errorExportingDictionary);
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
}
private void loadDictionaryList() {
VocableOpenHelper helper = VocableOpenHelper.getInstance(getApplicationContext());
list.clear();
for (Dictionary lib : helper.getDictionaries()) {
list.add(lib);
}
}
private void loadDirectionSymbol() {
int direction = TrainingApplication.getState().getDirection();
switch (direction) {
case TrainingSet.DIRECTION_FORWARD:
directionSymbol = "→";
break;
case TrainingSet.DIRECTION_BIDIRECTIONAL:
directionSymbol = "↔";
break;
case TrainingSet.DIRECTION_BACKWARD:
directionSymbol = "←";
break;
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
loadDictionaryVocables(position);
adapter.notifyDataSetChanged();
setSelection(position);
}
private void loadDictionaryVocables(final int position) {
VocableOpenHelper helper = VocableOpenHelper.getInstance(DictionaryListActivity.this);
Dictionary dictionary = list.get(position);
List<Vocable> vocables = helper.getVocables(dictionary.getId());
TrainingApplication.getState().setDictionary(dictionary);
TrainingApplication.getState().setVocables(vocables);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDIT_ACTION) {
String result = "";
if (resultCode == RESULT_OK) {
result = data.getStringExtra("result");
if ("save".equals(result)) {
int position = list.indexOf(TrainingApplication.getState().getDictionary());
loadDictionaryVocables(position);
adapter.notifyDataSetChanged();
setSelection(position);
} else if ("add".equals(result)) {
loadDictionaryList();
int position = list.size() - 1;
loadDictionaryVocables(position);
adapter.notifyDataSetChanged();
setSelection(position);
} else if ("delete".equals(result)) {
loadDictionaryList();
TrainingApplication.getState().setDictionary(null);
TrainingApplication.getState().setVocables(null);
adapter.notifyDataSetChanged();
}
}
if (resultCode == RESULT_CANCELED) {
}
}
if (requestCode == CONFIG_ACTION) {
loadDirectionSymbol();
adapter.notifyDataSetChanged();
}
if (requestCode == IMPORT_ACTION) {
if (resultCode == RESULT_OK) {
importDictionaryFromExternalStorage(data.getData());
loadDictionaryList();
int position = list.size() - 1;
loadDictionaryVocables(position);
adapter.notifyDataSetChanged();
setSelection(position);
}
if (resultCode == RESULT_CANCELED) {
}
}
}
private void importDictionaryFromExternalStorage(Uri importFile) {
try {
InputStream in = getContentResolver().openInputStream(importFile);
byte[] dictionaryBytes = IOUtils.toByteArray(in);
ZipUtil util = ZipUtil.getInstance();
Entity entity = util.unmarshall(dictionaryBytes);
Resources resources = getApplicationContext().getResources();
String text = resources.getString(R.string.importingDictionary);
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();
VocableOpenHelper helper = VocableOpenHelper.getInstance(getApplicationContext());
helper.persist(entity.getDictionary(), entity.getVocables());
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
private class DictionaryArrayAdapter extends ArrayAdapter<Dictionary> {
public DictionaryArrayAdapter(Context context, int resource,
List<Dictionary> objects) {
super(context, resource, objects);
}
private class ViewHolder {
public ImageView listItemPicture;
public TextView listItemName;
public Dictionary dictionary;
public TextView listItemCount;
public Button buttonEdit;
public Button buttonTraining;
public Button buttonMultipleChoice;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Dictionary dictionary = getItem(position);
PictureUtil util = PictureUtil
.getInstance(DictionaryListActivity.this);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.dictionary_list_item, parent, false);
final ViewHolder vh = new ViewHolder();
vh.listItemPicture = (ImageView) convertView.findViewById(R.id.listItemPicture);
vh.listItemName = (TextView) convertView.findViewById(R.id.listItemName);
vh.listItemCount = (TextView) convertView.findViewById(R.id.listItemCount);
vh.buttonEdit = (Button) convertView.findViewById(R.id.buttonEdit);
vh.buttonTraining = (Button) convertView.findViewById(R.id.buttonTraining);
vh.buttonMultipleChoice = (Button) convertView.findViewById(R.id.buttonMultipleChoice);
vh.buttonEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(DictionaryListActivity.this, VocableListActivity.class);
//intent.putExtra("dictionaryId", dictionaryId);
DictionaryListActivity.this.startActivityForResult(intent, EDIT_ACTION);
}
});
vh.buttonTraining.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(DictionaryListActivity.this, TrainingActivity.class);
//intent.putExtra("dictionaryId", dictionaryId);
DictionaryListActivity.this.startActivity(intent);
}
});
vh.buttonMultipleChoice.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(DictionaryListActivity.this, MultipleChoiceActivity.class);
//intent.putExtra("dictionaryId", dictionaryId);
DictionaryListActivity.this.startActivity(intent);
}
});
convertView.setTag(vh);
}
ViewHolder vh = (ViewHolder) convertView.getTag();
vh.dictionary = dictionary;
Drawable drawable = util.getDrawable(dictionary.getPicture());
vh.listItemPicture.setImageDrawable(drawable);
vh.listItemName.setText(String.format(" %s %s", directionSymbol, dictionary.getName()));
int visibility = View.GONE;
int visibilityTraining = View.GONE;
if (vh.dictionary == TrainingApplication.getState().getDictionary()) {
visibility = View.VISIBLE;
int count = TrainingApplication.getState().getVocables().size();
Resources resources = getApplicationContext().getResources();
vh.listItemCount.setText(resources.getString(R.string.count, count));
if (count > 0) {
visibilityTraining = View.VISIBLE;
}
vh.listItemCount.setText("");
}
vh.listItemCount.setVisibility(visibility);
vh.buttonEdit.setVisibility(visibility);
vh.buttonTraining.setVisibility(visibilityTraining);
vh.buttonMultipleChoice.setVisibility(visibilityTraining);
return convertView;
}
}
}
| src/at/hgz/picturetrainer/DictionaryListActivity.java | package at.hgz.picturetrainer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.commons.io.IOUtils;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import at.hgz.picturetrainer.db.Dictionary;
import at.hgz.picturetrainer.db.Vocable;
import at.hgz.picturetrainer.db.VocableOpenHelper;
import at.hgz.picturetrainer.img.PictureUtil;
import at.hgz.picturetrainer.set.TrainingSet;
import at.hgz.picturetrainer.zip.ZipUtil;
import at.hgz.picturetrainer.zip.ZipUtil.Entity;
public class DictionaryListActivity extends ListActivity {
private static final int EDIT_ACTION = 1;
private static final int CONFIG_ACTION = 2;
private static final int IMPORT_ACTION = 3;
private List<Dictionary> list = new ArrayList<Dictionary>();
private DictionaryArrayAdapter adapter;
private String directionSymbol = "↔";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dictionary_list);
loadConfig();
loadDictionaryList();
adapter = new DictionaryArrayAdapter(this, R.layout.dictionary_list_item, list);
setListAdapter(adapter);
}
@Override
protected void onDestroy() {
saveConfig();
super.onDestroy();
}
@Override
protected void onPause() {
saveConfig();
super.onPause();
}
@Override
protected void onStop() {
saveConfig();
super.onStop();
}
private void loadConfig() {
SharedPreferences settings = DictionaryListActivity.this.getPreferences(MODE_PRIVATE);
int direction = settings.getInt(ConfigActivity.WORD_DIRECTION, TrainingSet.DIRECTION_BIDIRECTIONAL);
TrainingApplication.getState().setDirection(direction);
boolean playSound = settings.getBoolean(ConfigActivity.PLAY_SOUND, true);
TrainingApplication.getState().setPlaySound(playSound);
}
private void saveConfig() {
if (TrainingApplication.getState().hasConfigChanged()) {
SharedPreferences settings = this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(ConfigActivity.WORD_DIRECTION, TrainingApplication.getState().getDirection());
editor.putBoolean(ConfigActivity.PLAY_SOUND, TrainingApplication.getState().isPlaySound());
editor.commit();
TrainingApplication.getState().setConfigChanged(false);
}
}
private boolean isDictionarySelected() {
return TrainingApplication.getState().getDictionary() != null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.dictionary_list_menu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem exportToExternalStorage = menu.findItem(R.id.exportToExternalStorage);
exportToExternalStorage.setVisible(isDictionarySelected());
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addDictionary:
{
PictureUtil util = PictureUtil.getInstance(DictionaryListActivity.this);
byte[] image = util.getDefaultPicture();
TrainingApplication.getState().setDictionary(new Dictionary(-1, image, ""));
List<Vocable> vocables = new ArrayList<Vocable>(5);
vocables.add(new Vocable(-1, -1, image, ""));
vocables.add(new Vocable(-1, -1, image, ""));
vocables.add(new Vocable(-1, -1, image, ""));
vocables.add(new Vocable(-1, -1, image, ""));
vocables.add(new Vocable(-1, -1, image, ""));
TrainingApplication.getState().setVocables(vocables);
Intent intent = new Intent(DictionaryListActivity.this, VocableListActivity.class);
//intent.putExtra("dictionaryId", dictionaryId);
DictionaryListActivity.this.startActivityForResult(intent, EDIT_ACTION);
return true;
}
case R.id.openConfig:
{
Intent intent = new Intent(DictionaryListActivity.this, ConfigActivity.class);
//intent.putExtra("dictionaryId", dictionaryId);
DictionaryListActivity.this.startActivityForResult(intent, CONFIG_ACTION);
return true;
}
case R.id.exportToExternalStorage:
{
exportDictionaryToExternalStorage();
return true;
}
case R.id.importFromExternalStorage:
{
Intent intent = new Intent(DictionaryListActivity.this, ImportActivity.class);
DictionaryListActivity.this.startActivityForResult(intent, IMPORT_ACTION);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
private void exportDictionaryToExternalStorage() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
ZipUtil util = ZipUtil.getInstance();
Dictionary dictionary = TrainingApplication.getState().getDictionary();
List<Vocable> vocables = TrainingApplication.getState().getVocables();
byte[] dictionaryBytes = util.marshall(dictionary, vocables);
File storageDir = getExternalFilesDir(null);
if (!storageDir.exists()) {
if (!storageDir.mkdirs()) {
Log.d("DictionaryListActivity", "failed to create directory");
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
File file;
int i = 1;
do {
file = new File(storageDir, "DICT_"+ timeStamp + (i > 1 ? "_" + i : "") + ".pt");
i++;
} while (file.exists());
try {
OutputStream out = new FileOutputStream(file);
try {
out.write(dictionaryBytes);
out.flush();
} catch (IOException ex) {
} finally {
if (out != null) {
out.close();
}
}
} catch (IOException ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
String text = getResources().getString(R.string.exportedDictionary, file.getName());
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
} else {
String text = getResources().getString(R.string.errorExportingDictionary);
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
}
private void loadDictionaryList() {
int direction = TrainingApplication.getState().getDirection();
switch (direction) {
case TrainingSet.DIRECTION_FORWARD:
directionSymbol = "→";
break;
case TrainingSet.DIRECTION_BIDIRECTIONAL:
directionSymbol = "↔";
break;
case TrainingSet.DIRECTION_BACKWARD:
directionSymbol = "←";
break;
}
VocableOpenHelper helper = VocableOpenHelper.getInstance(getApplicationContext());
list.clear();
for (Dictionary lib : helper.getDictionaries()) {
list.add(lib);
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
loadDictionaryVocables(position);
adapter.notifyDataSetChanged();
setSelection(position);
}
private void loadDictionaryVocables(final int position) {
VocableOpenHelper helper = VocableOpenHelper.getInstance(DictionaryListActivity.this);
Dictionary dictionary = list.get(position);
List<Vocable> vocables = helper.getVocables(dictionary.getId());
TrainingApplication.getState().setDictionary(dictionary);
TrainingApplication.getState().setVocables(vocables);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDIT_ACTION) {
String result = "";
if (resultCode == RESULT_OK) {
result = data.getStringExtra("result");
if ("save".equals(result)) {
int position = list.indexOf(TrainingApplication.getState().getDictionary());
loadDictionaryVocables(position);
adapter.notifyDataSetChanged();
setSelection(position);
} else if ("add".equals(result)) {
loadDictionaryList();
int position = list.size() - 1;
loadDictionaryVocables(position);
adapter.notifyDataSetChanged();
setSelection(position);
} else if ("delete".equals(result)) {
loadDictionaryList();
TrainingApplication.getState().setDictionary(null);
TrainingApplication.getState().setVocables(null);
adapter.notifyDataSetChanged();
}
}
if (resultCode == RESULT_CANCELED) {
}
}
if (requestCode == CONFIG_ACTION) {
adapter.notifyDataSetChanged();
}
if (requestCode == IMPORT_ACTION) {
if (resultCode == RESULT_OK) {
importDictionaryFromExternalStorage(data.getData());
loadDictionaryList();
int position = list.size() - 1;
loadDictionaryVocables(position);
adapter.notifyDataSetChanged();
setSelection(position);
}
if (resultCode == RESULT_CANCELED) {
}
}
}
private void importDictionaryFromExternalStorage(Uri importFile) {
try {
InputStream in = getContentResolver().openInputStream(importFile);
byte[] dictionaryBytes = IOUtils.toByteArray(in);
ZipUtil util = ZipUtil.getInstance();
Entity entity = util.unmarshall(dictionaryBytes);
Resources resources = getApplicationContext().getResources();
String text = resources.getString(R.string.importingDictionary);
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();
VocableOpenHelper helper = VocableOpenHelper.getInstance(getApplicationContext());
helper.persist(entity.getDictionary(), entity.getVocables());
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
private class DictionaryArrayAdapter extends ArrayAdapter<Dictionary> {
public DictionaryArrayAdapter(Context context, int resource,
List<Dictionary> objects) {
super(context, resource, objects);
}
private class ViewHolder {
public ImageView listItemPicture;
public TextView listItemName;
public Dictionary dictionary;
public TextView listItemCount;
public Button buttonEdit;
public Button buttonTraining;
public Button buttonMultipleChoice;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Dictionary dictionary = getItem(position);
PictureUtil util = PictureUtil
.getInstance(DictionaryListActivity.this);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.dictionary_list_item, parent, false);
final ViewHolder vh = new ViewHolder();
vh.listItemPicture = (ImageView) convertView.findViewById(R.id.listItemPicture);
vh.listItemName = (TextView) convertView.findViewById(R.id.listItemName);
vh.listItemCount = (TextView) convertView.findViewById(R.id.listItemCount);
vh.buttonEdit = (Button) convertView.findViewById(R.id.buttonEdit);
vh.buttonTraining = (Button) convertView.findViewById(R.id.buttonTraining);
vh.buttonMultipleChoice = (Button) convertView.findViewById(R.id.buttonMultipleChoice);
vh.buttonEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(DictionaryListActivity.this, VocableListActivity.class);
//intent.putExtra("dictionaryId", dictionaryId);
DictionaryListActivity.this.startActivityForResult(intent, EDIT_ACTION);
}
});
vh.buttonTraining.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(DictionaryListActivity.this, TrainingActivity.class);
//intent.putExtra("dictionaryId", dictionaryId);
DictionaryListActivity.this.startActivity(intent);
}
});
vh.buttonMultipleChoice.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(DictionaryListActivity.this, MultipleChoiceActivity.class);
//intent.putExtra("dictionaryId", dictionaryId);
DictionaryListActivity.this.startActivity(intent);
}
});
convertView.setTag(vh);
}
ViewHolder vh = (ViewHolder) convertView.getTag();
vh.dictionary = dictionary;
Drawable drawable = util.getDrawable(dictionary.getPicture());
vh.listItemPicture.setImageDrawable(drawable);
vh.listItemName.setText(String.format(" %s %s", directionSymbol, dictionary.getName()));
int visibility = View.GONE;
int visibilityTraining = View.GONE;
if (vh.dictionary == TrainingApplication.getState().getDictionary()) {
visibility = View.VISIBLE;
int count = TrainingApplication.getState().getVocables().size();
Resources resources = getApplicationContext().getResources();
vh.listItemCount.setText(resources.getString(R.string.count, count));
if (count > 0) {
visibilityTraining = View.VISIBLE;
}
vh.listItemCount.setText("");
}
vh.listItemCount.setVisibility(visibility);
vh.buttonEdit.setVisibility(visibility);
vh.buttonTraining.setVisibility(visibilityTraining);
vh.buttonMultipleChoice.setVisibility(visibilityTraining);
return convertView;
}
}
}
| bugfix translation direction config refresh
| src/at/hgz/picturetrainer/DictionaryListActivity.java | bugfix translation direction config refresh | <ide><path>rc/at/hgz/picturetrainer/DictionaryListActivity.java
<ide> setContentView(R.layout.activity_dictionary_list);
<ide>
<ide> loadConfig();
<add> loadDirectionSymbol();
<ide> loadDictionaryList();
<ide>
<ide> adapter = new DictionaryArrayAdapter(this, R.layout.dictionary_list_item, list);
<ide> }
<ide>
<ide> private void loadDictionaryList() {
<add> VocableOpenHelper helper = VocableOpenHelper.getInstance(getApplicationContext());
<add> list.clear();
<add> for (Dictionary lib : helper.getDictionaries()) {
<add> list.add(lib);
<add> }
<add> }
<add>
<add> private void loadDirectionSymbol() {
<ide> int direction = TrainingApplication.getState().getDirection();
<ide> switch (direction) {
<ide> case TrainingSet.DIRECTION_FORWARD:
<ide> case TrainingSet.DIRECTION_BACKWARD:
<ide> directionSymbol = "←";
<ide> break;
<del> }
<del>
<del> VocableOpenHelper helper = VocableOpenHelper.getInstance(getApplicationContext());
<del> list.clear();
<del> for (Dictionary lib : helper.getDictionaries()) {
<del> list.add(lib);
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> if (requestCode == CONFIG_ACTION) {
<add> loadDirectionSymbol();
<ide> adapter.notifyDataSetChanged();
<ide> }
<ide> |
|
Java | apache-2.0 | f1b01acd767dd8c2dc77a435d9a9737030104df1 | 0 | aika-algorithm/aika,aika-algorithm/aika | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package network.aika.network;
import network.aika.Document;
import network.aika.Model;
import network.aika.neuron.INeuron;
import network.aika.neuron.Neuron;
import network.aika.neuron.Synapse;
import network.aika.neuron.*;
import network.aika.neuron.activation.Range.Relation;
import network.aika.neuron.activation.Range;
import network.aika.lattice.OrNode;
import network.aika.neuron.activation.Selector;
import org.junit.Assert;
import org.junit.Test;
import static network.aika.neuron.activation.Range.Mapping.BEGIN;
import static network.aika.neuron.activation.Range.Mapping.END;
import static network.aika.neuron.activation.Range.Operator.GREATER_THAN;
import static network.aika.neuron.activation.Range.Operator.LESS_THAN;
import static network.aika.neuron.activation.Range.Relation.NONE;
import static network.aika.neuron.activation.Range.Operator.EQUALS;
/**
*
* @author Lukas Molzberger
*/
public class NegationTest {
@Test
public void testTwoNegativeInputs1() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron inB = m.createNeuron("B");
Neuron inC = m.createNeuron("C");
Neuron abcN = m.createNeuron("ABC");
Neuron.init(abcN,
5.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(10.0)
.setBias(-9.5)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inB)
.setWeight(-10.0)
.setBias(0.0)
.setRecurrent(true)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(2)
.setNeuron(inC)
.setWeight(-10.0)
.setBias(0.0)
.setRecurrent(true)
.setRangeOutput(true)
);
Document doc = m.createDocument("aaaaaaaaaaa", 0);
inA.addInput(doc, 0, 11);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(abcN.getActivation(doc, new Range(0, 11), false));
inB.addInput(doc, 2, 7);
System.out.println(doc.activationsToString(false, false, true));
inC.addInput(doc, 4, 9);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(abcN.getActivation(doc, new Range(0, 11), true));
}
@Test
public void testTwoNegativeInputs2() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron inB = m.createNeuron("B");
Neuron inC = m.createNeuron("C");
Neuron abcN = m.createNeuron("ABC");
Neuron outN = Neuron.init(m.createNeuron("OUT"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(abcN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
);
Neuron.init(abcN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inB)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0),
new Synapse.Builder()
.setSynapseId(2)
.setNeuron(inC)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0)
);
Document doc = m.createDocument("aaaaaaaaaaa", 0);
inA.addInput(doc, 0, 11);
System.out.println(doc.activationsToString(false, false, true));
inB.addInput(doc, 2, 7);
System.out.println(doc.activationsToString(false, false, true));
inC.addInput(doc, 4, 9);
System.out.println(doc.activationsToString(false, false, true));
// Assert.assertNull(Activation.get(t, outN.node, 0, new Range(0, 11), Range.Relation.EQUALS, null, null, null));
}
@Test
public void testSimpleNegation1() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron asN = m.createNeuron("AS");
Neuron inS = m.createNeuron("S");
Neuron outN = Neuron.init(m.createNeuron("OUT"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(asN)
.setWeight(1.0)
.setBias(0.0)
.setRecurrent(false)
.setRangeOutput(true)
);
Neuron.init(asN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setBias(-1.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inS)
.setWeight(-1.0)
.setBias(0.0)
.setRecurrent(true)
.addRangeRelation(Relation.EQUALS, 0)
);
Document doc = m.createDocument("aaaaaaaaaaa", 0);
inS.addInput(doc, 3, 8);
System.out.println(doc.activationsToString(false, false, true));
inA.addInput(doc, 0, 11);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(outN.getActivation(doc, new Range(0, 11), false));
doc.clearActivations();
}
@Test
public void testSimpleNegation2() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron asN = m.createNeuron("AS");
Neuron inS = m.createNeuron("S");
Neuron outN = Neuron.init(m.createNeuron("OUT"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(asN)
.setWeight(1.0)
.setBias(0.0)
.setRecurrent(false)
.setRangeOutput(true)
);
Neuron.init(asN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setBias(-1.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inS)
.setWeight(-1.0)
.setBias(0.0)
.setRecurrent(true)
.addRangeRelation(Relation.CONTAINS, 0)
);
Document doc = m.createDocument("aaaaaaaaaaa", 0);
inS.addInput(doc, 3, 8);
System.out.println(doc.activationsToString(false, false, true));
inA.addInput(doc, 0, 11);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(outN.getActivation(doc, new Range(0, 11), false));
doc.clearActivations();
}
@Test
public void testSimpleNegation3() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron asN = m.createNeuron("AS");
Neuron inS = m.createNeuron("S");
Neuron outN = Neuron.init(m.createNeuron("OUT"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(asN)
.setWeight(1.0)
.setBias(0.0)
.setRecurrent(false)
.setRangeOutput(true)
);
Neuron.init(asN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setBias(-1.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inS)
.setWeight(-1.0)
.setBias(0.0)
.setRecurrent(true)
.addRangeRelation(Relation.CONTAINS, 0)
);
Document doc = m.createDocument("aaaaaaaaaaa", 0);
inA.addInput(doc, 0, 11);
System.out.println(doc.activationsToString(false, false, true));
inS.addInput(doc, 3, 8);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(outN.getActivation(doc, new Range(0, 11), false));
doc.clearActivations();
}
@Test
public void testNegation1() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron inB = m.createNeuron("B");
Neuron asN = m.createNeuron("AS");
Neuron absN = m.createNeuron("ABS");
Neuron bsN = m.createNeuron("BS");
Neuron inS = Neuron.init(m.createNeuron("S"),
0.0,
INeuron.Type.INHIBITORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(asN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(absN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true)
);
Neuron.init(asN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inS)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0)
.addRangeRelation(Relation.CONTAINS, 0)
);
Neuron.init(absN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.addRangeRelation(Relation.create(Range.Operator.NONE, Range.Operator.NONE, Range.Operator.NONE, GREATER_THAN), 1)
.setRangeOutput(true, false),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inB)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.setRangeOutput(false, true),
new Synapse.Builder()
.setSynapseId(2)
.setNeuron(inS)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0)
.addRangeRelation(Relation.OVERLAPS, 0)
.addRangeRelation(Relation.OVERLAPS, 1)
);
{
Document doc = m.createDocument("aaaaaaaaaa", 0);
inA.addInput(doc, 0, 6);
System.out.println(doc.activationsToString(false, false, true));
inB.addInput(doc, 0, 6);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(inS.getActivation(doc, new Range(0, 6), false));
Assert.assertEquals(2, inS.getActivation(doc, new Range(0, 6), false).neuronInputs.size());
doc.clearActivations();
}
{
Document doc = m.createDocument("aaaaaaaaaa", 0);
inA.addInput(doc, 0, 6);
System.out.println(doc.activationsToString(false, false, true));
inB.addInput(doc, 3, 9);
System.out.println(doc.activationsToString(false, false, true));
// Assert.assertNotNull(Selector.get(t, inS.node, 0, new Range(0, 6), EQUALS, EQUALS, null, null, null));
Assert.assertNotNull(inS.getActivation(doc, new Range(0, 9), false));
// Assert.assertEquals(1, Activation.get(t, inS.node, 0, new Range(0, 6), EQUALS, EQUALS, null, null, null).key.interpretation.orInterprNodes.size());
Assert.assertEquals(1, inS.getActivation(doc, new Range(0, 6), false).neuronInputs.size());
Assert.assertEquals(1, inS.getActivation(doc, new Range(0, 9), false).neuronInputs.size());
doc.clearActivations();
}
}
@Test
public void testNegation2() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron inB = m.createNeuron("B");
Neuron inC = m.createNeuron("C");
Neuron asN = m.createNeuron("AS");
Neuron ascN = m.createNeuron("ASC");
Neuron bsN = m.createNeuron("BS");
Neuron inS = Neuron.init(m.createNeuron("S"),
0.0,
INeuron.Type.INHIBITORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(asN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(ascN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(2)
.setNeuron(bsN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true)
);
Neuron.init(asN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inS)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0)
.addRangeRelation(Relation.EQUALS, 0)
.setRangeOutput(true)
);
Neuron.init(ascN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inC)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.addRangeRelation(Relation.EQUALS, 0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(2)
.setNeuron(inS)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0)
.addRangeRelation(Relation.EQUALS, 0)
.setRangeOutput(true)
);
Neuron.init(bsN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inB)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inS)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0)
.addRangeRelation(Relation.EQUALS, 0)
.setRangeOutput(true)
);
Neuron outA = Neuron.init(m.createNeuron("OUT A"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(asN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true)
);
Neuron outAC = Neuron.init(m.createNeuron("OUT AC"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(ascN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true)
);
Neuron outB = Neuron.init(m.createNeuron("OUT B"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(bsN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true)
);
Document doc = m.createDocument("aaaaaaaaaa", 0);
inA.addInput(doc, 0, 6);
System.out.println(doc.activationsToString(false, false, true));
inB.addInput(doc, 0, 6);
System.out.println(doc.activationsToString(false, false, true));
inC.addInput(doc, 0, 6);
System.out.println(doc.activationsToString(false, false, true));
doc.process();
System.out.println(doc.activationsToString( true, false, true));
}
/**
*
* -----
* A ---| & |------
* -*| C | | ------
* | ------ | G---| & |
* \ | | H |-----
* \/-----------------| |
* /\-----------------| |
* / | ------
* | ------ |
* -*| & |------
* B ---| D |
* ------
*
*/
@Test
public void testOptions() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron inB = m.createNeuron("B");
Neuron pC = m.createNeuron("C");
Neuron pD = m.createNeuron("D");
Neuron.init(pC,
0.5,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(2.0)
.setBias(-2.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(pD)
.setWeight(-2.0)
.setBias(0.0)
.setRecurrent(true)
);
Neuron.init(pD,
0.5,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inB)
.setWeight(2.0)
.setBias(-2.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(pC)
.setWeight(-2.0)
.setBias(0.0)
.setRecurrent(true)
);
Neuron inG = m.createNeuron("G");
OrNode inGNode = inG.get().node.get();
Neuron pH = Neuron.init(m.createNeuron("H"),
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(pC)
.setBias(-2.0)
.setWeight(2.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(pD)
.setWeight(2.0)
.setBias(-2.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(2)
.setNeuron(inG)
.setWeight(2.0)
.setBias(-2.0)
.setRecurrent(false)
.setRangeOutput(true)
);
Document doc = m.createDocument("aaaaaaaaaa", 0);
inA.addInput(doc, 0, 1);
inB.addInput(doc, 0, 1);
inG.addInput(doc, 0, 1);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(pC.get().getActivation(doc, new Range(0, 1), false));
Assert.assertNotNull(pD.get().getActivation(doc, new Range(0, 1), false));
// Die Optionen 0 und 2 stehen in Konflikt. Da sie aber jetzt in Oder Optionen eingebettet sind, werden sie nicht mehr ausgefiltert.
// Assert.assertNull(pH.node.getFirstActivation(t));
}
}
| src/test/java/network/aika/network/NegationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package network.aika.network;
import network.aika.Document;
import network.aika.Model;
import network.aika.neuron.INeuron;
import network.aika.neuron.Neuron;
import network.aika.neuron.Synapse;
import network.aika.neuron.*;
import network.aika.neuron.activation.Range.Relation;
import network.aika.neuron.activation.Range;
import network.aika.lattice.OrNode;
import network.aika.neuron.activation.Selector;
import org.junit.Assert;
import org.junit.Test;
import static network.aika.neuron.activation.Range.Mapping.BEGIN;
import static network.aika.neuron.activation.Range.Mapping.END;
import static network.aika.neuron.activation.Range.Relation.NONE;
import static network.aika.neuron.activation.Range.Operator.EQUALS;
/**
*
* @author Lukas Molzberger
*/
public class NegationTest {
@Test
public void testTwoNegativeInputs1() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron inB = m.createNeuron("B");
Neuron inC = m.createNeuron("C");
Neuron abcN = m.createNeuron("ABC");
Neuron.init(abcN,
5.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(10.0)
.setBias(-9.5)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inB)
.setWeight(-10.0)
.setBias(0.0)
.setRecurrent(true)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(2)
.setNeuron(inC)
.setWeight(-10.0)
.setBias(0.0)
.setRecurrent(true)
.setRangeOutput(true)
);
Document doc = m.createDocument("aaaaaaaaaaa", 0);
inA.addInput(doc, 0, 11);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(abcN.getActivation(doc, new Range(0, 11), false));
inB.addInput(doc, 2, 7);
System.out.println(doc.activationsToString(false, false, true));
inC.addInput(doc, 4, 9);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(abcN.getActivation(doc, new Range(0, 11), true));
}
@Test
public void testTwoNegativeInputs2() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron inB = m.createNeuron("B");
Neuron inC = m.createNeuron("C");
Neuron abcN = m.createNeuron("ABC");
Neuron outN = Neuron.init(m.createNeuron("OUT"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(abcN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
);
Neuron.init(abcN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inB)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0),
new Synapse.Builder()
.setSynapseId(2)
.setNeuron(inC)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0)
);
Document doc = m.createDocument("aaaaaaaaaaa", 0);
inA.addInput(doc, 0, 11);
System.out.println(doc.activationsToString(false, false, true));
inB.addInput(doc, 2, 7);
System.out.println(doc.activationsToString(false, false, true));
inC.addInput(doc, 4, 9);
System.out.println(doc.activationsToString(false, false, true));
// Assert.assertNull(Activation.get(t, outN.node, 0, new Range(0, 11), Range.Relation.EQUALS, null, null, null));
}
@Test
public void testSimpleNegation1() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron asN = m.createNeuron("AS");
Neuron inS = m.createNeuron("S");
Neuron outN = Neuron.init(m.createNeuron("OUT"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(asN)
.setWeight(1.0)
.setBias(0.0)
.setRecurrent(false)
.setRangeOutput(true)
);
Neuron.init(asN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setBias(-1.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inS)
.setWeight(-1.0)
.setBias(0.0)
.setRecurrent(true)
.addRangeRelation(Relation.EQUALS, 0)
);
Document doc = m.createDocument("aaaaaaaaaaa", 0);
inS.addInput(doc, 3, 8);
System.out.println(doc.activationsToString(false, false, true));
inA.addInput(doc, 0, 11);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(outN.getActivation(doc, new Range(0, 11), false));
doc.clearActivations();
}
@Test
public void testSimpleNegation2() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron asN = m.createNeuron("AS");
Neuron inS = m.createNeuron("S");
Neuron outN = Neuron.init(m.createNeuron("OUT"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(asN)
.setWeight(1.0)
.setBias(0.0)
.setRecurrent(false)
.setRangeOutput(true)
);
Neuron.init(asN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setBias(-1.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inS)
.setWeight(-1.0)
.setBias(0.0)
.setRecurrent(true)
.addRangeRelation(Relation.CONTAINS, 0)
);
Document doc = m.createDocument("aaaaaaaaaaa", 0);
inS.addInput(doc, 3, 8);
System.out.println(doc.activationsToString(false, false, true));
inA.addInput(doc, 0, 11);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(outN.getActivation(doc, new Range(0, 11), false));
doc.clearActivations();
}
@Test
public void testSimpleNegation3() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron asN = m.createNeuron("AS");
Neuron inS = m.createNeuron("S");
Neuron outN = Neuron.init(m.createNeuron("OUT"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(asN)
.setWeight(1.0)
.setBias(0.0)
.setRecurrent(false)
.setRangeOutput(true)
);
Neuron.init(asN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setBias(-1.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inS)
.setWeight(-1.0)
.setBias(0.0)
.setRecurrent(true)
.addRangeRelation(Relation.CONTAINS, 0)
);
Document doc = m.createDocument("aaaaaaaaaaa", 0);
inA.addInput(doc, 0, 11);
System.out.println(doc.activationsToString(false, false, true));
inS.addInput(doc, 3, 8);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(outN.getActivation(doc, new Range(0, 11), false));
doc.clearActivations();
}
@Test
public void testNegation1() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron inB = m.createNeuron("B");
Neuron asN = m.createNeuron("AS");
Neuron absN = m.createNeuron("ABS");
Neuron bsN = m.createNeuron("BS");
Neuron inS = Neuron.init(m.createNeuron("S"),
0.0,
INeuron.Type.INHIBITORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(asN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(absN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true)
);
Neuron.init(asN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inS)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0)
.addRangeRelation(Relation.CONTAINS, 0)
);
Neuron.init(absN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.addRangeRelation(Relation.EQUALS, 1)
.setRangeOutput(BEGIN, Range.Mapping.NONE),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inB)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.setRangeOutput(Range.Mapping.NONE, END),
new Synapse.Builder()
.setSynapseId(2)
.setNeuron(inS)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0)
.addRangeRelation(Relation.OVERLAPS, 0)
.addRangeRelation(Relation.OVERLAPS, 1)
);
{
Document doc = m.createDocument("aaaaaaaaaa", 0);
inA.addInput(doc, 0, 6);
System.out.println(doc.activationsToString(false, false, true));
inB.addInput(doc, 0, 6);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(inS.getActivation(doc, new Range(0, 6), false));
Assert.assertEquals(2, inS.getActivation(doc, new Range(0, 6), false).neuronInputs.size());
doc.clearActivations();
}
{
Document doc = m.createDocument("aaaaaaaaaa", 0);
inA.addInput(doc, 0, 6);
System.out.println(doc.activationsToString(false, false, true));
inB.addInput(doc, 3, 9);
System.out.println(doc.activationsToString(false, false, true));
// Assert.assertNotNull(Selector.get(t, inS.node, 0, new Range(0, 6), EQUALS, EQUALS, null, null, null));
Assert.assertNotNull(inS.getActivation(doc, new Range(0, 9), false));
// Assert.assertEquals(1, Activation.get(t, inS.node, 0, new Range(0, 6), EQUALS, EQUALS, null, null, null).key.interpretation.orInterprNodes.size());
Assert.assertEquals(1, inS.getActivation(doc, new Range(0, 6), false).neuronInputs.size());
Assert.assertEquals(1, inS.getActivation(doc, new Range(0, 9), false).neuronInputs.size());
doc.clearActivations();
}
}
@Test
public void testNegation2() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron inB = m.createNeuron("B");
Neuron inC = m.createNeuron("C");
Neuron asN = m.createNeuron("AS");
Neuron ascN = m.createNeuron("ASC");
Neuron bsN = m.createNeuron("BS");
Neuron inS = Neuron.init(m.createNeuron("S"),
0.0,
INeuron.Type.INHIBITORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(asN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(ascN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(2)
.setNeuron(bsN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true)
);
Neuron.init(asN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inS)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0)
.addRangeRelation(Relation.EQUALS, 0)
.setRangeOutput(true)
);
Neuron.init(ascN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inC)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.addRangeRelation(Relation.EQUALS, 0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(2)
.setNeuron(inS)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0)
.addRangeRelation(Relation.EQUALS, 0)
.setRangeOutput(true)
);
Neuron.init(bsN,
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inB)
.setWeight(1.0)
.setRecurrent(false)
.setBias(-1.0)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inS)
.setWeight(-1.0)
.setRecurrent(true)
.setBias(0.0)
.addRangeRelation(Relation.EQUALS, 0)
.setRangeOutput(true)
);
Neuron outA = Neuron.init(m.createNeuron("OUT A"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(asN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true)
);
Neuron outAC = Neuron.init(m.createNeuron("OUT AC"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(ascN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true)
);
Neuron outB = Neuron.init(m.createNeuron("OUT B"),
0.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(bsN)
.setWeight(1.0)
.setRecurrent(false)
.setBias(0.0)
.setRangeOutput(true)
);
Document doc = m.createDocument("aaaaaaaaaa", 0);
inA.addInput(doc, 0, 6);
System.out.println(doc.activationsToString(false, false, true));
inB.addInput(doc, 0, 6);
System.out.println(doc.activationsToString(false, false, true));
inC.addInput(doc, 0, 6);
System.out.println(doc.activationsToString(false, false, true));
doc.process();
System.out.println(doc.activationsToString( true, false, true));
}
/**
*
* -----
* A ---| & |------
* -*| C | | ------
* | ------ | G---| & |
* \ | | H |-----
* \/-----------------| |
* /\-----------------| |
* / | ------
* | ------ |
* -*| & |------
* B ---| D |
* ------
*
*/
@Test
public void testOptions() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron inB = m.createNeuron("B");
Neuron pC = m.createNeuron("C");
Neuron pD = m.createNeuron("D");
Neuron.init(pC,
0.5,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(2.0)
.setBias(-2.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(pD)
.setWeight(-2.0)
.setBias(0.0)
.setRecurrent(true)
);
Neuron.init(pD,
0.5,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inB)
.setWeight(2.0)
.setBias(-2.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(pC)
.setWeight(-2.0)
.setBias(0.0)
.setRecurrent(true)
);
Neuron inG = m.createNeuron("G");
OrNode inGNode = inG.get().node.get();
Neuron pH = Neuron.init(m.createNeuron("H"),
0.001,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(pC)
.setBias(-2.0)
.setWeight(2.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(pD)
.setWeight(2.0)
.setBias(-2.0)
.setRecurrent(false)
.setRangeOutput(true),
new Synapse.Builder()
.setSynapseId(2)
.setNeuron(inG)
.setWeight(2.0)
.setBias(-2.0)
.setRecurrent(false)
.setRangeOutput(true)
);
Document doc = m.createDocument("aaaaaaaaaa", 0);
inA.addInput(doc, 0, 1);
inB.addInput(doc, 0, 1);
inG.addInput(doc, 0, 1);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(pC.get().getActivation(doc, new Range(0, 1), false));
Assert.assertNotNull(pD.get().getActivation(doc, new Range(0, 1), false));
// Die Optionen 0 und 2 stehen in Konflikt. Da sie aber jetzt in Oder Optionen eingebettet sind, werden sie nicht mehr ausgefiltert.
// Assert.assertNull(pH.node.getFirstActivation(t));
}
}
| fixed test case
| src/test/java/network/aika/network/NegationTest.java | fixed test case | <ide><path>rc/test/java/network/aika/network/NegationTest.java
<ide>
<ide> import static network.aika.neuron.activation.Range.Mapping.BEGIN;
<ide> import static network.aika.neuron.activation.Range.Mapping.END;
<add>import static network.aika.neuron.activation.Range.Operator.GREATER_THAN;
<add>import static network.aika.neuron.activation.Range.Operator.LESS_THAN;
<ide> import static network.aika.neuron.activation.Range.Relation.NONE;
<ide> import static network.aika.neuron.activation.Range.Operator.EQUALS;
<ide>
<ide> .setWeight(1.0)
<ide> .setRecurrent(false)
<ide> .setBias(-1.0)
<del> .addRangeRelation(Relation.EQUALS, 1)
<del> .setRangeOutput(BEGIN, Range.Mapping.NONE),
<add> .addRangeRelation(Relation.create(Range.Operator.NONE, Range.Operator.NONE, Range.Operator.NONE, GREATER_THAN), 1)
<add> .setRangeOutput(true, false),
<ide> new Synapse.Builder()
<ide> .setSynapseId(1)
<ide> .setNeuron(inB)
<ide> .setWeight(1.0)
<ide> .setRecurrent(false)
<ide> .setBias(-1.0)
<del> .setRangeOutput(Range.Mapping.NONE, END),
<add> .setRangeOutput(false, true),
<ide> new Synapse.Builder()
<ide> .setSynapseId(2)
<ide> .setNeuron(inS) |
|
JavaScript | apache-2.0 | 9cbe2d25f0552d57ff7c8c8b0b6e3158dc375cfa | 0 | harish2704/html-scrapper,harish2704/html-scrapper | /*jslint node: true, stupid: true*/
/*global */
var fs = require('fs');
var Cookie = require('tough-cookie');
var async = require('async');
var request = require('request');
var URL = require('url');
var _ = require('lodash');
var headers = {
'User-Argent' :'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/33.0.1750.152 Chrome/33.0.1750.152 Safari/537.36'
};
/**
* A simple class imitating a web-browser. It can be considered as a wrapper around famous 'request' module.
* Current implementation is very limited .
* Only get method is implemented. It can be done very easily.
*
* @param {Object} opts - Option object.
* @param {Object} opts.headers - [optional] additional headers used for all requests.
* default:
* ```js
*
* var headers = {
* 'User-Argent' :'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/33.0.1750.152 Chrome/33.0.1750.152 Safari/537.36'
* };
* ```
* @param {String} opts.proxy - [optional] proxy parameter that will be passed to request module.
* default: null
* @param {tough.CookieJar} opts.jar - [optional] Cookie.jar instance used for for the Browser. default ```request.jar()```
* It should be an instance of 'tough-cookie' jar;
* @return {undefined}
* @class
*/
function Browser ( opts ){
opts = opts || {};
// Members
this.headers = _.defaults({}, headers, opts.headers );
this.proxy = opts.proxy;
this.jar = opts.jar || request.jar();
}
/**
* make a HTTP/GET request.
*
* @param {String|Object} opts - If url a string is given, It is used as URL string. Else, It is passed to request.get with instance specific headers and jar settings.
* @param {function} cb - callback function. passed directly to request.get.
* @return {request}
*/
Browser.prototype.get = function( opts, cb ){
if( opts.constructor.name == 'Object'){
opts = _.clone(opts);
opts.headers = _.defaults( {}, this.headers, opts.headers );
} else {
opts = {
url: opts,
headers: this.headers
};
}
opts.jar = this.jar;
if(this.proxy){
opts.proxy = this.proxy;
}
return request.get(opts, cb);
};
module.exports = Browser;
| lib/Browser.js | /*jslint node: true, stupid: true*/
/*global */
var fs = require('fs');
var Cookie = require('tough-cookie');
var async = require('async');
var request = require('request');
var URL = require('url');
var _ = require('lodash');
var headers = {
'User-Argent' :'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/33.0.1750.152 Chrome/33.0.1750.152 Safari/537.36'
};
/**
* A simple class imitating a web-browser. It can be considered as a wrapper around famous 'request' module.
* Current implementation is very limited .
* Only get method is implemented. It can be done very easily.
*
* @param {Object} opts - Option object.
* @param {Object} opts.headers - [optional] additional headers used for all requests.
* default:
* ```js
*
* var headers = {
* 'User-Argent' :'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/33.0.1750.152 Chrome/33.0.1750.152 Safari/537.36'
* };
* ```
* @param {String} opts.proxy - [optional] proxy parameter that will be passed to request module.
* default: null
* @param {tough.CookieJar} jar - [optional] Cookie.jar instance used for for the Browser. default ```request.jar()```
* It should be an instance of 'tough-cookie' jar;
* @return {undefined}
* @class
*/
function Browser ( opts ){
opts = opts || {};
// Members
this.headers = _.defaults({}, headers, opts.headers );
this.proxy = opts.proxy;
this.jar = opts.jar || request.jar();
}
/**
* make a HTTP/GET request.
*
* @param {String|Object} opts - If url a string is given, It is used as URL string. Else, It is passed to request.get with instance specific headers and jar settings.
* @param {function} cb - callback function. passed directly to request.get.
* @return {request}
*/
Browser.prototype.get = function( opts, cb ){
if( opts.constructor.name == 'Object'){
opts = _.clone(opts);
opts.headers = _.defaults( {}, this.headers, opts.headers );
} else {
opts = {
url: opts,
headers: this.headers
};
}
opts.jar = this.jar;
if(this.proxy){
opts.proxy = this.proxy;
}
return request.get(opts, cb);
};
module.exports = Browser;
| Fix Docs
| lib/Browser.js | Fix Docs | <ide><path>ib/Browser.js
<ide> * ```
<ide> * @param {String} opts.proxy - [optional] proxy parameter that will be passed to request module.
<ide> * default: null
<del> * @param {tough.CookieJar} jar - [optional] Cookie.jar instance used for for the Browser. default ```request.jar()```
<add> * @param {tough.CookieJar} opts.jar - [optional] Cookie.jar instance used for for the Browser. default ```request.jar()```
<ide> * It should be an instance of 'tough-cookie' jar;
<ide> * @return {undefined}
<ide> * @class |
|
Java | apache-2.0 | 319c14237aa883175e75c447e107023e7836a926 | 0 | Aeronica/mxTune | package net.aeronica.libs.mml.core;
public class StatePart
{
private int volume;
private boolean volumeArcheAge;
private int octave;
private int mmlLength;
private boolean dotted;
private long runningTicks;
private boolean tied;
StatePart() {this.init();}
public void init()
{
volume = 8;
volumeArcheAge = false;
octave = 4;
mmlLength = 4;
dotted = false;
runningTicks = 0;
tied = false;
}
@Override
public String toString()
{
return "@PartState: oct=" + octave + ", vol=" + volume + ", mmlLength=" + mmlLength + " ,runningTicks=" + runningTicks + ", tied=" + tied;
}
public int getVolume()
{
if (this.volumeArcheAge)
return volume;
else
return getMinMax(0, 127, volume * 127 / 15);
}
public void setVolume(int volume)
{
this.volume = getMinMax(0, 127, volume);
if (this.volume > 15)
volumeArcheAge = true;
}
public int getOctave() {return octave;}
public void setOctave(int octave) {this.octave = getMinMax(1, 8, octave);}
/**
* You can <<<< an octave to 0, but you can't
* set octave to 0 via the octave command: o0
*/
public void downOctave() {this.octave = getMinMax(0, 8, this.octave - 1);}
public void upOctave() {this.octave = getMinMax(1, 8, this.octave + 1);}
public int getMMLLength() {return mmlLength;}
public boolean isDotted() {return dotted;}
public void setMMLLength(int mmlLength, boolean dotted)
{
this.mmlLength = getMinMax(1, 64, mmlLength);
this.dotted = dotted;
}
public void accumulateTicks(long n) {this.runningTicks = this.runningTicks + n;}
public long getRunningTicks() {return runningTicks;}
public boolean isTied() {return tied;}
public void setTied(boolean tied) {this.tied = tied;}
private int getMinMax(int min, int max, int value) {return (int) Math.max(Math.min(max, value), min);}
}
| src/main/java/net/aeronica/libs/mml/core/StatePart.java | package net.aeronica.libs.mml.core;
public class StatePart
{
private int volume;
private boolean volumeArcheAge;
private int octave;
private int mmlLength;
private boolean dotted;
private long runningTicks;
private boolean tied;
StatePart() {this.init();}
public void init()
{
volume = 8;
volumeArcheAge = false;
octave = 4;
mmlLength = 4;
dotted = false;
runningTicks = 0;
tied = false;
}
@Override
public String toString()
{
return "@PartState: oct=" + octave + ", vol=" + volume + ", mmlLength=" + mmlLength + " ,runningTicks=" + runningTicks + ", tied=" + tied;
}
public int getVolume()
{
if (this.volumeArcheAge)
return volume;
else
return getMinMax(0, 127, volume * 128 / 15);
}
public void setVolume(int volume)
{
this.volume = getMinMax(0, 127, volume);
if (this.volume > 15)
volumeArcheAge = true;
}
public int getOctave() {return octave;}
public void setOctave(int octave) {this.octave = getMinMax(1, 8, octave);}
/**
* You can <<<< an octave to 0, but you can't
* set octave to 0 via the octave command: o0
*/
public void downOctave() {this.octave = getMinMax(0, 8, this.octave - 1);}
public void upOctave() {this.octave = getMinMax(1, 8, this.octave + 1);}
public int getMMLLength() {return mmlLength;}
public boolean isDotted() {return dotted;}
public void setMMLLength(int mmlLength, boolean dotted)
{
this.mmlLength = getMinMax(1, 64, mmlLength);
this.dotted = dotted;
}
public void accumulateTicks(long n) {this.runningTicks = this.runningTicks + n;}
public long getRunningTicks() {return runningTicks;}
public boolean isTied() {return tied;}
public void setTied(boolean tied) {this.tied = tied;}
private int getMinMax(int min, int max, int value) {return (int) Math.max(Math.min(max, value), min);}
}
| Splitting hairs
| src/main/java/net/aeronica/libs/mml/core/StatePart.java | Splitting hairs | <ide><path>rc/main/java/net/aeronica/libs/mml/core/StatePart.java
<ide> if (this.volumeArcheAge)
<ide> return volume;
<ide> else
<del> return getMinMax(0, 127, volume * 128 / 15);
<add> return getMinMax(0, 127, volume * 127 / 15);
<ide> }
<ide>
<ide> public void setVolume(int volume) |
|
Java | apache-2.0 | 97b9c9684587f45e552db8e86a00387d927a2874 | 0 | alipay/SoloPi,alipay/SoloPi,alipay/SoloPi | /*
* Copyright (C) 2015-present, Ant Financial Services Group
*
* 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.
*/
package com.alipay.hulu.shared.node.tree.export.bean;
import android.os.Parcel;
import android.os.Parcelable;
import com.alipay.hulu.common.utils.StringUtil;
import com.alipay.hulu.shared.node.action.OperationMethod;
import com.alipay.hulu.shared.node.tree.OperationNode;
/**
* 操作步骤
* Created by cathor on 2017/12/12.
*/
public class OperationStep implements Parcelable {
/**
* 操作节点
*/
private OperationNode operationNode;
/**
* 操作方法
*/
private OperationMethod operationMethod;
/**
* 操作顺序
*/
private int operationIndex;
/**
* 操作ID
*/
private String operationId;
private String stepId;
@Override
public int describeContents() {
return operationNode.describeContents() | operationMethod.describeContents();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(operationNode, flags);
dest.writeParcelable(operationMethod, flags);
dest.writeInt(operationIndex);
dest.writeString(operationId);
dest.writeString(stepId);
}
public static final Creator<OperationStep> CREATOR = new Creator<OperationStep>() {
@Override
public OperationStep createFromParcel(Parcel source) {
return new OperationStep(source);
}
@Override
public OperationStep[] newArray(int size) {
return new OperationStep[size];
}
};
public OperationStep(){
stepId = StringUtil.generateRandomString(10);
}
private OperationStep(Parcel in) {
operationNode = in.readParcelable(OperationNode.class.getClassLoader());
operationMethod = in.readParcelable(OperationMethod.class.getClassLoader());
operationIndex = in.readInt();
operationId = in.readString();
stepId = in.readString();
}
/**
* Getter method for property <tt>operationNode</tt>.
*
* @return property value of operationNode
*/
public OperationNode getOperationNode() {
return operationNode;
}
/**
* Setter method for property <tt>operationNode</tt>.
*
* @param operationNode value to be assigned to property operationNode
*/
public void setOperationNode(OperationNode operationNode) {
this.operationNode = operationNode;
}
/**
* Getter method for property <tt>operationMethod</tt>.
*
* @return property value of operationMethod
*/
public OperationMethod getOperationMethod() {
return operationMethod;
}
/**
* Setter method for property <tt>operationMethod</tt>.
*
* @param operationMethod value to be assigned to property operationMethod
*/
public void setOperationMethod(OperationMethod operationMethod) {
this.operationMethod = operationMethod;
}
/**
* Getter method for property <tt>operationIndex</tt>.
*
* @return property value of operationIndex
*/
public int getOperationIndex() {
return operationIndex;
}
/**
* Setter method for property <tt>operationIndex</tt>.
*
* @param operationIndex value to be assigned to property operationIndex
*/
public void setOperationIndex(int operationIndex) {
this.operationIndex = operationIndex;
}
/**
* Getter method for property <tt>operationId</tt>.
*
* @return property value of operationId
*/
public String getOperationId() {
return operationId;
}
/**
* Setter method for property <tt>operationId</tt>.
*
* @param operationId value to be assigned to property operationId
*/
public void setOperationId(String operationId) {
this.operationId = operationId;
}
public String getStepId() {
return stepId;
}
public void setStepId(String stepId) {
this.stepId = stepId;
}
}
| src/shared/src/main/java/com/alipay/hulu/shared/node/tree/export/bean/OperationStep.java | /*
* Copyright (C) 2015-present, Ant Financial Services Group
*
* 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.
*/
package com.alipay.hulu.shared.node.tree.export.bean;
import android.os.Parcel;
import android.os.Parcelable;
import com.alipay.hulu.shared.node.action.OperationMethod;
import com.alipay.hulu.shared.node.tree.OperationNode;
/**
* 操作步骤
* Created by cathor on 2017/12/12.
*/
public class OperationStep implements Parcelable {
/**
* 操作节点
*/
private OperationNode operationNode;
/**
* 操作方法
*/
private OperationMethod operationMethod;
/**
* 操作顺序
*/
private int operationIndex;
/**
* 操作ID
*/
private String operationId;
@Override
public int describeContents() {
return operationNode.describeContents() | operationMethod.describeContents();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(operationNode, flags);
dest.writeParcelable(operationMethod, flags);
dest.writeInt(operationIndex);
dest.writeString(operationId);
}
public static final Creator<OperationStep> CREATOR = new Creator<OperationStep>() {
@Override
public OperationStep createFromParcel(Parcel source) {
return new OperationStep(source);
}
@Override
public OperationStep[] newArray(int size) {
return new OperationStep[size];
}
};
public OperationStep(){}
private OperationStep(Parcel in) {
operationNode = in.readParcelable(OperationNode.class.getClassLoader());
operationMethod = in.readParcelable(OperationMethod.class.getClassLoader());
operationIndex = in.readInt();
operationId = in.readString();
}
/**
* Getter method for property <tt>operationNode</tt>.
*
* @return property value of operationNode
*/
public OperationNode getOperationNode() {
return operationNode;
}
/**
* Setter method for property <tt>operationNode</tt>.
*
* @param operationNode value to be assigned to property operationNode
*/
public void setOperationNode(OperationNode operationNode) {
this.operationNode = operationNode;
}
/**
* Getter method for property <tt>operationMethod</tt>.
*
* @return property value of operationMethod
*/
public OperationMethod getOperationMethod() {
return operationMethod;
}
/**
* Setter method for property <tt>operationMethod</tt>.
*
* @param operationMethod value to be assigned to property operationMethod
*/
public void setOperationMethod(OperationMethod operationMethod) {
this.operationMethod = operationMethod;
}
/**
* Getter method for property <tt>operationIndex</tt>.
*
* @return property value of operationIndex
*/
public int getOperationIndex() {
return operationIndex;
}
/**
* Setter method for property <tt>operationIndex</tt>.
*
* @param operationIndex value to be assigned to property operationIndex
*/
public void setOperationIndex(int operationIndex) {
this.operationIndex = operationIndex;
}
/**
* Getter method for property <tt>operationId</tt>.
*
* @return property value of operationId
*/
public String getOperationId() {
return operationId;
}
/**
* Setter method for property <tt>operationId</tt>.
*
* @param operationId value to be assigned to property operationId
*/
public void setOperationId(String operationId) {
this.operationId = operationId;
}
}
| 新增stepId字段
| src/shared/src/main/java/com/alipay/hulu/shared/node/tree/export/bean/OperationStep.java | 新增stepId字段 | <ide><path>rc/shared/src/main/java/com/alipay/hulu/shared/node/tree/export/bean/OperationStep.java
<ide> import android.os.Parcel;
<ide> import android.os.Parcelable;
<ide>
<add>import com.alipay.hulu.common.utils.StringUtil;
<ide> import com.alipay.hulu.shared.node.action.OperationMethod;
<ide> import com.alipay.hulu.shared.node.tree.OperationNode;
<ide>
<ide> */
<ide> private String operationId;
<ide>
<add> private String stepId;
<add>
<add>
<ide>
<ide> @Override
<ide> public int describeContents() {
<ide> dest.writeParcelable(operationMethod, flags);
<ide> dest.writeInt(operationIndex);
<ide> dest.writeString(operationId);
<add> dest.writeString(stepId);
<ide> }
<ide>
<ide> public static final Creator<OperationStep> CREATOR = new Creator<OperationStep>() {
<ide> }
<ide> };
<ide>
<del> public OperationStep(){}
<add> public OperationStep(){
<add> stepId = StringUtil.generateRandomString(10);
<add> }
<ide>
<ide> private OperationStep(Parcel in) {
<ide> operationNode = in.readParcelable(OperationNode.class.getClassLoader());
<ide> operationMethod = in.readParcelable(OperationMethod.class.getClassLoader());
<ide> operationIndex = in.readInt();
<ide> operationId = in.readString();
<add> stepId = in.readString();
<ide> }
<ide>
<ide> /**
<ide> this.operationId = operationId;
<ide> }
<ide>
<add> public String getStepId() {
<add> return stepId;
<add> }
<add>
<add> public void setStepId(String stepId) {
<add> this.stepId = stepId;
<add> }
<ide> } |
|
Java | apache-2.0 | 8d127338932d800465aace691b2b2f6267879592 | 0 | davidsoergel/stats | /* $Id$ */
/*
* Copyright (c) 2001-2007 David Soergel
* 418 Richmond St., El Cerrito, CA 94530
* [email protected]
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of any contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.davidsoergel.stats;
import com.davidsoergel.dsutils.MathUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by IntelliJ IDEA. User: lorax Date: Jun 24, 2007 Time: 10:36:27 PM To change this template use File |
* Settings | File Templates.
*/
public class Multinomial<T>//extends HashMap<Double, T>
{
// ------------------------------ FIELDS ------------------------------
MultinomialDistribution dist = new MultinomialDistribution();
List<T> elements = new ArrayList<T>();
// private Map<T, Double> logProbs = new HashMap<T, Double>();
public Multinomial()
{
}
public Multinomial(T[] keys, Map<T, Double> values) throws DistributionException
{
for (T k : keys)
{
put(k, values.get(k));
}
normalize();
}
// -------------------------- OTHER METHODS --------------------------
public void put(T obj, double prob) throws DistributionException//throws DistributionException
{
if (elements.contains(obj))
{
dist.update(elements.indexOf(obj), prob);
//dist.normalize();
//throw new DistributionException("Can't add the same element to a Multinomial twice");// don't bother to handle this properly
}
else
{
elements.add(obj);
dist.add(prob);
//dist.normalize();
}
}
public void normalize() throws DistributionException
{
dist.normalize();
}
public boolean isAlreadyNormalized() throws DistributionException
{
return dist.isAlreadyNormalized();
}
public double get(T obj) throws DistributionException//throws DistributionException
{
int i = elements.indexOf(obj);
if (i == -1)
{
//return 0;
//return Double.NaN;
throw new DistributionException("No probability known: " + obj);
}
return dist.probs[i];
}
public double getLog(T obj) throws DistributionException
{
// Double result = logProbs.get(obj);
// if (result == null)
// {
// result = MathUtils.approximateLog(get(obj));
// logProbs.put(obj, result);
// }
// return result;
return MathUtils.approximateLog(get(obj));
}
public List<T> getElements()
{
return elements;
}
public T sample() throws DistributionException
{
return elements.get(dist.sample());
}
public Multinomial<T> clone()
{
Multinomial<T> result = new Multinomial<T>();
result.dist = new MultinomialDistribution(dist);
result.elements = new ArrayList<T>(elements);
return result;
}
public int size()
{
return elements.size();
}
public void mixIn(Multinomial<T> uniform, double smoothFactor) throws DistributionException
{
for (int c = 0; c < elements.size(); c++)
{
dist.probs[c] = (dist.probs[c] * (1. - smoothFactor)) + uniform.get(elements.get(c)) * smoothFactor;
}
}
public double KLDivergenceToThisFrom(Multinomial<T> belief) throws DistributionException
{
double divergence = 0;
for (T key : elements)
{
double p = get(key);
double q = belief.get(key);
if (p == 0 || q == 0)
{
throw new DistributionException("Can't compute KL divergence: distributions not smoothed");
}
divergence += p * MathUtils.approximateLog(p / q);
if (Double.isNaN(divergence))
{
throw new DistributionException("Got NaN when computing KL divergence.");
}
}
return divergence;
}
public static <T> Multinomial<T> mixture(Multinomial<T> basis, Multinomial<T> bias, double mixingProportion)
throws DistributionException
{
Multinomial<T> result = new Multinomial<T>();
// these may be slow, remove later?
assert basis.isAlreadyNormalized();
assert bias.isAlreadyNormalized();
assert basis.getElements().size() == bias.getElements().size();
for (T key : basis.getElements())
{
double p = (1. - mixingProportion) * basis.get(key) + mixingProportion * bias.get(key);
result.put(key, p);
}
assert result.isAlreadyNormalized();
return result;
}
}
| src/main/java/com/davidsoergel/stats/Multinomial.java | /* $Id$ */
/*
* Copyright (c) 2001-2007 David Soergel
* 418 Richmond St., El Cerrito, CA 94530
* [email protected]
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of any contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.davidsoergel.stats;
import com.davidsoergel.dsutils.MathUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by IntelliJ IDEA. User: lorax Date: Jun 24, 2007 Time: 10:36:27 PM To change this template use File |
* Settings | File Templates.
*/
public class Multinomial<T>//extends HashMap<Double, T>
{
// ------------------------------ FIELDS ------------------------------
MultinomialDistribution dist = new MultinomialDistribution();
List<T> elements = new ArrayList<T>();
private Map<T, Double> logProbs = new HashMap<T, Double>();
public Multinomial()
{
}
public Multinomial(T[] keys, Map<T, Double> values) throws DistributionException
{
for (T k : keys)
{
put(k, values.get(k));
}
normalize();
}
// -------------------------- OTHER METHODS --------------------------
public void put(T obj, double prob) throws DistributionException//throws DistributionException
{
if (elements.contains(obj))
{
dist.update(elements.indexOf(obj), prob);
//dist.normalize();
//throw new DistributionException("Can't add the same element to a Multinomial twice");// don't bother to handle this properly
}
else
{
elements.add(obj);
dist.add(prob);
//dist.normalize();
}
}
public void normalize() throws DistributionException
{
dist.normalize();
}
public boolean isAlreadyNormalized() throws DistributionException
{
return dist.isAlreadyNormalized();
}
public double get(T obj) throws DistributionException//throws DistributionException
{
int i = elements.indexOf(obj);
if (i == -1)
{
//return 0;
//return Double.NaN;
throw new DistributionException("No probability known: " + obj);
}
return dist.probs[i];
}
public double getLog(T obj) throws DistributionException
{
Double result = logProbs.get(obj);
if (result == null)
{
result = MathUtils.approximateLog(get(obj));
logProbs.put(obj, result);
}
return result;
}
public List<T> getElements()
{
return elements;
}
public T sample() throws DistributionException
{
return elements.get(dist.sample());
}
public Multinomial<T> clone()
{
Multinomial<T> result = new Multinomial<T>();
result.dist = new MultinomialDistribution(dist);
result.elements = new ArrayList<T>(elements);
return result;
}
public int size()
{
return elements.size();
}
public void mixIn(Multinomial<T> uniform, double smoothFactor) throws DistributionException
{
for (int c = 0; c < elements.size(); c++)
{
dist.probs[c] = (dist.probs[c] * (1. - smoothFactor)) + uniform.get(elements.get(c)) * smoothFactor;
}
}
public double KLDivergenceToThisFrom(Multinomial<T> belief) throws DistributionException
{
double divergence = 0;
for (T key : elements)
{
double p = get(key);
double q = belief.get(key);
if (p == 0 || q == 0)
{
throw new DistributionException("Can't compute KL divergence: distributions not smoothed");
}
divergence += p * MathUtils.approximateLog(p / q);
if (Double.isNaN(divergence))
{
throw new DistributionException("Got NaN when computing KL divergence.");
}
}
return divergence;
}
public static <T> Multinomial<T> mixture(Multinomial<T> basis, Multinomial<T> bias, double mixingProportion)
throws DistributionException
{
Multinomial<T> result = new Multinomial<T>();
// these may be slow, remove later?
assert basis.isAlreadyNormalized();
assert bias.isAlreadyNormalized();
assert basis.getElements().size() == bias.getElements().size();
for (T key : basis.getElements())
{
double p = (1. - mixingProportion) * basis.get(key) + mixingProportion * bias.get(key);
result.put(key, p);
}
assert result.isAlreadyNormalized();
return result;
}
}
| The PST fragmentLogProbability wasn't terminating; fixed
| src/main/java/com/davidsoergel/stats/Multinomial.java | The PST fragmentLogProbability wasn't terminating; fixed | <ide><path>rc/main/java/com/davidsoergel/stats/Multinomial.java
<ide> import com.davidsoergel.dsutils.MathUtils;
<ide>
<ide> import java.util.ArrayList;
<del>import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<ide>
<ide> MultinomialDistribution dist = new MultinomialDistribution();
<ide> List<T> elements = new ArrayList<T>();
<del> private Map<T, Double> logProbs = new HashMap<T, Double>();
<add> // private Map<T, Double> logProbs = new HashMap<T, Double>();
<ide>
<ide> public Multinomial()
<ide> {
<ide>
<ide> public double getLog(T obj) throws DistributionException
<ide> {
<del> Double result = logProbs.get(obj);
<del> if (result == null)
<del> {
<del> result = MathUtils.approximateLog(get(obj));
<del> logProbs.put(obj, result);
<del> }
<del> return result;
<add> // Double result = logProbs.get(obj);
<add> // if (result == null)
<add> // {
<add> // result = MathUtils.approximateLog(get(obj));
<add> // logProbs.put(obj, result);
<add> // }
<add> // return result;
<add> return MathUtils.approximateLog(get(obj));
<ide> }
<ide>
<ide> public List<T> getElements() |
|
Java | agpl-3.0 | 18574a1b6ba920595df2ca695d7fe25a4497caf7 | 0 | qcri-social/AIDR,qcri-social/AIDR,qcri-social/AIDR,qcri-social/Crisis-Computing,qcri-social/Crisis-Computing,qcri-social/Crisis-Computing,qcri-social/Crisis-Computing,qcri-social/AIDR | package qa.qcri.aidr.manager.repository.impl;
import java.io.Serializable;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Logger;
//import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import qa.qcri.aidr.manager.persistence.entities.Collection;
import qa.qcri.aidr.manager.persistence.entities.UserAccount;
import qa.qcri.aidr.manager.repository.CollectionRepository;
import qa.qcri.aidr.manager.util.CollectionStatus;
@Repository("collectionRepository")
public class CollectionRepositoryImpl extends GenericRepositoryImpl<Collection, Serializable> implements CollectionRepository{
private Logger logger = Logger.getLogger(CollectionRepositoryImpl.class);
@SuppressWarnings("unchecked")
@Override
public List<Collection> searchByName(String query, Long userId) throws Exception {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.ilike("name", query, MatchMode.ANYWHERE));
criteria.add(Restrictions.eq("owner.id", userId));
return (List<Collection>) criteria.list();
}
@SuppressWarnings("unchecked")
@Override
public List<Collection> getPaginatedDataForPublic(final Integer start, final Integer limit, final Enum statusValue) {
// Workaround as criteria query gets result for different managers and in the end we get less then limit records.
List<BigInteger> collectionIds = (List<BigInteger>) getHibernateTemplate().execute(new HibernateCallback<Object>() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
String sql = " SELECT DISTINCT c.id FROM collection c" +
" WHERE (c.publicly_listed = 1 and c.status = :statusValue) " +
" order by c.start_date DESC, c.created_at DESC LIMIT :start, :limit ";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setParameter("start", start);
sqlQuery.setParameter("limit", limit);
sqlQuery.setParameter("statusValue", statusValue.ordinal());
List<BigInteger> ids = (List<BigInteger>) sqlQuery.list();
return ids != null ? ids : Collections.emptyList();
}
});
List<Collection> a = new ArrayList<Collection>();
for(int i =0; i < collectionIds.size(); i++){
Collection collection = this.findById(collectionIds.get(i).longValue());
a.add(collection) ;
}
return a;
}
@Override
public Integer getPublicCollectionsCount(final Enum statusValue) {
return (Integer) getHibernateTemplate().execute(new HibernateCallback<Object>() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
String sql = " SELECT count(distinct c.id) FROM collection c" +
" WHERE (c.publicly_listed = 1 and c.status = :statusValue) " ;
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setParameter("statusValue", statusValue.ordinal());
BigInteger total = (BigInteger) sqlQuery.uniqueResult();
return total != null ? total.intValue() : 0;
}
});
}
@SuppressWarnings("unchecked")
@Override
public List<Collection> getPaginatedData(final Integer start, final Integer limit, final UserAccount user, final boolean onlyTrashed) {
/*List<Collection> result = new ArrayList<Collection>();
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.eq("owner.id", user.getId()));
if(onlyTrashed) {
criteria.add(Restrictions.eq("status", CollectionStatus.TRASHED));
} else {
criteria.add(Restrictions.ne("status", CollectionStatus.TRASHED));
}
result = criteria.list();*/
final Long userId = user.getId();
final String conditionTrashed;
if (onlyTrashed) {
conditionTrashed = "=";
} else {
conditionTrashed = "!=";
}
List<Object[]> collections = (List<Object[]>) getHibernateTemplate().execute(new HibernateCallback<Object>() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
String sql = " SELECT DISTINCT c.id, c.status FROM collection c " +
" LEFT OUTER JOIN collection_collaborator c_m " +
" ON c.id = c_m.collection_id " +
" WHERE ((c.owner_id =:userId OR c_m.account_id = :userId) AND c.status " + conditionTrashed + " :statusValue) " +
" ORDER BY Case c.status When :status1 Then 1 When :status2 Then 1 Else 3 End, " +
" Case c.start_date When null Then 1 Else c.start_date*-1 End " +
" LIMIT :start, :limit ";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setParameter("userId", userId);
sqlQuery.setParameter("start", start);
sqlQuery.setParameter("limit", limit);
sqlQuery.setParameter("status1", CollectionStatus.RUNNING.ordinal());
sqlQuery.setParameter("status2", CollectionStatus.RUNNING_WARNING.ordinal());
sqlQuery.setParameter("statusValue", CollectionStatus.TRASHED.ordinal());
List<Object[]> ids = (List<Object[]>) sqlQuery.list();
return ids != null ? ids : Collections.emptyList();
}
});
//MEGHNA: To prevent multiple db calls, we get collection id and status from db and update AidrCollection status
List<Collection> result = new ArrayList<Collection>();
BigInteger id;
for(Object[] col : collections)
{
id = (BigInteger)col[0];
Collection collection = this.findById(id.longValue());
collection.setStatus(CollectionStatus.values()[(Integer)col[1]]);
result.add(collection) ;
}
return result;
}
@Override
public Integer getCollectionsCount(final UserAccount user, final boolean onlyTrashed) {
return (Integer) getHibernateTemplate().execute(new HibernateCallback<Object>() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Long userId = user.getId();
final String conditionTrashed;
if (onlyTrashed) {
conditionTrashed = "=";
} else {
conditionTrashed = "!=";
}
String sql = " select count(distinct c.id) " +
" FROM collection c " +
" LEFT OUTER JOIN collection_collaborator c_m " +
" ON c.id = c_m.collection_id " +
" WHERE (c.status " + conditionTrashed + " :statusValue and (c.owner_id = :userId or c_m.account_id = :userId)) ";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setParameter("userId", userId);
sqlQuery.setParameter("statusValue", CollectionStatus.TRASHED.ordinal());
BigInteger total = (BigInteger) sqlQuery.uniqueResult();
return total != null ? total.intValue() : 0;
}
});
}
@Override
public Boolean exist(String code) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.eq("code", code));
criteria.add(Restrictions.ne("status", CollectionStatus.TRASHED));
Collection collection = (Collection) criteria.uniqueResult();
return collection != null;
}
@Override
public Boolean existName(String name) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.eq("name", name));
Collection collection = (Collection) criteria.uniqueResult();
return collection != null;
}
@Override
public Collection getRunningCollectionStatusByUser(Long userId) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
//criteria.add(Restrictions.eq("user.id", userId));
//criteria.add(Restrictions.eq("status", CollectionStatus.RUNNING));
LogicalExpression or = Restrictions.or(
Restrictions.eq("status", CollectionStatus.RUNNING),
Restrictions.eq("status", CollectionStatus.RUNNING_WARNING)
);
LogicalExpression orAll = Restrictions.or(
or,
Restrictions.eq("status", CollectionStatus.WARNING)
);
/*Is this check needed?
*
* LogicalExpression and = Restrictions.and(
orAll,
Restrictions.ne("status", CollectionStatus.TRASHED)
);*/
LogicalExpression andAll = Restrictions.and(
orAll,
Restrictions.eq("owner.id", userId)
);
criteria.add(andAll);
//criteria.add(Restrictions.ne("status", CollectionStatus.TRASHED));
return (Collection) criteria.uniqueResult();
}
@SuppressWarnings("unchecked")
@Override
public List<Collection> getAllCollectionByUser(Long userId) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.eq("owner.id", userId));
return (List<Collection>) criteria.list();
}
@Override
public List<Collection> getRunningCollections() {
return getRunningCollections(null, null, null, null, null);
}
@SuppressWarnings("unchecked")
@Override
public List<Collection> getRunningCollections(Integer start, Integer limit, String terms, String sortColumn, String sortDirection) {
Criteria criteriaIds = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteriaIds.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id"));
LogicalExpression or = Restrictions.or(
Restrictions.eq("status", CollectionStatus.RUNNING),
Restrictions.eq("status", CollectionStatus.RUNNING_WARNING)
);
LogicalExpression or2 = Restrictions.or(
or,
Restrictions.eq("status", CollectionStatus.INITIALIZING)
);
LogicalExpression orAll = Restrictions.or(
or2,
Restrictions.eq("status", CollectionStatus.WARNING)
);
LogicalExpression andAll = Restrictions.and(
orAll,
Restrictions.ne("status", CollectionStatus.TRASHED)
);
criteriaIds.add(andAll);
addCollectionSearchCriteria(terms, criteriaIds);
searchCollectionsAddOrder(sortColumn, sortDirection, criteriaIds);
if (start != null) {
criteriaIds.setFirstResult(start);
}
if (limit != null) {
criteriaIds.setMaxResults(limit);
}
List<Integer> ids = (List<Integer>) criteriaIds.list();
if (ids.size() == 0){
return Collections.emptyList();
}
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
criteria.add(Restrictions.in("id", ids));
searchCollectionsAddOrder(sortColumn, sortDirection, criteria);
return (List<Collection>) criteria.list();
}
@Override
public Long getRunningCollectionsCount(String terms) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id"));
LogicalExpression or = Restrictions.or(
Restrictions.eq("status", CollectionStatus.RUNNING),
Restrictions.eq("status", CollectionStatus.RUNNING_WARNING)
);
LogicalExpression or2 = Restrictions.or(
or,
Restrictions.eq("status", CollectionStatus.INITIALIZING)
);
LogicalExpression orAll = Restrictions.or(
or2,
Restrictions.eq("status", CollectionStatus.WARNING)
);
LogicalExpression andAll = Restrictions.and(
orAll,
Restrictions.ne("status", CollectionStatus.TRASHED)
);
criteria.add(andAll);
addCollectionSearchCriteria(terms, criteria);
ScrollableResults scroll = criteria.scroll();
int i = scroll.last() ? scroll.getRowNumber() + 1 : 0;
return Long.valueOf(i);
}
@SuppressWarnings("unchecked")
@Override
public List<Collection> getStoppedCollections(Integer start, Integer limit, String terms, String sortColumn, String sortDirection) {
Criteria criteriaIds = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteriaIds.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id"));
LogicalExpression or = Restrictions.or(
Restrictions.eq("status", CollectionStatus.STOPPED),
Restrictions.eq("status", CollectionStatus.NOT_RUNNING)
);
LogicalExpression orAll = Restrictions.or(
or,
Restrictions.eq("status", CollectionStatus.FATAL_ERROR)
);
criteriaIds.add(orAll);
addCollectionSearchCriteria(terms, criteriaIds);
searchCollectionsAddOrder(sortColumn, sortDirection, criteriaIds);
if (start != null) {
criteriaIds.setFirstResult(start);
}
if (limit != null) {
criteriaIds.setMaxResults(limit);
}
List<Integer> ids = (List<Integer>) criteriaIds.list();
if (ids.size() == 0){
return Collections.emptyList();
}
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
criteria.add(Restrictions.in("id", ids));
searchCollectionsAddOrder(sortColumn, sortDirection, criteria);
return (List<Collection>) criteria.list();
}
@Override
public Long getStoppedCollectionsCount(String terms) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id"));
LogicalExpression or = Restrictions.or(
Restrictions.eq("status", CollectionStatus.STOPPED),
Restrictions.eq("status", CollectionStatus.NOT_RUNNING)
);
LogicalExpression orAll = Restrictions.or(
or,
Restrictions.eq("status", CollectionStatus.FATAL_ERROR)
);
criteria.add(orAll);
addCollectionSearchCriteria(terms, criteria);
ScrollableResults scroll = criteria.scroll();
int i = scroll.last() ? scroll.getRowNumber() + 1 : 0;
return Long.valueOf(i);
}
private void addCollectionSearchCriteria(String terms, Criteria criteria) {
if (StringUtils.hasText(terms)){
String wildcard ='%'+ URLDecoder.decode(terms.trim())+'%';
LogicalExpression orNameCode = Restrictions.or(
Restrictions.ilike("name", wildcard),
Restrictions.ilike("code", wildcard)
);
LogicalExpression orAll = Restrictions.or(
orNameCode,
Restrictions.ilike("track", wildcard)
);
criteria.add(orAll);
}
}
private void searchCollectionsAddOrder(String sortColumn, String sortDirection, Criteria criteria) {
if (StringUtils.hasText(sortColumn)) {
if ("owner".equals(sortColumn)){
sortColumn = "owner.userName";
criteria.createAlias("owner", "owner");
}
Order order;
if ("ASC".equals(sortDirection)){
order = Order.asc(sortColumn);
} else {
order = Order.desc(sortColumn);
}
criteria.addOrder(order);
}
}
@Override
public Collection getInitializingCollectionStatusByUser(Long userId) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.eq("owner.id", userId));
criteria.add(Restrictions.eq("status", CollectionStatus.INITIALIZING));
return (Collection) criteria.uniqueResult();
}
@Override
public Collection start(Long collectionId) {
Collection collection = this.findById(collectionId);
Calendar now = Calendar.getInstance();
collection.setStartDate(now.getTime());
// collection.setEndDate(null);
collection.setStatus(CollectionStatus.RUNNING);
this.update(collection);
return collection;
}
@Override
public Collection stop(Long collectionId) {
Collection collection = this.findById(collectionId);
Calendar now = Calendar.getInstance();
collection.setEndDate(now.getTime());
collection.setStatus(CollectionStatus.STOPPED);
this.update(collection);
return collection;
}
@Override
public Collection findByCode(String code) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.eq("code", code));
try {
return (Collection) criteria.uniqueResult();
} catch (HibernateException e) {
logger.error("Hibernate exception while finding a collection by code: "+code + "/t"+e.getStackTrace());
return null;
}
}
@Override
public Collection trashCollectionById(Long collectionId) {
Collection collection = stop(collectionId);
collection.setStatus(CollectionStatus.TRASHED);
this.update(collection);
return collection;
}
@Override
public void update(Collection collection) {
collection.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
super.update(collection);
}
@Override
public void save(Collection collection) {
Timestamp now = new Timestamp(System.currentTimeMillis());
collection.setUpdatedAt(now);
collection.setCreatedAt(now);
super.save(collection);
}
@Override
public List<Collection> getAllCollections() {
List<Collection> collections = new ArrayList<Collection>();
collections = findAll();
return collections;
}
}
| aidr-manager/src/main/java/qa/qcri/aidr/manager/repository/impl/CollectionRepositoryImpl.java | package qa.qcri.aidr.manager.repository.impl;
import java.io.Serializable;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Logger;
//import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import qa.qcri.aidr.manager.persistence.entities.Collection;
import qa.qcri.aidr.manager.persistence.entities.UserAccount;
import qa.qcri.aidr.manager.repository.CollectionRepository;
import qa.qcri.aidr.manager.util.CollectionStatus;
@Repository("collectionRepository")
public class CollectionRepositoryImpl extends GenericRepositoryImpl<Collection, Serializable> implements CollectionRepository{
private Logger logger = Logger.getLogger(CollectionRepositoryImpl.class);
@SuppressWarnings("unchecked")
@Override
public List<Collection> searchByName(String query, Long userId) throws Exception {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.ilike("name", query, MatchMode.ANYWHERE));
criteria.add(Restrictions.eq("owner.id", userId));
return (List<Collection>) criteria.list();
}
@SuppressWarnings("unchecked")
@Override
public List<Collection> getPaginatedDataForPublic(final Integer start, final Integer limit, final Enum statusValue) {
// Workaround as criteria query gets result for different managers and in the end we get less then limit records.
List<BigInteger> collectionIds = (List<BigInteger>) getHibernateTemplate().execute(new HibernateCallback<Object>() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
String sql = " SELECT DISTINCT c.id FROM collection c" +
" WHERE (c.publicly_listed = 1 and c.status = :statusValue) " +
" order by c.start_date DESC, c.created_at DESC LIMIT :start, :limit ";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setParameter("start", start);
sqlQuery.setParameter("limit", limit);
sqlQuery.setParameter("statusValue", statusValue.ordinal());
List<BigInteger> ids = (List<BigInteger>) sqlQuery.list();
return ids != null ? ids : Collections.emptyList();
}
});
List<Collection> a = new ArrayList<Collection>();
for(int i =0; i < collectionIds.size(); i++){
Collection collection = this.findById(collectionIds.get(i).longValue());
a.add(collection) ;
}
return a;
}
@Override
public Integer getPublicCollectionsCount(final Enum statusValue) {
return (Integer) getHibernateTemplate().execute(new HibernateCallback<Object>() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
String sql = " SELECT count(distinct c.id) FROM collection c" +
" WHERE (c.publicly_listed = 1 and c.status = :statusValue) " ;
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setParameter("statusValue", statusValue.ordinal());
BigInteger total = (BigInteger) sqlQuery.uniqueResult();
return total != null ? total.intValue() : 0;
}
});
}
@SuppressWarnings("unchecked")
@Override
public List<Collection> getPaginatedData(final Integer start, final Integer limit, final UserAccount user, final boolean onlyTrashed) {
/*List<Collection> result = new ArrayList<Collection>();
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.eq("owner.id", user.getId()));
if(onlyTrashed) {
criteria.add(Restrictions.eq("status", CollectionStatus.TRASHED));
} else {
criteria.add(Restrictions.ne("status", CollectionStatus.TRASHED));
}
result = criteria.list();*/
final Long userId = user.getId();
final String conditionTrashed;
if (onlyTrashed) {
conditionTrashed = "=";
} else {
conditionTrashed = "!=";
}
List<Object[]> collections = (List<Object[]>) getHibernateTemplate().execute(new HibernateCallback<Object>() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
String sql = " SELECT DISTINCT c.id, c.status FROM collection c " +
" LEFT OUTER JOIN collection_collaborator c_m " +
" ON c.id = c_m.collection_id " +
" WHERE ((c.owner_id =:userId OR c_m.account_id = :userId) AND c.status " + conditionTrashed + " :statusValue) " +
" order by c.start_date IS NULL DESC, c.start_date DESC, c.created_at DESC LIMIT :start, :limit ";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setParameter("userId", userId);
sqlQuery.setParameter("start", start);
sqlQuery.setParameter("limit", limit);
sqlQuery.setParameter("statusValue", CollectionStatus.TRASHED.ordinal());
List<Object[]> ids = (List<Object[]>) sqlQuery.list();
return ids != null ? ids : Collections.emptyList();
}
});
//MEGHNA: To prevent multiple db calls, we get collection id and status from db and update AidrCollection status
List<Collection> result = new ArrayList<Collection>();
BigInteger id;
for(Object[] col : collections)
{
id = (BigInteger)col[0];
Collection collection = this.findById(id.longValue());
collection.setStatus(CollectionStatus.values()[(Integer)col[1]]);
result.add(collection) ;
}
return result;
}
@Override
public Integer getCollectionsCount(final UserAccount user, final boolean onlyTrashed) {
return (Integer) getHibernateTemplate().execute(new HibernateCallback<Object>() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Long userId = user.getId();
final String conditionTrashed;
if (onlyTrashed) {
conditionTrashed = "=";
} else {
conditionTrashed = "!=";
}
String sql = " select count(distinct c.id) " +
" FROM collection c " +
" LEFT OUTER JOIN collection_collaborator c_m " +
" ON c.id = c_m.collection_id " +
" WHERE (c.status " + conditionTrashed + " :statusValue and (c.owner_id = :userId or c_m.account_id = :userId)) ";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setParameter("userId", userId);
sqlQuery.setParameter("statusValue", CollectionStatus.TRASHED.ordinal());
BigInteger total = (BigInteger) sqlQuery.uniqueResult();
return total != null ? total.intValue() : 0;
}
});
}
@Override
public Boolean exist(String code) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.eq("code", code));
criteria.add(Restrictions.ne("status", CollectionStatus.TRASHED));
Collection collection = (Collection) criteria.uniqueResult();
return collection != null;
}
@Override
public Boolean existName(String name) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.eq("name", name));
Collection collection = (Collection) criteria.uniqueResult();
return collection != null;
}
@Override
public Collection getRunningCollectionStatusByUser(Long userId) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
//criteria.add(Restrictions.eq("user.id", userId));
//criteria.add(Restrictions.eq("status", CollectionStatus.RUNNING));
LogicalExpression or = Restrictions.or(
Restrictions.eq("status", CollectionStatus.RUNNING),
Restrictions.eq("status", CollectionStatus.RUNNING_WARNING)
);
LogicalExpression orAll = Restrictions.or(
or,
Restrictions.eq("status", CollectionStatus.WARNING)
);
/*Is this check needed?
*
* LogicalExpression and = Restrictions.and(
orAll,
Restrictions.ne("status", CollectionStatus.TRASHED)
);*/
LogicalExpression andAll = Restrictions.and(
orAll,
Restrictions.eq("owner.id", userId)
);
criteria.add(andAll);
//criteria.add(Restrictions.ne("status", CollectionStatus.TRASHED));
return (Collection) criteria.uniqueResult();
}
@SuppressWarnings("unchecked")
@Override
public List<Collection> getAllCollectionByUser(Long userId) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.eq("owner.id", userId));
return (List<Collection>) criteria.list();
}
@Override
public List<Collection> getRunningCollections() {
return getRunningCollections(null, null, null, null, null);
}
@SuppressWarnings("unchecked")
@Override
public List<Collection> getRunningCollections(Integer start, Integer limit, String terms, String sortColumn, String sortDirection) {
Criteria criteriaIds = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteriaIds.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id"));
LogicalExpression or = Restrictions.or(
Restrictions.eq("status", CollectionStatus.RUNNING),
Restrictions.eq("status", CollectionStatus.RUNNING_WARNING)
);
LogicalExpression or2 = Restrictions.or(
or,
Restrictions.eq("status", CollectionStatus.INITIALIZING)
);
LogicalExpression orAll = Restrictions.or(
or2,
Restrictions.eq("status", CollectionStatus.WARNING)
);
LogicalExpression andAll = Restrictions.and(
orAll,
Restrictions.ne("status", CollectionStatus.TRASHED)
);
criteriaIds.add(andAll);
addCollectionSearchCriteria(terms, criteriaIds);
searchCollectionsAddOrder(sortColumn, sortDirection, criteriaIds);
if (start != null) {
criteriaIds.setFirstResult(start);
}
if (limit != null) {
criteriaIds.setMaxResults(limit);
}
List<Integer> ids = (List<Integer>) criteriaIds.list();
if (ids.size() == 0){
return Collections.emptyList();
}
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
criteria.add(Restrictions.in("id", ids));
searchCollectionsAddOrder(sortColumn, sortDirection, criteria);
return (List<Collection>) criteria.list();
}
@Override
public Long getRunningCollectionsCount(String terms) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id"));
LogicalExpression or = Restrictions.or(
Restrictions.eq("status", CollectionStatus.RUNNING),
Restrictions.eq("status", CollectionStatus.RUNNING_WARNING)
);
LogicalExpression or2 = Restrictions.or(
or,
Restrictions.eq("status", CollectionStatus.INITIALIZING)
);
LogicalExpression orAll = Restrictions.or(
or2,
Restrictions.eq("status", CollectionStatus.WARNING)
);
LogicalExpression andAll = Restrictions.and(
orAll,
Restrictions.ne("status", CollectionStatus.TRASHED)
);
criteria.add(andAll);
addCollectionSearchCriteria(terms, criteria);
ScrollableResults scroll = criteria.scroll();
int i = scroll.last() ? scroll.getRowNumber() + 1 : 0;
return Long.valueOf(i);
}
@SuppressWarnings("unchecked")
@Override
public List<Collection> getStoppedCollections(Integer start, Integer limit, String terms, String sortColumn, String sortDirection) {
Criteria criteriaIds = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteriaIds.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id"));
LogicalExpression or = Restrictions.or(
Restrictions.eq("status", CollectionStatus.STOPPED),
Restrictions.eq("status", CollectionStatus.NOT_RUNNING)
);
LogicalExpression orAll = Restrictions.or(
or,
Restrictions.eq("status", CollectionStatus.FATAL_ERROR)
);
criteriaIds.add(orAll);
addCollectionSearchCriteria(terms, criteriaIds);
searchCollectionsAddOrder(sortColumn, sortDirection, criteriaIds);
if (start != null) {
criteriaIds.setFirstResult(start);
}
if (limit != null) {
criteriaIds.setMaxResults(limit);
}
List<Integer> ids = (List<Integer>) criteriaIds.list();
if (ids.size() == 0){
return Collections.emptyList();
}
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
criteria.add(Restrictions.in("id", ids));
searchCollectionsAddOrder(sortColumn, sortDirection, criteria);
return (List<Collection>) criteria.list();
}
@Override
public Long getStoppedCollectionsCount(String terms) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id"));
LogicalExpression or = Restrictions.or(
Restrictions.eq("status", CollectionStatus.STOPPED),
Restrictions.eq("status", CollectionStatus.NOT_RUNNING)
);
LogicalExpression orAll = Restrictions.or(
or,
Restrictions.eq("status", CollectionStatus.FATAL_ERROR)
);
criteria.add(orAll);
addCollectionSearchCriteria(terms, criteria);
ScrollableResults scroll = criteria.scroll();
int i = scroll.last() ? scroll.getRowNumber() + 1 : 0;
return Long.valueOf(i);
}
private void addCollectionSearchCriteria(String terms, Criteria criteria) {
if (StringUtils.hasText(terms)){
String wildcard ='%'+ URLDecoder.decode(terms.trim())+'%';
LogicalExpression orNameCode = Restrictions.or(
Restrictions.ilike("name", wildcard),
Restrictions.ilike("code", wildcard)
);
LogicalExpression orAll = Restrictions.or(
orNameCode,
Restrictions.ilike("track", wildcard)
);
criteria.add(orAll);
}
}
private void searchCollectionsAddOrder(String sortColumn, String sortDirection, Criteria criteria) {
if (StringUtils.hasText(sortColumn)) {
if ("owner".equals(sortColumn)){
sortColumn = "owner.userName";
criteria.createAlias("owner", "owner");
}
Order order;
if ("ASC".equals(sortDirection)){
order = Order.asc(sortColumn);
} else {
order = Order.desc(sortColumn);
}
criteria.addOrder(order);
}
}
@Override
public Collection getInitializingCollectionStatusByUser(Long userId) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.eq("owner.id", userId));
criteria.add(Restrictions.eq("status", CollectionStatus.INITIALIZING));
return (Collection) criteria.uniqueResult();
}
@Override
public Collection start(Long collectionId) {
Collection collection = this.findById(collectionId);
Calendar now = Calendar.getInstance();
collection.setStartDate(now.getTime());
// collection.setEndDate(null);
collection.setStatus(CollectionStatus.RUNNING);
this.update(collection);
return collection;
}
@Override
public Collection stop(Long collectionId) {
Collection collection = this.findById(collectionId);
Calendar now = Calendar.getInstance();
collection.setEndDate(now.getTime());
collection.setStatus(CollectionStatus.STOPPED);
this.update(collection);
return collection;
}
@Override
public Collection findByCode(String code) {
Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
criteria.add(Restrictions.eq("code", code));
try {
return (Collection) criteria.uniqueResult();
} catch (HibernateException e) {
logger.error("Hibernate exception while finding a collection by code: "+code + "/t"+e.getStackTrace());
return null;
}
}
@Override
public Collection trashCollectionById(Long collectionId) {
Collection collection = stop(collectionId);
collection.setStatus(CollectionStatus.TRASHED);
this.update(collection);
return collection;
}
@Override
public void update(Collection collection) {
collection.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
super.update(collection);
}
@Override
public void save(Collection collection) {
Timestamp now = new Timestamp(System.currentTimeMillis());
collection.setUpdatedAt(now);
collection.setCreatedAt(now);
super.save(collection);
}
@Override
public List<Collection> getAllCollections() {
List<Collection> collections = new ArrayList<Collection>();
collections = findAll();
return collections;
}
}
| Fixed My Collection Page ordering
| aidr-manager/src/main/java/qa/qcri/aidr/manager/repository/impl/CollectionRepositoryImpl.java | Fixed My Collection Page ordering | <ide><path>idr-manager/src/main/java/qa/qcri/aidr/manager/repository/impl/CollectionRepositoryImpl.java
<ide> " LEFT OUTER JOIN collection_collaborator c_m " +
<ide> " ON c.id = c_m.collection_id " +
<ide> " WHERE ((c.owner_id =:userId OR c_m.account_id = :userId) AND c.status " + conditionTrashed + " :statusValue) " +
<del> " order by c.start_date IS NULL DESC, c.start_date DESC, c.created_at DESC LIMIT :start, :limit ";
<add> " ORDER BY Case c.status When :status1 Then 1 When :status2 Then 1 Else 3 End, " +
<add> " Case c.start_date When null Then 1 Else c.start_date*-1 End " +
<add> " LIMIT :start, :limit ";
<ide>
<ide> SQLQuery sqlQuery = session.createSQLQuery(sql);
<ide> sqlQuery.setParameter("userId", userId);
<ide> sqlQuery.setParameter("start", start);
<ide> sqlQuery.setParameter("limit", limit);
<add> sqlQuery.setParameter("status1", CollectionStatus.RUNNING.ordinal());
<add> sqlQuery.setParameter("status2", CollectionStatus.RUNNING_WARNING.ordinal());
<ide> sqlQuery.setParameter("statusValue", CollectionStatus.TRASHED.ordinal());
<ide> List<Object[]> ids = (List<Object[]>) sqlQuery.list();
<ide> |
|
Java | apache-2.0 | 18f489fc4e2cff1b5fe31722f0ef48a95bba0148 | 0 | psoreide/bnd,psoreide/bnd,mcculls/bnd,mcculls/bnd,psoreide/bnd,mcculls/bnd | package aQute.bnd.build;
import static java.util.stream.Collectors.toList;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.TimeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aQute.bnd.annotation.plugin.BndPlugin;
import aQute.bnd.connection.settings.ConnectionSettings;
import aQute.bnd.exporter.subsystem.SubsystemExporter;
import aQute.bnd.header.Attrs;
import aQute.bnd.header.OSGiHeader;
import aQute.bnd.header.Parameters;
import aQute.bnd.http.HttpClient;
import aQute.bnd.maven.support.Maven;
import aQute.bnd.osgi.About;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Macro;
import aQute.bnd.osgi.Processor;
import aQute.bnd.osgi.Verifier;
import aQute.bnd.resource.repository.ResourceRepositoryImpl;
import aQute.bnd.service.BndListener;
import aQute.bnd.service.RepositoryPlugin;
import aQute.bnd.service.action.Action;
import aQute.bnd.service.extension.ExtensionActivator;
import aQute.bnd.service.lifecycle.LifeCyclePlugin;
import aQute.bnd.service.repository.Prepare;
import aQute.bnd.service.repository.RepositoryDigest;
import aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor;
import aQute.bnd.url.MultiURLConnectionHandler;
import aQute.bnd.version.Version;
import aQute.bnd.version.VersionRange;
import aQute.lib.deployer.FileRepo;
import aQute.lib.hex.Hex;
import aQute.lib.io.IO;
import aQute.lib.io.IOConstants;
import aQute.lib.settings.Settings;
import aQute.lib.strings.Strings;
import aQute.lib.utf8properties.UTF8Properties;
import aQute.lib.zip.ZipUtil;
import aQute.libg.uri.URIUtil;
import aQute.service.reporter.Reporter;
public class Workspace extends Processor {
private final static Logger logger = LoggerFactory.getLogger(Workspace.class);
public static final File BND_DEFAULT_WS = IO.getFile("~/.bnd/default-ws");
public static final String BND_CACHE_REPONAME = "bnd-cache";
public static final String EXT = "ext";
public static final String BUILDFILE = "build.bnd";
public static final String CNFDIR = "cnf";
public static final String BNDDIR = "bnd";
public static final String CACHEDIR = "cache/" + About.CURRENT;
public static final String STANDALONE_REPO_CLASS = "aQute.bnd.repository.osgi.OSGiRepository";
static final int BUFFER_SIZE = IOConstants.PAGE_SIZE * 16;
private static final String PLUGIN_STANDALONE = "-plugin.standalone_";
private final Pattern EMBEDDED_REPO_TESTING_PATTERN = Pattern
.compile(".*biz\\.aQute\\.bnd\\.embedded-repo(-.*)?\\.jar");
static class WorkspaceData {
List<RepositoryPlugin> repositories;
}
private final static Map<File,WeakReference<Workspace>> cache = newHashMap();
static Processor defaults = null;
final Map<String,Project> models = newHashMap();
private final Set<String> modelsUnderConstruction = newSet();
final Map<String,Action> commands = newMap();
final Maven maven = new Maven(Processor.getExecutor());
private final AtomicBoolean offline = new AtomicBoolean();
Settings settings = new Settings();
WorkspaceRepository workspaceRepo = new WorkspaceRepository(this);
static String overallDriver = "unset";
static Parameters overallGestalt = new Parameters();
/**
* Signal a BndListener plugin. We ran an infinite bug loop :-(
*/
final ThreadLocal<Reporter> signalBusy = new ThreadLocal<Reporter>();
ResourceRepositoryImpl resourceRepositoryImpl;
private Parameters gestalt;
private String driver;
private final WorkspaceLayout layout;
final Set<Project> trail = Collections
.newSetFromMap(new ConcurrentHashMap<Project,Boolean>());
private WorkspaceData data = new WorkspaceData();
private File buildDir;
/**
* This static method finds the workspace and creates a project (or returns
* an existing project)
*
* @param projectDir
*/
public static Project getProject(File projectDir) throws Exception {
projectDir = projectDir.getAbsoluteFile();
assert projectDir.isDirectory();
Workspace ws = getWorkspace(projectDir.getParentFile());
return ws.getProject(projectDir.getName());
}
static synchronized public Processor getDefaults() {
if (defaults != null)
return defaults;
UTF8Properties props = new UTF8Properties();
try (InputStream propStream = Workspace.class.getResourceAsStream("defaults.bnd")) {
if (propStream != null) {
props.load(propStream);
} else {
System.err.println("Cannot load defaults");
}
} catch (IOException e) {
throw new IllegalArgumentException("Unable to load bnd defaults.", e);
}
defaults = new Processor(props, false);
return defaults;
}
public static Workspace createDefaultWorkspace() throws Exception {
Workspace ws = new Workspace(BND_DEFAULT_WS, CNFDIR);
return ws;
}
public static Workspace getWorkspace(File workspaceDir) throws Exception {
return getWorkspace(workspaceDir, CNFDIR);
}
public static Workspace getWorkspaceWithoutException(File workspaceDir) throws Exception {
try {
return getWorkspace(workspaceDir);
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* /* Return the nearest workspace
*/
public static Workspace findWorkspace(File base) throws Exception {
File rover = base;
while (rover != null) {
File file = IO.getFile(rover, "cnf/build.bnd");
if (file.isFile())
return getWorkspace(rover);
rover = rover.getParentFile();
}
return null;
}
public static Workspace getWorkspace(File workspaceDir, String bndDir) throws Exception {
workspaceDir = workspaceDir.getAbsoluteFile();
// the cnf directory can actually be a
// file that redirects
while (workspaceDir.isDirectory()) {
File test = new File(workspaceDir, CNFDIR);
if (!test.exists())
test = new File(workspaceDir, bndDir);
if (test.isDirectory())
break;
if (test.isFile()) {
String redirect = IO.collect(test).trim();
test = getFile(test.getParentFile(), redirect).getAbsoluteFile();
workspaceDir = test;
}
if (!test.exists())
throw new IllegalArgumentException("No Workspace found from: " + workspaceDir);
}
synchronized (cache) {
WeakReference<Workspace> wsr = cache.get(workspaceDir);
Workspace ws;
if (wsr == null || (ws = wsr.get()) == null) {
ws = new Workspace(workspaceDir, bndDir);
cache.put(workspaceDir, new WeakReference<Workspace>(ws));
}
return ws;
}
}
public Workspace(File workspaceDir) throws Exception {
this(workspaceDir, CNFDIR);
}
public Workspace(File workspaceDir, String bndDir) throws Exception {
super(getDefaults());
workspaceDir = workspaceDir.getAbsoluteFile();
setBase(workspaceDir); // setBase before call to setFileSystem
this.layout = WorkspaceLayout.BND;
addBasicPlugin(new LoggingProgressPlugin());
setFileSystem(workspaceDir, bndDir);
}
public void setFileSystem(File workspaceDir, String bndDir) throws Exception {
workspaceDir = workspaceDir.getAbsoluteFile();
IO.mkdirs(workspaceDir);
assert workspaceDir.isDirectory();
synchronized (cache) {
WeakReference<Workspace> wsr = cache.get(getBase());
if ((wsr != null) && (wsr.get() == this)) {
cache.remove(getBase());
cache.put(workspaceDir, wsr);
}
}
File buildDir = new File(workspaceDir, bndDir).getAbsoluteFile();
if (!buildDir.isDirectory())
buildDir = new File(workspaceDir, CNFDIR).getAbsoluteFile();
setBuildDir(buildDir);
File buildFile = new File(buildDir, BUILDFILE).getAbsoluteFile();
if (!buildFile.isFile())
warning("No Build File in %s", workspaceDir);
setProperties(buildFile, workspaceDir);
propertiesChanged();
//
// There is a nasty bug/feature in Java that gives errors on our
// SSL use of github. The flag jsse.enableSNIExtension should be set
// to false. So here we provide a way to set system properties
// as early as possible
//
Attrs sysProps = OSGiHeader.parseProperties(mergeProperties(SYSTEMPROPERTIES));
for (Entry<String,String> e : sysProps.entrySet()) {
System.setProperty(e.getKey(), e.getValue());
}
}
private Workspace(WorkspaceLayout layout) throws Exception {
super(getDefaults());
this.layout = layout;
setBuildDir(IO.getFile(BND_DEFAULT_WS, CNFDIR));
}
public Project getProjectFromFile(File projectDir) {
projectDir = projectDir.getAbsoluteFile();
assert projectDir.isDirectory();
if (getBase().equals(projectDir.getParentFile())) {
return getProject(projectDir.getName());
}
return null;
}
public Project getProject(String bsn) {
synchronized (models) {
Project project = models.get(bsn);
if (project != null)
return project;
if (modelsUnderConstruction.add(bsn)) {
try {
File projectDir = getFile(bsn);
project = new Project(this, projectDir);
if (!project.isValid())
return null;
models.put(bsn, project);
} finally {
modelsUnderConstruction.remove(bsn);
}
}
return project;
}
}
void removeProject(Project p) throws Exception {
if (p.isCnf())
return;
synchronized (models) {
models.remove(p.getName());
}
for (LifeCyclePlugin lp : getPlugins(LifeCyclePlugin.class)) {
lp.delete(p);
}
}
public boolean isPresent(String name) {
return models.containsKey(name);
}
public Collection<Project> getCurrentProjects() {
return models.values();
}
@Override
public boolean refresh() {
data = new WorkspaceData();
if (super.refresh()) {
for (Project project : getCurrentProjects()) {
project.propertiesChanged();
}
return true;
}
return false;
}
@Override
public void propertiesChanged() {
data = new WorkspaceData();
File extDir = new File(getBuildDir(), EXT);
File[] extensions = extDir.listFiles();
if (extensions != null) {
for (File extension : extensions) {
String extensionName = extension.getName();
if (extensionName.endsWith(".bnd")) {
extensionName = extensionName.substring(0, extensionName.length() - ".bnd".length());
try {
doIncludeFile(extension, false, getProperties(), "ext." + extensionName);
} catch (Exception e) {
exception(e, "PropertiesChanged: %s", e);
}
}
}
}
super.propertiesChanged();
}
public String _workspace(@SuppressWarnings("unused") String args[]) {
return getBase().getAbsolutePath();
}
public void addCommand(String menu, Action action) {
commands.put(menu, action);
}
public void removeCommand(String menu) {
commands.remove(menu);
}
public void fillActions(Map<String,Action> all) {
all.putAll(commands);
}
public Collection<Project> getAllProjects() throws Exception {
Path basePath = getBase().toPath();
Path bndfile = Paths.get(Project.BNDFILE);
List<Project> projects = Files.walk(basePath, 1, FileVisitOption.FOLLOW_LINKS)
.filter(p -> !basePath.equals(p) && Files.isDirectory(p) && Files.isRegularFile(p.resolve(bndfile)))
.map(p -> getProject(p.getFileName()
.toString()))
.filter(Objects::nonNull)
.collect(toList());
return projects;
}
/**
* Inform any listeners that we changed a file (created/deleted/changed).
*
* @param f The changed file
*/
public void changedFile(File f) {
List<BndListener> listeners = getPlugins(BndListener.class);
for (BndListener l : listeners)
try {
l.changed(f);
} catch (Exception e) {
logger.debug("Exception in a BndListener changedFile method call", e);
}
}
public void bracket(boolean begin) {
List<BndListener> listeners = getPlugins(BndListener.class);
for (BndListener l : listeners)
try {
if (begin)
l.begin();
else
l.end();
} catch (Exception e) {
if (begin)
logger.debug("Exception in a BndListener begin method call", e);
else
logger.debug("Exception in a BndListener end method call", e);
}
}
public void signal(Reporter reporter) {
if (signalBusy.get() != null)
return;
signalBusy.set(reporter);
try {
List<BndListener> listeners = getPlugins(BndListener.class);
for (BndListener l : listeners)
try {
l.signal(this);
} catch (Exception e) {
logger.debug("Exception in a BndListener signal method call", e);
}
} catch (Exception e) {
// Ignore
} finally {
signalBusy.set(null);
}
}
@Override
public void signal() {
signal(this);
}
class CachedFileRepo extends FileRepo {
final Lock lock = new ReentrantLock();
boolean inited;
CachedFileRepo() {
super(BND_CACHE_REPONAME, getCache(BND_CACHE_REPONAME), false);
}
@Override
protected boolean init() throws Exception {
if (lock.tryLock(50, TimeUnit.SECONDS) == false)
throw new TimeLimitExceededException("Cached File Repo is locked and can't acquire it");
try {
if (super.init()) {
inited = true;
IO.mkdirs(root);
if (!root.isDirectory())
throw new IllegalArgumentException("Cache directory " + root + " not a directory");
try (InputStream in = getClass().getResourceAsStream(EMBEDDED_REPO)) {
if (in != null) {
unzip(in, root);
return true;
}
}
// We may be in unit test, look for
// biz.aQute.bnd.embedded-repo.jar on the
// classpath
StringTokenizer classPathTokenizer = new StringTokenizer(
System.getProperty("java.class.path", ""), File.pathSeparator);
while (classPathTokenizer.hasMoreTokens()) {
String classPathEntry = classPathTokenizer.nextToken().trim();
if (EMBEDDED_REPO_TESTING_PATTERN.matcher(classPathEntry).matches()) {
try (InputStream in = IO.stream(Paths.get(classPathEntry))) {
unzip(in, root);
return true;
}
}
}
error("Couldn't find biz.aQute.bnd.embedded-repo on the classpath");
return false;
} else
return false;
} finally {
lock.unlock();
}
}
private void unzip(InputStream in, File dir) throws Exception {
try (JarInputStream jin = new JarInputStream(in)) {
byte[] data = new byte[BUFFER_SIZE];
for (JarEntry jentry = jin.getNextJarEntry(); jentry != null; jentry = jin.getNextJarEntry()) {
if (jentry.isDirectory()) {
continue;
}
String jentryName = jentry.getName();
if (jentryName.startsWith("META-INF/")) {
continue;
}
File dest = getFile(dir, jentryName);
long modifiedTime = ZipUtil.getModifiedTime(jentry);
if (!dest.isFile() || dest.lastModified() < modifiedTime || modifiedTime <= 0) {
File dp = dest.getParentFile();
IO.mkdirs(dp);
try (OutputStream out = IO.outputStream(dest)) {
for (int size = jin.read(data); size > 0; size = jin.read(data)) {
out.write(data, 0, size);
}
}
}
}
}
}
}
public void syncCache() throws Exception {
CachedFileRepo cf = new CachedFileRepo();
cf.init();
cf.close();
}
public List<RepositoryPlugin> getRepositories() throws Exception {
if (data.repositories == null) {
data.repositories = getPlugins(RepositoryPlugin.class);
for (RepositoryPlugin repo : data.repositories) {
if (repo instanceof Prepare) {
((Prepare) repo).prepare();
}
}
}
return data.repositories;
}
public Collection<Project> getBuildOrder() throws Exception {
Set<Project> result = new LinkedHashSet<Project>();
for (Project project : getAllProjects()) {
Collection<Project> dependsOn = project.getDependson();
getBuildOrder(dependsOn, result);
result.add(project);
}
return result;
}
private void getBuildOrder(Collection<Project> dependsOn, Set<Project> result) throws Exception {
for (Project project : dependsOn) {
Collection<Project> subProjects = project.getDependson();
for (Project subProject : subProjects) {
result.add(subProject);
}
result.add(project);
}
}
public static Workspace getWorkspace(String path) throws Exception {
File file = IO.getFile(new File(""), path);
return getWorkspace(file);
}
public Maven getMaven() {
return maven;
}
@Override
protected void setTypeSpecificPlugins(Set<Object> list) {
try {
super.setTypeSpecificPlugins(list);
list.add(this);
list.add(maven);
list.add(settings);
if (!isTrue(getProperty(NOBUILDINCACHE))) {
CachedFileRepo repo = new CachedFileRepo();
list.add(repo);
}
resourceRepositoryImpl = new ResourceRepositoryImpl();
resourceRepositoryImpl.setCache(IO.getFile(getProperty(CACHEDIR, "~/.bnd/caches/shas")));
resourceRepositoryImpl.setExecutor(getExecutor());
resourceRepositoryImpl.setIndexFile(getFile(getBuildDir(), "repo.json"));
resourceRepositoryImpl.setURLConnector(new MultiURLConnectionHandler(this));
customize(resourceRepositoryImpl, null);
list.add(resourceRepositoryImpl);
//
// Exporters
//
list.add(new SubsystemExporter());
try {
HttpClient client = new HttpClient(getExecutor(), getScheduledExecutor());
client.setOffline(getOffline());
client.setRegistry(this);
try (ConnectionSettings cs = new ConnectionSettings(this, client)) {
cs.readSettings();
}
list.add(client);
} catch (Exception e) {
exception(e, "Failed to load the communication settings");
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Add any extensions listed
*
* @param list
*/
@Override
protected void addExtensions(Set<Object> list) {
//
// <bsn>; version=<range>
//
Parameters extensions = getMergedParameters(EXTENSION);
Map<DownloadBlocker,Attrs> blockers = new HashMap<DownloadBlocker,Attrs>();
for (Entry<String,Attrs> i : extensions.entrySet()) {
String bsn = removeDuplicateMarker(i.getKey());
String stringRange = i.getValue().get(VERSION_ATTRIBUTE);
logger.debug("Adding extension {}-{}", bsn, stringRange);
if (stringRange == null)
stringRange = Version.LOWEST.toString();
else if (!VersionRange.isVersionRange(stringRange)) {
error("Invalid version range %s on extension %s", stringRange, bsn);
continue;
}
try {
SortedSet<ResourceDescriptor> matches = resourceRepositoryImpl.find(null, bsn,
new VersionRange(stringRange));
if (matches.isEmpty()) {
error("Extension %s;version=%s not found in base repo", bsn, stringRange);
continue;
}
DownloadBlocker blocker = new DownloadBlocker(this);
blockers.put(blocker, i.getValue());
resourceRepositoryImpl.getResource(matches.last().id, blocker);
} catch (Exception e) {
error("Failed to load extension %s-%s, %s", bsn, stringRange, e);
}
}
logger.debug("Found extensions {}", blockers);
for (Entry<DownloadBlocker,Attrs> blocker : blockers.entrySet()) {
try {
String reason = blocker.getKey().getReason();
if (reason != null) {
error("Extension load failed: %s", reason);
continue;
}
@SuppressWarnings("resource")
URLClassLoader cl = new URLClassLoader(new URL[] {
blocker.getKey().getFile().toURI().toURL()
}, getClass().getClassLoader());
Enumeration<URL> manifests = cl.getResources("META-INF/MANIFEST.MF");
while (manifests.hasMoreElements()) {
try(InputStream is = manifests.nextElement().openStream()) {
Manifest m = new Manifest(is);
Parameters activators = new Parameters(m.getMainAttributes().getValue("Extension-Activator"), this);
for (Entry<String, Attrs> e : activators.entrySet()) {
try {
Class<?> c = cl.loadClass(e.getKey());
ExtensionActivator extensionActivator = (ExtensionActivator) c.getConstructor()
.newInstance();
customize(extensionActivator, blocker.getValue());
List<?> plugins = extensionActivator.activate(this, blocker.getValue());
list.add(extensionActivator);
if (plugins != null)
for (Object plugin : plugins) {
list.add(plugin);
}
} catch (ClassNotFoundException cnfe) {
error("Loading extension %s, extension activator missing: %s (ignored)", blocker,
e.getKey());
}
}
}
}
} catch (Exception e) {
error("failed to install extension %s due to %s", blocker, e);
}
}
}
public boolean isOffline() {
return offline.get();
}
public AtomicBoolean getOffline() {
return offline;
}
public Workspace setOffline(boolean on) {
offline.set(on);
return this;
}
/**
* Provide access to the global settings of this machine.
*
* @throws Exception
*/
public String _global(String[] args) throws Exception {
Macro.verifyCommand(args, "${global;<name>[;<default>]}, get a global setting from ~/.bnd/settings.json", null,
2, 3);
String key = args[1];
if (key.equals("key.public"))
return Hex.toHexString(settings.getPublicKey());
if (key.equals("key.private"))
return Hex.toHexString(settings.getPrivateKey());
String s = settings.get(key);
if (s != null)
return s;
if (args.length == 3)
return args[2];
return null;
}
public String _user(String[] args) throws Exception {
return _global(args);
}
/**
* Return the repository signature digests. These digests are a unique id
* for the contents of the repository
*/
public Object _repodigests(String[] args) throws Exception {
Macro.verifyCommand(args, "${repodigests;[;<repo names>]...}, get the repository digests", null, 1, 10000);
List<RepositoryPlugin> repos = getRepositories();
if (args.length > 1) {
repos: for (Iterator<RepositoryPlugin> it = repos.iterator(); it.hasNext();) {
String name = it.next().getName();
for (int i = 1; i < args.length; i++) {
if (name.equals(args[i])) {
continue repos;
}
}
it.remove();
}
}
List<String> digests = new ArrayList<String>();
for (RepositoryPlugin repo : repos) {
try {
if (repo instanceof RepositoryDigest) {
byte[] digest = ((RepositoryDigest) repo).getDigest();
digests.add(Hex.toHexString(digest));
} else {
if (args.length != 1)
error("Specified repo %s for ${repodigests} was named but it is not found", repo.getName());
}
} catch (Exception e) {
if (args.length != 1)
error("Specified repo %s for digests is not found", repo.getName());
// else Ignore
}
}
return join(digests, ",");
}
public static Run getRun(File file) throws Exception {
if (!file.isFile()) {
return null;
}
File projectDir = file.getParentFile();
File workspaceDir = projectDir.getParentFile();
if (!workspaceDir.isDirectory()) {
return null;
}
Workspace ws = getWorkspaceWithoutException(workspaceDir);
if (ws == null) {
return null;
}
return new Run(ws, projectDir, file);
}
/**
* Report details of this workspace
*/
public void report(Map<String,Object> table) throws Exception {
super.report(table);
table.put("Workspace", toString());
table.put("Plugins", getPlugins(Object.class));
table.put("Repos", getRepositories());
table.put("Projects in build order", getBuildOrder());
}
public File getCache(String name) {
return getFile(buildDir, CACHEDIR + "/" + name);
}
/**
* Return the workspace repo
*/
public WorkspaceRepository getWorkspaceRepository() {
return workspaceRepo;
}
public void checkStructure() {
if (!getBuildDir().isDirectory())
error("No directory for cnf %s", getBuildDir());
else {
File build = IO.getFile(getBuildDir(), BUILDFILE);
if (build.isFile()) {
error("No %s file in %s", BUILDFILE, getBuildDir());
}
}
}
public File getBuildDir() {
return buildDir;
}
public void setBuildDir(File buildDir) {
this.buildDir = buildDir;
}
public boolean isValid() {
return IO.getFile(getBuildDir(), BUILDFILE).isFile();
}
public RepositoryPlugin getRepository(String repo) throws Exception {
for (RepositoryPlugin r : getRepositories()) {
if (repo.equals(r.getName())) {
return r;
}
}
return null;
}
public void close() {
synchronized (cache) {
WeakReference<Workspace> wsr = cache.get(getBase());
if ((wsr != null) && (wsr.get() == this)) {
cache.remove(getBase());
}
}
try {
super.close();
} catch (IOException e) {
/* For backwards compatibility, we ignore the exception */
}
}
/**
* Get the bnddriver, can be null if not set. The overallDriver is the
* environment that runs this bnd.
*/
public String getDriver() {
if (driver == null) {
driver = getProperty(Constants.BNDDRIVER, null);
if (driver != null)
driver = driver.trim();
}
if (driver != null)
return driver;
return overallDriver;
}
/**
* Set the driver of this environment
*/
public static void setDriver(String driver) {
overallDriver = driver;
}
/**
* Macro to return the driver. Without any arguments, we return the name of
* the driver. If there are arguments, we check each of the arguments
* against the name of the driver. If it matches, we return the driver name.
* If none of the args match the driver name we return an empty string
* (which is false).
*/
public String _driver(String args[]) {
if (args.length == 1) {
return getDriver();
}
String driver = getDriver();
if (driver == null)
driver = getProperty(Constants.BNDDRIVER);
if (driver != null) {
for (int i = 1; i < args.length; i++) {
if (args[i].equalsIgnoreCase(driver))
return driver;
}
}
return "";
}
/**
* Add a gestalt to all workspaces. The gestalt is a set of parts describing
* the environment. Each part has a name and optionally attributes. This
* method adds a gestalt to the VM. Per workspace it is possible to augment
* this.
*/
public static void addGestalt(String part, Attrs attrs) {
Attrs already = overallGestalt.get(part);
if (attrs == null)
attrs = new Attrs();
if (already != null) {
already.putAll(attrs);
} else
already = attrs;
overallGestalt.put(part, already);
}
/**
* Get the attrs for a gestalt part
*/
public Attrs getGestalt(String part) {
return getGestalt().get(part);
}
/**
* Get the attrs for a gestalt part
*/
public Parameters getGestalt() {
if (gestalt == null) {
gestalt = getMergedParameters(Constants.GESTALT);
gestalt.mergeWith(overallGestalt, false);
}
return gestalt;
}
/**
* Get the layout style of the workspace.
*/
public WorkspaceLayout getLayout() {
return layout;
}
/**
* The macro to access the gestalt
* <p>
* {@code $ gestalt;part[;key[;value]]}
*/
public String _gestalt(String args[]) {
if (args.length >= 2) {
Attrs attrs = getGestalt(args[1]);
if (attrs == null)
return "";
if (args.length == 2)
return args[1];
String s = attrs.get(args[2]);
if (args.length == 3) {
if (s == null)
s = "";
return s;
}
if (args.length == 4) {
if (args[3].equals(s))
return s;
else
return "";
}
}
throw new IllegalArgumentException("${gestalt;<part>[;key[;<value>]]} has too many arguments");
}
@Override
public String toString() {
return "Workspace [" + getBase().getName() + "]";
}
/**
* Create a project in this workspace
*/
public Project createProject(String name) throws Exception {
if (!Verifier.SYMBOLICNAME.matcher(name).matches()) {
error("A project name is a Bundle Symbolic Name, this must therefore consist of only letters, digits and dots");
return null;
}
File pdir = getFile(name);
IO.mkdirs(pdir);
IO.store("#\n# " + name.toUpperCase().replace('.', ' ') + "\n#\n", getFile(pdir, Project.BNDFILE));
Project p = new Project(this, pdir);
IO.mkdirs(p.getTarget());
IO.mkdirs(p.getOutput());
IO.mkdirs(p.getTestOutput());
for (File dir : p.getSourcePath()) {
IO.mkdirs(dir);
}
IO.mkdirs(p.getTestSrc());
for (LifeCyclePlugin l : getPlugins(LifeCyclePlugin.class))
l.created(p);
if (!p.isValid()) {
error("project %s is not valid", p);
}
return p;
}
/**
* Create a new Workspace
*
* @param wsdir
* @throws Exception
*/
public static Workspace createWorkspace(File wsdir) throws Exception {
if (wsdir.exists())
return null;
IO.mkdirs(wsdir);
File cnf = IO.getFile(wsdir, CNFDIR);
IO.mkdirs(cnf);
IO.store("", new File(cnf, BUILDFILE));
IO.store("-nobundles: true\n", new File(cnf, Project.BNDFILE));
File ext = new File(cnf, EXT);
IO.mkdirs(ext);
Workspace ws = getWorkspace(wsdir);
return ws;
}
/**
* Add a plugin
*
* @param plugin
* @throws Exception
*/
public boolean addPlugin(Class< ? > plugin, String alias, Map<String,String> parameters, boolean force)
throws Exception {
BndPlugin ann = plugin.getAnnotation(BndPlugin.class);
if (alias == null) {
if (ann != null)
alias = ann.name();
else {
alias = Strings.getLastSegment(plugin.getName()).toLowerCase();
if (alias.endsWith("plugin")) {
alias = alias.substring(0, alias.length() - "plugin".length());
}
}
}
if (!Verifier.isBsn(alias)) {
error("Not a valid plugin name %s", alias);
}
File ext = getFile(Workspace.CNFDIR + "/" + Workspace.EXT);
IO.mkdirs(ext);
File f = new File(ext, alias + ".bnd");
if (!force) {
if (f.exists()) {
error("Plugin %s already exists", alias);
return false;
}
} else {
IO.delete(f);
}
Object l = plugin.getConstructor().newInstance();
try (Formatter setup = new Formatter()) {
setup.format("#\n" //
+ "# Plugin %s setup\n" //
+ "#\n", alias);
setup.format("-plugin.%s = %s", alias, plugin.getName());
for (Map.Entry<String,String> e : parameters.entrySet()) {
setup.format("; \\\n \t%s = '%s'", e.getKey(), escaped(e.getValue()));
}
setup.format("\n\n");
String out = setup.toString();
if (l instanceof LifeCyclePlugin) {
out = ((LifeCyclePlugin) l).augmentSetup(out, alias, parameters);
((LifeCyclePlugin) l).init(this);
}
logger.debug("setup {}", out);
IO.store(out, f);
}
refresh();
for (LifeCyclePlugin lp : getPlugins(LifeCyclePlugin.class)) {
lp.addedPlugin(this, plugin.getName(), alias, parameters);
}
return true;
}
static Pattern ESCAPE_P = Pattern.compile("(\"|')(.*)\1");
private Object escaped(String value) {
Matcher matcher = ESCAPE_P.matcher(value);
if (matcher.matches())
value = matcher.group(2);
return value.replaceAll("'", "\\'");
}
public boolean removePlugin(String alias) {
File ext = getFile(Workspace.CNFDIR + "/" + Workspace.EXT);
File f = new File(ext, alias + ".bnd");
if (!f.exists()) {
error("No such plugin %s", alias);
return false;
}
IO.delete(f);
refresh();
return true;
}
/**
* Create a workspace that does not inherit from a cnf directory etc.
*
* @param run
*/
public static Workspace createStandaloneWorkspace(Processor run, URI base) throws Exception {
Workspace ws = new Workspace(WorkspaceLayout.STANDALONE);
Parameters standalone = new Parameters(run.getProperty(STANDALONE), ws);
StringBuilder sb = new StringBuilder();
try (Formatter f = new Formatter(sb, Locale.US)) {
int counter = 1;
for (Map.Entry<String,Attrs> e : standalone.entrySet()) {
String locationStr = e.getKey();
if ("true".equalsIgnoreCase(locationStr))
break;
URI resolvedLocation = URIUtil.resolve(base, locationStr);
String key = f.format("%s%02d", PLUGIN_STANDALONE, counter).toString();
sb.setLength(0);
Attrs attrs = e.getValue();
String name = attrs.get("name");
if (name == null) {
name = String.format("repo%02d", counter);
}
f.format("%s; name='%s'; locations='%s'", STANDALONE_REPO_CLASS, name, resolvedLocation);
for (Map.Entry<String,String> attribEntry : attrs.entrySet()) {
if (!"name".equals(attribEntry.getKey()))
f.format("; %s='%s'", attribEntry.getKey(), attribEntry.getValue());
}
String value = f.toString();
sb.setLength(0);
ws.setProperty(key, value);
counter++;
}
}
return ws;
}
public boolean isDefaultWorkspace() {
return BND_DEFAULT_WS.equals(getBase());
}
}
| biz.aQute.bndlib/src/aQute/bnd/build/Workspace.java | package aQute.bnd.build;
import static java.util.stream.Collectors.toList;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.TimeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aQute.bnd.annotation.plugin.BndPlugin;
import aQute.bnd.connection.settings.ConnectionSettings;
import aQute.bnd.exporter.subsystem.SubsystemExporter;
import aQute.bnd.header.Attrs;
import aQute.bnd.header.OSGiHeader;
import aQute.bnd.header.Parameters;
import aQute.bnd.http.HttpClient;
import aQute.bnd.maven.support.Maven;
import aQute.bnd.osgi.About;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Macro;
import aQute.bnd.osgi.Processor;
import aQute.bnd.osgi.Verifier;
import aQute.bnd.resource.repository.ResourceRepositoryImpl;
import aQute.bnd.service.BndListener;
import aQute.bnd.service.RepositoryPlugin;
import aQute.bnd.service.action.Action;
import aQute.bnd.service.extension.ExtensionActivator;
import aQute.bnd.service.lifecycle.LifeCyclePlugin;
import aQute.bnd.service.repository.Prepare;
import aQute.bnd.service.repository.RepositoryDigest;
import aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor;
import aQute.bnd.url.MultiURLConnectionHandler;
import aQute.bnd.version.Version;
import aQute.bnd.version.VersionRange;
import aQute.lib.deployer.FileRepo;
import aQute.lib.hex.Hex;
import aQute.lib.io.IO;
import aQute.lib.io.IOConstants;
import aQute.lib.settings.Settings;
import aQute.lib.strings.Strings;
import aQute.lib.utf8properties.UTF8Properties;
import aQute.lib.zip.ZipUtil;
import aQute.libg.uri.URIUtil;
import aQute.service.reporter.Reporter;
public class Workspace extends Processor {
private final static Logger logger = LoggerFactory.getLogger(Workspace.class);
public static final File BND_DEFAULT_WS = IO.getFile("~/.bnd/default-ws");
public static final String BND_CACHE_REPONAME = "bnd-cache";
public static final String EXT = "ext";
public static final String BUILDFILE = "build.bnd";
public static final String CNFDIR = "cnf";
public static final String BNDDIR = "bnd";
public static final String CACHEDIR = "cache/" + About.CURRENT;
public static final String STANDALONE_REPO_CLASS = "aQute.bnd.repository.osgi.OSGiRepository";
static final int BUFFER_SIZE = IOConstants.PAGE_SIZE * 16;
private static final String PLUGIN_STANDALONE = "-plugin.standalone_";
private final Pattern EMBEDDED_REPO_TESTING_PATTERN = Pattern
.compile(".*biz\\.aQute\\.bnd\\.embedded-repo(-.*)?\\.jar");
static class WorkspaceData {
List<RepositoryPlugin> repositories;
}
private final static Map<File,WeakReference<Workspace>> cache = newHashMap();
static Processor defaults = null;
final Map<String,Project> models = newHashMap();
private final Set<String> modelsUnderConstruction = newSet();
final Map<String,Action> commands = newMap();
final Maven maven = new Maven(Processor.getExecutor());
private final AtomicBoolean offline = new AtomicBoolean();
Settings settings = new Settings();
WorkspaceRepository workspaceRepo = new WorkspaceRepository(this);
static String overallDriver = "unset";
static Parameters overallGestalt = new Parameters();
/**
* Signal a BndListener plugin. We ran an infinite bug loop :-(
*/
final ThreadLocal<Reporter> signalBusy = new ThreadLocal<Reporter>();
ResourceRepositoryImpl resourceRepositoryImpl;
private Parameters gestalt;
private String driver;
private final WorkspaceLayout layout;
final Set<Project> trail = Collections
.newSetFromMap(new ConcurrentHashMap<Project,Boolean>());
private WorkspaceData data = new WorkspaceData();
private File buildDir;
/**
* This static method finds the workspace and creates a project (or returns
* an existing project)
*
* @param projectDir
*/
public static Project getProject(File projectDir) throws Exception {
projectDir = projectDir.getAbsoluteFile();
assert projectDir.isDirectory();
Workspace ws = getWorkspace(projectDir.getParentFile());
return ws.getProject(projectDir.getName());
}
static synchronized public Processor getDefaults() {
if (defaults != null)
return defaults;
UTF8Properties props = new UTF8Properties();
try (InputStream propStream = Workspace.class.getResourceAsStream("defaults.bnd")) {
if (propStream != null) {
props.load(propStream);
} else {
System.err.println("Cannot load defaults");
}
} catch (IOException e) {
throw new IllegalArgumentException("Unable to load bnd defaults.", e);
}
defaults = new Processor(props, false);
return defaults;
}
public static Workspace createDefaultWorkspace() throws Exception {
Workspace ws = new Workspace(BND_DEFAULT_WS, CNFDIR);
return ws;
}
public static Workspace getWorkspace(File workspaceDir) throws Exception {
return getWorkspace(workspaceDir, CNFDIR);
}
public static Workspace getWorkspaceWithoutException(File workspaceDir) throws Exception {
try {
return getWorkspace(workspaceDir);
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* /* Return the nearest workspace
*/
public static Workspace findWorkspace(File base) throws Exception {
File rover = base;
while (rover != null) {
File file = IO.getFile(rover, "cnf/build.bnd");
if (file.isFile())
return getWorkspace(rover);
rover = rover.getParentFile();
}
return null;
}
public static Workspace getWorkspace(File workspaceDir, String bndDir) throws Exception {
workspaceDir = workspaceDir.getAbsoluteFile();
// the cnf directory can actually be a
// file that redirects
while (workspaceDir.isDirectory()) {
File test = new File(workspaceDir, CNFDIR);
if (!test.exists())
test = new File(workspaceDir, bndDir);
if (test.isDirectory())
break;
if (test.isFile()) {
String redirect = IO.collect(test).trim();
test = getFile(test.getParentFile(), redirect).getAbsoluteFile();
workspaceDir = test;
}
if (!test.exists())
throw new IllegalArgumentException("No Workspace found from: " + workspaceDir);
}
synchronized (cache) {
WeakReference<Workspace> wsr = cache.get(workspaceDir);
Workspace ws;
if (wsr == null || (ws = wsr.get()) == null) {
ws = new Workspace(workspaceDir, bndDir);
cache.put(workspaceDir, new WeakReference<Workspace>(ws));
}
return ws;
}
}
public Workspace(File workspaceDir) throws Exception {
this(workspaceDir, CNFDIR);
}
public Workspace(File workspaceDir, String bndDir) throws Exception {
super(getDefaults());
workspaceDir = workspaceDir.getAbsoluteFile();
setBase(workspaceDir); // setBase before call to setFileSystem
this.layout = WorkspaceLayout.BND;
addBasicPlugin(new LoggingProgressPlugin());
setFileSystem(workspaceDir, bndDir);
}
public void setFileSystem(File workspaceDir, String bndDir) throws Exception {
workspaceDir = workspaceDir.getAbsoluteFile();
IO.mkdirs(workspaceDir);
assert workspaceDir.isDirectory();
synchronized (cache) {
WeakReference<Workspace> wsr = cache.get(getBase());
if ((wsr != null) && (wsr.get() == this)) {
cache.remove(getBase());
cache.put(workspaceDir, wsr);
}
}
File buildDir = new File(workspaceDir, bndDir).getAbsoluteFile();
if (!buildDir.isDirectory())
buildDir = new File(workspaceDir, CNFDIR).getAbsoluteFile();
setBuildDir(buildDir);
File buildFile = new File(buildDir, BUILDFILE).getAbsoluteFile();
if (!buildFile.isFile())
warning("No Build File in %s", workspaceDir);
setProperties(buildFile, workspaceDir);
propertiesChanged();
//
// There is a nasty bug/feature in Java that gives errors on our
// SSL use of github. The flag jsse.enableSNIExtension should be set
// to false. So here we provide a way to set system properties
// as early as possible
//
Attrs sysProps = OSGiHeader.parseProperties(mergeProperties(SYSTEMPROPERTIES));
for (Entry<String,String> e : sysProps.entrySet()) {
System.setProperty(e.getKey(), e.getValue());
}
}
private Workspace(WorkspaceLayout layout) throws Exception {
super(getDefaults());
this.layout = layout;
setBuildDir(IO.getFile(BND_DEFAULT_WS, CNFDIR));
}
public Project getProjectFromFile(File projectDir) {
projectDir = projectDir.getAbsoluteFile();
assert projectDir.isDirectory();
if (getBase().equals(projectDir.getParentFile())) {
return getProject(projectDir.getName());
}
return null;
}
public Project getProject(String bsn) {
synchronized (models) {
Project project = models.get(bsn);
if (project != null)
return project;
if (modelsUnderConstruction.add(bsn)) {
try {
File projectDir = getFile(bsn);
project = new Project(this, projectDir);
if (!project.isValid())
return null;
models.put(bsn, project);
} finally {
modelsUnderConstruction.remove(bsn);
}
}
return project;
}
}
void removeProject(Project p) throws Exception {
if (p.isCnf())
return;
synchronized (models) {
models.remove(p.getName());
}
for (LifeCyclePlugin lp : getPlugins(LifeCyclePlugin.class)) {
lp.delete(p);
}
}
public boolean isPresent(String name) {
return models.containsKey(name);
}
public Collection<Project> getCurrentProjects() {
return models.values();
}
@Override
public boolean refresh() {
data = new WorkspaceData();
if (super.refresh()) {
for (Project project : getCurrentProjects()) {
project.propertiesChanged();
}
return true;
}
return false;
}
@Override
public void propertiesChanged() {
data = new WorkspaceData();
File extDir = new File(getBuildDir(), EXT);
File[] extensions = extDir.listFiles();
if (extensions != null) {
for (File extension : extensions) {
String extensionName = extension.getName();
if (extensionName.endsWith(".bnd")) {
extensionName = extensionName.substring(0, extensionName.length() - ".bnd".length());
try {
doIncludeFile(extension, false, getProperties(), "ext." + extensionName);
} catch (Exception e) {
exception(e, "PropertiesChanged: %s", e);
}
}
}
}
super.propertiesChanged();
}
public String _workspace(@SuppressWarnings("unused") String args[]) {
return getBase().getAbsolutePath();
}
public void addCommand(String menu, Action action) {
commands.put(menu, action);
}
public void removeCommand(String menu) {
commands.remove(menu);
}
public void fillActions(Map<String,Action> all) {
all.putAll(commands);
}
public Collection<Project> getAllProjects() throws Exception {
Path basePath = getBase().toPath();
Path bndfile = Paths.get(Project.BNDFILE);
List<Project> projects = Files.walk(basePath, 1, FileVisitOption.FOLLOW_LINKS)
.filter(p -> !basePath.equals(p) && Files.isDirectory(p) && Files.isRegularFile(p.resolve(bndfile)))
.map(p -> getProject(p.getFileName()
.toString()))
.filter(Objects::nonNull)
.collect(toList());
return projects;
}
/**
* Inform any listeners that we changed a file (created/deleted/changed).
*
* @param f The changed file
*/
public void changedFile(File f) {
List<BndListener> listeners = getPlugins(BndListener.class);
for (BndListener l : listeners)
try {
l.changed(f);
} catch (Exception e) {
logger.debug("Exception in a BndListener changedFile method call", e);
}
}
public void bracket(boolean begin) {
List<BndListener> listeners = getPlugins(BndListener.class);
for (BndListener l : listeners)
try {
if (begin)
l.begin();
else
l.end();
} catch (Exception e) {
if (begin)
logger.debug("Exception in a BndListener begin method call", e);
else
logger.debug("Exception in a BndListener end method call", e);
}
}
public void signal(Reporter reporter) {
if (signalBusy.get() != null)
return;
signalBusy.set(reporter);
try {
List<BndListener> listeners = getPlugins(BndListener.class);
for (BndListener l : listeners)
try {
l.signal(this);
} catch (Exception e) {
logger.debug("Exception in a BndListener signal method call", e);
}
} catch (Exception e) {
// Ignore
} finally {
signalBusy.set(null);
}
}
@Override
public void signal() {
signal(this);
}
class CachedFileRepo extends FileRepo {
final Lock lock = new ReentrantLock();
boolean inited;
CachedFileRepo() {
super(BND_CACHE_REPONAME, getCache(BND_CACHE_REPONAME), false);
}
@Override
protected boolean init() throws Exception {
if (lock.tryLock(50, TimeUnit.SECONDS) == false)
throw new TimeLimitExceededException("Cached File Repo is locked and can't acquire it");
try {
if (super.init()) {
inited = true;
IO.mkdirs(root);
if (!root.isDirectory())
throw new IllegalArgumentException("Cache directory " + root + " not a directory");
try (InputStream in = getClass().getResourceAsStream(EMBEDDED_REPO)) {
if (in != null) {
unzip(in, root);
return true;
}
}
// We may be in unit test, look for
// biz.aQute.bnd.embedded-repo.jar on the
// classpath
StringTokenizer classPathTokenizer = new StringTokenizer(
System.getProperty("java.class.path", ""), File.pathSeparator);
while (classPathTokenizer.hasMoreTokens()) {
String classPathEntry = classPathTokenizer.nextToken().trim();
if (EMBEDDED_REPO_TESTING_PATTERN.matcher(classPathEntry).matches()) {
try (InputStream in = IO.stream(Paths.get(classPathEntry))) {
unzip(in, root);
return true;
}
}
}
error("Couldn't find biz.aQute.bnd.embedded-repo on the classpath");
return false;
} else
return false;
} finally {
lock.unlock();
}
}
private void unzip(InputStream in, File dir) throws Exception {
try (JarInputStream jin = new JarInputStream(in)) {
byte[] data = new byte[BUFFER_SIZE];
for (JarEntry jentry = jin.getNextJarEntry(); jentry != null; jentry = jin.getNextJarEntry()) {
if (jentry.isDirectory()) {
continue;
}
String jentryName = jentry.getName();
if (jentryName.startsWith("META-INF/")) {
continue;
}
File dest = getFile(dir, jentryName);
long modifiedTime = ZipUtil.getModifiedTime(jentry);
if (!dest.isFile() || dest.lastModified() < modifiedTime || modifiedTime <= 0) {
File dp = dest.getParentFile();
IO.mkdirs(dp);
try (OutputStream out = IO.outputStream(dest)) {
for (int size = jin.read(data); size > 0; size = jin.read(data)) {
out.write(data, 0, size);
}
}
}
}
}
}
}
public void syncCache() throws Exception {
CachedFileRepo cf = new CachedFileRepo();
cf.init();
cf.close();
}
public List<RepositoryPlugin> getRepositories() throws Exception {
if (data.repositories == null) {
data.repositories = getPlugins(RepositoryPlugin.class);
for (RepositoryPlugin repo : data.repositories) {
if (repo instanceof Prepare) {
((Prepare) repo).prepare();
}
}
}
return data.repositories;
}
public Collection<Project> getBuildOrder() throws Exception {
List<Project> result = new ArrayList<Project>();
for (Project project : getAllProjects()) {
Collection<Project> dependsOn = project.getDependson();
getBuildOrder(dependsOn, result);
if (!result.contains(project)) {
result.add(project);
}
}
return result;
}
private void getBuildOrder(Collection<Project> dependsOn, List<Project> result) throws Exception {
for (Project project : dependsOn) {
Collection<Project> subProjects = project.getDependson();
for (Project subProject : subProjects) {
if (!result.contains(subProject)) {
result.add(subProject);
}
}
if (!result.contains(project)) {
result.add(project);
}
}
}
public static Workspace getWorkspace(String path) throws Exception {
File file = IO.getFile(new File(""), path);
return getWorkspace(file);
}
public Maven getMaven() {
return maven;
}
@Override
protected void setTypeSpecificPlugins(Set<Object> list) {
try {
super.setTypeSpecificPlugins(list);
list.add(this);
list.add(maven);
list.add(settings);
if (!isTrue(getProperty(NOBUILDINCACHE))) {
CachedFileRepo repo = new CachedFileRepo();
list.add(repo);
}
resourceRepositoryImpl = new ResourceRepositoryImpl();
resourceRepositoryImpl.setCache(IO.getFile(getProperty(CACHEDIR, "~/.bnd/caches/shas")));
resourceRepositoryImpl.setExecutor(getExecutor());
resourceRepositoryImpl.setIndexFile(getFile(getBuildDir(), "repo.json"));
resourceRepositoryImpl.setURLConnector(new MultiURLConnectionHandler(this));
customize(resourceRepositoryImpl, null);
list.add(resourceRepositoryImpl);
//
// Exporters
//
list.add(new SubsystemExporter());
try {
HttpClient client = new HttpClient(getExecutor(), getScheduledExecutor());
client.setOffline(getOffline());
client.setRegistry(this);
try (ConnectionSettings cs = new ConnectionSettings(this, client)) {
cs.readSettings();
}
list.add(client);
} catch (Exception e) {
exception(e, "Failed to load the communication settings");
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Add any extensions listed
*
* @param list
*/
@Override
protected void addExtensions(Set<Object> list) {
//
// <bsn>; version=<range>
//
Parameters extensions = getMergedParameters(EXTENSION);
Map<DownloadBlocker,Attrs> blockers = new HashMap<DownloadBlocker,Attrs>();
for (Entry<String,Attrs> i : extensions.entrySet()) {
String bsn = removeDuplicateMarker(i.getKey());
String stringRange = i.getValue().get(VERSION_ATTRIBUTE);
logger.debug("Adding extension {}-{}", bsn, stringRange);
if (stringRange == null)
stringRange = Version.LOWEST.toString();
else if (!VersionRange.isVersionRange(stringRange)) {
error("Invalid version range %s on extension %s", stringRange, bsn);
continue;
}
try {
SortedSet<ResourceDescriptor> matches = resourceRepositoryImpl.find(null, bsn,
new VersionRange(stringRange));
if (matches.isEmpty()) {
error("Extension %s;version=%s not found in base repo", bsn, stringRange);
continue;
}
DownloadBlocker blocker = new DownloadBlocker(this);
blockers.put(blocker, i.getValue());
resourceRepositoryImpl.getResource(matches.last().id, blocker);
} catch (Exception e) {
error("Failed to load extension %s-%s, %s", bsn, stringRange, e);
}
}
logger.debug("Found extensions {}", blockers);
for (Entry<DownloadBlocker,Attrs> blocker : blockers.entrySet()) {
try {
String reason = blocker.getKey().getReason();
if (reason != null) {
error("Extension load failed: %s", reason);
continue;
}
@SuppressWarnings("resource")
URLClassLoader cl = new URLClassLoader(new URL[] {
blocker.getKey().getFile().toURI().toURL()
}, getClass().getClassLoader());
Enumeration<URL> manifests = cl.getResources("META-INF/MANIFEST.MF");
while (manifests.hasMoreElements()) {
try(InputStream is = manifests.nextElement().openStream()) {
Manifest m = new Manifest(is);
Parameters activators = new Parameters(m.getMainAttributes().getValue("Extension-Activator"), this);
for (Entry<String, Attrs> e : activators.entrySet()) {
try {
Class<?> c = cl.loadClass(e.getKey());
ExtensionActivator extensionActivator = (ExtensionActivator) c.getConstructor()
.newInstance();
customize(extensionActivator, blocker.getValue());
List<?> plugins = extensionActivator.activate(this, blocker.getValue());
list.add(extensionActivator);
if (plugins != null)
for (Object plugin : plugins) {
list.add(plugin);
}
} catch (ClassNotFoundException cnfe) {
error("Loading extension %s, extension activator missing: %s (ignored)", blocker,
e.getKey());
}
}
}
}
} catch (Exception e) {
error("failed to install extension %s due to %s", blocker, e);
}
}
}
public boolean isOffline() {
return offline.get();
}
public AtomicBoolean getOffline() {
return offline;
}
public Workspace setOffline(boolean on) {
offline.set(on);
return this;
}
/**
* Provide access to the global settings of this machine.
*
* @throws Exception
*/
public String _global(String[] args) throws Exception {
Macro.verifyCommand(args, "${global;<name>[;<default>]}, get a global setting from ~/.bnd/settings.json", null,
2, 3);
String key = args[1];
if (key.equals("key.public"))
return Hex.toHexString(settings.getPublicKey());
if (key.equals("key.private"))
return Hex.toHexString(settings.getPrivateKey());
String s = settings.get(key);
if (s != null)
return s;
if (args.length == 3)
return args[2];
return null;
}
public String _user(String[] args) throws Exception {
return _global(args);
}
/**
* Return the repository signature digests. These digests are a unique id
* for the contents of the repository
*/
public Object _repodigests(String[] args) throws Exception {
Macro.verifyCommand(args, "${repodigests;[;<repo names>]...}, get the repository digests", null, 1, 10000);
List<RepositoryPlugin> repos = getRepositories();
if (args.length > 1) {
repos: for (Iterator<RepositoryPlugin> it = repos.iterator(); it.hasNext();) {
String name = it.next().getName();
for (int i = 1; i < args.length; i++) {
if (name.equals(args[i])) {
continue repos;
}
}
it.remove();
}
}
List<String> digests = new ArrayList<String>();
for (RepositoryPlugin repo : repos) {
try {
if (repo instanceof RepositoryDigest) {
byte[] digest = ((RepositoryDigest) repo).getDigest();
digests.add(Hex.toHexString(digest));
} else {
if (args.length != 1)
error("Specified repo %s for ${repodigests} was named but it is not found", repo.getName());
}
} catch (Exception e) {
if (args.length != 1)
error("Specified repo %s for digests is not found", repo.getName());
// else Ignore
}
}
return join(digests, ",");
}
public static Run getRun(File file) throws Exception {
if (!file.isFile()) {
return null;
}
File projectDir = file.getParentFile();
File workspaceDir = projectDir.getParentFile();
if (!workspaceDir.isDirectory()) {
return null;
}
Workspace ws = getWorkspaceWithoutException(workspaceDir);
if (ws == null) {
return null;
}
return new Run(ws, projectDir, file);
}
/**
* Report details of this workspace
*/
public void report(Map<String,Object> table) throws Exception {
super.report(table);
table.put("Workspace", toString());
table.put("Plugins", getPlugins(Object.class));
table.put("Repos", getRepositories());
table.put("Projects in build order", getBuildOrder());
}
public File getCache(String name) {
return getFile(buildDir, CACHEDIR + "/" + name);
}
/**
* Return the workspace repo
*/
public WorkspaceRepository getWorkspaceRepository() {
return workspaceRepo;
}
public void checkStructure() {
if (!getBuildDir().isDirectory())
error("No directory for cnf %s", getBuildDir());
else {
File build = IO.getFile(getBuildDir(), BUILDFILE);
if (build.isFile()) {
error("No %s file in %s", BUILDFILE, getBuildDir());
}
}
}
public File getBuildDir() {
return buildDir;
}
public void setBuildDir(File buildDir) {
this.buildDir = buildDir;
}
public boolean isValid() {
return IO.getFile(getBuildDir(), BUILDFILE).isFile();
}
public RepositoryPlugin getRepository(String repo) throws Exception {
for (RepositoryPlugin r : getRepositories()) {
if (repo.equals(r.getName())) {
return r;
}
}
return null;
}
public void close() {
synchronized (cache) {
WeakReference<Workspace> wsr = cache.get(getBase());
if ((wsr != null) && (wsr.get() == this)) {
cache.remove(getBase());
}
}
try {
super.close();
} catch (IOException e) {
/* For backwards compatibility, we ignore the exception */
}
}
/**
* Get the bnddriver, can be null if not set. The overallDriver is the
* environment that runs this bnd.
*/
public String getDriver() {
if (driver == null) {
driver = getProperty(Constants.BNDDRIVER, null);
if (driver != null)
driver = driver.trim();
}
if (driver != null)
return driver;
return overallDriver;
}
/**
* Set the driver of this environment
*/
public static void setDriver(String driver) {
overallDriver = driver;
}
/**
* Macro to return the driver. Without any arguments, we return the name of
* the driver. If there are arguments, we check each of the arguments
* against the name of the driver. If it matches, we return the driver name.
* If none of the args match the driver name we return an empty string
* (which is false).
*/
public String _driver(String args[]) {
if (args.length == 1) {
return getDriver();
}
String driver = getDriver();
if (driver == null)
driver = getProperty(Constants.BNDDRIVER);
if (driver != null) {
for (int i = 1; i < args.length; i++) {
if (args[i].equalsIgnoreCase(driver))
return driver;
}
}
return "";
}
/**
* Add a gestalt to all workspaces. The gestalt is a set of parts describing
* the environment. Each part has a name and optionally attributes. This
* method adds a gestalt to the VM. Per workspace it is possible to augment
* this.
*/
public static void addGestalt(String part, Attrs attrs) {
Attrs already = overallGestalt.get(part);
if (attrs == null)
attrs = new Attrs();
if (already != null) {
already.putAll(attrs);
} else
already = attrs;
overallGestalt.put(part, already);
}
/**
* Get the attrs for a gestalt part
*/
public Attrs getGestalt(String part) {
return getGestalt().get(part);
}
/**
* Get the attrs for a gestalt part
*/
public Parameters getGestalt() {
if (gestalt == null) {
gestalt = getMergedParameters(Constants.GESTALT);
gestalt.mergeWith(overallGestalt, false);
}
return gestalt;
}
/**
* Get the layout style of the workspace.
*/
public WorkspaceLayout getLayout() {
return layout;
}
/**
* The macro to access the gestalt
* <p>
* {@code $ gestalt;part[;key[;value]]}
*/
public String _gestalt(String args[]) {
if (args.length >= 2) {
Attrs attrs = getGestalt(args[1]);
if (attrs == null)
return "";
if (args.length == 2)
return args[1];
String s = attrs.get(args[2]);
if (args.length == 3) {
if (s == null)
s = "";
return s;
}
if (args.length == 4) {
if (args[3].equals(s))
return s;
else
return "";
}
}
throw new IllegalArgumentException("${gestalt;<part>[;key[;<value>]]} has too many arguments");
}
@Override
public String toString() {
return "Workspace [" + getBase().getName() + "]";
}
/**
* Create a project in this workspace
*/
public Project createProject(String name) throws Exception {
if (!Verifier.SYMBOLICNAME.matcher(name).matches()) {
error("A project name is a Bundle Symbolic Name, this must therefore consist of only letters, digits and dots");
return null;
}
File pdir = getFile(name);
IO.mkdirs(pdir);
IO.store("#\n# " + name.toUpperCase().replace('.', ' ') + "\n#\n", getFile(pdir, Project.BNDFILE));
Project p = new Project(this, pdir);
IO.mkdirs(p.getTarget());
IO.mkdirs(p.getOutput());
IO.mkdirs(p.getTestOutput());
for (File dir : p.getSourcePath()) {
IO.mkdirs(dir);
}
IO.mkdirs(p.getTestSrc());
for (LifeCyclePlugin l : getPlugins(LifeCyclePlugin.class))
l.created(p);
if (!p.isValid()) {
error("project %s is not valid", p);
}
return p;
}
/**
* Create a new Workspace
*
* @param wsdir
* @throws Exception
*/
public static Workspace createWorkspace(File wsdir) throws Exception {
if (wsdir.exists())
return null;
IO.mkdirs(wsdir);
File cnf = IO.getFile(wsdir, CNFDIR);
IO.mkdirs(cnf);
IO.store("", new File(cnf, BUILDFILE));
IO.store("-nobundles: true\n", new File(cnf, Project.BNDFILE));
File ext = new File(cnf, EXT);
IO.mkdirs(ext);
Workspace ws = getWorkspace(wsdir);
return ws;
}
/**
* Add a plugin
*
* @param plugin
* @throws Exception
*/
public boolean addPlugin(Class< ? > plugin, String alias, Map<String,String> parameters, boolean force)
throws Exception {
BndPlugin ann = plugin.getAnnotation(BndPlugin.class);
if (alias == null) {
if (ann != null)
alias = ann.name();
else {
alias = Strings.getLastSegment(plugin.getName()).toLowerCase();
if (alias.endsWith("plugin")) {
alias = alias.substring(0, alias.length() - "plugin".length());
}
}
}
if (!Verifier.isBsn(alias)) {
error("Not a valid plugin name %s", alias);
}
File ext = getFile(Workspace.CNFDIR + "/" + Workspace.EXT);
IO.mkdirs(ext);
File f = new File(ext, alias + ".bnd");
if (!force) {
if (f.exists()) {
error("Plugin %s already exists", alias);
return false;
}
} else {
IO.delete(f);
}
Object l = plugin.getConstructor().newInstance();
try (Formatter setup = new Formatter()) {
setup.format("#\n" //
+ "# Plugin %s setup\n" //
+ "#\n", alias);
setup.format("-plugin.%s = %s", alias, plugin.getName());
for (Map.Entry<String,String> e : parameters.entrySet()) {
setup.format("; \\\n \t%s = '%s'", e.getKey(), escaped(e.getValue()));
}
setup.format("\n\n");
String out = setup.toString();
if (l instanceof LifeCyclePlugin) {
out = ((LifeCyclePlugin) l).augmentSetup(out, alias, parameters);
((LifeCyclePlugin) l).init(this);
}
logger.debug("setup {}", out);
IO.store(out, f);
}
refresh();
for (LifeCyclePlugin lp : getPlugins(LifeCyclePlugin.class)) {
lp.addedPlugin(this, plugin.getName(), alias, parameters);
}
return true;
}
static Pattern ESCAPE_P = Pattern.compile("(\"|')(.*)\1");
private Object escaped(String value) {
Matcher matcher = ESCAPE_P.matcher(value);
if (matcher.matches())
value = matcher.group(2);
return value.replaceAll("'", "\\'");
}
public boolean removePlugin(String alias) {
File ext = getFile(Workspace.CNFDIR + "/" + Workspace.EXT);
File f = new File(ext, alias + ".bnd");
if (!f.exists()) {
error("No such plugin %s", alias);
return false;
}
IO.delete(f);
refresh();
return true;
}
/**
* Create a workspace that does not inherit from a cnf directory etc.
*
* @param run
*/
public static Workspace createStandaloneWorkspace(Processor run, URI base) throws Exception {
Workspace ws = new Workspace(WorkspaceLayout.STANDALONE);
Parameters standalone = new Parameters(run.getProperty(STANDALONE), ws);
StringBuilder sb = new StringBuilder();
try (Formatter f = new Formatter(sb, Locale.US)) {
int counter = 1;
for (Map.Entry<String,Attrs> e : standalone.entrySet()) {
String locationStr = e.getKey();
if ("true".equalsIgnoreCase(locationStr))
break;
URI resolvedLocation = URIUtil.resolve(base, locationStr);
String key = f.format("%s%02d", PLUGIN_STANDALONE, counter).toString();
sb.setLength(0);
Attrs attrs = e.getValue();
String name = attrs.get("name");
if (name == null) {
name = String.format("repo%02d", counter);
}
f.format("%s; name='%s'; locations='%s'", STANDALONE_REPO_CLASS, name, resolvedLocation);
for (Map.Entry<String,String> attribEntry : attrs.entrySet()) {
if (!"name".equals(attribEntry.getKey()))
f.format("; %s='%s'", attribEntry.getKey(), attribEntry.getValue());
}
String value = f.toString();
sb.setLength(0);
ws.setProperty(key, value);
counter++;
}
}
return ws;
}
public boolean isDefaultWorkspace() {
return BND_DEFAULT_WS.equals(getBase());
}
}
| workspace: Use LinkedHashSet to generate workspace build order.
This models the desired characteristics and may give better perf on
large workspaces.
Signed-off-by: BJ Hargrave <[email protected]>
| biz.aQute.bndlib/src/aQute/bnd/build/Workspace.java | workspace: Use LinkedHashSet to generate workspace build order. | <ide><path>iz.aQute.bndlib/src/aQute/bnd/build/Workspace.java
<ide> import java.util.Formatter;
<ide> import java.util.HashMap;
<ide> import java.util.Iterator;
<add>import java.util.LinkedHashSet;
<ide> import java.util.List;
<ide> import java.util.Locale;
<ide> import java.util.Map;
<ide> }
<ide>
<ide> public Collection<Project> getBuildOrder() throws Exception {
<del> List<Project> result = new ArrayList<Project>();
<add> Set<Project> result = new LinkedHashSet<Project>();
<ide> for (Project project : getAllProjects()) {
<ide> Collection<Project> dependsOn = project.getDependson();
<ide> getBuildOrder(dependsOn, result);
<del> if (!result.contains(project)) {
<del> result.add(project);
<del> }
<add> result.add(project);
<ide> }
<ide> return result;
<ide> }
<ide>
<del> private void getBuildOrder(Collection<Project> dependsOn, List<Project> result) throws Exception {
<add> private void getBuildOrder(Collection<Project> dependsOn, Set<Project> result) throws Exception {
<ide> for (Project project : dependsOn) {
<ide> Collection<Project> subProjects = project.getDependson();
<ide> for (Project subProject : subProjects) {
<del> if (!result.contains(subProject)) {
<del> result.add(subProject);
<del> }
<del> }
<del> if (!result.contains(project)) {
<del> result.add(project);
<del> }
<add> result.add(subProject);
<add> }
<add> result.add(project);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 3efe0ce533546a949df3f795999ff7b081c309e4 | 0 | ST-DDT/CrazyLogin,ST-DDT/CrazyLogin | src/de/st_ddt/crazylogin/crypt/CustomEncryptor.java | package de.st_ddt.crazylogin.crypt;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
public abstract class CustomEncryptor implements Encryptor
{
//You have to use the default constructor (without parameters)
//If you access the config, please use "customEncryptor.valueName" to store data
@Override
public abstract String encrypt(String name, String salt, String password) throws UnsupportedEncodingException, NoSuchAlgorithmException;
@Override
public abstract boolean match(String name, String password, String encrypted);
@Override
public String getAlgorithm()
{
return "Custom";
}
}
| CrazyLogin: moved custom encryptor to API | src/de/st_ddt/crazylogin/crypt/CustomEncryptor.java | CrazyLogin: moved custom encryptor to API | <ide><path>rc/de/st_ddt/crazylogin/crypt/CustomEncryptor.java
<del>package de.st_ddt.crazylogin.crypt;
<del>
<del>import java.io.UnsupportedEncodingException;
<del>import java.security.NoSuchAlgorithmException;
<del>
<del>public abstract class CustomEncryptor implements Encryptor
<del>{
<del>
<del> //You have to use the default constructor (without parameters)
<del> //If you access the config, please use "customEncryptor.valueName" to store data
<del>
<del> @Override
<del> public abstract String encrypt(String name, String salt, String password) throws UnsupportedEncodingException, NoSuchAlgorithmException;
<del>
<del> @Override
<del> public abstract boolean match(String name, String password, String encrypted);
<del>
<del> @Override
<del> public String getAlgorithm()
<del> {
<del> return "Custom";
<del> }
<del>} |
||
Java | apache-2.0 | 5cd99b8c4d38034250ad94a49c5e0b65e9f5d914 | 0 | leonardoxh/Masks | /*
* Copyright 2014 Leonardo Rossetto
*
* 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.
*/
package com.github.leonardoxh.masks;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
/**
* Default input mask this will change the <code>#</code> char to an number
* @see com.github.leonardoxh.masks.Masks
* @author Leonardo Rossetto <[email protected]>
*/
public class InputMask implements TextWatcher {
private boolean isUpdating;
private String mOldString = "";
private final EditText mEditText;
private final String mMask;
public static final String CPF_MASK = "###.###.###-##";
public static final String CNPJ_MASK = "##.###.###/####-##";
public static final String TELEPHONE_BR = "(##) ####-####";
public InputMask(EditText editText, String mask) {
mEditText = editText;
mMask = mask;
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String str = s.toString().replaceAll("[^\\d]", "");
StringBuilder mask = new StringBuilder();
if (isUpdating) {
mOldString = str;
isUpdating = false;
return;
}
int i = 0;
for(char m : mMask.toCharArray()) {
if (m != '#' && str.length() > mOldString.length()) {
mask.append(m);
continue;
}
try {
mask.append(str.charAt(i));
} catch (Exception e) {
break;
}
i++;
}
isUpdating = true;
mEditText.setText(mask.toString());
mEditText.setSelection(mask.length());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override
public void afterTextChanged(Editable s) { }
}
| library/library/src/main/java/com/github/leonardoxh/masks/InputMask.java | /*
* Copyright 2014 Leonardo Rossetto
*
* 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.
*/
package com.github.leonardoxh.masks;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
/**
* Default input mask this will change the <code>#</code> char to an number
* @see com.github.leonardoxh.masks.Masks
* @author Leonardo Rossetto <[email protected]>
*/
public class InputMask implements TextWatcher {
private boolean isUpdating;
private String mOldString = "";
private final EditText mEditText;
private final String mMask;
public InputMask(EditText editText, String mask) {
mEditText = editText;
mMask = mask;
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String str = s.toString().replaceAll("[^\\d]", "");
String mask = "";
if (isUpdating) {
mOldString = str;
isUpdating = false;
return;
}
int i = 0;
for(char m : mMask.toCharArray()) {
if (m != '#' && str.length() > mOldString.length()) {
mask += m;
continue;
}
try {
mask += str.charAt(i);
} catch (Exception e) {
break;
}
i++;
}
isUpdating = true;
mEditText.setText(mask);
mEditText.setSelection(mask.length());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override
public void afterTextChanged(Editable s) { }
}
| Speed up
| library/library/src/main/java/com/github/leonardoxh/masks/InputMask.java | Speed up | <ide><path>ibrary/library/src/main/java/com/github/leonardoxh/masks/InputMask.java
<ide> private final EditText mEditText;
<ide> private final String mMask;
<ide>
<add> public static final String CPF_MASK = "###.###.###-##";
<add> public static final String CNPJ_MASK = "##.###.###/####-##";
<add> public static final String TELEPHONE_BR = "(##) ####-####";
<add>
<ide> public InputMask(EditText editText, String mask) {
<ide> mEditText = editText;
<ide> mMask = mask;
<ide> public void onTextChanged(CharSequence s, int start, int before,
<ide> int count) {
<ide> String str = s.toString().replaceAll("[^\\d]", "");
<del> String mask = "";
<add> StringBuilder mask = new StringBuilder();
<ide> if (isUpdating) {
<ide> mOldString = str;
<ide> isUpdating = false;
<ide> int i = 0;
<ide> for(char m : mMask.toCharArray()) {
<ide> if (m != '#' && str.length() > mOldString.length()) {
<del> mask += m;
<add> mask.append(m);
<ide> continue;
<ide> }
<ide> try {
<del> mask += str.charAt(i);
<add> mask.append(str.charAt(i));
<ide> } catch (Exception e) {
<ide> break;
<ide> }
<ide> i++;
<ide> }
<ide> isUpdating = true;
<del> mEditText.setText(mask);
<add> mEditText.setText(mask.toString());
<ide> mEditText.setSelection(mask.length());
<ide> }
<ide> |
|
Java | apache-2.0 | c9e1bf33aaff20b4698f926b0a11589167beab65 | 0 | salikjan/camel,pax95/camel,tdiesler/camel,onders86/camel,christophd/camel,gilfernandes/camel,nboukhed/camel,anton-k11/camel,cunningt/camel,tlehoux/camel,ullgren/camel,zregvart/camel,curso007/camel,w4tson/camel,driseley/camel,drsquidop/camel,anton-k11/camel,davidkarlsen/camel,pkletsko/camel,jamesnetherton/camel,driseley/camel,lburgazzoli/camel,tlehoux/camel,yuruki/camel,curso007/camel,Thopap/camel,prashant2402/camel,zregvart/camel,tadayosi/camel,tdiesler/camel,lburgazzoli/camel,allancth/camel,tlehoux/camel,salikjan/camel,mcollovati/camel,lburgazzoli/apache-camel,akhettar/camel,NickCis/camel,mgyongyosi/camel,nicolaferraro/camel,CodeSmell/camel,scranton/camel,prashant2402/camel,NickCis/camel,yuruki/camel,DariusX/camel,kevinearls/camel,chirino/camel,onders86/camel,pax95/camel,DariusX/camel,jonmcewen/camel,ullgren/camel,chirino/camel,punkhorn/camel-upstream,onders86/camel,christophd/camel,rmarting/camel,lburgazzoli/apache-camel,jamesnetherton/camel,kevinearls/camel,gilfernandes/camel,cunningt/camel,nboukhed/camel,anoordover/camel,jamesnetherton/camel,dmvolod/camel,tlehoux/camel,pkletsko/camel,Thopap/camel,rmarting/camel,acartapanis/camel,tdiesler/camel,gilfernandes/camel,mcollovati/camel,ssharma/camel,isavin/camel,jkorab/camel,jonmcewen/camel,lburgazzoli/apache-camel,NickCis/camel,rmarting/camel,anoordover/camel,anton-k11/camel,alvinkwekel/camel,lburgazzoli/camel,allancth/camel,veithen/camel,alvinkwekel/camel,acartapanis/camel,snurmine/camel,tdiesler/camel,scranton/camel,lburgazzoli/camel,driseley/camel,jkorab/camel,curso007/camel,lburgazzoli/apache-camel,pkletsko/camel,cunningt/camel,akhettar/camel,adessaigne/camel,gautric/camel,kevinearls/camel,akhettar/camel,nboukhed/camel,onders86/camel,RohanHart/camel,adessaigne/camel,apache/camel,onders86/camel,zregvart/camel,acartapanis/camel,nikhilvibhav/camel,apache/camel,acartapanis/camel,driseley/camel,anton-k11/camel,nicolaferraro/camel,lburgazzoli/camel,objectiser/camel,yuruki/camel,punkhorn/camel-upstream,RohanHart/camel,punkhorn/camel-upstream,akhettar/camel,apache/camel,gautric/camel,pax95/camel,lburgazzoli/camel,NickCis/camel,adessaigne/camel,cunningt/camel,yuruki/camel,cunningt/camel,gnodet/camel,kevinearls/camel,chirino/camel,pmoerenhout/camel,tadayosi/camel,Thopap/camel,acartapanis/camel,yuruki/camel,lburgazzoli/apache-camel,tadayosi/camel,cunningt/camel,pax95/camel,jonmcewen/camel,veithen/camel,snurmine/camel,mgyongyosi/camel,ssharma/camel,Fabryprog/camel,Thopap/camel,rmarting/camel,chirino/camel,apache/camel,veithen/camel,gnodet/camel,w4tson/camel,jkorab/camel,isavin/camel,dmvolod/camel,christophd/camel,pkletsko/camel,gilfernandes/camel,CodeSmell/camel,pmoerenhout/camel,akhettar/camel,punkhorn/camel-upstream,objectiser/camel,davidkarlsen/camel,onders86/camel,driseley/camel,curso007/camel,anoordover/camel,gnodet/camel,anton-k11/camel,allancth/camel,snurmine/camel,drsquidop/camel,RohanHart/camel,jkorab/camel,jkorab/camel,gnodet/camel,CodeSmell/camel,jamesnetherton/camel,DariusX/camel,tadayosi/camel,isavin/camel,mcollovati/camel,pax95/camel,mgyongyosi/camel,objectiser/camel,CodeSmell/camel,scranton/camel,sverkera/camel,drsquidop/camel,rmarting/camel,pmoerenhout/camel,dmvolod/camel,anton-k11/camel,pmoerenhout/camel,ssharma/camel,pax95/camel,w4tson/camel,nboukhed/camel,prashant2402/camel,DariusX/camel,anoordover/camel,apache/camel,scranton/camel,rmarting/camel,scranton/camel,tdiesler/camel,adessaigne/camel,mcollovati/camel,snurmine/camel,Thopap/camel,w4tson/camel,acartapanis/camel,nboukhed/camel,scranton/camel,jkorab/camel,tdiesler/camel,veithen/camel,drsquidop/camel,ullgren/camel,Thopap/camel,kevinearls/camel,drsquidop/camel,sverkera/camel,mgyongyosi/camel,nboukhed/camel,dmvolod/camel,akhettar/camel,Fabryprog/camel,snurmine/camel,prashant2402/camel,pmoerenhout/camel,ssharma/camel,ssharma/camel,christophd/camel,ssharma/camel,snurmine/camel,RohanHart/camel,gautric/camel,zregvart/camel,nicolaferraro/camel,curso007/camel,alvinkwekel/camel,ullgren/camel,mgyongyosi/camel,sverkera/camel,allancth/camel,pkletsko/camel,allancth/camel,jonmcewen/camel,veithen/camel,anoordover/camel,NickCis/camel,dmvolod/camel,allancth/camel,RohanHart/camel,christophd/camel,nikhilvibhav/camel,Fabryprog/camel,nikhilvibhav/camel,dmvolod/camel,apache/camel,davidkarlsen/camel,nicolaferraro/camel,jamesnetherton/camel,jamesnetherton/camel,tadayosi/camel,tlehoux/camel,veithen/camel,sverkera/camel,christophd/camel,alvinkwekel/camel,gnodet/camel,gautric/camel,prashant2402/camel,gautric/camel,isavin/camel,chirino/camel,drsquidop/camel,curso007/camel,RohanHart/camel,driseley/camel,chirino/camel,adessaigne/camel,mgyongyosi/camel,sverkera/camel,yuruki/camel,Fabryprog/camel,lburgazzoli/apache-camel,adessaigne/camel,anoordover/camel,jonmcewen/camel,objectiser/camel,tlehoux/camel,gilfernandes/camel,tadayosi/camel,nikhilvibhav/camel,prashant2402/camel,isavin/camel,pmoerenhout/camel,kevinearls/camel,davidkarlsen/camel,w4tson/camel,w4tson/camel,jonmcewen/camel,sverkera/camel,NickCis/camel,gautric/camel,gilfernandes/camel,pkletsko/camel,isavin/camel | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.camel.component.ignite.messaging;
import java.net.URI;
import java.util.Map;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.component.ignite.AbstractIgniteEndpoint;
import org.apache.camel.component.ignite.ClusterGroupExpression;
import org.apache.camel.component.ignite.IgniteComponent;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteMessaging;
/**
* Ignite Messaging endpoint.
*/
@UriEndpoint(scheme = "ignite:messaging", title = "Ignite Messaging", syntax = "ignite:messaging:[topic]", label = "nosql,cache,messaging",
consumerClass = IgniteMessagingConsumer.class)
public class IgniteMessagingEndpoint extends AbstractIgniteEndpoint {
@UriParam
@Metadata(required = "true")
private String topic;
@UriParam
private ClusterGroupExpression clusterGroupExpression;
@UriParam
private IgniteMessagingSendMode sendMode = IgniteMessagingSendMode.UNORDERED;
@UriParam
private Long timeout;
public IgniteMessagingEndpoint(String endpointUri, URI remainingUri, Map<String, Object> parameters, IgniteComponent igniteComponent) {
super(endpointUri, igniteComponent);
topic = remainingUri.getHost();
}
@Override
public Producer createProducer() throws Exception {
// Validate options.
if (topic == null) {
throw new IllegalStateException("Cannot initialize an Ignite Messaging Producer with a null topic.");
}
if (sendMode == IgniteMessagingSendMode.ORDERED && timeout == null) {
throw new IllegalStateException("Cannot initialize an Ignite Messaging Producer in ORDERED send mode without a timeout.");
}
// Initialize the Producer.
IgniteMessaging messaging = createIgniteMessaging();
return new IgniteMessagingProducer(this, igniteComponent().getIgnite(), messaging);
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
// Validate options.
if (topic == null) {
throw new IllegalStateException("Cannot initialize an Ignite Messaging Consumer with a null topic.");
}
// Initialize the Consumer.
IgniteMessaging messaging = createIgniteMessaging();
IgniteMessagingConsumer consumer = new IgniteMessagingConsumer(this, processor, messaging);
configureConsumer(consumer);
return consumer;
}
private IgniteMessaging createIgniteMessaging() {
Ignite ignite = ignite();
IgniteMessaging messaging = clusterGroupExpression == null ? ignite.message() : ignite.message(clusterGroupExpression.getClusterGroup(ignite));
return messaging;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public ClusterGroupExpression getClusterGroupExpression() {
return clusterGroupExpression;
}
public void setClusterGroupExpression(ClusterGroupExpression clusterGroupExpression) {
this.clusterGroupExpression = clusterGroupExpression;
}
public Long getTimeout() {
return timeout;
}
public void setTimeout(Long timeout) {
this.timeout = timeout;
}
public IgniteMessagingSendMode getSendMode() {
return sendMode;
}
public void setSendMode(IgniteMessagingSendMode sendMode) {
this.sendMode = sendMode;
}
}
| components/camel-ignite/src/main/java/org/apache/camel/component/ignite/messaging/IgniteMessagingEndpoint.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.camel.component.ignite.messaging;
import java.net.URI;
import java.util.Map;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.component.ignite.AbstractIgniteEndpoint;
import org.apache.camel.component.ignite.ClusterGroupExpression;
import org.apache.camel.component.ignite.IgniteComponent;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteMessaging;
/**
* Ignite Messaging endpoint.
*/
@UriEndpoint(scheme = "ignite:messaging", title = "Ignite Messaging", syntax = "ignite:messaging:[topic]", label = "nosql,cache,messaging",
consumerClass = IgniteMessagingConsumer.class)
public class IgniteMessagingEndpoint extends AbstractIgniteEndpoint {
@UriParam
@Metadata(required = "true")
private String topic;
@UriParam
private ClusterGroupExpression clusterGroupExpression;
@UriParam
private IgniteMessagingSendMode sendMode = IgniteMessagingSendMode.UNORDERED;
@UriParam
private Long timeout;
public IgniteMessagingEndpoint(String endpointUri, URI remainingUri, Map<String, Object> parameters, IgniteComponent igniteComponent) {
super(endpointUri, igniteComponent);
topic = remainingUri.getHost();
}
@Override
public Producer createProducer() throws Exception {
// Validate options.
if (topic == null) {
throw new IllegalStateException("Cannot initialize an Ignite Messaging Producer with a null topic.");
}
if (sendMode == IgniteMessagingSendMode.ORDERED && timeout == null) {
throw new IllegalStateException("Cannot initialize an Ignite Messaging Producer in ORDERED send mode without a timeout.");
}
// Initialize the Producer.
IgniteMessaging messaging = createIgniteMessaging();
return new IgniteMessagingProducer(this, igniteComponent().getIgnite(), messaging);
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
// Validate options.
if (topic == null) {
new IllegalStateException("Cannot initialize an Ignite Messaging Producer with a null topic.");
}
// Initialize the Consumer.
IgniteMessaging messaging = createIgniteMessaging();
IgniteMessagingConsumer consumer = new IgniteMessagingConsumer(this, processor, messaging);
configureConsumer(consumer);
return consumer;
}
private IgniteMessaging createIgniteMessaging() {
Ignite ignite = ignite();
IgniteMessaging messaging = clusterGroupExpression == null ? ignite.message() : ignite.message(clusterGroupExpression.getClusterGroup(ignite));
return messaging;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public ClusterGroupExpression getClusterGroupExpression() {
return clusterGroupExpression;
}
public void setClusterGroupExpression(ClusterGroupExpression clusterGroupExpression) {
this.clusterGroupExpression = clusterGroupExpression;
}
public Long getTimeout() {
return timeout;
}
public void setTimeout(Long timeout) {
this.timeout = timeout;
}
public IgniteMessagingSendMode getSendMode() {
return sendMode;
}
public void setSendMode(IgniteMessagingSendMode sendMode) {
this.sendMode = sendMode;
}
}
| CAMEL-10637: Throw IllegalStateException with a correct exception message
| components/camel-ignite/src/main/java/org/apache/camel/component/ignite/messaging/IgniteMessagingEndpoint.java | CAMEL-10637: Throw IllegalStateException with a correct exception message | <ide><path>omponents/camel-ignite/src/main/java/org/apache/camel/component/ignite/messaging/IgniteMessagingEndpoint.java
<ide> public Consumer createConsumer(Processor processor) throws Exception {
<ide> // Validate options.
<ide> if (topic == null) {
<del> new IllegalStateException("Cannot initialize an Ignite Messaging Producer with a null topic.");
<add> throw new IllegalStateException("Cannot initialize an Ignite Messaging Consumer with a null topic.");
<ide> }
<ide>
<ide> // Initialize the Consumer. |
|
Java | lgpl-2.1 | 8ef216ab0c7dc49cf831eb929a0a99542aa0f264 | 0 | jfree/jfreechart-fse,oskopek/jfreechart-fse,oskopek/jfreechart-fse,jfree/jfreechart-fse | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2014, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ------------------
* SpiderWebPlot.java
* ------------------
* (C) Copyright 2005-2014, by Heaps of Flavour Pty Ltd and Contributors.
*
* Company Info: http://www.i4-talent.com
*
* Original Author: Don Elliott;
* Contributor(s): David Gilbert (for Object Refinery Limited);
* Nina Jeliazkova;
*
* Changes
* -------
* 28-Jan-2005 : First cut - missing a few features - still to do:
* - needs tooltips/URL/label generator functions
* - ticks on axes / background grid?
* 31-Jan-2005 : Renamed SpiderWebPlot, added label generator support, and
* reformatted for consistency with other source files in
* JFreeChart (DG);
* 20-Apr-2005 : Renamed CategoryLabelGenerator
* --> CategoryItemLabelGenerator (DG);
* 05-May-2005 : Updated draw() method parameters (DG);
* 10-Jun-2005 : Added equals() method and fixed serialization (DG);
* 16-Jun-2005 : Added default constructor and get/setDataset()
* methods (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 05-Apr-2006 : Fixed bug preventing the display of zero values - see patch
* 1462727 (DG);
* 05-Apr-2006 : Added support for mouse clicks, tool tips and URLs - see patch
* 1463455 (DG);
* 01-Jun-2006 : Fix bug 1493199, NullPointerException when drawing with null
* info (DG);
* 05-Feb-2007 : Added attributes for axis stroke and paint, while fixing
* bug 1651277, and implemented clone() properly (DG);
* 06-Feb-2007 : Changed getPlotValue() to protected, as suggested in bug
* 1605202 (DG);
* 05-Mar-2007 : Restore clip region correctly (see bug 1667750) (DG);
* 18-May-2007 : Set dataset for LegendItem (DG);
* 02-Jun-2008 : Fixed bug with chart entities using TableOrder.BY_COLUMN (DG);
* 02-Jun-2008 : Fixed bug with null dataset (DG);
* 01-Jun-2009 : Set series key in getLegendItems() (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
* 10-Mar-2014 : Removed LegendItemCollection (DG);
*
*/
package org.jfree.chart.plot;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jfree.chart.LegendItem;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.util.ObjectUtils;
import org.jfree.chart.util.PaintUtils;
import org.jfree.chart.util.Rotation;
import org.jfree.chart.util.ShapeUtils;
import org.jfree.chart.util.StrokeList;
import org.jfree.chart.util.TableOrder;
import org.jfree.chart.entity.CategoryItemEntity;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.labels.CategoryToolTipGenerator;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.urls.CategoryURLGenerator;
import org.jfree.chart.util.SerialUtils;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.general.DatasetUtilities;
/**
* A plot that displays data from a {@link CategoryDataset} in the form of a
* "spider web". Multiple series can be plotted on the same axis to allow
* easy comparison. This plot doesn't support negative values at present.
*/
public class SpiderWebPlot extends Plot implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -5376340422031599463L;
/** The default head radius percent (currently 1%). */
public static final double DEFAULT_HEAD = 0.01;
/** The default axis label gap (currently 10%). */
public static final double DEFAULT_AXIS_LABEL_GAP = 0.10;
/** The default interior gap. */
public static final double DEFAULT_INTERIOR_GAP = 0.25;
/** The maximum interior gap (currently 40%). */
public static final double MAX_INTERIOR_GAP = 0.40;
/** The default starting angle for the radar chart axes. */
public static final double DEFAULT_START_ANGLE = 90.0;
/** The default series label font. */
public static final Font DEFAULT_LABEL_FONT = new Font("SansSerif",
Font.PLAIN, 10);
/** The default series label paint. */
public static final Paint DEFAULT_LABEL_PAINT = Color.BLACK;
/** The default series label background paint. */
public static final Paint DEFAULT_LABEL_BACKGROUND_PAINT
= new Color(255, 255, 192);
/** The default series label outline paint. */
public static final Paint DEFAULT_LABEL_OUTLINE_PAINT = Color.BLACK;
/** The default series label outline stroke. */
public static final Stroke DEFAULT_LABEL_OUTLINE_STROKE
= new BasicStroke(0.5f);
/** The default series label shadow paint. */
public static final Paint DEFAULT_LABEL_SHADOW_PAINT = Color.LIGHT_GRAY;
/**
* The default maximum value plotted - forces the plot to evaluate
* the maximum from the data passed in
*/
public static final double DEFAULT_MAX_VALUE = -1.0;
/** The head radius as a percentage of the available drawing area. */
protected double headPercent;
/** The space left around the outside of the plot as a percentage. */
private double interiorGap;
/** The gap between the labels and the axes as a %age of the radius. */
private double axisLabelGap;
/**
* The paint used to draw the axis lines.
*
* @since 1.0.4
*/
private transient Paint axisLinePaint;
/**
* The stroke used to draw the axis lines.
*
* @since 1.0.4
*/
private transient Stroke axisLineStroke;
/** The dataset. */
private CategoryDataset dataset;
/** The maximum value we are plotting against on each category axis */
private double maxValue;
/**
* The data extract order (BY_ROW or BY_COLUMN). This denotes whether
* the data series are stored in rows (in which case the category names are
* derived from the column keys) or in columns (in which case the category
* names are derived from the row keys).
*/
private TableOrder dataExtractOrder;
/** The starting angle. */
private double startAngle;
/** The direction for drawing the radar axis & plots. */
private Rotation direction;
/** The legend item shape. */
private transient Shape legendItemShape;
/** A map containing the paint for each series. */
private transient Map<Integer, Paint> seriesPaintMap;
/** The base series paint (fallback). */
private transient Paint baseSeriesPaint;
/** A map containing the outline paint for each series. */
private transient Map<Integer, Paint> seriesOutlinePaintMap;
/** The base series outline paint (fallback). */
private transient Paint baseSeriesOutlinePaint;
/** The series outline stroke list. */
private StrokeList seriesOutlineStrokeList;
/** The base series outline stroke (fallback). */
private transient Stroke baseSeriesOutlineStroke;
/** The font used to display the category labels. */
private Font labelFont;
/** The color used to draw the category labels. */
private transient Paint labelPaint;
/** The label generator. */
private CategoryItemLabelGenerator labelGenerator;
/** controls if the web polygons are filled or not */
private boolean webFilled = true;
/** A tooltip generator for the plot (<code>null</code> permitted). */
private CategoryToolTipGenerator toolTipGenerator;
/** A URL generator for the plot (<code>null</code> permitted). */
private CategoryURLGenerator urlGenerator;
/**
* Creates a default plot with no dataset.
*/
public SpiderWebPlot() {
this(null);
}
/**
* Creates a new spider web plot with the given dataset, with each row
* representing a series.
*
* @param dataset the dataset (<code>null</code> permitted).
*/
public SpiderWebPlot(CategoryDataset dataset) {
this(dataset, TableOrder.BY_ROW);
}
/**
* Creates a new spider web plot with the given dataset.
*
* @param dataset the dataset.
* @param extract controls how data is extracted ({@link TableOrder#BY_ROW}
* or {@link TableOrder#BY_COLUMN}).
*/
public SpiderWebPlot(CategoryDataset dataset, TableOrder extract) {
super();
if (extract == null) {
throw new IllegalArgumentException("Null 'extract' argument.");
}
this.dataset = dataset;
if (dataset != null) {
dataset.addChangeListener(this);
}
this.dataExtractOrder = extract;
this.headPercent = DEFAULT_HEAD;
this.axisLabelGap = DEFAULT_AXIS_LABEL_GAP;
this.axisLinePaint = Color.BLACK;
this.axisLineStroke = new BasicStroke(1.0f);
this.interiorGap = DEFAULT_INTERIOR_GAP;
this.startAngle = DEFAULT_START_ANGLE;
this.direction = Rotation.CLOCKWISE;
this.maxValue = DEFAULT_MAX_VALUE;
this.seriesPaintMap = new HashMap<Integer, Paint>();
this.baseSeriesPaint = null;
this.seriesOutlinePaintMap = new HashMap<Integer, Paint>();
this.baseSeriesOutlinePaint = Color.GRAY;
this.seriesOutlineStrokeList = new StrokeList();
this.baseSeriesOutlineStroke = DEFAULT_OUTLINE_STROKE;
this.labelFont = DEFAULT_LABEL_FONT;
this.labelPaint = DEFAULT_LABEL_PAINT;
this.labelGenerator = new StandardCategoryItemLabelGenerator();
this.legendItemShape = DEFAULT_LEGEND_ITEM_CIRCLE;
}
/**
* Returns a short string describing the type of plot.
*
* @return The plot type.
*/
@Override
public String getPlotType() {
// return localizationResources.getString("Radar_Plot");
return ("Spider Web Plot");
}
/**
* Returns the dataset.
*
* @return The dataset (possibly <code>null</code>).
*
* @see #setDataset(CategoryDataset)
*/
public CategoryDataset getDataset() {
return this.dataset;
}
/**
* Sets the dataset used by the plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @see #getDataset()
*/
public void setDataset(CategoryDataset dataset) {
// if there is an existing dataset, remove the plot from the list of
// change listeners...
if (this.dataset != null) {
this.dataset.removeChangeListener(this);
}
// set the new dataset, and register the chart as a change listener...
this.dataset = dataset;
if (dataset != null) {
dataset.addChangeListener(this);
}
// send a dataset change event to self to trigger plot change event
datasetChanged(new DatasetChangeEvent(this, dataset));
}
/**
* Method to determine if the web chart is to be filled.
*
* @return A boolean.
*
* @see #setWebFilled(boolean)
*/
public boolean isWebFilled() {
return this.webFilled;
}
/**
* Sets the webFilled flag and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param flag the flag.
*
* @see #isWebFilled()
*/
public void setWebFilled(boolean flag) {
this.webFilled = flag;
fireChangeEvent();
}
/**
* Returns the data extract order (by row or by column).
*
* @return The data extract order (never <code>null</code>).
*
* @see #setDataExtractOrder(TableOrder)
*/
public TableOrder getDataExtractOrder() {
return this.dataExtractOrder;
}
/**
* Sets the data extract order (by row or by column) and sends a
* {@link PlotChangeEvent}to all registered listeners.
*
* @param order the order (<code>null</code> not permitted).
*
* @throws IllegalArgumentException if <code>order</code> is
* <code>null</code>.
*
* @see #getDataExtractOrder()
*/
public void setDataExtractOrder(TableOrder order) {
if (order == null) {
throw new IllegalArgumentException("Null 'order' argument");
}
this.dataExtractOrder = order;
fireChangeEvent();
}
/**
* Returns the head percent.
*
* @return The head percent.
*
* @see #setHeadPercent(double)
*/
public double getHeadPercent() {
return this.headPercent;
}
/**
* Sets the head percent and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param percent the percent.
*
* @see #getHeadPercent()
*/
public void setHeadPercent(double percent) {
this.headPercent = percent;
fireChangeEvent();
}
/**
* Returns the start angle for the first radar axis.
* <BR>
* This is measured in degrees starting from 3 o'clock (Java Arc2D default)
* and measuring anti-clockwise.
*
* @return The start angle.
*
* @see #setStartAngle(double)
*/
public double getStartAngle() {
return this.startAngle;
}
/**
* Sets the starting angle and sends a {@link PlotChangeEvent} to all
* registered listeners.
* <P>
* The initial default value is 90 degrees, which corresponds to 12 o'clock.
* A value of zero corresponds to 3 o'clock... this is the encoding used by
* Java's Arc2D class.
*
* @param angle the angle (in degrees).
*
* @see #getStartAngle()
*/
public void setStartAngle(double angle) {
this.startAngle = angle;
fireChangeEvent();
}
/**
* Returns the maximum value any category axis can take.
*
* @return The maximum value.
*
* @see #setMaxValue(double)
*/
public double getMaxValue() {
return this.maxValue;
}
/**
* Sets the maximum value any category axis can take and sends
* a {@link PlotChangeEvent} to all registered listeners.
*
* @param value the maximum value.
*
* @see #getMaxValue()
*/
public void setMaxValue(double value) {
this.maxValue = value;
fireChangeEvent();
}
/**
* Returns the direction in which the radar axes are drawn
* (clockwise or anti-clockwise).
*
* @return The direction (never <code>null</code>).
*
* @see #setDirection(Rotation)
*/
public Rotation getDirection() {
return this.direction;
}
/**
* Sets the direction in which the radar axes are drawn and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param direction the direction (<code>null</code> not permitted).
*
* @see #getDirection()
*/
public void setDirection(Rotation direction) {
if (direction == null) {
throw new IllegalArgumentException("Null 'direction' argument.");
}
this.direction = direction;
fireChangeEvent();
}
/**
* Returns the interior gap, measured as a percentage of the available
* drawing space.
*
* @return The gap (as a percentage of the available drawing space).
*
* @see #setInteriorGap(double)
*/
public double getInteriorGap() {
return this.interiorGap;
}
/**
* Sets the interior gap and sends a {@link PlotChangeEvent} to all
* registered listeners. This controls the space between the edges of the
* plot and the plot area itself (the region where the axis labels appear).
*
* @param percent the gap (as a percentage of the available drawing space).
*
* @see #getInteriorGap()
*/
public void setInteriorGap(double percent) {
if ((percent < 0.0) || (percent > MAX_INTERIOR_GAP)) {
throw new IllegalArgumentException(
"Percentage outside valid range.");
}
if (this.interiorGap != percent) {
this.interiorGap = percent;
fireChangeEvent();
}
}
/**
* Returns the axis label gap.
*
* @return The axis label gap.
*
* @see #setAxisLabelGap(double)
*/
public double getAxisLabelGap() {
return this.axisLabelGap;
}
/**
* Sets the axis label gap and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param gap the gap.
*
* @see #getAxisLabelGap()
*/
public void setAxisLabelGap(double gap) {
this.axisLabelGap = gap;
fireChangeEvent();
}
/**
* Returns the paint used to draw the axis lines.
*
* @return The paint used to draw the axis lines (never <code>null</code>).
*
* @see #setAxisLinePaint(Paint)
* @see #getAxisLineStroke()
* @since 1.0.4
*/
public Paint getAxisLinePaint() {
return this.axisLinePaint;
}
/**
* Sets the paint used to draw the axis lines and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getAxisLinePaint()
* @since 1.0.4
*/
public void setAxisLinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.axisLinePaint = paint;
fireChangeEvent();
}
/**
* Returns the stroke used to draw the axis lines.
*
* @return The stroke used to draw the axis lines (never <code>null</code>).
*
* @see #setAxisLineStroke(Stroke)
* @see #getAxisLinePaint()
* @since 1.0.4
*/
public Stroke getAxisLineStroke() {
return this.axisLineStroke;
}
/**
* Sets the stroke used to draw the axis lines and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getAxisLineStroke()
* @since 1.0.4
*/
public void setAxisLineStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.axisLineStroke = stroke;
fireChangeEvent();
}
//// SERIES PAINT /////////////////////////
/**
* Returns the paint for the specified series.
*
* @param series the series index (zero-based).
*
* @return The paint (never <code>null</code>).
*
* @see #setSeriesPaint(int, Paint)
*/
public Paint getSeriesPaint(int series) {
Paint result = this.seriesPaintMap.get(series);
if (result == null) {
DrawingSupplier supplier = getDrawingSupplier();
if (supplier != null) {
Paint p = supplier.getNextPaint();
this.seriesPaintMap.put(series, p);
result = p;
}
else {
result = this.baseSeriesPaint;
}
}
return result;
}
/**
* Sets the paint used to fill a series of the radar and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param paint the paint (<code>null</code> permitted).
*
* @see #getSeriesPaint(int)
*/
public void setSeriesPaint(int series, Paint paint) {
this.seriesPaintMap.put(series, paint);
fireChangeEvent();
}
/**
* Returns the base series paint. This is used when no other paint is
* available.
*
* @return The paint (never <code>null</code>).
*
* @see #setBaseSeriesPaint(Paint)
*/
public Paint getBaseSeriesPaint() {
return this.baseSeriesPaint;
}
/**
* Sets the base series paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getBaseSeriesPaint()
*/
public void setBaseSeriesPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.baseSeriesPaint = paint;
fireChangeEvent();
}
//// SERIES OUTLINE PAINT ////////////////////////////
/**
* Returns the paint for the specified series.
*
* @param series the series index (zero-based).
*
* @return The paint (never <code>null</code>).
*/
public Paint getSeriesOutlinePaint(int series) {
Paint result = this.seriesOutlinePaintMap.get(series);
if (result == null) {
result = this.baseSeriesOutlinePaint;
}
return result;
}
/**
* Sets the paint used to fill a series of the radar and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param paint the paint (<code>null</code> permitted).
*/
public void setSeriesOutlinePaint(int series, Paint paint) {
this.seriesOutlinePaintMap.put(series, paint);
fireChangeEvent();
}
/**
* Returns the base series paint. This is used when no other paint is
* available.
*
* @return The paint (never <code>null</code>).
*/
public Paint getBaseSeriesOutlinePaint() {
return this.baseSeriesOutlinePaint;
}
/**
* Sets the base series paint.
*
* @param paint the paint (<code>null</code> not permitted).
*/
public void setBaseSeriesOutlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.baseSeriesOutlinePaint = paint;
fireChangeEvent();
}
//// SERIES OUTLINE STROKE /////////////////////
/**
* Returns the stroke for the specified series.
*
* @param series the series index (zero-based).
*
* @return The stroke (never <code>null</code>).
*/
public Stroke getSeriesOutlineStroke(int series) {
Stroke result = this.seriesOutlineStrokeList.getStroke(series);
if (result == null) {
result = this.baseSeriesOutlineStroke;
}
return result;
}
/**
* Sets the stroke used to fill a series of the radar and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param stroke the stroke (<code>null</code> permitted).
*/
public void setSeriesOutlineStroke(int series, Stroke stroke) {
this.seriesOutlineStrokeList.setStroke(series, stroke);
fireChangeEvent();
}
/**
* Returns the base series stroke. This is used when no other stroke is
* available.
*
* @return The stroke (never <code>null</code>).
*/
public Stroke getBaseSeriesOutlineStroke() {
return this.baseSeriesOutlineStroke;
}
/**
* Sets the base series stroke.
*
* @param stroke the stroke (<code>null</code> not permitted).
*/
public void setBaseSeriesOutlineStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.baseSeriesOutlineStroke = stroke;
fireChangeEvent();
}
/**
* Returns the shape used for legend items.
*
* @return The shape (never <code>null</code>).
*
* @see #setLegendItemShape(Shape)
*/
public Shape getLegendItemShape() {
return this.legendItemShape;
}
/**
* Sets the shape used for legend items and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param shape the shape (<code>null</code> not permitted).
*
* @see #getLegendItemShape()
*/
public void setLegendItemShape(Shape shape) {
if (shape == null) {
throw new IllegalArgumentException("Null 'shape' argument.");
}
this.legendItemShape = shape;
fireChangeEvent();
}
/**
* Returns the series label font.
*
* @return The font (never <code>null</code>).
*
* @see #setLabelFont(Font)
*/
public Font getLabelFont() {
return this.labelFont;
}
/**
* Sets the series label font and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getLabelFont()
*/
public void setLabelFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.labelFont = font;
fireChangeEvent();
}
/**
* Returns the series label paint.
*
* @return The paint (never <code>null</code>).
*
* @see #setLabelPaint(Paint)
*/
public Paint getLabelPaint() {
return this.labelPaint;
}
/**
* Sets the series label paint and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLabelPaint()
*/
public void setLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.labelPaint = paint;
fireChangeEvent();
}
/**
* Returns the label generator.
*
* @return The label generator (never <code>null</code>).
*
* @see #setLabelGenerator(CategoryItemLabelGenerator)
*/
public CategoryItemLabelGenerator getLabelGenerator() {
return this.labelGenerator;
}
/**
* Sets the label generator and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param generator the generator (<code>null</code> not permitted).
*
* @see #getLabelGenerator()
*/
public void setLabelGenerator(CategoryItemLabelGenerator generator) {
if (generator == null) {
throw new IllegalArgumentException("Null 'generator' argument.");
}
this.labelGenerator = generator;
}
/**
* Returns the tool tip generator for the plot.
*
* @return The tool tip generator (possibly <code>null</code>).
*
* @see #setToolTipGenerator(CategoryToolTipGenerator)
*
* @since 1.0.2
*/
public CategoryToolTipGenerator getToolTipGenerator() {
return this.toolTipGenerator;
}
/**
* Sets the tool tip generator for the plot and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getToolTipGenerator()
*
* @since 1.0.2
*/
public void setToolTipGenerator(CategoryToolTipGenerator generator) {
this.toolTipGenerator = generator;
fireChangeEvent();
}
/**
* Returns the URL generator for the plot.
*
* @return The URL generator (possibly <code>null</code>).
*
* @see #setURLGenerator(CategoryURLGenerator)
*
* @since 1.0.2
*/
public CategoryURLGenerator getURLGenerator() {
return this.urlGenerator;
}
/**
* Sets the URL generator for the plot and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getURLGenerator()
*
* @since 1.0.2
*/
public void setURLGenerator(CategoryURLGenerator generator) {
this.urlGenerator = generator;
fireChangeEvent();
}
/**
* Returns a collection of legend items for the spider web chart.
*
* @return The legend items (never <code>null</code>).
*/
@Override
public List<LegendItem> getLegendItems() {
List<LegendItem> result = new ArrayList<LegendItem>();
if (getDataset() == null) {
return result;
}
// TODO : support for fixed legend items
List<Comparable> keys = null;
if (this.dataExtractOrder == TableOrder.BY_ROW) {
keys = this.dataset.getRowKeys();
}
else if (this.dataExtractOrder == TableOrder.BY_COLUMN) {
keys = this.dataset.getColumnKeys();
}
if (keys == null) {
return result;
}
int series = 0;
Shape shape = getLegendItemShape();
for (Comparable key : keys) {
String label = key.toString();
String description = label;
Paint paint = getSeriesPaint(series);
Paint outlinePaint = getSeriesOutlinePaint(series);
Stroke stroke = getSeriesOutlineStroke(series);
LegendItem item = new LegendItem(label, description,
null, null, shape, paint, stroke, outlinePaint);
item.setDataset(getDataset());
item.setSeriesKey(key);
item.setSeriesIndex(series);
result.add(item);
series++;
}
return result;
}
/**
* Returns a cartesian point from a polar angle, length and bounding box
*
* @param bounds the area inside which the point needs to be.
* @param angle the polar angle, in degrees.
* @param length the relative length. Given in percent of maximum extend.
*
* @return The cartesian point.
*/
protected Point2D getWebPoint(Rectangle2D bounds,
double angle, double length) {
double angrad = Math.toRadians(angle);
double x = Math.cos(angrad) * length * bounds.getWidth() / 2;
double y = -Math.sin(angrad) * length * bounds.getHeight() / 2;
return new Point2D.Double(bounds.getX() + x + bounds.getWidth() / 2,
bounds.getY() + y + bounds.getHeight() / 2);
}
/**
* Draws the plot on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device.
* @param area the area within which the plot should be drawn.
* @param anchor the anchor point (<code>null</code> permitted).
* @param parentState the state from the parent plot, if there is one.
* @param info collects info about the drawing.
*/
@Override
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,
PlotState parentState, PlotRenderingInfo info) {
// adjust for insets...
RectangleInsets insets = getInsets();
insets.trim(area);
if (info != null) {
info.setPlotArea(area);
info.setDataArea(area);
}
drawBackground(g2, area);
drawOutline(g2, area);
Shape savedClip = g2.getClip();
g2.clip(area);
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
getForegroundAlpha()));
if (!DatasetUtilities.isEmptyOrNull(this.dataset)) {
int seriesCount, catCount;
if (this.dataExtractOrder == TableOrder.BY_ROW) {
seriesCount = this.dataset.getRowCount();
catCount = this.dataset.getColumnCount();
}
else {
seriesCount = this.dataset.getColumnCount();
catCount = this.dataset.getRowCount();
}
// ensure we have a maximum value to use on the axes
if (this.maxValue == DEFAULT_MAX_VALUE) {
calculateMaxValue(seriesCount, catCount);
}
// Next, setup the plot area
// adjust the plot area by the interior spacing value
double gapHorizontal = area.getWidth() * getInteriorGap();
double gapVertical = area.getHeight() * getInteriorGap();
double X = area.getX() + gapHorizontal / 2;
double Y = area.getY() + gapVertical / 2;
double W = area.getWidth() - gapHorizontal;
double H = area.getHeight() - gapVertical;
double headW = area.getWidth() * this.headPercent;
double headH = area.getHeight() * this.headPercent;
// make the chart area a square
double min = Math.min(W, H) / 2;
X = (X + X + W) / 2 - min;
Y = (Y + Y + H) / 2 - min;
W = 2 * min;
H = 2 * min;
Point2D centre = new Point2D.Double(X + W / 2, Y + H / 2);
Rectangle2D radarArea = new Rectangle2D.Double(X, Y, W, H);
// draw the axis and category label
for (int cat = 0; cat < catCount; cat++) {
double angle = getStartAngle()
+ (getDirection().getFactor() * cat * 360 / catCount);
Point2D endPoint = getWebPoint(radarArea, angle, 1);
// 1 = end of axis
Line2D line = new Line2D.Double(centre, endPoint);
g2.setPaint(this.axisLinePaint);
g2.setStroke(this.axisLineStroke);
g2.draw(line);
drawLabel(g2, radarArea, 0.0, cat, angle, 360.0 / catCount);
}
// Now actually plot each of the series polygons..
for (int series = 0; series < seriesCount; series++) {
drawRadarPoly(g2, radarArea, centre, info, series, catCount,
headH, headW);
}
}
else {
drawNoDataMessage(g2, area);
}
g2.setClip(savedClip);
g2.setComposite(originalComposite);
drawOutline(g2, area);
}
/**
* loop through each of the series to get the maximum value
* on each category axis
*
* @param seriesCount the number of series
* @param catCount the number of categories
*/
private void calculateMaxValue(int seriesCount, int catCount) {
double v;
Number nV;
for (int seriesIndex = 0; seriesIndex < seriesCount; seriesIndex++) {
for (int catIndex = 0; catIndex < catCount; catIndex++) {
nV = getPlotValue(seriesIndex, catIndex);
if (nV != null) {
v = nV.doubleValue();
if (v > this.maxValue) {
this.maxValue = v;
}
}
}
}
}
/**
* Draws a radar plot polygon.
*
* @param g2 the graphics device.
* @param plotArea the area we are plotting in (already adjusted).
* @param centre the centre point of the radar axes
* @param info chart rendering info.
* @param series the series within the dataset we are plotting
* @param catCount the number of categories per radar plot
* @param headH the data point height
* @param headW the data point width
*/
protected void drawRadarPoly(Graphics2D g2,
Rectangle2D plotArea,
Point2D centre,
PlotRenderingInfo info,
int series, int catCount,
double headH, double headW) {
Polygon polygon = new Polygon();
EntityCollection entities = null;
if (info != null) {
entities = info.getOwner().getEntityCollection();
}
// plot the data...
for (int cat = 0; cat < catCount; cat++) {
Number dataValue = getPlotValue(series, cat);
if (dataValue != null) {
double value = dataValue.doubleValue();
if (value >= 0) { // draw the polygon series...
// Finds our starting angle from the centre for this axis
double angle = getStartAngle()
+ (getDirection().getFactor() * cat * 360 / catCount);
// The following angle calc will ensure there isn't a top
// vertical axis - this may be useful if you don't want any
// given criteria to 'appear' move important than the
// others..
// + (getDirection().getFactor()
// * (cat + 0.5) * 360 / catCount);
// find the point at the appropriate distance end point
// along the axis/angle identified above and add it to the
// polygon
Point2D point = getWebPoint(plotArea, angle,
value / this.maxValue);
polygon.addPoint((int) point.getX(), (int) point.getY());
// put an elipse at the point being plotted..
Paint paint = getSeriesPaint(series);
Paint outlinePaint = getSeriesOutlinePaint(series);
Stroke outlineStroke = getSeriesOutlineStroke(series);
Ellipse2D head = new Ellipse2D.Double(point.getX()
- headW / 2, point.getY() - headH / 2, headW,
headH);
g2.setPaint(paint);
g2.fill(head);
g2.setStroke(outlineStroke);
g2.setPaint(outlinePaint);
g2.draw(head);
if (entities != null) {
int row; int col;
if (this.dataExtractOrder == TableOrder.BY_ROW) {
row = series;
col = cat;
}
else {
row = cat;
col = series;
}
String tip = null;
if (this.toolTipGenerator != null) {
tip = this.toolTipGenerator.generateToolTip(
this.dataset, row, col);
}
String url = null;
if (this.urlGenerator != null) {
url = this.urlGenerator.generateURL(this.dataset,
row, col);
}
Shape area = new Rectangle(
(int) (point.getX() - headW),
(int) (point.getY() - headH),
(int) (headW * 2), (int) (headH * 2));
CategoryItemEntity entity = new CategoryItemEntity(
area, tip, url, this.dataset,
this.dataset.getRowKey(row),
this.dataset.getColumnKey(col));
entities.add(entity);
}
}
}
}
// Plot the polygon
Paint paint = getSeriesPaint(series);
g2.setPaint(paint);
g2.setStroke(getSeriesOutlineStroke(series));
g2.draw(polygon);
// Lastly, fill the web polygon if this is required
if (this.webFilled) {
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
0.1f));
g2.fill(polygon);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
getForegroundAlpha()));
}
}
/**
* Returns the value to be plotted at the interseries of the
* series and the category. This allows us to plot
* <code>BY_ROW</code> or <code>BY_COLUMN</code> which basically is just
* reversing the definition of the categories and data series being
* plotted.
*
* @param series the series to be plotted.
* @param cat the category within the series to be plotted.
*
* @return The value to be plotted (possibly <code>null</code>).
*
* @see #getDataExtractOrder()
*/
protected Number getPlotValue(int series, int cat) {
Number value = null;
if (this.dataExtractOrder == TableOrder.BY_ROW) {
value = this.dataset.getValue(series, cat);
}
else if (this.dataExtractOrder == TableOrder.BY_COLUMN) {
value = this.dataset.getValue(cat, series);
}
return value;
}
/**
* Draws the label for one axis.
*
* @param g2 the graphics device.
* @param plotArea the plot area
* @param value the value of the label (ignored).
* @param cat the category (zero-based index).
* @param startAngle the starting angle.
* @param extent the extent of the arc.
*/
protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, double value,
int cat, double startAngle, double extent) {
FontRenderContext frc = g2.getFontRenderContext();
String label;
if (this.dataExtractOrder == TableOrder.BY_ROW) {
// if series are in rows, then the categories are the column keys
label = this.labelGenerator.generateColumnLabel(this.dataset, cat);
}
else {
// if series are in columns, then the categories are the row keys
label = this.labelGenerator.generateRowLabel(this.dataset, cat);
}
Rectangle2D labelBounds = getLabelFont().getStringBounds(label, frc);
LineMetrics lm = getLabelFont().getLineMetrics(label, frc);
double ascent = lm.getAscent();
Point2D labelLocation = calculateLabelLocation(labelBounds, ascent,
plotArea, startAngle);
Composite saveComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
1.0f));
g2.setPaint(getLabelPaint());
g2.setFont(getLabelFont());
g2.drawString(label, (float) labelLocation.getX(),
(float) labelLocation.getY());
g2.setComposite(saveComposite);
}
/**
* Returns the location for a label
*
* @param labelBounds the label bounds.
* @param ascent the ascent (height of font).
* @param plotArea the plot area
* @param startAngle the start angle for the pie series.
*
* @return The location for a label.
*/
protected Point2D calculateLabelLocation(Rectangle2D labelBounds,
double ascent,
Rectangle2D plotArea,
double startAngle)
{
Arc2D arc1 = new Arc2D.Double(plotArea, startAngle, 0, Arc2D.OPEN);
Point2D point1 = arc1.getEndPoint();
double deltaX = -(point1.getX() - plotArea.getCenterX())
* this.axisLabelGap;
double deltaY = -(point1.getY() - plotArea.getCenterY())
* this.axisLabelGap;
double labelX = point1.getX() - deltaX;
double labelY = point1.getY() - deltaY;
if (labelX < plotArea.getCenterX()) {
labelX -= labelBounds.getWidth();
}
if (labelX == plotArea.getCenterX()) {
labelX -= labelBounds.getWidth() / 2;
}
if (labelY > plotArea.getCenterY()) {
labelY += ascent;
}
return new Point2D.Double(labelX, labelY);
}
/**
* Tests this plot for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof SpiderWebPlot)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
SpiderWebPlot that = (SpiderWebPlot) obj;
if (!this.dataExtractOrder.equals(that.dataExtractOrder)) {
return false;
}
if (this.headPercent != that.headPercent) {
return false;
}
if (this.interiorGap != that.interiorGap) {
return false;
}
if (this.startAngle != that.startAngle) {
return false;
}
if (!this.direction.equals(that.direction)) {
return false;
}
if (this.maxValue != that.maxValue) {
return false;
}
if (this.webFilled != that.webFilled) {
return false;
}
if (this.axisLabelGap != that.axisLabelGap) {
return false;
}
if (!PaintUtils.equal(this.axisLinePaint, that.axisLinePaint)) {
return false;
}
if (!this.axisLineStroke.equals(that.axisLineStroke)) {
return false;
}
if (!ShapeUtils.equal(this.legendItemShape, that.legendItemShape)) {
return false;
}
if (!PaintUtils.equalMaps(this.seriesPaintMap,
that.seriesPaintMap)) {
return false;
}
if (!PaintUtils.equal(this.baseSeriesPaint, that.baseSeriesPaint)) {
return false;
}
if (!PaintUtils.equalMaps(this.seriesOutlinePaintMap,
that.seriesOutlinePaintMap)) {
return false;
}
if (!PaintUtils.equal(this.baseSeriesOutlinePaint,
that.baseSeriesOutlinePaint)) {
return false;
}
if (!this.seriesOutlineStrokeList.equals(
that.seriesOutlineStrokeList)) {
return false;
}
if (!this.baseSeriesOutlineStroke.equals(
that.baseSeriesOutlineStroke)) {
return false;
}
if (!this.labelFont.equals(that.labelFont)) {
return false;
}
if (!PaintUtils.equal(this.labelPaint, that.labelPaint)) {
return false;
}
if (!this.labelGenerator.equals(that.labelGenerator)) {
return false;
}
if (!ObjectUtils.equal(this.toolTipGenerator,
that.toolTipGenerator)) {
return false;
}
if (!ObjectUtils.equal(this.urlGenerator,
that.urlGenerator)) {
return false;
}
return true;
}
/**
* Returns a clone of this plot.
*
* @return A clone of this plot.
*
* @throws CloneNotSupportedException if the plot cannot be cloned for
* any reason.
*/
@Override
public Object clone() throws CloneNotSupportedException {
SpiderWebPlot clone = (SpiderWebPlot) super.clone();
clone.legendItemShape = ShapeUtils.clone(this.legendItemShape);
clone.seriesPaintMap = new HashMap<Integer, Paint>(this.seriesPaintMap);
clone.seriesOutlinePaintMap
= new HashMap<Integer, Paint>(this.seriesOutlinePaintMap);
clone.seriesOutlineStrokeList
= (StrokeList) this.seriesOutlineStrokeList.clone();
return clone;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtils.writeShape(this.legendItemShape, stream);
SerialUtils.writePaint(this.baseSeriesPaint, stream);
SerialUtils.writePaintMap(this.seriesPaintMap, stream);
SerialUtils.writePaint(this.baseSeriesOutlinePaint, stream);
SerialUtils.writePaintMap(this.seriesOutlinePaintMap, stream);
SerialUtils.writeStroke(this.baseSeriesOutlineStroke, stream);
SerialUtils.writePaint(this.labelPaint, stream);
SerialUtils.writePaint(this.axisLinePaint, stream);
SerialUtils.writeStroke(this.axisLineStroke, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream) throws IOException,
ClassNotFoundException {
stream.defaultReadObject();
this.legendItemShape = SerialUtils.readShape(stream);
this.baseSeriesPaint = SerialUtils.readPaint(stream);
this.seriesPaintMap = SerialUtils.readPaintMap(stream);
this.baseSeriesOutlinePaint = SerialUtils.readPaint(stream);
this.seriesOutlinePaintMap = SerialUtils.readPaintMap(stream);
this.baseSeriesOutlineStroke = SerialUtils.readStroke(stream);
this.labelPaint = SerialUtils.readPaint(stream);
this.axisLinePaint = SerialUtils.readPaint(stream);
this.axisLineStroke = SerialUtils.readStroke(stream);
if (this.dataset != null) {
this.dataset.addChangeListener(this);
}
}
}
| src/main/java/org/jfree/chart/plot/SpiderWebPlot.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2014, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ------------------
* SpiderWebPlot.java
* ------------------
* (C) Copyright 2005-2014, by Heaps of Flavour Pty Ltd and Contributors.
*
* Company Info: http://www.i4-talent.com
*
* Original Author: Don Elliott;
* Contributor(s): David Gilbert (for Object Refinery Limited);
* Nina Jeliazkova;
*
* Changes
* -------
* 28-Jan-2005 : First cut - missing a few features - still to do:
* - needs tooltips/URL/label generator functions
* - ticks on axes / background grid?
* 31-Jan-2005 : Renamed SpiderWebPlot, added label generator support, and
* reformatted for consistency with other source files in
* JFreeChart (DG);
* 20-Apr-2005 : Renamed CategoryLabelGenerator
* --> CategoryItemLabelGenerator (DG);
* 05-May-2005 : Updated draw() method parameters (DG);
* 10-Jun-2005 : Added equals() method and fixed serialization (DG);
* 16-Jun-2005 : Added default constructor and get/setDataset()
* methods (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 05-Apr-2006 : Fixed bug preventing the display of zero values - see patch
* 1462727 (DG);
* 05-Apr-2006 : Added support for mouse clicks, tool tips and URLs - see patch
* 1463455 (DG);
* 01-Jun-2006 : Fix bug 1493199, NullPointerException when drawing with null
* info (DG);
* 05-Feb-2007 : Added attributes for axis stroke and paint, while fixing
* bug 1651277, and implemented clone() properly (DG);
* 06-Feb-2007 : Changed getPlotValue() to protected, as suggested in bug
* 1605202 (DG);
* 05-Mar-2007 : Restore clip region correctly (see bug 1667750) (DG);
* 18-May-2007 : Set dataset for LegendItem (DG);
* 02-Jun-2008 : Fixed bug with chart entities using TableOrder.BY_COLUMN (DG);
* 02-Jun-2008 : Fixed bug with null dataset (DG);
* 01-Jun-2009 : Set series key in getLegendItems() (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
* 10-Mar-2014 : Removed LegendItemCollection (DG);
*
*/
package org.jfree.chart.plot;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jfree.chart.LegendItem;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.util.ObjectUtils;
import org.jfree.chart.util.PaintUtils;
import org.jfree.chart.util.Rotation;
import org.jfree.chart.util.ShapeUtils;
import org.jfree.chart.util.StrokeList;
import org.jfree.chart.util.TableOrder;
import org.jfree.chart.entity.CategoryItemEntity;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.labels.CategoryToolTipGenerator;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.urls.CategoryURLGenerator;
import org.jfree.chart.util.SerialUtils;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.general.DatasetUtilities;
/**
* A plot that displays data from a {@link CategoryDataset} in the form of a
* "spider web". Multiple series can be plotted on the same axis to allow
* easy comparison. This plot doesn't support negative values at present.
*/
public class SpiderWebPlot extends Plot implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -5376340422031599463L;
/** The default head radius percent (currently 1%). */
public static final double DEFAULT_HEAD = 0.01;
/** The default axis label gap (currently 10%). */
public static final double DEFAULT_AXIS_LABEL_GAP = 0.10;
/** The default interior gap. */
public static final double DEFAULT_INTERIOR_GAP = 0.25;
/** The maximum interior gap (currently 40%). */
public static final double MAX_INTERIOR_GAP = 0.40;
/** The default starting angle for the radar chart axes. */
public static final double DEFAULT_START_ANGLE = 90.0;
/** The default series label font. */
public static final Font DEFAULT_LABEL_FONT = new Font("SansSerif",
Font.PLAIN, 10);
/** The default series label paint. */
public static final Paint DEFAULT_LABEL_PAINT = Color.BLACK;
/** The default series label background paint. */
public static final Paint DEFAULT_LABEL_BACKGROUND_PAINT
= new Color(255, 255, 192);
/** The default series label outline paint. */
public static final Paint DEFAULT_LABEL_OUTLINE_PAINT = Color.BLACK;
/** The default series label outline stroke. */
public static final Stroke DEFAULT_LABEL_OUTLINE_STROKE
= new BasicStroke(0.5f);
/** The default series label shadow paint. */
public static final Paint DEFAULT_LABEL_SHADOW_PAINT = Color.LIGHT_GRAY;
/**
* The default maximum value plotted - forces the plot to evaluate
* the maximum from the data passed in
*/
public static final double DEFAULT_MAX_VALUE = -1.0;
/** The head radius as a percentage of the available drawing area. */
protected double headPercent;
/** The space left around the outside of the plot as a percentage. */
private double interiorGap;
/** The gap between the labels and the axes as a %age of the radius. */
private double axisLabelGap;
/**
* The paint used to draw the axis lines.
*
* @since 1.0.4
*/
private transient Paint axisLinePaint;
/**
* The stroke used to draw the axis lines.
*
* @since 1.0.4
*/
private transient Stroke axisLineStroke;
/** The dataset. */
private CategoryDataset dataset;
/** The maximum value we are plotting against on each category axis */
private double maxValue;
/**
* The data extract order (BY_ROW or BY_COLUMN). This denotes whether
* the data series are stored in rows (in which case the category names are
* derived from the column keys) or in columns (in which case the category
* names are derived from the row keys).
*/
private TableOrder dataExtractOrder;
/** The starting angle. */
private double startAngle;
/** The direction for drawing the radar axis & plots. */
private Rotation direction;
/** The legend item shape. */
private transient Shape legendItemShape;
/** A map containing the paint for each series. */
private transient Map<Integer, Paint> seriesPaintMap;
/** The base series paint (fallback). */
private transient Paint baseSeriesPaint;
/** A map containing the outline paint for each series. */
private transient Map<Integer, Paint> seriesOutlinePaintMap;
/** The base series outline paint (fallback). */
private transient Paint baseSeriesOutlinePaint;
/** The series outline stroke list. */
private StrokeList seriesOutlineStrokeList;
/** The base series outline stroke (fallback). */
private transient Stroke baseSeriesOutlineStroke;
/** The font used to display the category labels. */
private Font labelFont;
/** The color used to draw the category labels. */
private transient Paint labelPaint;
/** The label generator. */
private CategoryItemLabelGenerator labelGenerator;
/** controls if the web polygons are filled or not */
private boolean webFilled = true;
/** A tooltip generator for the plot (<code>null</code> permitted). */
private CategoryToolTipGenerator toolTipGenerator;
/** A URL generator for the plot (<code>null</code> permitted). */
private CategoryURLGenerator urlGenerator;
/**
* Creates a default plot with no dataset.
*/
public SpiderWebPlot() {
this(null);
}
/**
* Creates a new spider web plot with the given dataset, with each row
* representing a series.
*
* @param dataset the dataset (<code>null</code> permitted).
*/
public SpiderWebPlot(CategoryDataset dataset) {
this(dataset, TableOrder.BY_ROW);
}
/**
* Creates a new spider web plot with the given dataset.
*
* @param dataset the dataset.
* @param extract controls how data is extracted ({@link TableOrder#BY_ROW}
* or {@link TableOrder#BY_COLUMN}).
*/
public SpiderWebPlot(CategoryDataset dataset, TableOrder extract) {
super();
if (extract == null) {
throw new IllegalArgumentException("Null 'extract' argument.");
}
this.dataset = dataset;
if (dataset != null) {
dataset.addChangeListener(this);
}
this.dataExtractOrder = extract;
this.headPercent = DEFAULT_HEAD;
this.axisLabelGap = DEFAULT_AXIS_LABEL_GAP;
this.axisLinePaint = Color.BLACK;
this.axisLineStroke = new BasicStroke(1.0f);
this.interiorGap = DEFAULT_INTERIOR_GAP;
this.startAngle = DEFAULT_START_ANGLE;
this.direction = Rotation.CLOCKWISE;
this.maxValue = DEFAULT_MAX_VALUE;
this.seriesPaintMap = new HashMap<Integer, Paint>();
this.baseSeriesPaint = null;
this.seriesOutlinePaintMap = new HashMap<Integer, Paint>();
this.baseSeriesOutlinePaint = DEFAULT_OUTLINE_PAINT;
this.seriesOutlineStrokeList = new StrokeList();
this.baseSeriesOutlineStroke = DEFAULT_OUTLINE_STROKE;
this.labelFont = DEFAULT_LABEL_FONT;
this.labelPaint = DEFAULT_LABEL_PAINT;
this.labelGenerator = new StandardCategoryItemLabelGenerator();
this.legendItemShape = DEFAULT_LEGEND_ITEM_CIRCLE;
}
/**
* Returns a short string describing the type of plot.
*
* @return The plot type.
*/
@Override
public String getPlotType() {
// return localizationResources.getString("Radar_Plot");
return ("Spider Web Plot");
}
/**
* Returns the dataset.
*
* @return The dataset (possibly <code>null</code>).
*
* @see #setDataset(CategoryDataset)
*/
public CategoryDataset getDataset() {
return this.dataset;
}
/**
* Sets the dataset used by the plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @see #getDataset()
*/
public void setDataset(CategoryDataset dataset) {
// if there is an existing dataset, remove the plot from the list of
// change listeners...
if (this.dataset != null) {
this.dataset.removeChangeListener(this);
}
// set the new dataset, and register the chart as a change listener...
this.dataset = dataset;
if (dataset != null) {
dataset.addChangeListener(this);
}
// send a dataset change event to self to trigger plot change event
datasetChanged(new DatasetChangeEvent(this, dataset));
}
/**
* Method to determine if the web chart is to be filled.
*
* @return A boolean.
*
* @see #setWebFilled(boolean)
*/
public boolean isWebFilled() {
return this.webFilled;
}
/**
* Sets the webFilled flag and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param flag the flag.
*
* @see #isWebFilled()
*/
public void setWebFilled(boolean flag) {
this.webFilled = flag;
fireChangeEvent();
}
/**
* Returns the data extract order (by row or by column).
*
* @return The data extract order (never <code>null</code>).
*
* @see #setDataExtractOrder(TableOrder)
*/
public TableOrder getDataExtractOrder() {
return this.dataExtractOrder;
}
/**
* Sets the data extract order (by row or by column) and sends a
* {@link PlotChangeEvent}to all registered listeners.
*
* @param order the order (<code>null</code> not permitted).
*
* @throws IllegalArgumentException if <code>order</code> is
* <code>null</code>.
*
* @see #getDataExtractOrder()
*/
public void setDataExtractOrder(TableOrder order) {
if (order == null) {
throw new IllegalArgumentException("Null 'order' argument");
}
this.dataExtractOrder = order;
fireChangeEvent();
}
/**
* Returns the head percent.
*
* @return The head percent.
*
* @see #setHeadPercent(double)
*/
public double getHeadPercent() {
return this.headPercent;
}
/**
* Sets the head percent and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param percent the percent.
*
* @see #getHeadPercent()
*/
public void setHeadPercent(double percent) {
this.headPercent = percent;
fireChangeEvent();
}
/**
* Returns the start angle for the first radar axis.
* <BR>
* This is measured in degrees starting from 3 o'clock (Java Arc2D default)
* and measuring anti-clockwise.
*
* @return The start angle.
*
* @see #setStartAngle(double)
*/
public double getStartAngle() {
return this.startAngle;
}
/**
* Sets the starting angle and sends a {@link PlotChangeEvent} to all
* registered listeners.
* <P>
* The initial default value is 90 degrees, which corresponds to 12 o'clock.
* A value of zero corresponds to 3 o'clock... this is the encoding used by
* Java's Arc2D class.
*
* @param angle the angle (in degrees).
*
* @see #getStartAngle()
*/
public void setStartAngle(double angle) {
this.startAngle = angle;
fireChangeEvent();
}
/**
* Returns the maximum value any category axis can take.
*
* @return The maximum value.
*
* @see #setMaxValue(double)
*/
public double getMaxValue() {
return this.maxValue;
}
/**
* Sets the maximum value any category axis can take and sends
* a {@link PlotChangeEvent} to all registered listeners.
*
* @param value the maximum value.
*
* @see #getMaxValue()
*/
public void setMaxValue(double value) {
this.maxValue = value;
fireChangeEvent();
}
/**
* Returns the direction in which the radar axes are drawn
* (clockwise or anti-clockwise).
*
* @return The direction (never <code>null</code>).
*
* @see #setDirection(Rotation)
*/
public Rotation getDirection() {
return this.direction;
}
/**
* Sets the direction in which the radar axes are drawn and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param direction the direction (<code>null</code> not permitted).
*
* @see #getDirection()
*/
public void setDirection(Rotation direction) {
if (direction == null) {
throw new IllegalArgumentException("Null 'direction' argument.");
}
this.direction = direction;
fireChangeEvent();
}
/**
* Returns the interior gap, measured as a percentage of the available
* drawing space.
*
* @return The gap (as a percentage of the available drawing space).
*
* @see #setInteriorGap(double)
*/
public double getInteriorGap() {
return this.interiorGap;
}
/**
* Sets the interior gap and sends a {@link PlotChangeEvent} to all
* registered listeners. This controls the space between the edges of the
* plot and the plot area itself (the region where the axis labels appear).
*
* @param percent the gap (as a percentage of the available drawing space).
*
* @see #getInteriorGap()
*/
public void setInteriorGap(double percent) {
if ((percent < 0.0) || (percent > MAX_INTERIOR_GAP)) {
throw new IllegalArgumentException(
"Percentage outside valid range.");
}
if (this.interiorGap != percent) {
this.interiorGap = percent;
fireChangeEvent();
}
}
/**
* Returns the axis label gap.
*
* @return The axis label gap.
*
* @see #setAxisLabelGap(double)
*/
public double getAxisLabelGap() {
return this.axisLabelGap;
}
/**
* Sets the axis label gap and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param gap the gap.
*
* @see #getAxisLabelGap()
*/
public void setAxisLabelGap(double gap) {
this.axisLabelGap = gap;
fireChangeEvent();
}
/**
* Returns the paint used to draw the axis lines.
*
* @return The paint used to draw the axis lines (never <code>null</code>).
*
* @see #setAxisLinePaint(Paint)
* @see #getAxisLineStroke()
* @since 1.0.4
*/
public Paint getAxisLinePaint() {
return this.axisLinePaint;
}
/**
* Sets the paint used to draw the axis lines and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getAxisLinePaint()
* @since 1.0.4
*/
public void setAxisLinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.axisLinePaint = paint;
fireChangeEvent();
}
/**
* Returns the stroke used to draw the axis lines.
*
* @return The stroke used to draw the axis lines (never <code>null</code>).
*
* @see #setAxisLineStroke(Stroke)
* @see #getAxisLinePaint()
* @since 1.0.4
*/
public Stroke getAxisLineStroke() {
return this.axisLineStroke;
}
/**
* Sets the stroke used to draw the axis lines and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getAxisLineStroke()
* @since 1.0.4
*/
public void setAxisLineStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.axisLineStroke = stroke;
fireChangeEvent();
}
//// SERIES PAINT /////////////////////////
/**
* Returns the paint for the specified series.
*
* @param series the series index (zero-based).
*
* @return The paint (never <code>null</code>).
*
* @see #setSeriesPaint(int, Paint)
*/
public Paint getSeriesPaint(int series) {
Paint result = this.seriesPaintMap.get(series);
if (result == null) {
DrawingSupplier supplier = getDrawingSupplier();
if (supplier != null) {
Paint p = supplier.getNextPaint();
this.seriesPaintMap.put(series, p);
result = p;
}
else {
result = this.baseSeriesPaint;
}
}
return result;
}
/**
* Sets the paint used to fill a series of the radar and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param paint the paint (<code>null</code> permitted).
*
* @see #getSeriesPaint(int)
*/
public void setSeriesPaint(int series, Paint paint) {
this.seriesPaintMap.put(series, paint);
fireChangeEvent();
}
/**
* Returns the base series paint. This is used when no other paint is
* available.
*
* @return The paint (never <code>null</code>).
*
* @see #setBaseSeriesPaint(Paint)
*/
public Paint getBaseSeriesPaint() {
return this.baseSeriesPaint;
}
/**
* Sets the base series paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getBaseSeriesPaint()
*/
public void setBaseSeriesPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.baseSeriesPaint = paint;
fireChangeEvent();
}
//// SERIES OUTLINE PAINT ////////////////////////////
/**
* Returns the paint for the specified series.
*
* @param series the series index (zero-based).
*
* @return The paint (never <code>null</code>).
*/
public Paint getSeriesOutlinePaint(int series) {
Paint result = this.seriesOutlinePaintMap.get(series);
if (result == null) {
result = this.baseSeriesOutlinePaint;
}
return result;
}
/**
* Sets the paint used to fill a series of the radar and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param paint the paint (<code>null</code> permitted).
*/
public void setSeriesOutlinePaint(int series, Paint paint) {
this.seriesOutlinePaintMap.put(series, paint);
fireChangeEvent();
}
/**
* Returns the base series paint. This is used when no other paint is
* available.
*
* @return The paint (never <code>null</code>).
*/
public Paint getBaseSeriesOutlinePaint() {
return this.baseSeriesOutlinePaint;
}
/**
* Sets the base series paint.
*
* @param paint the paint (<code>null</code> not permitted).
*/
public void setBaseSeriesOutlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.baseSeriesOutlinePaint = paint;
fireChangeEvent();
}
//// SERIES OUTLINE STROKE /////////////////////
/**
* Returns the stroke for the specified series.
*
* @param series the series index (zero-based).
*
* @return The stroke (never <code>null</code>).
*/
public Stroke getSeriesOutlineStroke(int series) {
Stroke result = this.seriesOutlineStrokeList.getStroke(series);
if (result == null) {
result = this.baseSeriesOutlineStroke;
}
return result;
}
/**
* Sets the stroke used to fill a series of the radar and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param stroke the stroke (<code>null</code> permitted).
*/
public void setSeriesOutlineStroke(int series, Stroke stroke) {
this.seriesOutlineStrokeList.setStroke(series, stroke);
fireChangeEvent();
}
/**
* Returns the base series stroke. This is used when no other stroke is
* available.
*
* @return The stroke (never <code>null</code>).
*/
public Stroke getBaseSeriesOutlineStroke() {
return this.baseSeriesOutlineStroke;
}
/**
* Sets the base series stroke.
*
* @param stroke the stroke (<code>null</code> not permitted).
*/
public void setBaseSeriesOutlineStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.baseSeriesOutlineStroke = stroke;
fireChangeEvent();
}
/**
* Returns the shape used for legend items.
*
* @return The shape (never <code>null</code>).
*
* @see #setLegendItemShape(Shape)
*/
public Shape getLegendItemShape() {
return this.legendItemShape;
}
/**
* Sets the shape used for legend items and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param shape the shape (<code>null</code> not permitted).
*
* @see #getLegendItemShape()
*/
public void setLegendItemShape(Shape shape) {
if (shape == null) {
throw new IllegalArgumentException("Null 'shape' argument.");
}
this.legendItemShape = shape;
fireChangeEvent();
}
/**
* Returns the series label font.
*
* @return The font (never <code>null</code>).
*
* @see #setLabelFont(Font)
*/
public Font getLabelFont() {
return this.labelFont;
}
/**
* Sets the series label font and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getLabelFont()
*/
public void setLabelFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.labelFont = font;
fireChangeEvent();
}
/**
* Returns the series label paint.
*
* @return The paint (never <code>null</code>).
*
* @see #setLabelPaint(Paint)
*/
public Paint getLabelPaint() {
return this.labelPaint;
}
/**
* Sets the series label paint and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLabelPaint()
*/
public void setLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.labelPaint = paint;
fireChangeEvent();
}
/**
* Returns the label generator.
*
* @return The label generator (never <code>null</code>).
*
* @see #setLabelGenerator(CategoryItemLabelGenerator)
*/
public CategoryItemLabelGenerator getLabelGenerator() {
return this.labelGenerator;
}
/**
* Sets the label generator and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param generator the generator (<code>null</code> not permitted).
*
* @see #getLabelGenerator()
*/
public void setLabelGenerator(CategoryItemLabelGenerator generator) {
if (generator == null) {
throw new IllegalArgumentException("Null 'generator' argument.");
}
this.labelGenerator = generator;
}
/**
* Returns the tool tip generator for the plot.
*
* @return The tool tip generator (possibly <code>null</code>).
*
* @see #setToolTipGenerator(CategoryToolTipGenerator)
*
* @since 1.0.2
*/
public CategoryToolTipGenerator getToolTipGenerator() {
return this.toolTipGenerator;
}
/**
* Sets the tool tip generator for the plot and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getToolTipGenerator()
*
* @since 1.0.2
*/
public void setToolTipGenerator(CategoryToolTipGenerator generator) {
this.toolTipGenerator = generator;
fireChangeEvent();
}
/**
* Returns the URL generator for the plot.
*
* @return The URL generator (possibly <code>null</code>).
*
* @see #setURLGenerator(CategoryURLGenerator)
*
* @since 1.0.2
*/
public CategoryURLGenerator getURLGenerator() {
return this.urlGenerator;
}
/**
* Sets the URL generator for the plot and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getURLGenerator()
*
* @since 1.0.2
*/
public void setURLGenerator(CategoryURLGenerator generator) {
this.urlGenerator = generator;
fireChangeEvent();
}
/**
* Returns a collection of legend items for the spider web chart.
*
* @return The legend items (never <code>null</code>).
*/
@Override
public List<LegendItem> getLegendItems() {
List<LegendItem> result = new ArrayList<LegendItem>();
if (getDataset() == null) {
return result;
}
// TODO : support for fixed legend items
List<Comparable> keys = null;
if (this.dataExtractOrder == TableOrder.BY_ROW) {
keys = this.dataset.getRowKeys();
}
else if (this.dataExtractOrder == TableOrder.BY_COLUMN) {
keys = this.dataset.getColumnKeys();
}
if (keys == null) {
return result;
}
int series = 0;
Shape shape = getLegendItemShape();
for (Comparable key : keys) {
String label = key.toString();
String description = label;
Paint paint = getSeriesPaint(series);
Paint outlinePaint = getSeriesOutlinePaint(series);
Stroke stroke = getSeriesOutlineStroke(series);
LegendItem item = new LegendItem(label, description,
null, null, shape, paint, stroke, outlinePaint);
item.setDataset(getDataset());
item.setSeriesKey(key);
item.setSeriesIndex(series);
result.add(item);
series++;
}
return result;
}
/**
* Returns a cartesian point from a polar angle, length and bounding box
*
* @param bounds the area inside which the point needs to be.
* @param angle the polar angle, in degrees.
* @param length the relative length. Given in percent of maximum extend.
*
* @return The cartesian point.
*/
protected Point2D getWebPoint(Rectangle2D bounds,
double angle, double length) {
double angrad = Math.toRadians(angle);
double x = Math.cos(angrad) * length * bounds.getWidth() / 2;
double y = -Math.sin(angrad) * length * bounds.getHeight() / 2;
return new Point2D.Double(bounds.getX() + x + bounds.getWidth() / 2,
bounds.getY() + y + bounds.getHeight() / 2);
}
/**
* Draws the plot on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device.
* @param area the area within which the plot should be drawn.
* @param anchor the anchor point (<code>null</code> permitted).
* @param parentState the state from the parent plot, if there is one.
* @param info collects info about the drawing.
*/
@Override
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,
PlotState parentState, PlotRenderingInfo info) {
// adjust for insets...
RectangleInsets insets = getInsets();
insets.trim(area);
if (info != null) {
info.setPlotArea(area);
info.setDataArea(area);
}
drawBackground(g2, area);
drawOutline(g2, area);
Shape savedClip = g2.getClip();
g2.clip(area);
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
getForegroundAlpha()));
if (!DatasetUtilities.isEmptyOrNull(this.dataset)) {
int seriesCount, catCount;
if (this.dataExtractOrder == TableOrder.BY_ROW) {
seriesCount = this.dataset.getRowCount();
catCount = this.dataset.getColumnCount();
}
else {
seriesCount = this.dataset.getColumnCount();
catCount = this.dataset.getRowCount();
}
// ensure we have a maximum value to use on the axes
if (this.maxValue == DEFAULT_MAX_VALUE) {
calculateMaxValue(seriesCount, catCount);
}
// Next, setup the plot area
// adjust the plot area by the interior spacing value
double gapHorizontal = area.getWidth() * getInteriorGap();
double gapVertical = area.getHeight() * getInteriorGap();
double X = area.getX() + gapHorizontal / 2;
double Y = area.getY() + gapVertical / 2;
double W = area.getWidth() - gapHorizontal;
double H = area.getHeight() - gapVertical;
double headW = area.getWidth() * this.headPercent;
double headH = area.getHeight() * this.headPercent;
// make the chart area a square
double min = Math.min(W, H) / 2;
X = (X + X + W) / 2 - min;
Y = (Y + Y + H) / 2 - min;
W = 2 * min;
H = 2 * min;
Point2D centre = new Point2D.Double(X + W / 2, Y + H / 2);
Rectangle2D radarArea = new Rectangle2D.Double(X, Y, W, H);
// draw the axis and category label
for (int cat = 0; cat < catCount; cat++) {
double angle = getStartAngle()
+ (getDirection().getFactor() * cat * 360 / catCount);
Point2D endPoint = getWebPoint(radarArea, angle, 1);
// 1 = end of axis
Line2D line = new Line2D.Double(centre, endPoint);
g2.setPaint(this.axisLinePaint);
g2.setStroke(this.axisLineStroke);
g2.draw(line);
drawLabel(g2, radarArea, 0.0, cat, angle, 360.0 / catCount);
}
// Now actually plot each of the series polygons..
for (int series = 0; series < seriesCount; series++) {
drawRadarPoly(g2, radarArea, centre, info, series, catCount,
headH, headW);
}
}
else {
drawNoDataMessage(g2, area);
}
g2.setClip(savedClip);
g2.setComposite(originalComposite);
drawOutline(g2, area);
}
/**
* loop through each of the series to get the maximum value
* on each category axis
*
* @param seriesCount the number of series
* @param catCount the number of categories
*/
private void calculateMaxValue(int seriesCount, int catCount) {
double v;
Number nV;
for (int seriesIndex = 0; seriesIndex < seriesCount; seriesIndex++) {
for (int catIndex = 0; catIndex < catCount; catIndex++) {
nV = getPlotValue(seriesIndex, catIndex);
if (nV != null) {
v = nV.doubleValue();
if (v > this.maxValue) {
this.maxValue = v;
}
}
}
}
}
/**
* Draws a radar plot polygon.
*
* @param g2 the graphics device.
* @param plotArea the area we are plotting in (already adjusted).
* @param centre the centre point of the radar axes
* @param info chart rendering info.
* @param series the series within the dataset we are plotting
* @param catCount the number of categories per radar plot
* @param headH the data point height
* @param headW the data point width
*/
protected void drawRadarPoly(Graphics2D g2,
Rectangle2D plotArea,
Point2D centre,
PlotRenderingInfo info,
int series, int catCount,
double headH, double headW) {
Polygon polygon = new Polygon();
EntityCollection entities = null;
if (info != null) {
entities = info.getOwner().getEntityCollection();
}
// plot the data...
for (int cat = 0; cat < catCount; cat++) {
Number dataValue = getPlotValue(series, cat);
if (dataValue != null) {
double value = dataValue.doubleValue();
if (value >= 0) { // draw the polygon series...
// Finds our starting angle from the centre for this axis
double angle = getStartAngle()
+ (getDirection().getFactor() * cat * 360 / catCount);
// The following angle calc will ensure there isn't a top
// vertical axis - this may be useful if you don't want any
// given criteria to 'appear' move important than the
// others..
// + (getDirection().getFactor()
// * (cat + 0.5) * 360 / catCount);
// find the point at the appropriate distance end point
// along the axis/angle identified above and add it to the
// polygon
Point2D point = getWebPoint(plotArea, angle,
value / this.maxValue);
polygon.addPoint((int) point.getX(), (int) point.getY());
// put an elipse at the point being plotted..
Paint paint = getSeriesPaint(series);
Paint outlinePaint = getSeriesOutlinePaint(series);
Stroke outlineStroke = getSeriesOutlineStroke(series);
Ellipse2D head = new Ellipse2D.Double(point.getX()
- headW / 2, point.getY() - headH / 2, headW,
headH);
g2.setPaint(paint);
g2.fill(head);
g2.setStroke(outlineStroke);
g2.setPaint(outlinePaint);
g2.draw(head);
if (entities != null) {
int row; int col;
if (this.dataExtractOrder == TableOrder.BY_ROW) {
row = series;
col = cat;
}
else {
row = cat;
col = series;
}
String tip = null;
if (this.toolTipGenerator != null) {
tip = this.toolTipGenerator.generateToolTip(
this.dataset, row, col);
}
String url = null;
if (this.urlGenerator != null) {
url = this.urlGenerator.generateURL(this.dataset,
row, col);
}
Shape area = new Rectangle(
(int) (point.getX() - headW),
(int) (point.getY() - headH),
(int) (headW * 2), (int) (headH * 2));
CategoryItemEntity entity = new CategoryItemEntity(
area, tip, url, this.dataset,
this.dataset.getRowKey(row),
this.dataset.getColumnKey(col));
entities.add(entity);
}
}
}
}
// Plot the polygon
Paint paint = getSeriesPaint(series);
g2.setPaint(paint);
g2.setStroke(getSeriesOutlineStroke(series));
g2.draw(polygon);
// Lastly, fill the web polygon if this is required
if (this.webFilled) {
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
0.1f));
g2.fill(polygon);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
getForegroundAlpha()));
}
}
/**
* Returns the value to be plotted at the interseries of the
* series and the category. This allows us to plot
* <code>BY_ROW</code> or <code>BY_COLUMN</code> which basically is just
* reversing the definition of the categories and data series being
* plotted.
*
* @param series the series to be plotted.
* @param cat the category within the series to be plotted.
*
* @return The value to be plotted (possibly <code>null</code>).
*
* @see #getDataExtractOrder()
*/
protected Number getPlotValue(int series, int cat) {
Number value = null;
if (this.dataExtractOrder == TableOrder.BY_ROW) {
value = this.dataset.getValue(series, cat);
}
else if (this.dataExtractOrder == TableOrder.BY_COLUMN) {
value = this.dataset.getValue(cat, series);
}
return value;
}
/**
* Draws the label for one axis.
*
* @param g2 the graphics device.
* @param plotArea the plot area
* @param value the value of the label (ignored).
* @param cat the category (zero-based index).
* @param startAngle the starting angle.
* @param extent the extent of the arc.
*/
protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, double value,
int cat, double startAngle, double extent) {
FontRenderContext frc = g2.getFontRenderContext();
String label;
if (this.dataExtractOrder == TableOrder.BY_ROW) {
// if series are in rows, then the categories are the column keys
label = this.labelGenerator.generateColumnLabel(this.dataset, cat);
}
else {
// if series are in columns, then the categories are the row keys
label = this.labelGenerator.generateRowLabel(this.dataset, cat);
}
Rectangle2D labelBounds = getLabelFont().getStringBounds(label, frc);
LineMetrics lm = getLabelFont().getLineMetrics(label, frc);
double ascent = lm.getAscent();
Point2D labelLocation = calculateLabelLocation(labelBounds, ascent,
plotArea, startAngle);
Composite saveComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
1.0f));
g2.setPaint(getLabelPaint());
g2.setFont(getLabelFont());
g2.drawString(label, (float) labelLocation.getX(),
(float) labelLocation.getY());
g2.setComposite(saveComposite);
}
/**
* Returns the location for a label
*
* @param labelBounds the label bounds.
* @param ascent the ascent (height of font).
* @param plotArea the plot area
* @param startAngle the start angle for the pie series.
*
* @return The location for a label.
*/
protected Point2D calculateLabelLocation(Rectangle2D labelBounds,
double ascent,
Rectangle2D plotArea,
double startAngle)
{
Arc2D arc1 = new Arc2D.Double(plotArea, startAngle, 0, Arc2D.OPEN);
Point2D point1 = arc1.getEndPoint();
double deltaX = -(point1.getX() - plotArea.getCenterX())
* this.axisLabelGap;
double deltaY = -(point1.getY() - plotArea.getCenterY())
* this.axisLabelGap;
double labelX = point1.getX() - deltaX;
double labelY = point1.getY() - deltaY;
if (labelX < plotArea.getCenterX()) {
labelX -= labelBounds.getWidth();
}
if (labelX == plotArea.getCenterX()) {
labelX -= labelBounds.getWidth() / 2;
}
if (labelY > plotArea.getCenterY()) {
labelY += ascent;
}
return new Point2D.Double(labelX, labelY);
}
/**
* Tests this plot for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof SpiderWebPlot)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
SpiderWebPlot that = (SpiderWebPlot) obj;
if (!this.dataExtractOrder.equals(that.dataExtractOrder)) {
return false;
}
if (this.headPercent != that.headPercent) {
return false;
}
if (this.interiorGap != that.interiorGap) {
return false;
}
if (this.startAngle != that.startAngle) {
return false;
}
if (!this.direction.equals(that.direction)) {
return false;
}
if (this.maxValue != that.maxValue) {
return false;
}
if (this.webFilled != that.webFilled) {
return false;
}
if (this.axisLabelGap != that.axisLabelGap) {
return false;
}
if (!PaintUtils.equal(this.axisLinePaint, that.axisLinePaint)) {
return false;
}
if (!this.axisLineStroke.equals(that.axisLineStroke)) {
return false;
}
if (!ShapeUtils.equal(this.legendItemShape, that.legendItemShape)) {
return false;
}
if (!PaintUtils.equalMaps(this.seriesPaintMap,
that.seriesPaintMap)) {
return false;
}
if (!PaintUtils.equal(this.baseSeriesPaint, that.baseSeriesPaint)) {
return false;
}
if (!PaintUtils.equalMaps(this.seriesOutlinePaintMap,
that.seriesOutlinePaintMap)) {
return false;
}
if (!PaintUtils.equal(this.baseSeriesOutlinePaint,
that.baseSeriesOutlinePaint)) {
return false;
}
if (!this.seriesOutlineStrokeList.equals(
that.seriesOutlineStrokeList)) {
return false;
}
if (!this.baseSeriesOutlineStroke.equals(
that.baseSeriesOutlineStroke)) {
return false;
}
if (!this.labelFont.equals(that.labelFont)) {
return false;
}
if (!PaintUtils.equal(this.labelPaint, that.labelPaint)) {
return false;
}
if (!this.labelGenerator.equals(that.labelGenerator)) {
return false;
}
if (!ObjectUtils.equal(this.toolTipGenerator,
that.toolTipGenerator)) {
return false;
}
if (!ObjectUtils.equal(this.urlGenerator,
that.urlGenerator)) {
return false;
}
return true;
}
/**
* Returns a clone of this plot.
*
* @return A clone of this plot.
*
* @throws CloneNotSupportedException if the plot cannot be cloned for
* any reason.
*/
@Override
public Object clone() throws CloneNotSupportedException {
SpiderWebPlot clone = (SpiderWebPlot) super.clone();
clone.legendItemShape = ShapeUtils.clone(this.legendItemShape);
clone.seriesPaintMap = new HashMap<Integer, Paint>(this.seriesPaintMap);
clone.seriesOutlinePaintMap
= new HashMap<Integer, Paint>(this.seriesOutlinePaintMap);
clone.seriesOutlineStrokeList
= (StrokeList) this.seriesOutlineStrokeList.clone();
return clone;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtils.writeShape(this.legendItemShape, stream);
SerialUtils.writePaint(this.baseSeriesPaint, stream);
SerialUtils.writePaintMap(this.seriesPaintMap, stream);
SerialUtils.writePaint(this.baseSeriesOutlinePaint, stream);
SerialUtils.writePaintMap(this.seriesOutlinePaintMap, stream);
SerialUtils.writeStroke(this.baseSeriesOutlineStroke, stream);
SerialUtils.writePaint(this.labelPaint, stream);
SerialUtils.writePaint(this.axisLinePaint, stream);
SerialUtils.writeStroke(this.axisLineStroke, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream) throws IOException,
ClassNotFoundException {
stream.defaultReadObject();
this.legendItemShape = SerialUtils.readShape(stream);
this.baseSeriesPaint = SerialUtils.readPaint(stream);
this.seriesPaintMap = SerialUtils.readPaintMap(stream);
this.baseSeriesOutlinePaint = SerialUtils.readPaint(stream);
this.seriesOutlinePaintMap = SerialUtils.readPaintMap(stream);
this.baseSeriesOutlineStroke = SerialUtils.readStroke(stream);
this.labelPaint = SerialUtils.readPaint(stream);
this.axisLinePaint = SerialUtils.readPaint(stream);
this.axisLineStroke = SerialUtils.readStroke(stream);
if (this.dataset != null) {
this.dataset.addChangeListener(this);
}
}
}
| Default outline paint is gone. | src/main/java/org/jfree/chart/plot/SpiderWebPlot.java | Default outline paint is gone. | <ide><path>rc/main/java/org/jfree/chart/plot/SpiderWebPlot.java
<ide> this.baseSeriesPaint = null;
<ide>
<ide> this.seriesOutlinePaintMap = new HashMap<Integer, Paint>();
<del> this.baseSeriesOutlinePaint = DEFAULT_OUTLINE_PAINT;
<add> this.baseSeriesOutlinePaint = Color.GRAY;
<ide>
<ide> this.seriesOutlineStrokeList = new StrokeList();
<ide> this.baseSeriesOutlineStroke = DEFAULT_OUTLINE_STROKE; |
|
Java | apache-2.0 | cc17025efabda3f47f21e0a144b38e87bee4ace1 | 0 | robovm/robovm-studio,wreckJ/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,izonder/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,holmes/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,caot/intellij-community,consulo/consulo,Distrotech/intellij-community,blademainer/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,amith01994/intellij-community,diorcety/intellij-community,ernestp/consulo,michaelgallacher/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,clumsy/intellij-community,fitermay/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,signed/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,jexp/idea2,vladmm/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,diorcety/intellij-community,ibinti/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,ibinti/intellij-community,clumsy/intellij-community,apixandru/intellij-community,da1z/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,kdwink/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,caot/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,kool79/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,FHannes/intellij-community,diorcety/intellij-community,supersven/intellij-community,diorcety/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,jagguli/intellij-community,da1z/intellij-community,signed/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,ryano144/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,vladmm/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,clumsy/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,consulo/consulo,MER-GROUP/intellij-community,holmes/intellij-community,amith01994/intellij-community,adedayo/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,adedayo/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,consulo/consulo,dslomov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,izonder/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,da1z/intellij-community,robovm/robovm-studio,petteyg/intellij-community,MER-GROUP/intellij-community,consulo/consulo,youdonghai/intellij-community,FHannes/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,izonder/intellij-community,jagguli/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,vladmm/intellij-community,joewalnes/idea-community,supersven/intellij-community,dslomov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,signed/intellij-community,kdwink/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,semonte/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,semonte/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,apixandru/intellij-community,slisson/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,caot/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,caot/intellij-community,holmes/intellij-community,amith01994/intellij-community,izonder/intellij-community,holmes/intellij-community,retomerz/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ryano144/intellij-community,caot/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,ibinti/intellij-community,blademainer/intellij-community,da1z/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,izonder/intellij-community,asedunov/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,ernestp/consulo,semonte/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,allotria/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,tmpgit/intellij-community,supersven/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,youdonghai/intellij-community,supersven/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,signed/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,tmpgit/intellij-community,kool79/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,holmes/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,dslomov/intellij-community,samthor/intellij-community,caot/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,da1z/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,kool79/intellij-community,xfournet/intellij-community,vladmm/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,slisson/intellij-community,ibinti/intellij-community,samthor/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,signed/intellij-community,Distrotech/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,jexp/idea2,pwoodworth/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,robovm/robovm-studio,ernestp/consulo,signed/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,supersven/intellij-community,FHannes/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,retomerz/intellij-community,da1z/intellij-community,xfournet/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,signed/intellij-community,jexp/idea2,allotria/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,jexp/idea2,vvv1559/intellij-community,ibinti/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,vladmm/intellij-community,semonte/intellij-community,apixandru/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,da1z/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,jexp/idea2,akosyakov/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,allotria/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,ibinti/intellij-community,robovm/robovm-studio,amith01994/intellij-community,joewalnes/idea-community,petteyg/intellij-community,signed/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,holmes/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,da1z/intellij-community,fnouama/intellij-community,signed/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,kdwink/intellij-community,consulo/consulo,Lekanich/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,nicolargo/intellij-community,ryano144/intellij-community,joewalnes/idea-community,hurricup/intellij-community,Lekanich/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,xfournet/intellij-community,slisson/intellij-community,clumsy/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,nicolargo/intellij-community,consulo/consulo,akosyakov/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,ernestp/consulo,robovm/robovm-studio,alphafoobar/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,samthor/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,jexp/idea2,retomerz/intellij-community,jexp/idea2,allotria/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,izonder/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,caot/intellij-community,diorcety/intellij-community,ryano144/intellij-community,kdwink/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,caot/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,da1z/intellij-community,fitermay/intellij-community,signed/intellij-community,fitermay/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ryano144/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,slisson/intellij-community,samthor/intellij-community,suncycheng/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,jexp/idea2,muntasirsyed/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,allotria/intellij-community,hurricup/intellij-community,supersven/intellij-community,kool79/intellij-community,diorcety/intellij-community,da1z/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,samthor/intellij-community,jagguli/intellij-community,kool79/intellij-community,Lekanich/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,fnouama/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,ibinti/intellij-community,xfournet/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,kool79/intellij-community,retomerz/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,caot/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,samthor/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,samthor/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,caot/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,allotria/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,FHannes/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,ryano144/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,ryano144/intellij-community,semonte/intellij-community,asedunov/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,FHannes/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,ibinti/intellij-community,izonder/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,ernestp/consulo,Distrotech/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,semonte/intellij-community,Lekanich/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,izonder/intellij-community,caot/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,joewalnes/idea-community,FHannes/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,jagguli/intellij-community,petteyg/intellij-community,da1z/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community | package com.intellij.ide.favoritesTreeView;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.ide.CopyPasteManagerEx;
import com.intellij.ide.DeleteProvider;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.IdeView;
import com.intellij.ide.dnd.aware.DnDAwareTree;
import com.intellij.ide.projectView.impl.ModuleGroup;
import com.intellij.ide.projectView.impl.nodes.LibraryGroupElement;
import com.intellij.ide.projectView.impl.nodes.NamedLibraryElement;
import com.intellij.ide.projectView.impl.nodes.PackageElement;
import com.intellij.ide.ui.customization.CustomizableActionsSchemas;
import com.intellij.ide.util.DeleteHandler;
import com.intellij.ide.util.EditorHelper;
import com.intellij.ide.util.PackageUtil;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.ide.util.treeView.NodeDescriptor;
import com.intellij.ide.util.treeView.NodeRenderer;
import com.intellij.navigation.ItemPresentation;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.DataConstantsEx;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ui.configuration.actions.ModuleDeleteProvider;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.pom.Navigatable;
import com.intellij.psi.*;
import com.intellij.ui.*;
import com.intellij.util.EditSourceOnDoubleClickHandler;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FavoritesTreeViewPanel extends JPanel implements DataProvider {
@NonNls public static final String ABSTRACT_TREE_NODE_TRANSFERABLE = "AbstractTransferable";
private FavoritesTreeStructure myFavoritesTreeStructure;
private FavoritesViewTreeBuilder myBuilder;
private CopyPasteManagerEx.CopyPasteDelegator myCopyPasteDelegator;
private MouseListener myTreePopupHandler;
@NonNls public static final String CONTEXT_FAVORITES_ROOTS = "FavoritesRoot";
@NonNls public static final String FAVORITES_LIST_NAME = "FavoritesListName";
protected Project myProject;
private final String myHelpId;
protected DnDAwareTree myTree;
private final MyDeletePSIElementProvider myDeletePSIElementProvider = new MyDeletePSIElementProvider();
private final ModuleDeleteProvider myDeleteModuleProvider = new ModuleDeleteProvider();
private String myListName;
private IdeView myIdeView = new MyIdeView();
public FavoritesTreeViewPanel(Project project, String helpId, String name) {
super(new BorderLayout());
myProject = project;
myHelpId = helpId;
myListName = name;
myFavoritesTreeStructure = new FavoritesTreeStructure(project, myListName);
DefaultMutableTreeNode root = new DefaultMutableTreeNode();
root.setUserObject(myFavoritesTreeStructure.getRootElement());
final DefaultTreeModel treeModel = new DefaultTreeModel(root);
myTree = new DnDAwareTree(treeModel) {
public void setRowHeight(int i) {
super.setRowHeight(0);
}
};
myBuilder = new FavoritesViewTreeBuilder(myProject, myTree, treeModel, myFavoritesTreeStructure, myListName);
TreeUtil.installActions(myTree);
UIUtil.setLineStyleAngled(myTree);
myTree.setRootVisible(false);
myTree.setShowsRootHandles(true);
myTree.setLargeModel(true);
new TreeSpeedSearch(myTree);
ToolTipManager.sharedInstance().registerComponent(myTree);
TreeToolTipHandler.install(myTree);
myTree.setCellRenderer(new NodeRenderer() {
public void customizeCellRenderer(JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
super.customizeCellRenderer(tree, value, selected, expanded, leaf, row, hasFocus);
if (value instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
//only favorites roots to explain
final Object userObject = node.getUserObject();
if (userObject instanceof FavoritesTreeNodeDescriptor) {
final FavoritesTreeNodeDescriptor favoritesTreeNodeDescriptor = (FavoritesTreeNodeDescriptor)userObject;
AbstractTreeNode treeNode = favoritesTreeNodeDescriptor.getElement();
final ItemPresentation presentation = treeNode.getPresentation();
String locationString = presentation != null ? presentation.getLocationString() : null;
if (locationString != null && locationString.length() > 0) {
append(" (" + locationString + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
}
else if (node.getParent() != null && node.getParent().getParent() == null) {
final String location = favoritesTreeNodeDescriptor.getLocation();
if (location != null && location.length() > 0) {
append(" (" + location + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
}
}
}
}
}
});
JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree);
myTreePopupHandler = PopupHandler.installPopupHandler(myTree, (ActionGroup)CustomizableActionsSchemas.getInstance()
.getCorrectedAction(IdeActions.GROUP_FAVORITES_VIEW_POPUP), ActionPlaces.FAVORITES_VIEW_POPUP, ActionManager.getInstance());
add(scrollPane, BorderLayout.CENTER);
//add(createActionsToolbar(), BorderLayout.NORTH);
EditSourceOnDoubleClickHandler.install(myTree);
myCopyPasteDelegator = new CopyPasteManagerEx.CopyPasteDelegator(myProject, this) {
@NotNull
protected PsiElement[] getSelectedElements() {
return getSelectedPsiElements();
}
};
}
public void updateTreePopupHandler() {
myTree.removeMouseListener(myTreePopupHandler);
ActionGroup group = (ActionGroup)CustomizableActionsSchemas.getInstance().getCorrectedAction(IdeActions.GROUP_FAVORITES_VIEW_POPUP);
myTreePopupHandler = PopupHandler.installPopupHandler(myTree, group, ActionPlaces.FAVORITES_VIEW_POPUP, ActionManager.getInstance());
}
public void selectElement(final Object selector, final VirtualFile file) {
myBuilder.select(selector, file, true);
}
public void dispose() {
Disposer.dispose(myBuilder);
myBuilder = null;
}
public DnDAwareTree getTree() {
return myTree;
}
public String getName() {
return myListName;
}
public void setName(String name) {
myListName = name;
}
@NotNull
private PsiElement[] getSelectedPsiElements() {
final Object[] elements = getSelectedNodeElements();
if (elements == null) {
return PsiElement.EMPTY_ARRAY;
}
ArrayList<PsiElement> result = new ArrayList<PsiElement>();
for (Object element : elements) {
if (element instanceof PsiElement) {
result.add((PsiElement)element);
}
else if (element instanceof SmartPsiElementPointer) {
PsiElement psiElement = ((SmartPsiElementPointer)element).getElement();
if (psiElement != null) {
result.add(psiElement);
}
}
}
return result.toArray(new PsiElement[result.size()]);
}
public FavoritesTreeStructure getFavoritesTreeStructure() {
return myFavoritesTreeStructure;
}
public Object getData(String dataId) {
if (DataConstants.PROJECT.equals(dataId)) {
return myProject;
}
if (DataConstants.NAVIGATABLE.equals(dataId)) {
final FavoritesTreeNodeDescriptor[] selectedNodeDescriptors = getSelectedNodeDescriptors();
return selectedNodeDescriptors.length == 1 ? selectedNodeDescriptors[0].getElement() : null;
}
if (DataConstants.NAVIGATABLE_ARRAY.equals(dataId)) {
final List<Navigatable> selectedElements = getSelectedElements(Navigatable.class);
return selectedElements.toArray(new Navigatable[selectedElements.size()]);
}
if (DataConstants.CUT_PROVIDER.equals(dataId)) {
return myCopyPasteDelegator.getCutProvider();
}
if (DataConstants.COPY_PROVIDER.equals(dataId)) {
return myCopyPasteDelegator.getCopyProvider();
}
if (DataConstants.PASTE_PROVIDER.equals(dataId)) {
return myCopyPasteDelegator.getPasteProvider();
}
if (DataConstants.HELP_ID.equals(dataId)) {
return myHelpId;
}
if (DataConstants.PSI_ELEMENT.equals(dataId)) {
Object[] elements = getSelectedNodeElements();
if (elements == null || elements.length != 1) {
return null;
}
final PsiElement psiElement;
if (elements[0] instanceof SmartPsiElementPointer) {
psiElement = ((SmartPsiElementPointer)elements[0]).getElement();
}
else if (elements[0] instanceof PsiElement) {
psiElement = (PsiElement)elements[0];
}
else if (elements[0] instanceof PackageElement) {
psiElement = ((PackageElement)elements[0]).getPackage();
}
else {
return null;
}
return psiElement != null && psiElement.isValid() ? psiElement : null;
}
if (DataConstants.PSI_ELEMENT_ARRAY.equals(dataId)) {
final PsiElement[] elements = getSelectedPsiElements();
if (elements == null) {
return null;
}
ArrayList<PsiElement> result = new ArrayList<PsiElement>();
for (PsiElement element : elements) {
if (element.isValid()) {
result.add(element);
}
}
return result.isEmpty() ? null : result.toArray(new PsiElement[result.size()]);
}
if (DataConstants.IDE_VIEW.equals(dataId)) {
return myIdeView;
}
if (DataConstantsEx.TARGET_PSI_ELEMENT.equals(dataId)) {
return null;
}
if (DataConstants.MODULE_CONTEXT.equals(dataId)) {
Module[] selected = getSelectedModules();
return selected != null && selected.length == 1 ? selected[0] : null;
}
if (DataConstants.MODULE_CONTEXT_ARRAY.equals(dataId)) {
return getSelectedModules();
}
if (DataConstants.DELETE_ELEMENT_PROVIDER.equals(dataId)) {
final Object[] elements = getSelectedNodeElements();
return elements != null && elements.length >= 1 && elements[0] instanceof Module
? myDeleteModuleProvider
: myDeletePSIElementProvider;
}
if (DataConstantsEx.MODULE_GROUP_ARRAY.equals(dataId)) {
final List<ModuleGroup> selectedElements = getSelectedElements(ModuleGroup.class);
return selectedElements.isEmpty() ? null : selectedElements.toArray(new ModuleGroup[selectedElements.size()]);
}
if (DataConstantsEx.LIBRARY_GROUP_ARRAY.equals(dataId)) {
final List<LibraryGroupElement> selectedElements = getSelectedElements(LibraryGroupElement.class);
return selectedElements.isEmpty() ? null : selectedElements.toArray(new LibraryGroupElement[selectedElements.size()]);
}
if (DataConstantsEx.NAMED_LIBRARY_ARRAY.equals(dataId)) {
final List<NamedLibraryElement> selectedElements = getSelectedElements(NamedLibraryElement.class);
return selectedElements.isEmpty() ? null : selectedElements.toArray(new NamedLibraryElement[selectedElements.size()]);
}
if (CONTEXT_FAVORITES_ROOTS.equals(dataId)) {
List<FavoritesTreeNodeDescriptor> result = new ArrayList<FavoritesTreeNodeDescriptor>();
FavoritesTreeNodeDescriptor[] selectedNodeDescriptors = getSelectedNodeDescriptors();
for (FavoritesTreeNodeDescriptor selectedNodeDescriptor : selectedNodeDescriptors) {
FavoritesTreeNodeDescriptor root = selectedNodeDescriptor.getFavoritesRoot();
if (root != null && !(root.getElement().getValue() instanceof String)) {
result.add(root);
}
}
return result.toArray(new FavoritesTreeNodeDescriptor[result.size()]);
}
if (FAVORITES_LIST_NAME.equals(dataId)) {
return myListName;
}
FavoritesTreeNodeDescriptor[] descriptors = getSelectedNodeDescriptors();
if (descriptors.length > 0) {
List<AbstractTreeNode> nodes = new ArrayList<AbstractTreeNode>();
for (FavoritesTreeNodeDescriptor descriptor : descriptors) {
nodes.add(descriptor.getElement());
}
return myFavoritesTreeStructure.getDataFromProviders(nodes, dataId);
}
return null;
}
private <T> List<T> getSelectedElements(Class<T> klass) {
final Object[] elements = getSelectedNodeElements();
ArrayList<T> result = new ArrayList<T>();
if (elements == null) {
return result;
}
for (Object element : elements) {
if (element == null) continue;
if (klass.isAssignableFrom(element.getClass())) {
result.add((T)element);
}
}
return result;
}
private Module[] getSelectedModules() {
final Object[] elements = getSelectedNodeElements();
if (elements == null) {
return null;
}
ArrayList<Module> result = new ArrayList<Module>();
for (Object element : elements) {
if (element instanceof Module) {
result.add((Module)element);
}
else if (element instanceof ModuleGroup) {
result.addAll(((ModuleGroup)element).modulesInGroup(myProject, true));
}
}
return result.isEmpty() ? null : result.toArray(new Module[result.size()]);
}
private Object[] getSelectedNodeElements() {
final FavoritesTreeNodeDescriptor[] selectedNodeDescriptors = getSelectedNodeDescriptors();
ArrayList<Object> result = new ArrayList<Object>();
for (FavoritesTreeNodeDescriptor selectedNodeDescriptor : selectedNodeDescriptors) {
if (selectedNodeDescriptor != null) {
Object value = selectedNodeDescriptor.getElement().getValue();
if (value instanceof SmartPsiElementPointer) {
value = ((SmartPsiElementPointer)value).getElement();
}
result.add(value);
}
}
return result.toArray(new Object[result.size()]);
}
@NotNull
public FavoritesTreeNodeDescriptor[] getSelectedNodeDescriptors() {
TreePath[] path = myTree.getSelectionPaths();
if (path == null) {
return FavoritesTreeNodeDescriptor.EMPTY_ARRAY;
}
ArrayList<FavoritesTreeNodeDescriptor> result = new ArrayList<FavoritesTreeNodeDescriptor>();
for (TreePath treePath : path) {
DefaultMutableTreeNode lastPathNode = (DefaultMutableTreeNode)treePath.getLastPathComponent();
Object userObject = lastPathNode.getUserObject();
if (!(userObject instanceof FavoritesTreeNodeDescriptor)) {
continue;
}
FavoritesTreeNodeDescriptor treeNodeDescriptor = (FavoritesTreeNodeDescriptor)userObject;
result.add(treeNodeDescriptor);
}
return result.toArray(new FavoritesTreeNodeDescriptor[result.size()]);
}
public static String getQualifiedName(final VirtualFile file) {
return file.getPresentableUrl();
}
public FavoritesViewTreeBuilder getBuilder() {
return myBuilder;
}
private final class MyDeletePSIElementProvider implements DeleteProvider {
public boolean canDeleteElement(DataContext dataContext) {
final PsiElement[] elements = getElementsToDelete();
return DeleteHandler.shouldEnableDeleteAction(elements);
}
public void deleteElement(DataContext dataContext) {
List<PsiElement> allElements = Arrays.asList(getElementsToDelete());
List<PsiElement> validElements = new ArrayList<PsiElement>();
for (PsiElement psiElement : allElements) {
if (psiElement != null && psiElement.isValid()) validElements.add(psiElement);
}
final PsiElement[] elements = validElements.toArray(new PsiElement[validElements.size()]);
LocalHistoryAction a = LocalHistory.startAction(myProject, IdeBundle.message("progress.deleting"));
try {
DeleteHandler.deletePsiElement(elements, myProject);
}
finally {
a.finish();
}
}
private PsiElement[] getElementsToDelete() {
ArrayList<PsiElement> result = new ArrayList<PsiElement>();
Object[] elements = getSelectedNodeElements();
for (int idx = 0; elements != null && idx < elements.length; idx++) {
if (elements[idx] instanceof PsiElement) {
final PsiElement element = (PsiElement)elements[idx];
result.add(element);
if (element instanceof PsiDirectory) {
final VirtualFile virtualFile = ((PsiDirectory)element).getVirtualFile();
final String path = virtualFile.getPath();
if (path.endsWith(JarFileSystem.JAR_SEPARATOR)) { // if is jar-file root
final VirtualFile vFile =
LocalFileSystem.getInstance().findFileByPath(path.substring(0, path.length() - JarFileSystem.JAR_SEPARATOR.length()));
if (vFile != null) {
final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vFile);
if (psiFile != null) {
elements[idx] = psiFile;
}
}
}
}
}
}
return result.toArray(new PsiElement[result.size()]);
}
}
private final class MyIdeView implements IdeView {
public void selectElement(final PsiElement element) {
if (element != null) {
final boolean isDirectory = element instanceof PsiDirectory;
if (!isDirectory) {
Editor editor = EditorHelper.openInEditor(element);
if (editor != null) {
ToolWindowManager.getInstance(myProject).activateEditorComponent();
}
}
}
}
private PsiDirectory getDirectory() {
if (myBuilder == null) return null;
final FavoritesTreeNodeDescriptor[] selectedNodeDescriptors = getSelectedNodeDescriptors();
if (selectedNodeDescriptors.length != 1) return null;
final FavoritesTreeNodeDescriptor currentDescriptor = selectedNodeDescriptors[0];
if (currentDescriptor != null) {
if (currentDescriptor.getElement() != null) {
final AbstractTreeNode currentNode = currentDescriptor.getElement();
if (currentNode.getValue() instanceof PsiDirectory) {
return (PsiDirectory)currentNode.getValue();
}
}
final NodeDescriptor parentDescriptor = currentDescriptor.getParentDescriptor();
if (parentDescriptor != null) {
final Object parentElement = parentDescriptor.getElement();
if (parentElement instanceof AbstractTreeNode) {
final AbstractTreeNode parentNode = (AbstractTreeNode)parentElement;
final Object directory = parentNode.getValue();
if (directory instanceof PsiDirectory) {
return (PsiDirectory)directory;
}
}
}
}
return null;
}
public PsiDirectory[] getDirectories() {
PsiDirectory directory = getDirectory();
return directory == null ? PsiDirectory.EMPTY_ARRAY : new PsiDirectory[]{directory};
}
public PsiDirectory getOrChooseDirectory() {
return PackageUtil.getOrChooseDirectory(this);
}
}
} | source/com/intellij/ide/favoritesTreeView/FavoritesTreeViewPanel.java | package com.intellij.ide.favoritesTreeView;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.ide.*;
import com.intellij.ide.dnd.aware.DnDAwareTree;
import com.intellij.ide.projectView.impl.ModuleGroup;
import com.intellij.ide.projectView.impl.nodes.LibraryGroupElement;
import com.intellij.ide.projectView.impl.nodes.NamedLibraryElement;
import com.intellij.ide.projectView.impl.nodes.PackageElement;
import com.intellij.ide.ui.customization.CustomizableActionsSchemas;
import com.intellij.ide.util.DeleteHandler;
import com.intellij.ide.util.EditorHelper;
import com.intellij.ide.util.PackageUtil;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.ide.util.treeView.NodeDescriptor;
import com.intellij.ide.util.treeView.NodeRenderer;
import com.intellij.navigation.ItemPresentation;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.DataConstantsEx;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ui.configuration.actions.ModuleDeleteProvider;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.pom.Navigatable;
import com.intellij.psi.*;
import com.intellij.ui.*;
import com.intellij.util.EditSourceOnDoubleClickHandler;
import com.intellij.util.OpenSourceUtil;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FavoritesTreeViewPanel extends JPanel implements DataProvider {
@NonNls public static final String ABSTRACT_TREE_NODE_TRANSFERABLE = "AbstractTransferable";
private FavoritesTreeStructure myFavoritesTreeStructure;
private FavoritesViewTreeBuilder myBuilder;
private CopyPasteManagerEx.CopyPasteDelegator myCopyPasteDelegator;
private MouseListener myTreePopupHandler;
@NonNls public static final String CONTEXT_FAVORITES_ROOTS = "FavoritesRoot";
@NonNls public static final String FAVORITES_LIST_NAME = "FavoritesListName";
protected Project myProject;
private final String myHelpId;
protected DnDAwareTree myTree;
private final MyDeletePSIElementProvider myDeletePSIElementProvider = new MyDeletePSIElementProvider();
private final ModuleDeleteProvider myDeleteModuleProvider = new ModuleDeleteProvider();
private String myListName;
private IdeView myIdeView = new MyIdeView();
public FavoritesTreeViewPanel(Project project, String helpId, String name) {
super(new BorderLayout());
myProject = project;
myHelpId = helpId;
myListName = name;
myFavoritesTreeStructure = new FavoritesTreeStructure(project, myListName);
DefaultMutableTreeNode root = new DefaultMutableTreeNode();
root.setUserObject(myFavoritesTreeStructure.getRootElement());
final DefaultTreeModel treeModel = new DefaultTreeModel(root);
myTree = new DnDAwareTree(treeModel) {
public void setRowHeight(int i) {
super.setRowHeight(0);
}
};
myBuilder = new FavoritesViewTreeBuilder(myProject, myTree, treeModel, myFavoritesTreeStructure, myListName);
TreeUtil.installActions(myTree);
UIUtil.setLineStyleAngled(myTree);
myTree.setRootVisible(false);
myTree.setShowsRootHandles(true);
myTree.setLargeModel(true);
new TreeSpeedSearch(myTree);
ToolTipManager.sharedInstance().registerComponent(myTree);
TreeToolTipHandler.install(myTree);
myTree.setCellRenderer(new NodeRenderer() {
public void customizeCellRenderer(JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
super.customizeCellRenderer(tree, value, selected, expanded, leaf, row, hasFocus);
if (value instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
//only favorites roots to explain
final Object userObject = node.getUserObject();
if (userObject instanceof FavoritesTreeNodeDescriptor) {
final FavoritesTreeNodeDescriptor favoritesTreeNodeDescriptor = (FavoritesTreeNodeDescriptor)userObject;
AbstractTreeNode treeNode = favoritesTreeNodeDescriptor.getElement();
final ItemPresentation presentation = treeNode.getPresentation();
String locationString = presentation != null ? presentation.getLocationString() : null;
if (locationString != null && locationString.length() > 0) {
append(" (" + locationString + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
}
else if (node.getParent() != null && node.getParent().getParent() == null) {
final String location = favoritesTreeNodeDescriptor.getLocation();
if (location != null && location.length() > 0) {
append(" (" + location + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
}
}
}
}
}
});
JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree);
myTreePopupHandler = PopupHandler.installPopupHandler(myTree, (ActionGroup)CustomizableActionsSchemas.getInstance()
.getCorrectedAction(IdeActions.GROUP_FAVORITES_VIEW_POPUP), ActionPlaces.FAVORITES_VIEW_POPUP, ActionManager.getInstance());
add(scrollPane, BorderLayout.CENTER);
//add(createActionsToolbar(), BorderLayout.NORTH);
EditSourceOnDoubleClickHandler.install(myTree);
myTree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (!e.isPopupTrigger() && e.getClickCount() == 2) {
OpenSourceUtil.openSourcesFrom(DataManager.getInstance().getDataContext(FavoritesTreeViewPanel.this), true);
}
}
});
myTree.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
OpenSourceUtil.openSourcesFrom(DataManager.getInstance().getDataContext(FavoritesTreeViewPanel.this), false);
}
}
});
myCopyPasteDelegator = new CopyPasteManagerEx.CopyPasteDelegator(myProject, this) {
@NotNull
protected PsiElement[] getSelectedElements() {
return getSelectedPsiElements();
}
};
}
public void updateTreePopupHandler() {
myTree.removeMouseListener(myTreePopupHandler);
ActionGroup group = (ActionGroup)CustomizableActionsSchemas.getInstance().getCorrectedAction(IdeActions.GROUP_FAVORITES_VIEW_POPUP);
myTreePopupHandler = PopupHandler.installPopupHandler(myTree, group, ActionPlaces.FAVORITES_VIEW_POPUP, ActionManager.getInstance());
}
public void selectElement(final Object selector, final VirtualFile file) {
myBuilder.select(selector, file, true);
}
public void dispose() {
Disposer.dispose(myBuilder);
myBuilder = null;
}
public DnDAwareTree getTree() {
return myTree;
}
public String getName() {
return myListName;
}
public void setName(String name) {
myListName = name;
}
@NotNull
private PsiElement[] getSelectedPsiElements() {
final Object[] elements = getSelectedNodeElements();
if (elements == null) {
return PsiElement.EMPTY_ARRAY;
}
ArrayList<PsiElement> result = new ArrayList<PsiElement>();
for (Object element : elements) {
if (element instanceof PsiElement) {
result.add((PsiElement)element);
}
else if (element instanceof SmartPsiElementPointer) {
PsiElement psiElement = ((SmartPsiElementPointer)element).getElement();
if (psiElement != null) {
result.add(psiElement);
}
}
}
return result.toArray(new PsiElement[result.size()]);
}
public FavoritesTreeStructure getFavoritesTreeStructure() {
return myFavoritesTreeStructure;
}
public Object getData(String dataId) {
if (DataConstants.PROJECT.equals(dataId)) {
return myProject;
}
if (DataConstants.NAVIGATABLE.equals(dataId)) {
final FavoritesTreeNodeDescriptor[] selectedNodeDescriptors = getSelectedNodeDescriptors();
return selectedNodeDescriptors.length == 1 ? selectedNodeDescriptors[0].getElement() : null;
}
if (DataConstants.NAVIGATABLE_ARRAY.equals(dataId)) {
final List<Navigatable> selectedElements = getSelectedElements(Navigatable.class);
return selectedElements.toArray(new Navigatable[selectedElements.size()]);
}
if (DataConstants.CUT_PROVIDER.equals(dataId)) {
return myCopyPasteDelegator.getCutProvider();
}
if (DataConstants.COPY_PROVIDER.equals(dataId)) {
return myCopyPasteDelegator.getCopyProvider();
}
if (DataConstants.PASTE_PROVIDER.equals(dataId)) {
return myCopyPasteDelegator.getPasteProvider();
}
if (DataConstants.HELP_ID.equals(dataId)) {
return myHelpId;
}
if (DataConstants.PSI_ELEMENT.equals(dataId)) {
Object[] elements = getSelectedNodeElements();
if (elements == null || elements.length != 1) {
return null;
}
final PsiElement psiElement;
if (elements[0] instanceof SmartPsiElementPointer) {
psiElement = ((SmartPsiElementPointer)elements[0]).getElement();
}
else if (elements[0] instanceof PsiElement) {
psiElement = (PsiElement)elements[0];
}
else if (elements[0] instanceof PackageElement) {
psiElement = ((PackageElement)elements[0]).getPackage();
}
else {
return null;
}
return psiElement != null && psiElement.isValid() ? psiElement : null;
}
if (DataConstants.PSI_ELEMENT_ARRAY.equals(dataId)) {
final PsiElement[] elements = getSelectedPsiElements();
if (elements == null) {
return null;
}
ArrayList<PsiElement> result = new ArrayList<PsiElement>();
for (PsiElement element : elements) {
if (element.isValid()) {
result.add(element);
}
}
return result.isEmpty() ? null : result.toArray(new PsiElement[result.size()]);
}
if (DataConstants.IDE_VIEW.equals(dataId)) {
return myIdeView;
}
if (DataConstantsEx.TARGET_PSI_ELEMENT.equals(dataId)) {
return null;
}
if (DataConstants.MODULE_CONTEXT.equals(dataId)) {
Module[] selected = getSelectedModules();
return selected != null && selected.length == 1 ? selected[0] : null;
}
if (DataConstants.MODULE_CONTEXT_ARRAY.equals(dataId)) {
return getSelectedModules();
}
if (DataConstants.DELETE_ELEMENT_PROVIDER.equals(dataId)) {
final Object[] elements = getSelectedNodeElements();
return elements != null && elements.length >= 1 && elements[0] instanceof Module
? myDeleteModuleProvider
: myDeletePSIElementProvider;
}
if (DataConstantsEx.MODULE_GROUP_ARRAY.equals(dataId)) {
final List<ModuleGroup> selectedElements = getSelectedElements(ModuleGroup.class);
return selectedElements.isEmpty() ? null : selectedElements.toArray(new ModuleGroup[selectedElements.size()]);
}
if (DataConstantsEx.LIBRARY_GROUP_ARRAY.equals(dataId)) {
final List<LibraryGroupElement> selectedElements = getSelectedElements(LibraryGroupElement.class);
return selectedElements.isEmpty() ? null : selectedElements.toArray(new LibraryGroupElement[selectedElements.size()]);
}
if (DataConstantsEx.NAMED_LIBRARY_ARRAY.equals(dataId)) {
final List<NamedLibraryElement> selectedElements = getSelectedElements(NamedLibraryElement.class);
return selectedElements.isEmpty() ? null : selectedElements.toArray(new NamedLibraryElement[selectedElements.size()]);
}
if (CONTEXT_FAVORITES_ROOTS.equals(dataId)) {
List<FavoritesTreeNodeDescriptor> result = new ArrayList<FavoritesTreeNodeDescriptor>();
FavoritesTreeNodeDescriptor[] selectedNodeDescriptors = getSelectedNodeDescriptors();
for (FavoritesTreeNodeDescriptor selectedNodeDescriptor : selectedNodeDescriptors) {
FavoritesTreeNodeDescriptor root = selectedNodeDescriptor.getFavoritesRoot();
if (root != null && !(root.getElement().getValue() instanceof String)) {
result.add(root);
}
}
return result.toArray(new FavoritesTreeNodeDescriptor[result.size()]);
}
if (FAVORITES_LIST_NAME.equals(dataId)) {
return myListName;
}
FavoritesTreeNodeDescriptor[] descriptors = getSelectedNodeDescriptors();
if (descriptors.length > 0) {
List<AbstractTreeNode> nodes = new ArrayList<AbstractTreeNode>();
for (FavoritesTreeNodeDescriptor descriptor : descriptors) {
nodes.add(descriptor.getElement());
}
return myFavoritesTreeStructure.getDataFromProviders(nodes, dataId);
}
return null;
}
private <T> List<T> getSelectedElements(Class<T> klass) {
final Object[] elements = getSelectedNodeElements();
ArrayList<T> result = new ArrayList<T>();
if (elements == null) {
return result;
}
for (Object element : elements) {
if (element == null) continue;
if (klass.isAssignableFrom(element.getClass())) {
result.add((T)element);
}
}
return result;
}
private Module[] getSelectedModules() {
final Object[] elements = getSelectedNodeElements();
if (elements == null) {
return null;
}
ArrayList<Module> result = new ArrayList<Module>();
for (Object element : elements) {
if (element instanceof Module) {
result.add((Module)element);
}
else if (element instanceof ModuleGroup) {
result.addAll(((ModuleGroup)element).modulesInGroup(myProject, true));
}
}
return result.isEmpty() ? null : result.toArray(new Module[result.size()]);
}
private Object[] getSelectedNodeElements() {
final FavoritesTreeNodeDescriptor[] selectedNodeDescriptors = getSelectedNodeDescriptors();
ArrayList<Object> result = new ArrayList<Object>();
for (FavoritesTreeNodeDescriptor selectedNodeDescriptor : selectedNodeDescriptors) {
if (selectedNodeDescriptor != null) {
Object value = selectedNodeDescriptor.getElement().getValue();
if (value instanceof SmartPsiElementPointer) {
value = ((SmartPsiElementPointer)value).getElement();
}
result.add(value);
}
}
return result.toArray(new Object[result.size()]);
}
@NotNull
public FavoritesTreeNodeDescriptor[] getSelectedNodeDescriptors() {
TreePath[] path = myTree.getSelectionPaths();
if (path == null) {
return FavoritesTreeNodeDescriptor.EMPTY_ARRAY;
}
ArrayList<FavoritesTreeNodeDescriptor> result = new ArrayList<FavoritesTreeNodeDescriptor>();
for (TreePath treePath : path) {
DefaultMutableTreeNode lastPathNode = (DefaultMutableTreeNode)treePath.getLastPathComponent();
Object userObject = lastPathNode.getUserObject();
if (!(userObject instanceof FavoritesTreeNodeDescriptor)) {
continue;
}
FavoritesTreeNodeDescriptor treeNodeDescriptor = (FavoritesTreeNodeDescriptor)userObject;
result.add(treeNodeDescriptor);
}
return result.toArray(new FavoritesTreeNodeDescriptor[result.size()]);
}
public static String getQualifiedName(final VirtualFile file) {
return file.getPresentableUrl();
}
public FavoritesViewTreeBuilder getBuilder() {
return myBuilder;
}
private final class MyDeletePSIElementProvider implements DeleteProvider {
public boolean canDeleteElement(DataContext dataContext) {
final PsiElement[] elements = getElementsToDelete();
return DeleteHandler.shouldEnableDeleteAction(elements);
}
public void deleteElement(DataContext dataContext) {
List<PsiElement> allElements = Arrays.asList(getElementsToDelete());
List<PsiElement> validElements = new ArrayList<PsiElement>();
for (PsiElement psiElement : allElements) {
if (psiElement != null && psiElement.isValid()) validElements.add(psiElement);
}
final PsiElement[] elements = validElements.toArray(new PsiElement[validElements.size()]);
LocalHistoryAction a = LocalHistory.startAction(myProject, IdeBundle.message("progress.deleting"));
try {
DeleteHandler.deletePsiElement(elements, myProject);
}
finally {
a.finish();
}
}
private PsiElement[] getElementsToDelete() {
ArrayList<PsiElement> result = new ArrayList<PsiElement>();
Object[] elements = getSelectedNodeElements();
for (int idx = 0; elements != null && idx < elements.length; idx++) {
if (elements[idx] instanceof PsiElement) {
final PsiElement element = (PsiElement)elements[idx];
result.add(element);
if (element instanceof PsiDirectory) {
final VirtualFile virtualFile = ((PsiDirectory)element).getVirtualFile();
final String path = virtualFile.getPath();
if (path.endsWith(JarFileSystem.JAR_SEPARATOR)) { // if is jar-file root
final VirtualFile vFile =
LocalFileSystem.getInstance().findFileByPath(path.substring(0, path.length() - JarFileSystem.JAR_SEPARATOR.length()));
if (vFile != null) {
final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vFile);
if (psiFile != null) {
elements[idx] = psiFile;
}
}
}
}
}
}
return result.toArray(new PsiElement[result.size()]);
}
}
private final class MyIdeView implements IdeView {
public void selectElement(final PsiElement element) {
if (element != null) {
final boolean isDirectory = element instanceof PsiDirectory;
if (!isDirectory) {
Editor editor = EditorHelper.openInEditor(element);
if (editor != null) {
ToolWindowManager.getInstance(myProject).activateEditorComponent();
}
}
}
}
private PsiDirectory getDirectory() {
if (myBuilder == null) return null;
final FavoritesTreeNodeDescriptor[] selectedNodeDescriptors = getSelectedNodeDescriptors();
if (selectedNodeDescriptors.length != 1) return null;
final FavoritesTreeNodeDescriptor currentDescriptor = selectedNodeDescriptors[0];
if (currentDescriptor != null) {
if (currentDescriptor.getElement() != null) {
final AbstractTreeNode currentNode = currentDescriptor.getElement();
if (currentNode.getValue() instanceof PsiDirectory) {
return (PsiDirectory)currentNode.getValue();
}
}
final NodeDescriptor parentDescriptor = currentDescriptor.getParentDescriptor();
if (parentDescriptor != null) {
final Object parentElement = parentDescriptor.getElement();
if (parentElement instanceof AbstractTreeNode) {
final AbstractTreeNode parentNode = (AbstractTreeNode)parentElement;
final Object directory = parentNode.getValue();
if (directory instanceof PsiDirectory) {
return (PsiDirectory)directory;
}
}
}
}
return null;
}
public PsiDirectory[] getDirectories() {
PsiDirectory directory = getDirectory();
return directory == null ? PsiDirectory.EMPTY_ARRAY : new PsiDirectory[]{directory};
}
public PsiDirectory getOrChooseDirectory() {
return PackageUtil.getOrChooseDirectory(this);
}
}
} | disable useless navigation (IDEADEV-22418)
| source/com/intellij/ide/favoritesTreeView/FavoritesTreeViewPanel.java | disable useless navigation (IDEADEV-22418) | <ide><path>ource/com/intellij/ide/favoritesTreeView/FavoritesTreeViewPanel.java
<ide>
<ide> import com.intellij.history.LocalHistory;
<ide> import com.intellij.history.LocalHistoryAction;
<del>import com.intellij.ide.*;
<add>import com.intellij.ide.CopyPasteManagerEx;
<add>import com.intellij.ide.DeleteProvider;
<add>import com.intellij.ide.IdeBundle;
<add>import com.intellij.ide.IdeView;
<ide> import com.intellij.ide.dnd.aware.DnDAwareTree;
<ide> import com.intellij.ide.projectView.impl.ModuleGroup;
<ide> import com.intellij.ide.projectView.impl.nodes.LibraryGroupElement;
<ide> import com.intellij.psi.*;
<ide> import com.intellij.ui.*;
<ide> import com.intellij.util.EditSourceOnDoubleClickHandler;
<del>import com.intellij.util.OpenSourceUtil;
<ide> import com.intellij.util.ui.UIUtil;
<ide> import com.intellij.util.ui.tree.TreeUtil;
<ide> import org.jetbrains.annotations.NonNls;
<ide> import javax.swing.tree.DefaultTreeModel;
<ide> import javax.swing.tree.TreePath;
<ide> import java.awt.*;
<del>import java.awt.event.*;
<add>import java.awt.event.MouseListener;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide> //add(createActionsToolbar(), BorderLayout.NORTH);
<ide>
<ide> EditSourceOnDoubleClickHandler.install(myTree);
<del> myTree.addMouseListener(new MouseAdapter() {
<del> public void mouseClicked(MouseEvent e) {
<del> if (!e.isPopupTrigger() && e.getClickCount() == 2) {
<del> OpenSourceUtil.openSourcesFrom(DataManager.getInstance().getDataContext(FavoritesTreeViewPanel.this), true);
<del> }
<del> }
<del> });
<del>
<del> myTree.addKeyListener(new KeyAdapter() {
<del> public void keyPressed(KeyEvent e) {
<del> if (e.getKeyCode() == KeyEvent.VK_ENTER) {
<del> OpenSourceUtil.openSourcesFrom(DataManager.getInstance().getDataContext(FavoritesTreeViewPanel.this), false);
<del> }
<del> }
<del> });
<ide> myCopyPasteDelegator = new CopyPasteManagerEx.CopyPasteDelegator(myProject, this) {
<ide> @NotNull
<ide> protected PsiElement[] getSelectedElements() { |
|
Java | agpl-3.0 | 9575006398d549dfc694a555456b476717c035f1 | 0 | rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat | package roart.iclij.component;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Map.Entry;
import java.util.OptionalDouble;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import roart.common.cache.MyCache;
import roart.common.config.CacheConstants;
import roart.common.config.ConfigConstants;
import roart.common.constants.Constants;
import roart.common.constants.EvolveConstants;
import roart.common.constants.ServiceConstants;
import roart.common.model.MetaItem;
import roart.common.pipeline.PipelineConstants;
import roart.common.util.JsonUtil;
import roart.common.util.MapUtil;
import roart.common.util.MathUtil;
import roart.common.util.MetaUtil;
import roart.common.util.TimeUtil;
import roart.common.util.ValidateUtil;
import roart.iclij.component.adviser.Adviser;
import roart.iclij.component.adviser.AdviserFactory;
import roart.component.model.ComponentData;
import roart.component.model.SimulateInvestData;
import roart.constants.IclijConstants;
import roart.constants.SimConstants;
import roart.db.IclijDbDao;
import roart.evolution.chromosome.AbstractChromosome;
import roart.iclij.evolution.chromosome.impl.ConfigMapChromosome2;
import roart.iclij.evolution.chromosome.winner.IclijConfigMapChromosomeWinner;
import roart.evolution.config.EvolutionConfig;
import roart.evolution.fitness.Fitness;
import roart.evolution.iclijconfigmap.genetics.gene.impl.IclijConfigMapChromosome;
import roart.evolution.iclijconfigmap.genetics.gene.impl.IclijConfigMapGene;
import roart.iclij.config.AutoSimulateInvestConfig;
import roart.iclij.config.IclijConfig;
import roart.iclij.config.IclijConfigConstants;
import roart.iclij.config.IclijXMLConfig;
import roart.iclij.config.MLConfigs;
import roart.iclij.config.Market;
import roart.iclij.config.SimulateFilter;
import roart.iclij.config.SimulateInvestConfig;
import roart.iclij.filter.Memories;
import roart.iclij.model.MLMetricsItem;
import roart.iclij.model.IncDecItem;
import roart.iclij.model.MemoryItem;
import roart.iclij.model.Parameters;
import roart.iclij.model.SimDataItem;
import roart.iclij.model.Trend;
import roart.iclij.model.action.MarketActionData;
import roart.iclij.service.IclijServiceResult;
import roart.iclij.verifyprofit.TrendUtil;
import roart.service.model.ProfitData;
import roart.simulate.model.Capital;
import roart.simulate.model.SimulateStock;
import roart.simulate.model.StockHistory;
import roart.simulate.util.SimUtil;
public class SimulateInvestComponent extends ComponentML {
private static final boolean VERIFYCACHE = false;
private static final int MAXARR = 0;
@Override
public void enable(Map<String, Object> valueMap) {
}
@Override
public void disable(Map<String, Object> valueMap) {
}
@Override
public ComponentData handle(MarketActionData action, Market market, ComponentData param, ProfitData profitdata,
Memories positions, boolean evolve, Map<String, Object> aMap, String subcomponent, String mlmarket,
Parameters parameters, boolean hasParent) {
ComponentData componentData = new ComponentData(param);
SimulateInvestData simulateParam;
if (param instanceof SimulateInvestData) {
simulateParam = (SimulateInvestData) param;
} else {
simulateParam = new SimulateInvestData(param);
}
IclijConfig config = param.getInput().getConfig();
// four cases
// autosimconfig set, both evolve and not, and simconfig is null
// autoconfig is not set, and simconfig is set, both evolve and not
// simconfig from siminvest
// localsimconfig from market config file
// simconfig and localsimconfig merges, with simconfig values win
// four cases
// sim: vl
// imp: vl filt
// auto: vl filt
// impauto: vl filt
// extradelay: delay for getting prices
// extradelay: buy and sell is on the same date, just an approx
// delay: days after buy/sell decision.
String conffilters = (String) param.getConfigValueMap().remove(IclijConfigConstants.SIMULATEINVESTFILTERS);
String confautofilters = (String) param.getConfigValueMap().remove(IclijConfigConstants.AUTOSIMULATEINVESTFILTERS);
AutoSimulateInvestConfig autoSimConfig = getAutoSimConfig(config);
SimulateInvestConfig simConfig = getSimConfig(config);
// coming from improvesim
List<SimulateFilter> filter = get(conffilters);
List<SimulateFilter> autofilter = get(confautofilters);
if (simConfig != null) {
filter = simConfig.getFilters();
}
if (autoSimConfig != null) {
autofilter = autoSimConfig.getFilters();
}
//Integer overrideAdviser = null;
boolean evolving = param instanceof SimulateInvestData;
if (!(param instanceof SimulateInvestData)) {
// if not evolving, plain simulating
SimulateInvestConfig localSimConfig = getSimulate(market.getSimulate());
// override with file config
localSimConfig.merge(simConfig);
if (simConfig != null) {
//simConfig.merge(localSimConfig);
}
if (localSimConfig.getExtradelay() != null) {
//extradelay = localSimConfig.getExtradelay();
}
simConfig = localSimConfig;
} else {
// if evolving
/*
if (simulateParam.getConfig() != null) {
overrideAdviser = simulateParam.getConfig().getAdviser();
simConfig.merge(simulateParam.getConfig());
}
*/
/*
if (!simulateParam.getInput().getValuemap().isEmpty()) {
overrideAdviser = simulateParam.getConfig().getAdviser();
simConfig.merge(simulateParam.getConfig());
}
*/
// file configured sim config
SimulateInvestConfig localSimConfig = getSimulate(market.getSimulate());
localSimConfig.merge(simConfig);
if (localSimConfig != null && localSimConfig.getVolumelimits() != null && simConfig.getVolumelimits() == null) {
// override base simconfig with file config volumelimits
//simConfig.setVolumelimits(localSimConfig.getVolumelimits());
}
if (localSimConfig != null && localSimConfig.getExtradelay() != null) {
// use file config extradelay
//simConfig.setExtradelay(localSimConfig.getExtradelay());
//extradelay = localSimConfig.getExtradelay();
}
simConfig = localSimConfig;
}
if (autoSimConfig != null/* && !evolving*/) {
simConfig.setStartdate(autoSimConfig.getStartdate());
simConfig.setEnddate(autoSimConfig.getEnddate());
simConfig.setInterval(autoSimConfig.getInterval());
simConfig.setVolumelimits(autoSimConfig.getVolumelimits());
}
int extradelay = 0;
if (simConfig.getExtradelay() != null) {
extradelay = simConfig.getExtradelay();
}
// coming from improvesim
//List<SimulateFilter> filter = simConfig.getFilters();
//simConfig.setFilters(null);
Data data = new Data();
if (simulateParam.getStockDates() != null) {
data.stockDates = simulateParam.getStockDates();
} else {
data.stockDates = param.getService().getDates(market.getConfig().getMarket());
}
if (!TimeUtil.rangeCheck(data.stockDates, TimeUtil.replace(simConfig.getStartdate()), TimeUtil.replace(simConfig.getEnddate()))) {
Map<String, Object> map = new HashMap<>();
map.put(SimConstants.EMPTY, true);
map.put(EvolveConstants.TITLETEXT, emptyNull(simConfig.getStartdate(), "start") + "-" + emptyNull(simConfig.getEnddate(), "end") + " " + ("any"));
componentData.getUpdateMap().putAll(map);
if (evolving) {
componentData.setResultMap(new HashMap<>());
}
Double score = 0.0;
Map<String, Double> scoreMap = new HashMap<>();
if (score.isNaN()) {
int jj = 0;
}
scoreMap.put("" + score, score);
scoreMap.put(SimConstants.SCORE, score);
componentData.setScoreMap(scoreMap);
handle2(action, market, componentData, profitdata, positions, evolve, aMap, subcomponent, mlmarket, parameters, hasParent);
return componentData;
}
data.categoryValueFillMap = param.getFillCategoryValueMap();
data.categoryValueMap = param.getCategoryValueMap();
data.volumeMap = param.getVolumeMap();
BiMap<String, LocalDate> stockDatesBiMap = getStockDatesBiMap(market.getConfig().getMarket(), data.stockDates);
//ComponentData componentData = component.improve2(action, param, market, profitdata, null, buy, subcomponent, parameters, mlTests);
String mldate = getMlDate(market, simConfig, data, autoSimConfig);
int investStartOffset = data.stockDates.size() - 1 - TimeUtil.getIndexEqualBefore(data.stockDates, mldate);
String adatestring = data.stockDates.get(data.stockDates.size() - 1 - investStartOffset);
LocalDate investStart = stockDatesBiMap.get(adatestring);
/*
try {
investStart = TimeUtil.convertDate(mldate);
} catch (ParseException e1) {
log.error(Constants.EXCEPTION, e1);
}
*/
LocalDate investEnd = param.getFutureDate();
try {
String enddate;
if (autoSimConfig != null) {
enddate = autoSimConfig.getEnddate();
} else {
enddate = simConfig.getEnddate();
}
if (enddate != null) {
enddate = enddate.replace('-', '.');
investEnd = TimeUtil.convertDate(enddate);
}
} catch (ParseException e1) {
log.error(Constants.EXCEPTION, e1);
}
int endIndexOffset = 0;
if (investEnd != null) {
String investEndStr = TimeUtil.convertDate2(investEnd);
int investEndIndex = TimeUtil.getIndexEqualBefore(data.stockDates, investEndStr);
endIndexOffset = data.stockDates.size() - 1 - investEndIndex;
}
boolean intervalwhole;
if (autoSimConfig != null) {
intervalwhole = config.getAutoSimulateInvestIntervalwhole();
} else {
intervalwhole = config.wantsSimulateInvestIntervalWhole();
}
int end = 1;
if (intervalwhole) {
end = autoSimConfig != null ? autoSimConfig.getInterval() : simConfig.getInterval();
}
List<String> parametersList = new ArrayList<>(); //adviser.getParameters();
if (parametersList.isEmpty()) {
parametersList.add(null);
}
List<Double> scores = new ArrayList<>();
//LocalDate date = TimeUtil.getEqualBefore(data.stockDates, investStart);
//int indexOffset = data.stockDates.size() - 1 - TimeUtil.getIndexEqualAfter(data.stockDates, datestring2);
// TODO investend and other reset of more params
Parameters realParameters = parameters;
if (realParameters == null || realParameters.getThreshold() == 1.0) {
String aParameter = JsonUtil.convert(realParameters);
investEnd = getAdjustedInvestEnd(extradelay, data, investEnd);
LocalDate lastInvestEnd = getAdjustedLastInvestEnd(data, investEnd, simConfig.getDelay());
setDataIdx(data, investStart, lastInvestEnd);
setExclusions(market, data, simConfig);
setDataVolumeAndTrend(market, param, simConfig, data, investStart, investEnd, lastInvestEnd, evolving);
long time0 = System.currentTimeMillis();
Map<String, Object> resultMap = new HashMap<>();
for (int offset = 0; offset < end; offset++) {
Integer origAdviserId = (Integer) param.getInput().getValuemap().get(IclijConfigConstants.SIMULATEINVESTADVISER);
Mydate mydate = new Mydate();
mydate.indexOffset = investStartOffset - offset;
if (mydate.indexOffset < 0) {
continue;
}
String adatestring2 = data.stockDates.get(data.stockDates.size() - 1 - mydate.indexOffset);
mydate.date = stockDatesBiMap.get(adatestring2);
//getAdjustedDate(data, investStart, offset, mydate);
Map<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> simConfigs;
List<SimulateFilter[]> filters = new ArrayList<>();
if (autoSimConfig == null) {
simConfigs = new HashMap<>();
List<SimulateFilter> listoverride = filter; //simConfig.getFilters();
List<SimulateFilter[]> list = getDefaultList();
if (list != null) {
filters.addAll(list);
}
if (listoverride != null) {
mergeFilterList(list, listoverride);
}
//simConfigs = new ArrayList<>();
//simConfigs.add(getSimConfig(config));
} else {
simConfigs = getSimConfigs(market.getConfig().getMarket(), autoSimConfig, autofilter, filters, config);
simConfigs = new HashMap<>(simConfigs);
}
List<SimulateInvestConfig> simsConfigs = new ArrayList<>();
if (autoSimConfig == null) {
simsConfigs.add(simConfig);
} else {
Set<Pair<LocalDate, LocalDate>> keys = new HashSet<>();
if (mydate.date != null) {
simsConfigs = getSimConfigs(simConfigs, mydate, keys, market);
simConfigs.keySet().removeAll(keys);
}
}
List<Triple<SimulateInvestConfig, OneRun, Results>> simTriplets = getTriples(market, param, data,
investStart, investEnd, mydate, simsConfigs);
if (evolving || offset > 0) {
investEnd = lastInvestEnd;
}
SimulateInvestConfig currentSimConfig = null;
if (autoSimConfig == null) {
currentSimConfig = simConfig;
}
OneRun currentOneRun = getOneRun(market, param, simConfig, data, investStart, investEnd, null);
Adviser selladviser = null;
Adviser voteadviser = null;
SimulateInvestConfig sell = null;
SimulateInvestConfig vote = null;
if (autoSimConfig == null) {
int adviserId = simConfig.getAdviser();
currentOneRun.adviser = new AdviserFactory().get(adviserId, market, investStart, investEnd, param, simConfig);
currentOneRun.adviser.getValueMap(data.stockDates, data.firstidx, data.lastidx, data.getCatValMap(simConfig.getInterpolate()));
} else {
selladviser = new AdviserFactory().get(-1, market, investStart, investEnd, param, simConfig);
sell = JsonUtil.copy(simConfig);
sell.setConfidence(true);
sell.setConfidenceValue(2.0);
sell.setConfidenceFindTimes(0);
if (autoSimConfig.getVote() != null && autoSimConfig.getVote()) {
voteadviser = new AdviserFactory().get(-2, market, investStart, investEnd, param, simConfig);
vote = JsonUtil.copy(simConfig);
//vote.setConfidence(true);
//vote.setConfidenceValue(2.0);
//vote.setConfidenceFindTimes(0);
//currentSimConfig = vote;
}
}
Results mainResult = new Results();
/*
if (mydate.date != null) {
mydate.date = TimeUtil.getForwardEqualAfter2(mydate.date, 0 , data.stockDates);
String datestring2 = TimeUtil.convertDate2(mydate.date);
mydate.indexOffset = data.stockDates.size() - 1 - TimeUtil.getIndexEqualAfter(data.stockDates, datestring2);
}
*/
while (mydate.indexOffset >= endIndexOffset) {
boolean lastInvest = offset == 0 && mydate.indexOffset == endIndexOffset;
/*
if (currentSimConfig != null) {
doOneRun(param, currentSimConfig, extradelay, evolving, aParameter, offset, currentOneRun, mainResult,
data, lastInvest, mydate, autoSimConfig != null, stockDatesBiMap);
}
*/
if (autoSimConfig != null) {
if (MAXARR > 0 && !simTriplets.isEmpty() && simTriplets.get(0).getMiddle().autoscore != null && simTriplets.get(0).getMiddle().autoscore != 0) {
Collections.shuffle(simTriplets);
}
for (Triple<SimulateInvestConfig, OneRun, Results> aPair : simTriplets) {
SimulateInvestConfig aSimConfig = aPair.getLeft();
OneRun aOneRun = aPair.getMiddle();
Results aResult = aPair.getRight();
doOneRun(param, aSimConfig, extradelay, evolving, aParameter, offset, aOneRun, aResult,
data, lastInvest, mydate, autoSimConfig != null, stockDatesBiMap, false, endIndexOffset);
}
}
if (currentSimConfig != null) {
if (!simTriplets.isEmpty() && simTriplets.get(0).getMiddle().autoscore != null && simTriplets.get(0).getMiddle().autoscore != 0 && autoSimConfig.getVote() != null && autoSimConfig.getVote()) {
List<String> buys = new ArrayList<>();
//Collections.sort(simTriplets, (o1, o2) -> Double.compare(o2.getMiddle().autoscore, o1.getMiddle().autoscore));
List<Triple<SimulateInvestConfig, OneRun, Results>> new2 = getAdviserTriplets(simTriplets);
List<Triple<SimulateInvestConfig, OneRun, Results>> others = new2;
for (Triple<SimulateInvestConfig, OneRun, Results> triplet : others) {
OneRun aresult = triplet.getMiddle();
buys.addAll(aresult.buys.stream().map(SimulateStock::getId).collect(Collectors.toList()));
}
currentOneRun.adviser.setExtra(buys);
}
doOneRun(param, currentSimConfig, extradelay, evolving, aParameter, offset, currentOneRun, mainResult,
data, lastInvest, mydate, autoSimConfig != null, stockDatesBiMap, true, endIndexOffset);
}
if (autoSimConfig != null) {
for (Triple<SimulateInvestConfig, OneRun, Results> aTriple : simTriplets) {
SimulateInvestConfig aSimConfig = aTriple.getLeft();
OneRun aOneRun = aTriple.getMiddle();
Results aResult = aTriple.getRight();
// best or best last
double score = getScore(autoSimConfig, aOneRun, aResult);
aOneRun.autoscore = score;
if (score < 0) {
int jj = 0;
}
}
// no. hits etc may be reset if changed
// winnerAdviser
Collections.sort(simTriplets, (o1, o2) -> Double.compare(o2.getMiddle().autoscore, o1.getMiddle().autoscore));
if (MAXARR > 0) {
if (MAXARR < 11) {
if (!simTriplets.isEmpty() && simTriplets.get(0).getMiddle().autoscore != 0) {
List<Triple<SimulateInvestConfig, OneRun, Results>> new2 = getAdviserTriplets(
simTriplets);
if (simTriplets.size() != new2.size()) {
for (Triple<SimulateInvestConfig, OneRun, Results> anew : new2) {
SimulateInvestConfig aconf = anew.getLeft();
log.info("" + aconf.asValuedMap());
}
}
simTriplets = new2;
}
} else {
simTriplets = simTriplets.subList(0, Math.min(MAXARR, simTriplets.size()));
}
}
// overwrite/merge currentOnerun etc
// and get new date range
// and remove old or bad
Set<Pair<LocalDate, LocalDate>> keys = new HashSet<>();
simsConfigs = getSimConfigs(simConfigs, mydate, keys, market);
simConfigs.keySet().removeAll(keys);
List<Triple<SimulateInvestConfig, OneRun, Results>> newSimTriplets = getTriples(market, param, data,
investStart, investEnd, mydate, simsConfigs);
if (newSimTriplets.size() > 0) {
if (MAXARR > 0) {
//newSimTriplets = newSimTriplets.subList(0, Math.min(MAXARR, simTriplets.size()));
}
List<Double> alist = simTriplets.stream().map(o -> (o.getMiddle().capital.amount + getSum(o.getMiddle().mystocks).amount)).collect(Collectors.toList());
log.info("alist {}", alist);
double autolimit = autoSimConfig.getDellimit();
simTriplets = simTriplets.stream().filter(o -> (o.getMiddle().capital.amount + getSum(o.getMiddle().mystocks).amount) > autolimit).collect(Collectors.toList());
}
simTriplets.addAll(newSimTriplets);
}
if (autoSimConfig != null && !simTriplets.isEmpty()) {
List<Double> alist = simTriplets.stream().map(o -> (o.getMiddle().autoscore)).collect(Collectors.toList());
log.info("alist {}", alist);
OneRun oneRun = simTriplets.get(0).getMiddle();
if (oneRun.runs > 1 && ((oneRun.autoscore != null && oneRun.autoscore > autoSimConfig.getAutoscorelimit()) || (autoSimConfig.getKeepAdviser() && currentOneRun.autoscore != null && currentOneRun.autoscore > autoSimConfig.getKeepAdviserLimit()))) {
if (autoSimConfig.getVote() != null && autoSimConfig.getVote()) {
currentOneRun.adviser = voteadviser;
//currentOneRun.hits = SerializationUtils.clone(oneRun.hits);
//currentOneRun.trendDec = SerializationUtils.clone(oneRun.trendDec);
//currentOneRun.trendInc = SerializationUtils.clone(oneRun.trendInc);
currentSimConfig = vote;
} else {
// calc autoscore
Double score = getScore(autoSimConfig, currentOneRun, mainResult);
if (!(autoSimConfig.getKeepAdviser() && score != null && score > autoSimConfig.getKeepAdviserLimit())) {
currentOneRun.adviser = oneRun.adviser;
currentOneRun.hits = SerializationUtils.clone(oneRun.hits);
currentOneRun.trendDec = SerializationUtils.clone(oneRun.trendDec);
currentOneRun.trendInc = SerializationUtils.clone(oneRun.trendInc);
//oneRun.
currentSimConfig = simTriplets.get(0).getLeft();
}
}
} else {
currentOneRun.adviser = selladviser;
if (autoSimConfig.getVote() == null || !autoSimConfig.getVote()) {
currentOneRun.hits = SerializationUtils.clone(oneRun.hits);
currentOneRun.trendDec = SerializationUtils.clone(oneRun.trendDec);
currentOneRun.trendInc = SerializationUtils.clone(oneRun.trendInc);
}
currentSimConfig = sell;
}
}
mydate.prevIndexOffset = mydate.indexOffset;
//int interval = autoSimConfig != null ? autoSimConfig.getInterval() : simConfig.getInterval();
if (mydate.indexOffset - simConfig.getInterval() < 0 * endIndexOffset) {
break;
}
mydate.indexOffset -= simConfig.getInterval();
String adatestring3 = data.stockDates.get(data.stockDates.size() - 1 - mydate.indexOffset);
mydate.date = stockDatesBiMap.get(adatestring3);
}
/*
if (offset == 0) {
try {
lastbuysell(stockDates, date, adviser, capital, simConfig, categoryValueMap, mystocks, extradelay, prevIndexOffset, hits, findTimes, aParameter, param.getUpdateMap(), trendInc, trendDec, configExcludeList, param, market, interval, filteredCategoryValueMap, volumeMap, delay);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
*/
List<Triple<SimulateInvestConfig, OneRun, Results>> endSimTriplets = new ArrayList<>();
endSimTriplets.add(new ImmutableTriple(currentSimConfig, currentOneRun, mainResult));
for (Triple<SimulateInvestConfig, OneRun, Results> aPair : endSimTriplets) {
SimulateInvestConfig aSimConfig = aPair.getLeft();
OneRun aOneRun = aPair.getMiddle();
Results aResult = aPair.getRight();
//boolean lastInvest = offset == 0 && mydate.date != null && lastInvestEnd != null && mydate.date.isAfter(lastInvestEnd);
// check
/*
if (aOneRun.saveLastInvest) {
aOneRun.mystocks = aOneRun.savedStocks;
}
*/
// index == prev
update(data.getCatValMap(simConfig.getInterpolate()), aOneRun.mystocks, endIndexOffset + extradelay, new ArrayList<>(), endIndexOffset + extradelay, endIndexOffset);
Capital sum = getSum(aOneRun.mystocks);
sum.amount += aOneRun.capital.amount;
long days = 0;
if (investStart != null && investEnd != null) {
days = ChronoUnit.DAYS.between(investStart, investEnd);
}
double years = (double) days / 365;
Double score = sum.amount / aOneRun.resultavg;
if (score < -0.1) {
log.error("Negative amount");
}
if (score < 0) {
score = 0.0;
}
if (years != 0) {
score = Math.pow(score, 1 / years);
} else {
score = 0.0;
}
if (score < -1) {
int jj = 0;
}
if (score > 10) {
int jj = 0;
}
if (score > 100) {
int jj = 0;
}
if (score.isNaN()) {
int jj = 0;
}
if (offset == 0) {
Map<String, Object> map = new HashMap<>();
if (!evolving) {
for (SimulateStock stock : aOneRun.mystocks) {
// wrong price in dev
stock.setSellprice(stock.getPrice());
stock.setStatus("END");
}
aResult.stockhistory.addAll(aOneRun.mystocks);
map.put(SimConstants.SUMHISTORY, aResult.sumHistory);
map.put(SimConstants.STOCKHISTORY, aResult.stockhistory);
map.put(SimConstants.PLOTDEFAULT, aResult.plotDefault);
map.put(SimConstants.PLOTDATES, aResult.plotDates);
map.put(SimConstants.PLOTCAPITAL, aResult.plotCapital);
map.put(SimConstants.STARTDATE, investStart);
map.put(SimConstants.ENDDATE, investEnd);
map.put(SimConstants.FILTER, JsonUtil.convert(filter));
map.put(SimConstants.LASTSTOCKS, aOneRun.mystocks.stream().map(SimulateStock::getId).toList());
List<Pair<String, Double>> tradeStocks = SimUtil.getTradeStocks(aResult.stockhistory);
map.put(SimConstants.TRADESTOCKS, tradeStocks);
param.getUpdateMap().putAll(map);
param.getUpdateMap().putIfAbsent(SimConstants.LASTBUYSELL, "Not buying or selling today");
componentData.getUpdateMap().putAll(map);
} else {
if (autoSimConfig != null) {
map.put(EvolveConstants.TITLETEXT, emptyNull(autoSimConfig.getStartdate(), "start") + "-" + emptyNull(autoSimConfig.getEnddate(), "end") + " " + (emptyNull(origAdviserId, "all")));
} else {
map.put(EvolveConstants.TITLETEXT, emptyNull(simConfig.getStartdate(), "start") + "-" + emptyNull(simConfig.getEnddate(), "end") + " " + (emptyNull(origAdviserId, "all")));
}
map.put(SimConstants.FILTER, JsonUtil.convert(filter));
componentData.getUpdateMap().putAll(map);
}
}
if (evolving) {
for (SimulateStock stock : aOneRun.mystocks) {
stock.setSellprice(stock.getPrice());
stock.setStatus("END");
}
aResult.stockhistory.addAll(aOneRun.mystocks);
boolean doFilter = (autoSimConfig != null && autoSimConfig.getImproveFilters()) || (autoSimConfig == null && simConfig.getImproveFilters());
if (doFilter) {
SimulateFilter afilter;
if (autoSimConfig != null) {
afilter = filters.get(0)[0];
} else {
afilter = filters.get(0)[currentSimConfig.getAdviser()];
}
if (afilter.getStable() > 0) {
List<StockHistory> history = aResult.history;
if (!history.isEmpty()) {
if (!SimUtil.isStable(afilter, history, null)) {
score = 0.0;
}
}
}
if (afilter.getCorrelation() > 0) {
if (!(aResult.plotCapital.size() < 2) && !SimUtil.isCorrelating(afilter, aResult.plotCapital, null)) {
score = 0.0;
}
}
if (afilter.getLucky() > 0) {
List<StockHistory> history = aResult.history;
if (!history.isEmpty()) {
StockHistory last = history.get(history.size() - 1);
double total = last.getCapital().amount + last.getSum().amount - 1;
if (total > 0.0) {
List<Pair<String, Double>> list = SimUtil.getTradeStocks(aResult.stockhistory);
double max = 0;
if (!list.isEmpty()) {
max = list.get(0).getValue();
}
if (max / total > afilter.getLucky()) {
score = 0.0;
}
}
}
}
if (afilter.getShortrun() > 0) {
List<StockHistory> history = aResult.history;
if (history.size() < afilter.getShortrun()) {
score = 0.0;
}
}
}
Map<String, Object> map = new HashMap<>();
map.put(SimConstants.HISTORY, aResult.history);
map.put(SimConstants.STOCKHISTORY, aResult.stockhistory);
map.put(SimConstants.PLOTCAPITAL, aResult.plotCapital);
map.put(SimConstants.SCORE, score);
map.put(SimConstants.STARTDATE, TimeUtil.convertDate2(investStart));
map.put(SimConstants.ENDDATE, TimeUtil.convertDate2(investEnd));
if (autoSimConfig != null) {
map.put(EvolveConstants.TITLETEXT, emptyNull(autoSimConfig.getStartdate(), "start") + "-" + emptyNull(autoSimConfig.getEnddate(), "end") + " " + (emptyNull(origAdviserId, "all")));
} else {
map.put(EvolveConstants.SIMTEXT, market.getConfig().getMarket() + " " + emptyNull(simConfig.getStartdate(), "start") + "-" + emptyNull(simConfig.getEnddate(), "end") + " " + (emptyNull(origAdviserId, "all")));
}
map.put(SimConstants.FILTER, JsonUtil.convert(filter));
//map.put("market", market.getConfig().getMarket());
resultMap.put("" + offset, map);
}
scores.add(score);
}
}
if (evolving) {
componentData.setResultMap(resultMap);
}
log.debug("time0 {}", System.currentTimeMillis() - time0);
}
Double score = 0.0;
if (!scores.isEmpty()) {
OptionalDouble average = scores
.stream()
.mapToDouble(a -> a)
.average();
score = average.getAsDouble();
}
if (intervalwhole) {
String stats = scores.stream().filter(Objects::nonNull).mapToDouble(e -> (Double) e).summaryStatistics().toString();
Map<String, Object> map = new HashMap<>();
map.put(SimConstants.SCORES, scores);
map.put(SimConstants.STATS, stats);
double min = Collections.min(scores);
double max = Collections.max(scores);
int minDay = scores.indexOf(min);
int maxDay = scores.indexOf(max);
map.put(SimConstants.MINMAX, "min " + min + " at " + minDay + " and max " + max + " at " + maxDay);
param.getUpdateMap().putAll(map);
componentData.getUpdateMap().putAll(map);
}
Map<String, Double> scoreMap = new HashMap<>();
if (score.isNaN()) {
int jj = 0;
}
scoreMap.put("" + score, score);
scoreMap.put(SimConstants.SCORE, score);
componentData.setScoreMap(scoreMap);
//componentData.setFuturedays(0);
handle2(action, market, componentData, profitdata, positions, evolve, aMap, subcomponent, mlmarket, parameters, hasParent);
return componentData;
}
private Double getScore(AutoSimulateInvestConfig autoSimConfig, OneRun aOneRun, Results aResult) {
int numlast = autoSimConfig.getLastcount();
Double score;
if (numlast == 0 || aOneRun.runs == 1) {
Capital sum = getSum(aOneRun.mystocks);
sum.amount += aOneRun.capital.amount;
score = (sum.amount - 1) / aOneRun.runs;
if (aResult.plotCapital.size() > 0) {
if (numlast == 0) {
if (score != ((aResult.plotCapital.get(aResult.plotCapital.size() - 1) - 1)/ aResult.plotCapital.size())) {
System.out.println("sc " + score + " " + aOneRun.runs);
System.out.println("" + aResult.plotCapital.get(aResult.plotCapital.size() - 1));
System.out.println("" + aResult.plotCapital.size());
System.out.println("" + (((aResult.plotCapital.get(aResult.plotCapital.size() - 1) - 1)/ aResult.plotCapital.size())));
System.out.println("ERRERR");
}
}
int firstidx = aResult.plotCapital.size() - 1 - numlast;
if (firstidx < 0 || numlast == 0) {
firstidx = 0;
}
double newscore = aResult.plotCapital.get(aResult.plotCapital.size() - 1) - aResult.plotCapital.get(firstidx);
newscore = newscore / (aResult.plotCapital.size() - firstidx);
if (Math.abs(newscore - score) > 0.00000000001 ) {
System.out.println("ERRERR");
}
}
} else {
int firstidx = aResult.plotCapital.size() - 1 - numlast;
if (firstidx < 0) {
firstidx = 0;
}
score = null;
if (aResult.plotCapital.size() > 0) {
score = aResult.plotCapital.get(aResult.plotCapital.size() - 1) - aResult.plotCapital.get(firstidx);
score = score / (aResult.plotCapital.size() - firstidx);
} else {
int jj = 0;
}
}
return score;
}
private List<Triple<SimulateInvestConfig, OneRun, Results>> getAdviserTriplets(
List<Triple<SimulateInvestConfig, OneRun, Results>> simTriplets) {
Integer[] advs = new Integer[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<Triple<SimulateInvestConfig, OneRun, Results>> new2 = new ArrayList<>();
int i = 0;
for (int j = 0; i < 10 && j < simTriplets.size(); j++) {
int adv = simTriplets.get(j).getLeft().getAdviser();
if (advs[adv] == null) {
continue;
}
advs[adv] = null;
new2.add(simTriplets.get(j));
i++;
}
return new2;
}
private List<Triple<SimulateInvestConfig, OneRun, Results>> getTriples(Market market, ComponentData param,
Data data, LocalDate investStart, LocalDate investEnd, Mydate mydate, List<SimulateInvestConfig> simsConfigs) {
List<Triple<SimulateInvestConfig, OneRun, Results>> simPairs = new ArrayList<>();
for (SimulateInvestConfig aConfig : simsConfigs) {
int adviserId = aConfig.getAdviser();
OneRun onerun = getOneRun(market, param, aConfig, data, investStart, investEnd, adviserId);
Results results = new Results();
Triple<SimulateInvestConfig, OneRun, Results> aTriple = new ImmutableTriple(aConfig, onerun, results);
simPairs.add(aTriple);
}
return simPairs;
}
private OneRun getOneRun(Market market, ComponentData param, SimulateInvestConfig simConfig, Data data,
LocalDate investStart, LocalDate investEnd, Integer adviserId) {
OneRun onerun = new OneRun();
if (adviserId != null) {
onerun.adviser = new AdviserFactory().get(adviserId, market, investStart, investEnd, param, simConfig);
onerun.adviser.getValueMap(data.stockDates, data.firstidx, data.lastidx, data.getCatValMap(simConfig.getInterpolate()));
}
onerun.capital = new Capital();
onerun.capital.amount = 1;
onerun.beatavg = 0;
onerun.runs = 0;
onerun.mystocks = new ArrayList<>();
onerun.resultavg = 1;
onerun.hits = new ImmutablePair[simConfig.getConfidenceFindTimes()];
onerun.trendInc = new Integer[] { 0 };
onerun.trendDec = new Integer[] { 0 };
onerun.saveLastInvest = false;
return onerun;
}
private List<SimulateInvestConfig> getSimConfigs(Map<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> simConfigs, Mydate mydate,
Set<Pair<LocalDate, LocalDate>> keys, Market market) {
List<SimulateInvestConfig> simsConfigs = new ArrayList<>();
for (Entry<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> entry : simConfigs.entrySet()) {
Pair<LocalDate, LocalDate> key = entry.getKey();
List<SimulateInvestConfig> value = entry.getValue();
int months = Period.between(key.getLeft(), key.getRight()).getMonths();
LocalDate checkDate = mydate.date.minusMonths(months);
if (!checkDate.isBefore(key.getLeft()) && checkDate.isBefore(key.getRight())) {
// TODO value.merge...
List<SimulateInvestConfig> configs = value;
for (SimulateInvestConfig config : configs) {
SimulateInvestConfig defaultConfig = getSimulate(market.getSimulate());
defaultConfig.merge(config);
simsConfigs.add(defaultConfig);
}
keys.add(key);
}
}
return simsConfigs;
}
private SimulateInvestConfig getSimulate(SimulateInvestConfig simulate) {
if (simulate == null) {
return new SimulateInvestConfig();
}
SimulateInvestConfig newSimConfig = new SimulateInvestConfig(simulate);
if (!newSimConfig.equals(simulate)) {
log.error("Unequal clone");
}
return newSimConfig;
}
private void setExclusions(Market market, Data data, SimulateInvestConfig simConfig) {
String[] excludes = null;
if (market.getSimulate() != null) {
excludes = market.getSimulate().getExcludes();
}
if (excludes == null) {
excludes = new String[0];
}
data.configExcludeList = Arrays.asList(excludes);
Set<String> configExcludeSet = new HashSet<>(data.configExcludeList);
Set<String> abnormExcludes = getTrendExclude(data, market);
data.filteredCategoryValueMap = new HashMap<>(data.getCatValMap(false));
data.filteredCategoryValueMap.keySet().removeAll(configExcludeSet);
data.filteredCategoryValueMap.keySet().removeAll(abnormExcludes);
data.filteredCategoryValueFillMap = new HashMap<>(data.getCatValMap(true));
data.filteredCategoryValueFillMap.keySet().removeAll(configExcludeSet);
data.filteredCategoryValueFillMap.keySet().removeAll(abnormExcludes);
}
private Set<String> getTrendExclude(Data data, Market market) {
IclijConfig instance = IclijXMLConfig.getConfigInstance();
Double margin = instance.getAbnormalChange();
if (margin == null) {
return new HashSet<>();
}
Set<String> abnormExcludes = null;
String key = CacheConstants.SIMULATEINVESTTRENDEXCLUDE + market.getConfig().getMarket() + "_" + data.firstidx + "_" + data.lastidx + "_" + margin;
abnormExcludes = (Set<String>) MyCache.getInstance().get(key);
Set<String> newAbnormExcludes = null;
if (abnormExcludes == null || VERIFYCACHE) {
long time0 = System.currentTimeMillis();
try {
newAbnormExcludes = new TrendUtil().getTrend(null, data.stockDates, null, null, data.getCatValMap(false), data.firstidx, data.lastidx, margin);
log.info("Abnormal excludes {}", newAbnormExcludes);
} catch (Exception e) {
log.error(Constants.ERROR, e);
}
log.debug("time millis {}", System.currentTimeMillis() - time0);
}
if (VERIFYCACHE && abnormExcludes != null) {
if (newAbnormExcludes != null && !newAbnormExcludes.equals(abnormExcludes)) {
log.error("Difference with cache");
}
}
if (abnormExcludes != null) {
return abnormExcludes;
}
abnormExcludes = newAbnormExcludes;
MyCache.getInstance().put(key, abnormExcludes);
return abnormExcludes;
}
private Map<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> getSimConfigs(String market, AutoSimulateInvestConfig autoSimConf, List<SimulateFilter> filter, List<SimulateFilter[]> filters, IclijConfig config) {
List<SimDataItem> all = new ArrayList<>();
try {
String simkey = CacheConstants.SIMDATA + market + autoSimConf.getStartdate() + autoSimConf.getEnddate();
all = (List<SimDataItem>) MyCache.getInstance().get(simkey);
if (all == null) {
LocalDate startDate = TimeUtil.convertDate(TimeUtil.replace(autoSimConf.getStartdate()));
LocalDate endDate = null;
if (autoSimConf.getEnddate() != null) {
endDate = TimeUtil.convertDate(TimeUtil.replace(autoSimConf.getEnddate()));
}
all = SimDataItem.getAll(market, null, null); // fix later: , startDate, endDate);
MyCache.getInstance().put(simkey, all);
}
/*
if (VERIFYCACHE && trendMap != null) {
for (Entry<Integer, Trend> entry : newTrendMap.entrySet()) {
int key2 = entry.getKey();
Trend v2 = entry.getValue();
Trend v = trendMap.get(key2);
if (v2 != null && !v2.toString().equals(v.toString())) {
log.error("Difference with cache");
}
}
}
*/
} catch (Exception e) {
log.error(Constants.ERROR, e);
}
List<SimulateFilter[]> list = null;
if (autoSimConf != null) {
List<SimulateFilter> listoverride = filter; //autoSimConf.getFilters();
list = getDefaultList();
if (list != null) {
filters.addAll(list);
}
if (listoverride != null) {
mergeFilterList(list, listoverride);
}
}
String listString = JsonUtil.convert(list);
String key = CacheConstants.AUTOSIMCONFIG + market + autoSimConf.getStartdate() + autoSimConf.getEnddate() + "_" + autoSimConf.getInterval() + "_" + autoSimConf.getPeriod() + "_" + autoSimConf.getScorelimit().doubleValue() + " " + listString;
Map<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> retMap = (Map<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>>) MyCache.getInstance().get(key);
Map<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> newRetMap = new HashMap<>();
if (retMap == null || VERIFYCACHE) {
for (SimDataItem data : all) {
if (autoSimConf.getScorelimit().doubleValue() > data.getScore().doubleValue()) {
continue;
}
Integer period = null;
int months = Period.between(data.getStartdate(), data.getEnddate()).getMonths();
switch (months) {
case 1:
period = 0;
break;
case 3:
period = 1;
break;
case 12:
period = 2;
break;
}
if (period == null) {
continue;
}
if (period.intValue() == autoSimConf.getPeriod().intValue()) {
String amarket = data.getMarket();
if (market.equals(amarket)) {
String configStr = data.getConfig();
//SimulateInvestConfig s = JsonUtil.convert(configStr, SimulateInvestConfig.class);
Map defaultMap = config.getDeflt();
Map map = JsonUtil.convert(configStr, Map.class);
Map newMap = new HashMap<>();
newMap.putAll(defaultMap);
newMap.putAll(map);
IclijConfig dummy = new IclijConfig();
dummy.setConfigValueMap(newMap);
SimulateInvestConfig simConf = getSimConfig(dummy);
if (simConf.getInterval().intValue() != autoSimConf.getInterval().intValue()) {
continue;
}
simConf.setVolumelimits(autoSimConf.getVolumelimits());
int adviser = simConf.getAdviser();
String filterStr = data.getFilter();
SimulateFilter myFilter = JsonUtil.convert((String)filterStr, SimulateFilter.class);
SimulateFilter[] autoSimConfFilters = list.get(0);
if (autoSimConfFilters != null) {
SimulateFilter autoSimConfFilter = autoSimConfFilters[adviser];
if (myFilter != null && autoSimConfFilter != null) {
if (myFilter.getCorrelation() != null && autoSimConfFilter.getCorrelation() > 0 && autoSimConfFilter.getCorrelation() > myFilter.getCorrelation()) {
continue;
}
if (autoSimConfFilter.getLucky() > 0 && autoSimConfFilter.getLucky() < myFilter.getLucky()) {
continue;
}
if (autoSimConfFilter.getStable() > 0 && autoSimConfFilter.getStable() < myFilter.getStable()) {
continue;
}
if (autoSimConfFilter.getShortrun() > 0 && autoSimConfFilter.getShortrun() > myFilter.getShortrun()) {
continue;
}
if (autoSimConfFilter.getPopulationabove() > myFilter.getPopulationabove()) {
continue;
}
}
}
Pair<LocalDate, LocalDate> aKey = new ImmutablePair(data.getStartdate(), data.getEnddate());
MapUtil.mapAddMe(newRetMap, aKey, simConf);
}
}
}
}
if (VERIFYCACHE && retMap != null) {
for (Entry<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> entry : newRetMap.entrySet()) {
Pair<LocalDate, LocalDate> key2 = entry.getKey();
List<SimulateInvestConfig> v2 = entry.getValue();
List<SimulateInvestConfig> v = retMap.get(key2);
if (v == null || v2 == null || v.size() != v2.size()) {
log.error("Difference with cache");
continue;
}
for (int i = 0; i < v.size(); i++) {
if (!v.get(i).equals(v2.get(i))) {
log.error("Difference with cache");
}
}
}
}
if (retMap != null) {
return retMap;
}
retMap = newRetMap;
MyCache.getInstance().put(key, retMap);
return retMap;
}
private void mergeFilterList(List<SimulateFilter[]> list, List<SimulateFilter> listoverride) {
for (int i = 0; i < listoverride.size(); i++) {
SimulateFilter afilter = list.get(0)[i];
SimulateFilter otherfilter = listoverride.get(i);
afilter.merge(otherfilter);
}
}
private List<SimulateFilter[]> getDefaultList() {
List<SimulateFilter[]> list = null;
IclijConfig instance = IclijXMLConfig.getConfigInstance();
try {
list = IclijXMLConfig.getSimulate(instance);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
return list;
}
private void getAdjustedDate(Data data, LocalDate investStart, int offset, Mydate mydate) {
mydate.date = investStart;
mydate.date = TimeUtil.getEqualBefore(data.stockDates, mydate.date);
if (mydate.date == null) {
try {
mydate.date = TimeUtil.convertDate(data.stockDates.get(0));
} catch (ParseException e) {
log.error(Constants.ERROR, e);
}
}
mydate.date = TimeUtil.getForwardEqualAfter2(mydate.date, offset, data.stockDates);
mydate.prevIndexOffset = 0;
}
private void getAdjustedDate(Data data, LocalDate investStart, int offset, LocalDate date) {
date = investStart;
date = TimeUtil.getEqualBefore(data.stockDates, date);
if (date == null) {
try {
date = TimeUtil.convertDate(data.stockDates.get(0));
} catch (ParseException e) {
log.error(Constants.ERROR, e);
}
}
date = TimeUtil.getForwardEqualAfter2(date, offset, data.stockDates);
//return data.stockDates.size() - 1 - data.stockDates.indexOf(date)
}
private void setDataVolumeAndTrend(Market market, ComponentData param, SimulateInvestConfig simConfig, Data data,
LocalDate investStart, LocalDate investEnd, LocalDate lastInvestEnd, boolean evolving) {
// vol lim w/ adviser?
data.volumeExcludeMap = getVolumeExcludeMap(market, simConfig, data, investStart, investEnd, data.firstidx, data.lastidx, false);
data.volumeExcludeFillMap = getVolumeExcludeMap(market, simConfig, data, investStart, investEnd, data.firstidx, data.lastidx, true);
data.trendMap = getTrendIncDec(market, param, data.stockDates, simConfig.getInterval(), data.firstidx, data.lastidx, simConfig, data, false);
data.trendFillMap = getTrendIncDec(market, param, data.stockDates, simConfig.getInterval(), data.firstidx, data.lastidx, simConfig, data, true);
if (evolving) {
data.trendStrMap = getTrendIncDecStr(market, param, data.stockDates, simConfig.getInterval(), data.firstidx, data.lastidx, simConfig, data, false, data.trendMap);
data.trendStrFillMap = getTrendIncDecStr(market, param, data.stockDates, simConfig.getInterval(), data.firstidx, data.lastidx, simConfig, data, true, data.trendFillMap);
}
Set<Integer> keys = data.trendMap.keySet();
List<Integer> keylist = new ArrayList<>(keys);
Collections.sort(keylist);
log.debug("keylist {}", keylist);
}
private void setDataIdx(Data data, LocalDate investStart, LocalDate lastInvestEnd) {
LocalDate date = investStart;
date = TimeUtil.getEqualBefore(data.stockDates, date);
if (date == null) {
try {
date = TimeUtil.convertDate(data.stockDates.get(0));
} catch (ParseException e) {
log.error(Constants.ERROR, e);
}
}
date = TimeUtil.getForwardEqualAfter2(date, 0 /* findTime */, data.stockDates);
String datestring = TimeUtil.convertDate2(date);
int firstidx = TimeUtil.getIndexEqualAfter(data.stockDates, datestring);
int maxinterval = 20;
firstidx -= maxinterval * 2;
if (firstidx < 0) {
firstidx = 0;
}
String lastInvestEndS = TimeUtil.convertDate2(lastInvestEnd);
int lastidx = data.stockDates.indexOf(lastInvestEndS);
lastidx += maxinterval;
if (lastidx >= data.stockDates.size()) {
lastidx = data.stockDates.size() - 1;
}
firstidx = data.stockDates.size() - 1 - firstidx;
lastidx = data.stockDates.size() - 1 - lastidx;
data.firstidx = firstidx;
data.lastidx = lastidx;
}
private Map<Integer, List<String>> getVolumeExcludeMap(Market market, SimulateInvestConfig simConfig, Data data, LocalDate investStart,
LocalDate investEnd, int firstidx, int lastidx, boolean interpolate) {
String key = CacheConstants.SIMULATEINVESTVOLUMELIMITS + market.getConfig().getMarket() + "_" + simConfig.getInterval() + investStart + investEnd + interpolate + simConfig.getVolumelimits();
Map<Integer, List<String>> verifyVolumeExcludeMap = data.getVolumeExcludeMap(interpolate);
Map<Integer, List<String>> volumeExcludeMap = (Map<Integer, List<String>>) MyCache.getInstance().get(key);
Map<Integer, List<String>> newVolumeExcludeMap = null;
if (volumeExcludeMap == null || VERIFYCACHE) {
long time00 = System.currentTimeMillis();
newVolumeExcludeMap = getVolumeExcludesFull(simConfig, simConfig.getInterval(), data.getCatValMap(interpolate), data.volumeMap, firstidx, lastidx);
log.debug("time0 {}", System.currentTimeMillis() - time00);
}
verifyVolumeExcludeMap(newVolumeExcludeMap, verifyVolumeExcludeMap);
if (volumeExcludeMap == null) {
volumeExcludeMap = newVolumeExcludeMap;
MyCache.getInstance().put(key, volumeExcludeMap);
}
return volumeExcludeMap;
}
private void verifyVolumeExcludeMap(Map<Integer, List<String>> newVolumeExcludeMap,
Map<Integer, List<String>> aVolumeExcludeMap) {
if (VERIFYCACHE && aVolumeExcludeMap != null) {
for (Entry<Integer, List<String>> entry : newVolumeExcludeMap.entrySet()) {
int key2 = entry.getKey();
List<String> v2 = entry.getValue();
List<String> v = aVolumeExcludeMap.get(key2);
if (v2 != null && !v2.equals(v)) {
log.error("Difference with cache");
}
}
}
}
private LocalDate getAdjustedLastInvestEnd(Data data, LocalDate investEnd, int delay) {
LocalDate lastInvestEnd = TimeUtil.getBackEqualBefore2(investEnd, 0 /* findTime */, data.stockDates);
if (lastInvestEnd != null) {
String aDate = TimeUtil.convertDate2(lastInvestEnd);
if (aDate != null) {
int idx = data.stockDates.indexOf(aDate) - delay;
if (idx >=0 ) {
aDate = data.stockDates.get(idx);
try {
lastInvestEnd = TimeUtil.convertDate(aDate);
} catch (ParseException e) {
log.error(Constants.EXCEPTION, e);
}
}
}
}
return lastInvestEnd;
}
private LocalDate getAdjustedInvestEnd(int extradelay, Data data, LocalDate investEnd) {
investEnd = TimeUtil.getBackEqualBefore2(investEnd, 0 /* findTime */, data.stockDates);
if (investEnd != null) {
String aDate = TimeUtil.convertDate2(investEnd);
if (aDate != null) {
int idx = data.stockDates.indexOf(aDate);
if (idx >=0 ) {
aDate = data.stockDates.get(idx);
try {
investEnd = TimeUtil.convertDate(aDate);
} catch (ParseException e) {
log.error(Constants.EXCEPTION, e);
}
}
}
}
return investEnd;
}
private String getMlDate(Market market, SimulateInvestConfig simConfig, Data data, AutoSimulateInvestConfig autoSimConfig) {
String mldate = null;
if (simConfig.getMldate()) {
mldate = market.getConfig().getMldate();
if (mldate != null) {
mldate = mldate.replace('-', '.');
}
//mldate = ((SimulateInvestActionData) action).getMlDate(market, stockDates);
//mldate = ((ImproveSimulateInvestActionData) action).getMlDate(market, stockDates);
} else {
Short populate = market.getConfig().getPopulate();
if (populate == null) {
//mldate = ((SimulateInvestActionData) action).getMlDate(market, stockDates);
mldate = market.getConfig().getMldate();
if (mldate != null) {
mldate = mldate.replace('-', '.');
}
} else {
mldate = data.stockDates.get(populate);
}
}
if (mldate == null) {
mldate = data.stockDates.get(0);
}
if (autoSimConfig != null && autoSimConfig.getStartdate() != null) {
mldate = autoSimConfig.getStartdate();
mldate = mldate.replace('-', '.');
return mldate;
}
if (simConfig.getStartdate() != null) {
mldate = simConfig.getStartdate();
mldate = mldate.replace('-', '.');
}
return mldate;
}
private void doOneRun(ComponentData param, SimulateInvestConfig simConfig, int extradelay, boolean evolving,
String aParameter, int offset, OneRun onerun,
Results results, Data data, boolean lastInvest,
Mydate mydate, boolean auto, BiMap<String, LocalDate> stockDatesBiMap, boolean isMain, int endIndexOffset) {
if (getBSValueIndexOffset(mydate, simConfig) >= endIndexOffset) {
doBuySell(simConfig, onerun, results, data, mydate.indexOffset, stockDatesBiMap);
}
/*
if (lastInvest) {
// not with evolving?
onerun.savedStocks = copy(onerun.mystocks);
onerun.saveLastInvest = true;
}
*/
//Trend trend = getTrendIncDec(market, param, stockDates, interval, filteredCategoryValueMap, trendInc, trendDec, indexOffset);
// no interpolation for trend
Trend trend = getTrendIncDec(data.stockDates, onerun.trendInc, onerun.trendDec, getValueIndexOffset(mydate, simConfig), data.getTrendMap(false /*simConfig.getInterpolate()*/));
// get recommendations
List<String> myExcludes = getExclusions(simConfig, data.stockDates, data.configExcludeList, getValueIndexOffset(mydate, simConfig), data.getVolumeExcludeMap(simConfig.getInterpolate()));
double myavg = increase(onerun.mystocks, getValueIndexOffset(mydate, simConfig), data.getCatValMap(simConfig.getInterpolate()), mydate.prevIndexOffset + extradelay, endIndexOffset);
List<SimulateStock> holdIncrease = new ArrayList<>();
int up = update(data.getCatValMap(simConfig.getInterpolate()), onerun.mystocks, getValueIndexOffset(mydate, simConfig), holdIncrease, mydate.prevIndexOffset + extradelay, endIndexOffset);
List<SimulateStock> sells = new ArrayList<>();
List<SimulateStock> buys = new ArrayList<>();
onerun.buys = buys;
double myreliability = getReliability(onerun.mystocks, onerun.hits, simConfig.getConfidenceFindTimes(), up);
if (simConfig.getStoploss()) {
stoploss(onerun.mystocks, data.stockDates, getValueIndexOffset(mydate, simConfig), data.getCatValMap(simConfig.getInterpolate()), getValueIndexOffset(mydate, simConfig) + 1, sells, simConfig.getStoplossValue(), "STOP", stockDatesBiMap, endIndexOffset);
}
if (simConfig.getIntervalStoploss()) {
stoploss(onerun.mystocks, data.stockDates, getValueIndexOffset(mydate, simConfig), data.getCatValMap(simConfig.getInterpolate()), getValueIndexOffset(mydate, simConfig) + simConfig.getInterval(), sells, simConfig.getIntervalStoplossValue(), "ISTOP", stockDatesBiMap, endIndexOffset);
}
holdIncrease.removeAll(sells);
boolean confidence = !simConfig.getConfidence() || myreliability >= simConfig.getConfidenceValue();
boolean confidence1 = !simConfig.getConfidencetrendincrease() || onerun.trendInc[0] >= simConfig.getConfidencetrendincreaseTimes();
boolean noconfidence2 = simConfig.getNoconfidencetrenddecrease() && onerun.trendDec[0] >= simConfig.getNoconfidencetrenddecreaseTimes();
boolean noconfidence = !confidence || !confidence1 || noconfidence2;
List<SimulateStock> nextstocks = new ArrayList<>();
if (!noconfidence) {
nextstocks = confidenceBuyHoldSell(simConfig, data.stockDates, data.getCatValMap(simConfig.getInterpolate()), onerun.adviser, myExcludes,
aParameter, onerun.mystocks, sells, buys, holdIncrease, mydate);
} else {
nextstocks = noConfidenceHoldSell(onerun.mystocks, holdIncrease, sells, simConfig);
}
sells = addEvent(onerun, sells, "SELL", getBSIndexOffset(mydate, simConfig));
buys = addEvent(onerun, buys, "BUY", getBSIndexOffset(mydate, simConfig));
if (true) {
if (getBSValueIndexOffset(mydate, simConfig) >= endIndexOffset) {
doBuySell(simConfig, onerun, results, data, mydate.indexOffset, stockDatesBiMap);
}
if (true) {
List<String> myids = onerun.mystocks.stream().map(SimulateStock::getId).collect(Collectors.toList());
if (myids.size() != onerun.mystocks.size()) {
log.error("Sizes");
}
// to delay?
update(data.getCatValMap(simConfig.getInterpolate()), onerun.mystocks, getValueIndexOffset(mydate, simConfig), new ArrayList<>(), mydate.prevIndexOffset + extradelay, endIndexOffset);
if (trend != null && trend.incAverage != 0) {
onerun.resultavg *= trend.incAverage;
}
// depends on delay DELAY
Capital sum = getSum(onerun.mystocks);
//boolean noconf = simConfig.getConfidence() && myreliability < simConfig.getConfidenceValue();
String hasNoConf = noconfidence ? "NOCONF" : "";
String historydatestring = TimeUtil.convertDate2(mydate.date); //data.stockDates.get(data.stockDates.size() - 1 - (mydate.indexOffset - extradelay - simConfig.getDelay()));
List<String> ids = onerun.mystocks.stream().map(SimulateStock::getId).collect(Collectors.toList());
if (!evolving) {
if (offset == 0) {
String adv = auto ? " Adv" + simConfig.getAdviser() : "";
results.sumHistory.add(historydatestring + " " + onerun.capital.toString() + " " + sum.toString() + " " + new MathUtil().round(onerun.resultavg, 2) + " " + hasNoConf + " " + ids + " " + trend + adv);
results.plotDates.add(historydatestring);
results.plotDefault.add(onerun.resultavg);
results.plotCapital.add(sum.amount + onerun.capital.amount);
} else {
results.plotDates.add(historydatestring);
}
} else {
results.plotDates.add(historydatestring);
results.plotCapital.add(sum.amount + onerun.capital.amount);
Integer adv = auto ? simConfig.getAdviser() : null;
Capital aCapital = new Capital();
aCapital.amount = onerun.capital.amount;
// no interpolation for trend
String trendStr = getTrendIncDecStr(data.stockDates, onerun.trendInc, onerun.trendDec, getValueIndexOffset(mydate, simConfig), data.getTrendStrMap(false /*simConfig.getInterpolate()*/));
StockHistory aHistory = new StockHistory(historydatestring, aCapital, sum, onerun.resultavg, hasNoConf, ids, trendStr, adv);
results.history.add(aHistory);
}
if (Double.isInfinite(onerun.resultavg)) {
int jj = 0;
}
onerun.runs++;
if (myavg > trend.incAverage) {
onerun.beatavg++;
}
}
}
if (!lastInvest) {
// in last too?
// 1
for (int j = 1; j < simConfig.getInterval(); j++) {
if (mydate.indexOffset - j < endIndexOffset) {
break;
}
if (getBSValueIndexOffset(mydate, simConfig) - j >= endIndexOffset) {
doBuySell(simConfig, onerun, results, data, mydate.indexOffset - j, stockDatesBiMap);
}
sells = new ArrayList<>();
//System.out.println(interval + " " + j);
if (simConfig.getStoploss()) {
// TODO delay DELAY
stoploss(onerun.mystocks, data.stockDates, getValueIndexOffset(mydate, simConfig) - j, data.getCatValMap(simConfig.getInterpolate()), getValueIndexOffset(mydate, simConfig) - j + 1, sells, simConfig.getStoplossValue(), "STOP", stockDatesBiMap, endIndexOffset);
}
sells = addEvent(onerun, sells, "SELL", getBSIndexOffset(mydate, simConfig) - j);
//addEvent(onerun, buys, "BUY", mydate.indexOffset - j - simConfig.getDelay() - extradelay);
if (getBSValueIndexOffset(mydate, simConfig) - j >= endIndexOffset) {
doBuySell(simConfig, onerun, results, data, mydate.indexOffset - j, stockDatesBiMap);
}
//sell(data.stockDates, data.getCatValMap(simConfig.getInterpolate()), onerun.capital, sells, results.stockhistory, mydate.indexOffset - j - extradelay - simConfig.getDelay(), mydate.date, onerun.mystocks, stockDatesBiMap);
if (offset == 0 && !sells.isEmpty()) {
boolean last = mydate.indexOffset - j == endIndexOffset;
boolean aLastInvest = offset == 0 && last /*date.isAfter(lastInvestEnd) && j == simConfig.getInterval() - 1*/;
if (aLastInvest && isMain) {
List<String> ids = onerun.mystocks.stream().map(SimulateStock::getId).collect(Collectors.toList());
List<String> sellids = sells.stream().map(SimulateStock::getId).collect(Collectors.toList());
//ids.removeAll(sellids);
param.getUpdateMap().put(SimConstants.LASTBUYSELL, "Stoploss sell: " + sellids + " Stocks: " + ids);
} else {
int jj = 0;
}
}
}
} else {
if (!evolving && offset == 0) {
List<String> ids = onerun.mystocks.stream().map(SimulateStock::getId).collect(Collectors.toList());
List<String> buyids = buys.stream().map(SimulateStock::getId).collect(Collectors.toList());
List<String> sellids = sells.stream().map(SimulateStock::getId).collect(Collectors.toList());
if (!noconfidence) {
int buyCnt = simConfig.getStocks() - nextstocks.size();
buyCnt = Math.min(buyCnt, buys.size());
//ids.addAll(buyids.subList(0, buyCnt));
buyids = buyids.subList(0, buyCnt);
} else {
buyids.clear();
}
//ids.removeAll(sellids);
if (isMain) {
param.getUpdateMap().put(SimConstants.LASTBUYSELL, "Buy: " + buyids + " Sell: " + sellids + " Stocks: " + ids);
}
}
}
}
private List<SimulateStock> addEvent(OneRun onerun, List<SimulateStock> stocks, String bs, int myIndexoffset) {
if (stocks == null || stocks.isEmpty()) {
return stocks;
}
List<SimulateStock> filterStocks = getFilterStocks(onerun, stocks);
if (filterStocks == null || filterStocks.isEmpty()) {
return filterStocks;
}
Map<String, List<SimulateStock>> aBSMap = new HashMap<>();
aBSMap.put(bs, filterStocks);
Map<String, List<SimulateStock>> bsMap = onerun.eventMap.computeIfAbsent(myIndexoffset, k -> new HashMap<>());
bsMap.putAll(aBSMap);
return filterStocks;
}
private List<SimulateStock> getFilterStocks(OneRun onerun, List<SimulateStock> stocks) {
List<SimulateStock> filterStocks = new ArrayList<>();
for (SimulateStock stock : stocks) {
boolean found = false;
for (Entry<Integer, Map<String, List<SimulateStock>>> entry : onerun.eventMap.entrySet()) {
Map<String, List<SimulateStock>> aMap = entry.getValue();
for (Entry<String, List<SimulateStock>> anEntry : aMap.entrySet()) {
if (anEntry.getValue().contains(stock)) {
found = true;
}
}
}
if (!found) {
filterStocks.add(stock);
}
}
return filterStocks;
}
private void doBuySell(SimulateInvestConfig simConfig, OneRun onerun, Results results, Data data, int indexOffset,
BiMap<String, LocalDate> stockDatesBiMap) {
Map<String, List<SimulateStock>> myMaps = onerun.eventMap.remove(indexOffset);
if (myMaps != null) {
List<SimulateStock> mySells = myMaps.remove("SELL");
if (mySells != null) {
sell(data.stockDates, data.getCatValMap(simConfig.getInterpolate()), onerun.capital, mySells, results.stockhistory, indexOffset, onerun.mystocks, stockDatesBiMap);
}
List<SimulateStock> myBuys = myMaps.remove("BUY");
if (myBuys != null) {
buy(data.stockDates, data.getCatValMap(simConfig.getInterpolate()), onerun.capital, simConfig.getStocks(), onerun.mystocks, myBuys, indexOffset, stockDatesBiMap);
}
}
}
private BiMap<String, LocalDate> getStockDatesBiMap(String market, List<String> stockDates) {
String key = CacheConstants.DATESMAP + market; // + config.getDate();
BiMap<String, LocalDate> list = (BiMap<String, LocalDate>) MyCache.getInstance().get(key);
if (list != null) {
return list;
}
list = createStockDatesBiMap(stockDates);
MyCache.getInstance().put(key, list);
return list;
}
private BiMap<String, LocalDate> createStockDatesBiMap(List<String> stockDates) {
BiMap<String, LocalDate> biMap = HashBiMap.create();
for (String aDate : stockDates) {
try {
LocalDate date = TimeUtil.convertDate(aDate);
biMap.put(aDate, date);
} catch (ParseException e) {
log.error(Constants.EXCEPTION, e);
}
}
return biMap;
}
private List<SimulateStock> copy(List<SimulateStock> mystocks) {
List<SimulateStock> list = new ArrayList<>();
for (SimulateStock stock : mystocks) {
SimulateStock copy = stock.copy();
list.add(copy);
}
return list;
}
private List<String> getExclusions(SimulateInvestConfig simConfig, List<String> stockDates, List<String> configExcludeList,
int indexOffset, Map<Integer, List<String>> newVolumeMap) {
List<String> myExcludes = new ArrayList<>();
List<String> volumeExcludes = new ArrayList<>();
/*
getVolumeExcludes(simConfig, extradelay, stockDates, interval, categoryValueMap, volumeMap, delay,
indexOffset, volumeExcludes);
*/
long time0 = System.currentTimeMillis();
getVolumeExcludes(simConfig, stockDates, indexOffset, volumeExcludes, newVolumeMap);
//log.info("timed0 {}", System.currentTimeMillis() - time0);
myExcludes.addAll(configExcludeList);
myExcludes.addAll(volumeExcludes);
return myExcludes;
}
private Trend getTrendIncDec(List<String> stockDates, Integer[] trendInc, Integer[] trendDec, int indexOffset,
Map<Integer, Trend> trendMap) {
int idx = stockDates.size() - 1 - indexOffset;
Trend trend = trendMap.get(idx);
if (trend == null) {
int jj = 0;
}
if (trend != null && trend.incAverage < 0) {
int jj = 0;
}
log.debug("Trend {}", trend);
if (trend != null) {
if (trend.incAverage > 1) {
trendInc[0]++;
trendDec[0] = 0;
} else {
trendInc[0] = 0;
trendDec[0]++;
}
}
return trend;
}
private String getTrendIncDecStr(List<String> stockDates, Integer[] trendInc, Integer[] trendDec, int indexOffset,
Map<Integer, String> trendMap) {
int idx = stockDates.size() - 1 - indexOffset;
String trend = trendMap.get(idx);
return trend;
}
private Map<Integer, Trend> getTrendIncDec(Market market, ComponentData param, List<String> stockDates, int interval,
int firstidx, int lastidx, SimulateInvestConfig simConfig, Data data, boolean interpolate) {
Map<Integer, Trend> trendMap = null;
String key = CacheConstants.SIMULATEINVESTTREND + market.getConfig().getMarket() + "_" + interval + "_" + simConfig.getStartdate() + simConfig.getEnddate() + interpolate;
trendMap = (Map<Integer, Trend>) MyCache.getInstance().get(key);
Map<Integer, Trend> newTrendMap = null;
if (trendMap == null || VERIFYCACHE) {
long time0 = System.currentTimeMillis();
try {
newTrendMap = new TrendUtil().getTrend(interval, null, stockDates, param, market, data.getFilterCatValMap(interpolate), firstidx, lastidx);
} catch (Exception e) {
log.error(Constants.ERROR, e);
}
log.debug("time millis {}", System.currentTimeMillis() - time0);
}
if (VERIFYCACHE && trendMap != null) {
for (Entry<Integer, Trend> entry : newTrendMap.entrySet()) {
int key2 = entry.getKey();
Trend v2 = entry.getValue();
Trend v = trendMap.get(key2);
if (v2 != null && !v2.toString().equals(v.toString())) {
log.error("Difference with cache");
}
}
}
if (trendMap != null) {
return trendMap;
}
trendMap = newTrendMap;
MyCache.getInstance().put(key, trendMap);
return trendMap;
}
private Map<Integer, String> getTrendIncDecStr(Market market, ComponentData param, List<String> stockDates, int interval,
int firstidx, int lastidx, SimulateInvestConfig simConfig, Data data, boolean interpolate, Map<Integer, Trend> trendMap) {
Map<Integer, String> trendStrMap = null;
String key = CacheConstants.SIMULATEINVESTTREND + market.getConfig().getMarket() + "_" + interval + "_" + simConfig.getStartdate() + simConfig.getEnddate() + interpolate + "str";
trendStrMap = (Map<Integer, String>) MyCache.getInstance().get(key);
if (trendStrMap != null) {
return trendStrMap;
}
trendStrMap = new HashMap<>();
for (Entry<Integer, Trend> entry : trendMap.entrySet()) {
Integer aKey = entry.getKey();
Trend trend = entry.getValue();
trendStrMap.put(aKey, trend.toString());
}
MyCache.getInstance().put(key, trendStrMap);
return trendStrMap;
}
@Deprecated
private void getVolumeExcludes(SimulateInvestConfig simConfig, int extradelay, List<String> stockDates,
int interval, Map<String, List<List<Double>>> categoryValueMap,
Map<String, List<List<Object>>> volumeMap, int delay, int indexOffset, List<String> volumeExcludes) {
if (simConfig.getVolumelimits() != null) {
Map<String, Double> volumeLimits = simConfig.getVolumelimits();
for (Entry<String, List<List<Double>>> entry : categoryValueMap.entrySet()) {
String id = entry.getKey();
int anOffset = indexOffset /* - extradelay - delay */;
int len = interval * 2;
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
int size = mainList.size();
int first = size - anOffset - len;
if (first < 0) {
first = 0;
}
List<List<Object>> list = volumeMap.get(id);
String currency = null;
for (int i = 0; i < list.size(); i++) {
currency = (String) list.get(i).get(1);
if (currency != null) {
break;
}
}
Double limit = volumeLimits.get(currency);
if (limit == null) {
continue;
}
double sum = 0.0;
int count = 0;
for (int i = first; i <= size - 1 - anOffset; i++) {
Integer volume = (Integer) list.get(i).get(0);
if (volume != null) {
Double price = mainList.get(i /* mainList.size() - 1 - indexOffset */);
if (price == null) {
if (volume > 0) {
log.debug("Price null with volume > 0");
}
continue;
}
sum += volume * price;
count++;
}
}
if (count > 0 && sum / count < limit) {
volumeExcludes.add(id);
}
}
}
}
}
@Deprecated
private Map<String, double[]> getVolumeExcludesFull(SimulateInvestConfig simConfig, List<String> stockDates, int interval,
Map<String, List<List<Double>>> categoryValueMap, Map<String, List<List<Object>>> volumeMap) {
Map<String, double[]> newVolumeMap = new HashMap<>();
if (simConfig.getVolumelimits() != null) {
for (Entry<String, List<List<Double>>> entry : categoryValueMap.entrySet()) {
String id = entry.getKey();
int len = interval * 2;
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
List<List<Object>> list = volumeMap.get(id);
if (mainList != null) {
int size = mainList.size();
double[] newList = new double[size];
for (int i = 0; i < size; i++) {
Integer volume = (Integer) list.get(i).get(0);
Double price = mainList.get(i /* mainList.size() - 1 - indexOffset */);
if (volume != null) {
if (price == null) {
if (volume > 0) {
log.debug("Price null with volume > 0");
}
continue;
}
} else {
continue;
}
for (int j = 0; j < len; j++) {
int idx = i + j;
if (idx > size - 1) {
break;
}
newList[idx] += price * volume;
}
}
newVolumeMap.put(id, newList);
}
}
}
return newVolumeMap;
}
@Deprecated
private void getVolumeExcludes(SimulateInvestConfig simConfig, int extradelay, List<String> stockDates,
int interval, Map<String, List<List<Double>>> categoryValueMap,
Map<String, List<List<Object>>> volumeMap, int delay, int indexOffset, List<String> volumeExcludes, Map<String, double[]> newVolumeMap) {
if (simConfig.getVolumelimits() != null) {
Map<String, Double> volumeLimits = simConfig.getVolumelimits();
int len = interval * 2;
for (Entry<String, List<List<Double>>> entry : categoryValueMap.entrySet()) {
String id = entry.getKey();
String currency = getCurrency(volumeMap, id);
Double limit = volumeLimits.get(currency);
if (limit == null) {
continue;
}
int count = len;
double[] sums = newVolumeMap.get(id);
int idx = sums.length - 1 - indexOffset;
if (idx < count) {
count = idx;
}
double sum = sums[idx];
if (count > 0 && sum / count < limit) {
volumeExcludes.add(id);
}
}
}
}
private String getCurrency(Map<String, List<List<Object>>> volumeMap, String id) {
String currency = null;
List<List<Object>> list = volumeMap.get(id);
for (int i = list.size() - 1; i >= 0; i--) {
currency = (String) list.get(i).get(1);
if (currency != null) {
break;
}
}
return currency;
}
private Map<Integer, List<String>> getVolumeExcludesFull(SimulateInvestConfig simConfig, int interval, Map<String, List<List<Double>>> categoryValueMap,
Map<String, List<List<Object>>> volumeMap, int firstidx, int lastidx) {
Map<Integer, List<String>> listlist = new HashMap<>();
if (simConfig.getVolumelimits() != null) {
Map<String, Double> volumeLimits = simConfig.getVolumelimits();
for (Entry<String, List<List<Double>>> entry : categoryValueMap.entrySet()) {
String id = entry.getKey();
String currency = getCurrency(volumeMap, id);
Double limit = volumeLimits.get(currency);
if (limit == null) {
continue;
}
int len = interval * 2;
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
List<List<Object>> list = volumeMap.get(id);
if (mainList != null) {
int size = mainList.size();
MutablePair<Double, Integer>[] newList = new MutablePair[size];
int start = size - 1 - firstidx;
int end = size - 1 - lastidx;
for (int i = start; i <= end; i++) {
Integer volume = (Integer) list.get(i).get(0);
Double price = mainList.get(i /* mainList.size() - 1 - indexOffset */);
if (volume != null) {
if (price == null) {
if (volume > 0) {
log.debug("Price null with volume > 0");
}
continue;
}
} else {
continue;
}
for (int j = 0; j < len; j++) {
int idx = i + j;
if (idx > size - 1) {
break;
}
MutablePair<Double, Integer> pair = newList[idx];
if (pair == null) {
pair = new MutablePair(0.0, 0);
newList[idx] = pair;
}
pair.setLeft(pair.getLeft() + price * volume);
pair.setRight(pair.getRight() + 1);
}
}
// now make the skip lists
int count = len;
Pair<Double, Integer>[] sums = newList;
for (int i = start; i <= end; i++) {
List<String> datedlist = listlist.get(i);
if (datedlist == null) {
datedlist = new ArrayList<>();
listlist.put(i, datedlist);
}
int idx = i;
if (idx < count) {
count = idx;
}
Pair<Double, Integer> pair = sums[idx];
if (pair == null) {
datedlist.add(id);
continue;
}
Double sum = pair.getLeft();
Integer count2 = pair.getRight();
if (count2 != null && count != count2) {
int jj = 0;
}
if (count2 != null && count2 == 0) {
int jj = 0;
}
if (count2 != 0 && sum / count2 < limit) {
datedlist.add(id);
}
}
}
}
}
Set<Integer> keys = listlist.keySet();
List<Integer> keylist = new ArrayList<>(keys);
Collections.sort(keylist);
log.debug("keylist {}", keylist);
for (int key : keylist) {
log.debug("keylist size {} {}", key, listlist.get(key).size());
}
return listlist;
}
private void getVolumeExcludes(SimulateInvestConfig simConfig, List<String> stockDates, int indexOffset,
List<String> volumeExcludes, Map<Integer, List<String>> listlist) {
if (simConfig.getVolumelimits() != null) {
int idx = stockDates.size() - 1 - indexOffset;
if (idx < 0) {
return;
}
List<String> list = listlist.get(idx);
if (list == null) {
return;
}
volumeExcludes.addAll(list);
}
}
private List<SimulateStock> confidenceBuyHoldSell(SimulateInvestConfig simConfig, List<String> stockDates,
Map<String, List<List<Double>>> categoryValueMap, Adviser adviser, List<String> excludeList,
String aParameter, List<SimulateStock> mystocks, List<SimulateStock> sells, List<SimulateStock> buys, List<SimulateStock> holdIncrease,
Mydate mydate) {
List<SimulateStock> hold;
if (simConfig.getConfidenceholdincrease() == null || simConfig.getConfidenceholdincrease()) {
hold = holdIncrease;
} else {
hold = new ArrayList<>();
}
List<String> anExcludeList = new ArrayList<>(excludeList);
List<String> ids1 = sells.stream().map(SimulateStock::getId).collect(Collectors.toList());
List<String> ids2 = hold.stream().map(SimulateStock::getId).collect(Collectors.toList());
anExcludeList.addAll(ids1);
anExcludeList.addAll(ids2);
Set<String> anExcludeSet = new LinkedHashSet<>(anExcludeList);
// full list
List<String> myincl = adviser.getIncs(aParameter, simConfig.getStocks(), getValueIndexOffset(mydate, simConfig), stockDates, anExcludeList);
Set<String> myincs = new LinkedHashSet<>(myincl);
//myincs = new ArrayList<>(myincs);
myincs.removeAll(anExcludeSet);
//List<IncDecItem> myincs = ds.getIncs(valueList);
//List<ValueList> valueList = ds.getValueList(categoryValueMap, indexOffset);
// full list, except if null value
//int delay = simConfig.getDelay();
List<SimulateStock> buysTmp = getBuyList(categoryValueMap, myincs, simConfig.getStocks());
myincs = null;
//buysTmp = filter(buysTmp, sells);
List<SimulateStock> keeps = keep(mystocks, buysTmp);
keeps.addAll(hold);
buysTmp = filter(buysTmp, mystocks);
//buysTmp = buysTmp.subList(0, Math.min(buysTmp.size(), simConfig.getStocks() - mystocks.size()));
buys.clear();
buys.addAll(buysTmp);
List<SimulateStock> newsells = filter(mystocks, keeps);
//mystocks.removeAll(newsells);
myAddAll(sells, newsells);
mystocks = keeps;
return mystocks;
}
private List<SimulateStock> noConfidenceHoldSell(List<SimulateStock> mystocks, List<SimulateStock> holdIncrease, List<SimulateStock> sells, SimulateInvestConfig simConfig) {
List<SimulateStock> keeps;
if (simConfig.getNoconfidenceholdincrease() == null || simConfig.getNoconfidenceholdincrease()) {
keeps = holdIncrease;
} else {
keeps = new ArrayList<>();
}
List<SimulateStock> newsells = filter(mystocks, keeps);
//mystocks.removeAll(newsells);
myAddAll(sells, newsells);
mystocks = keeps;
return mystocks;
}
private SimulateInvestConfig getSimConfig(IclijConfig config) {
if (config.getConfigValueMap().get(IclijConfigConstants.SIMULATEINVESTDELAY) == null || (int) config.getConfigValueMap().get(IclijConfigConstants.SIMULATEINVESTDELAY) == 0) {
return null;
}
SimulateInvestConfig simConfig = new SimulateInvestConfig();
simConfig.setAdviser(config.getSimulateInvestAdviser());
simConfig.setBuyweight(config.wantsSimulateInvestBuyweight());
simConfig.setConfidence(config.wantsSimulateInvestConfidence());
simConfig.setConfidenceValue(config.getSimulateInvestConfidenceValue());
simConfig.setConfidenceFindTimes(config.getSimulateInvestConfidenceFindtimes());
simConfig.setAbovebelow(config.getSimulateInvestAboveBelow());
simConfig.setConfidenceholdincrease(config.wantsSimulateInvestConfidenceHoldIncrease());
simConfig.setNoconfidenceholdincrease(config.wantsSimulateInvestNoConfidenceHoldIncrease());
simConfig.setConfidencetrendincrease(config.wantsSimulateInvestConfidenceTrendIncrease());
simConfig.setConfidencetrendincreaseTimes(config.wantsSimulateInvestConfidenceTrendIncreaseTimes());
simConfig.setNoconfidencetrenddecrease(config.wantsSimulateInvestNoConfidenceTrendDecrease());
simConfig.setNoconfidencetrenddecreaseTimes(config.wantsSimulateInvestNoConfidenceTrendDecreaseTimes());
try {
simConfig.setImproveFilters(config.getSimulateInvestImproveFilters());
} catch (Exception e) {
int jj = 0;
}
simConfig.setInterval(config.getSimulateInvestInterval());
simConfig.setIndicatorPure(config.wantsSimulateInvestIndicatorPure());
simConfig.setIndicatorRebase(config.wantsSimulateInvestIndicatorRebase());
simConfig.setIndicatorReverse(config.wantsSimulateInvestIndicatorReverse());
simConfig.setIndicatorDirection(config.wantsSimulateInvestIndicatorDirection());
simConfig.setIndicatorDirectionUp(config.wantsSimulateInvestIndicatorDirectionUp());
simConfig.setMldate(config.wantsSimulateInvestMLDate());
try {
simConfig.setPeriod(config.getSimulateInvestPeriod());
} catch (Exception e) {
int jj = 0;
}
simConfig.setStoploss(config.wantsSimulateInvestStoploss());
simConfig.setStoplossValue(config.getSimulateInvestStoplossValue());
simConfig.setIntervalStoploss(config.wantsSimulateInvestIntervalStoploss());
simConfig.setIntervalStoplossValue(config.getSimulateInvestIntervalStoplossValue());
simConfig.setStocks(config.getSimulateInvestStocks());
simConfig.setInterpolate(config.wantsSimulateInvestInterpolate());
simConfig.setDay(config.getSimulateInvestDay());
simConfig.setDelay(config.getSimulateInvestDelay());
try {
simConfig.setFuturecount(config.getSimulateInvestFutureCount());
simConfig.setFuturetime(config.getSimulateInvestFutureTime());
} catch (Exception e) {
}
Map<String, Double> map = JsonUtil.convert(config.getSimulateInvestVolumelimits(), Map.class);
simConfig.setVolumelimits(map);
SimulateFilter[] array = JsonUtil.convert(config.getSimulateInvestFilters(), SimulateFilter[].class);
List<SimulateFilter> list = null;
if (array != null) {
list = Arrays.asList(array);
}
simConfig.setFilters(list);
try {
simConfig.setEnddate(config.getSimulateInvestEnddate());
} catch (Exception e) {
}
try {
simConfig.setStartdate(config.getSimulateInvestStartdate());
} catch (Exception e) {
}
return simConfig;
}
private List<SimulateFilter> get(String json) {
SimulateFilter[] array = JsonUtil.convert(json, SimulateFilter[].class);
List<SimulateFilter> list = null;
if (array != null) {
list = Arrays.asList(array);
}
return list;
}
private AutoSimulateInvestConfig getAutoSimConfig(IclijConfig config) {
if (config.getConfigValueMap().get(IclijConfigConstants.AUTOSIMULATEINVESTINTERVAL) == null || (int) config.getConfigValueMap().get(IclijConfigConstants.AUTOSIMULATEINVESTINTERVAL) == 0) {
return null;
}
AutoSimulateInvestConfig simConfig = new AutoSimulateInvestConfig();
simConfig.setInterval(config.getAutoSimulateInvestInterval());
simConfig.setIntervalwhole(config.getAutoSimulateInvestIntervalwhole());
simConfig.setImproveFilters(config.getAutoSimulateInvestImproveFilters());
simConfig.setPeriod(config.getAutoSimulateInvestPeriod());
simConfig.setLastcount(config.getAutoSimulateInvestLastCount());
simConfig.setDellimit(config.getAutoSimulateInvestDelLimit());
simConfig.setScorelimit(config.getAutoSimulateInvestScoreLimit());
simConfig.setAutoscorelimit(config.getAutoSimulateInvestAutoScoreLimit());
simConfig.setKeepAdviser(config.getAutoSimulateInvestKeepAdviser());
simConfig.setKeepAdviserLimit(config.getAutoSimulateInvestKeepAdviserLimit());
simConfig.setVote(config.getAutoSimulateInvestVote());
simConfig.setFuturecount(config.getAutoSimulateInvestFutureCount());
simConfig.setFuturetime(config.getAutoSimulateInvestFutureTime());
Map<String, Double> map = JsonUtil.convert(config.getAutoSimulateInvestVolumelimits(), Map.class);
simConfig.setVolumelimits(map);
SimulateFilter[] array = JsonUtil.convert(config.getAutoSimulateInvestFilters(), SimulateFilter[].class);
List<SimulateFilter> list = null;
if (array != null) {
list = Arrays.asList(array);
}
simConfig.setFilters(list);
try {
simConfig.setEnddate(config.getAutoSimulateInvestEnddate());
} catch (Exception e) {
}
try {
simConfig.setStartdate(config.getAutoSimulateInvestStartdate());
} catch (Exception e) {
}
return simConfig;
}
private String emptyNull(Object object) {
if (object == null) {
return "";
} else {
return "" + object;
}
}
private String emptyNull(Object object, String defaults) {
if (object == null) {
return defaults;
} else {
return "" + object;
}
}
private List<SimulateStock> filter(List<SimulateStock> stocks, List<SimulateStock> others) {
List<String> ids = others.stream().map(SimulateStock::getId).collect(Collectors.toList());
return stocks.stream().filter(e -> !ids.contains(e.getId())).collect(Collectors.toList());
}
private List<SimulateStock> keep(List<SimulateStock> stocks, List<SimulateStock> others) {
List<String> ids = others.stream().map(SimulateStock::getId).collect(Collectors.toList());
return stocks.stream().filter(e -> ids.contains(e.getId())).collect(Collectors.toList());
}
private Capital getSum(List<SimulateStock> mystocks) {
Capital sum = new Capital();
for (SimulateStock astock : mystocks) {
sum.amount += astock.getCount() * astock.getPrice();
}
return sum;
}
@Override
public ComponentData improve(MarketActionData action, ComponentData componentparam, Market market, ProfitData profitdata,
Memories positions, Boolean buy, String subcomponent, Parameters parameters, boolean wantThree,
List<MLMetricsItem> mlTests, Fitness fitness, boolean save) {
return null;
}
@Override
public MLConfigs getOverrideMLConfig(ComponentData componentdata) {
return null;
}
@Override
public void calculateIncDec(ComponentData param, ProfitData profitdata, Memories positions, Boolean above,
List<MLMetricsItem> mlTests, Parameters parameters) {
}
@Override
public List<MemoryItem> calculateMemory(ComponentData param, Parameters parameters) throws Exception {
return null;
}
@Override
public String getPipeline() {
return PipelineConstants.SIMULATEINVEST;
}
@Override
protected List<String> getConfList() {
return null;
}
@Override
public String getThreshold() {
return null;
}
@Override
public String getFuturedays() {
return null;
}
public Object[] calculateAccuracy(ComponentData componentparam) throws Exception {
return new Object[] { componentparam.getScoreMap().get(SimConstants.SCORE) };
}
private double increase(List<SimulateStock> mystocks, int indexOffset, Map<String, List<List<Double>>> categoryValueMap, int prevIndexOffset, int endIndexOffset) {
List<Double> incs = new ArrayList<>();
for (SimulateStock item : mystocks) {
String id = item.getId();
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
if (indexOffset < endIndexOffset) {
continue;
}
Double valNow = mainList.get(mainList.size() - 1 - indexOffset);
if (prevIndexOffset < endIndexOffset) {
continue;
}
Double valWas = mainList.get(mainList.size() - 1 - prevIndexOffset);
if (valWas != null && valNow != null) {
double inc = valNow / valWas;
incs.add(inc);
}
} else {
// put back if unknown
//mystocks.add(item);
}
}
if (incs.isEmpty()) {
return 1.0;
}
OptionalDouble average = incs
.stream()
.mapToDouble(a -> a)
.average();
return average.getAsDouble();
}
private double getReliability(List<SimulateStock> mystocks, Pair<Integer, Integer>[] hits, int findTimes, int up) {
Pair<Integer, Integer> pair = new ImmutablePair(up, mystocks.size());
for (int j = findTimes - 1; j > 0; j--) {
hits[j] = hits[j - 1];
}
hits[0] = pair;
double count = 0;
int total = 0;
for (Pair<Integer, Integer> aPair : hits) {
if (aPair == null) {
continue;
}
count += aPair.getLeft();
total += aPair.getRight();
}
double reliability = 1;
if (total > 0) {
reliability = count / total;
}
return reliability;
}
private void stoploss(List<SimulateStock> mystocks, List<String> stockDates, int indexOffset, Map<String, List<List<Double>>> categoryValueMap, int prevIndexOffset,
List<SimulateStock> sells, double stoploss, String stop, BiMap<String, LocalDate> stockDatesBiMap, int endIndexOffset) {
List<SimulateStock> newSells = new ArrayList<>();
for (SimulateStock item : mystocks) {
String id = item.getId();
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
String dateNowStr = stockDates.get(stockDates.size() - 1 - indexOffset);
LocalDate dateNow = convertDate(stockDatesBiMap, dateNowStr);
if (!dateNow.isAfter(item.getBuydate())) {
continue;
}
Double valNow = mainList.get(mainList.size() - 1 - indexOffset);
if (prevIndexOffset < endIndexOffset) {
int jj = 0;
continue;
}
Double valWas = mainList.get(mainList.size() - 1 - prevIndexOffset);
if (valWas != null && valNow != null && valNow != 0 && valWas != 0 && valNow / valWas < stoploss) {
log.debug("Id etc {} {} {} {} {} {} {}", stop, id, valWas, valNow, dateNowStr, prevIndexOffset, indexOffset);
item.setStatus(stop);
newSells.add(item);
}
}
}
//mystocks.removeAll(newSells);
myAddAll(sells, newSells);
}
private LocalDate convertDate(BiMap<String, LocalDate> stockDatesBiMap, String dateStr) {
LocalDate date = stockDatesBiMap.get(dateStr);
if (date != null) {
return date;
}
try {
date = TimeUtil.convertDate(dateStr);
} catch (ParseException e) {
log.error(Constants.EXCEPTION, e);
}
return date;
}
private void buy(List<String> stockDates, Map<String, List<List<Double>>> categoryValueMap, Capital capital, int buytop, List<SimulateStock> mystocks, List<SimulateStock> newbuys, int indexOffset, BiMap<String, LocalDate> stockDatesBiMap) {
int buys = buytop - mystocks.size();
buys = Math.min(buys, newbuys.size());
double totalamount = 0;
for (int i = 0; i < buys; i++) {
SimulateStock astock = newbuys.get(i);
String id = astock.getId();
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
Double valNow = mainList.get(mainList.size() - 1 - indexOffset);
if (valNow != null) {
double amount = 0;
amount = capital.amount / buys;
astock.setBuyprice(valNow);
astock.setCount(amount / astock.getBuyprice());
String dateNow = stockDates.get(stockDates.size() - 1 - indexOffset);
LocalDate date = convertDate(stockDatesBiMap, dateNow);
astock.setBuydate(date);
mystocks.add(astock);
totalamount += amount;
} else {
log.error("Not found {}", id);
}
}
}
capital.amount -= totalamount;
}
private int update(Map<String, List<List<Double>>> categoryValueMap, List<SimulateStock> mystocks, int indexOffset,
List<SimulateStock> noConfKeep, int prevIndexOffset, int endIndexOffset) {
int up = 0;
for (SimulateStock item : mystocks) {
String id = item.getId();
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
if (indexOffset < endIndexOffset) {
int jj = 0;
}
Double valNow = mainList.get(mainList.size() - 1 - indexOffset);
if (valNow != null) {
item.setPrice(valNow);
} else {
if (item.getPrice() == 0.0) {
item.setPrice(item.getBuyprice());
}
}
if (prevIndexOffset < endIndexOffset) {
continue;
}
Double valWas = mainList.get(mainList.size() - 1 - prevIndexOffset);
if (valNow != null && valWas != null) {
if (valNow > valWas) {
up++;
noConfKeep.add(item);
}
}
}
}
return up;
}
private void sell(List<String> stockDates, Map<String, List<List<Double>>> categoryValueMap, Capital capital,
List<SimulateStock> sells, List<SimulateStock> stockhistory, int indexOffset, List<SimulateStock> mystocks, BiMap<String, LocalDate> stockDatesBiMap) {
for (SimulateStock item : sells) {
String id = item.getId();
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
Double valNow = mainList.get(mainList.size() - 1 - indexOffset);
if (valNow != null) {
item.setSellprice(valNow);
String dateNow = stockDates.get(stockDates.size() - 1 - indexOffset);
LocalDate date = convertDate(stockDatesBiMap, dateNow);
item.setSelldate(date);
stockhistory.add(item);
capital.amount += item.getCount() * item.getSellprice();
mystocks.remove(item);
} else {
// put back if unknown
//mystocks.add(item);
}
} else {
// put back if unknown
//mystocks.add(item);
}
}
}
private List<SimulateStock> getSellList(List<SimulateStock> mystocks, List<SimulateStock> newbuys) {
List<String> myincids = newbuys.stream().map(SimulateStock::getId).collect(Collectors.toList());
return mystocks.stream().filter(e -> !myincids.contains(e.getId())).collect(Collectors.toList());
}
private List<SimulateStock> getBuyList(Map<String, List<List<Double>>> categoryValueMap, Set<String> myincs,
Integer count) {
List<SimulateStock> newbuys = new ArrayList<>();
for (String id : myincs) {
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
SimulateStock astock = new SimulateStock();
astock.setId(id);
//astock.price = -1;
newbuys.add(astock);
count--;
if (count == 0) {
break;
}
}
}
return newbuys;
}
private List<IncDecItem> getAllIncDecs(Market market, LocalDate investStart, LocalDate investEnd) {
try {
return IclijDbDao.getAllIncDecs(market.getConfig().getMarket(), investStart, investEnd, null);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
return new ArrayList<>();
}
private List<MemoryItem> getAllMemories(Market market, LocalDate investStart, LocalDate investEnd) {
try {
return IclijDbDao.getAllMemories(market.getConfig().getMarket(), IclijConstants.IMPROVEABOVEBELOW, PipelineConstants.ABOVEBELOW, null, null, investStart, investEnd);
// also filter on params
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
return new ArrayList<>();
}
private List<MetaItem> getAllMetas(ComponentData param) {
return param.getService().getMetas();
}
private void myAddAll(List<SimulateStock> mainList, List<SimulateStock> list) {
for (SimulateStock stock : list) {
if (!mainList.contains(stock)) {
mainList.add(stock);
}
}
}
private int getValueIndexOffset(Mydate mydate, SimulateInvestConfig simConfig) {
int extradelay = 0;
if (simConfig.getExtradelay() != null) {
extradelay = simConfig.getExtradelay();
}
return mydate.indexOffset + extradelay;
}
private int getBSIndexOffset(Mydate mydate, SimulateInvestConfig simConfig) {
int extradelay = 0;
if (simConfig.getExtradelay() != null) {
extradelay = simConfig.getExtradelay();
}
return mydate.indexOffset - extradelay - simConfig.getDelay();
}
private int getBSValueIndexOffset(Mydate mydate, SimulateInvestConfig simConfig) {
int extradelay = 0;
if (simConfig.getExtradelay() != null) {
extradelay = simConfig.getExtradelay();
}
return mydate.indexOffset - extradelay;
}
class OneRun {
Adviser adviser;
Capital capital;
int beatavg;
int runs;
List<SimulateStock> mystocks;
double resultavg;
List<SimulateStock> savedStocks;
boolean saveLastInvest;
Integer[] trendInc = new Integer[] { 0 };
Integer[] trendDec = new Integer[] { 0 };
Pair<Integer, Integer>[] hits;
Double autoscore;
List<SimulateStock> buys;
Map<Integer, Map<String, List<SimulateStock>>> eventMap = new HashMap<>();
}
class Results {
List<SimulateStock> stockhistory = new ArrayList<>();
List<StockHistory> history = new ArrayList<>();
List<String> sumHistory = new ArrayList<>();
List<String> plotDates = new ArrayList<>();
List<Double> plotCapital = new ArrayList<>();
List<Double> plotDefault = new ArrayList<>();
}
class Data {
int lastidx;
int firstidx;
Map<String, List<List<Double>>> categoryValueMap;
Map<String, List<List<Double>>> categoryValueFillMap;
Map<String, List<List<Double>>> filteredCategoryValueMap;
Map<String, List<List<Double>>> filteredCategoryValueFillMap;
List<String> stockDates;
Map<Integer, List<String>> volumeExcludeMap;
Map<Integer, List<String>> volumeExcludeFillMap;
List<String> configExcludeList;
Map<String, List<List<Object>>> volumeMap;
Map<Integer, Trend> trendMap;
Map<Integer, Trend> trendFillMap;
Map<Integer, String> trendStrMap;
Map<Integer, String> trendStrFillMap;
public Map<String, List<List<Double>>> getCatValMap(boolean interpolate) {
if (interpolate) {
return categoryValueFillMap;
} else {
return categoryValueMap;
}
}
public Map<String, List<List<Double>>> getFilterCatValMap(boolean interpolate) {
if (interpolate) {
return filteredCategoryValueFillMap;
} else {
return filteredCategoryValueMap;
}
}
public Map<Integer, List<String>> getVolumeExcludeMap(boolean interpolate) {
if (interpolate) {
return volumeExcludeFillMap;
} else {
return volumeExcludeMap;
}
}
public Map<Integer, Trend> getTrendMap(boolean interpolate) {
if (interpolate) {
return trendFillMap;
} else {
return trendMap;
}
}
public Map<Integer, String> getTrendStrMap(boolean interpolate) {
if (interpolate) {
return trendStrFillMap;
} else {
return trendStrMap;
}
}
}
class Mydate {
LocalDate date;
int indexOffset;
int prevIndexOffset;
}
// loop
// get u/n/d trend
// get exclusions, defaults + current low volume traded
// deprecated: get stocks increase
// updated stock prices, return eventual hold list
// check interval stoploss, move stocks to sell list
// calculate reliability
// calculate confidence
// if confidence
//// get recommendations
//// remove exclusions
//// eventually do hold
//// all not recommended nor on hold will be sold
// else
//// all not on hold will be sold
// sell
// buy
// update again
// calculate resultavg
// add to history lists
// loop
//// check 1 day stoploss, move stocks to sell list
//// sell
// lastbuy, get a new buy/sell recommendation
/*
*/
// sim will
// lucky shots / short runs
// config commons / invariants
// one company lucky percentage value / rerun without
// some lucky few days
// too few good results
/*
*/
// loop
// update values with indexoffset - extra
// get advise based on indexoffset info (TODO extra)
// get istoploss sells with indexoffset
// get buy list with indexoffset - delay - extra
// stoploss is based on indexoffset - extra
// algo 0
// loop
// get recommend for buy sell on date1
// sell buy on date1
// date1 = date1 + 1w
// calculate capital after 1w, new date1
// endloop
// #calculate capital after 1w
// # remember stoploss
// algo 1
// loop
// get findprofit recommendations from last week on date1
// ignore sell buy if not reliable lately
// sell buy
// date += 1w
// calc new capital
// endloop
// algo 2
// incr date by 1w
// loop
// date1
// stocklist
// check pr date1 top 5 for last 1m 1w etc
// if stocklist in top 5, keep, else sell
// buy stocklist in top 5
// date1 += 1w
// calc new capital
// endloop
// #get stocklist value
// use mach highest mom
// improve with ds
}
| iclij/iclij-common/iclij-component/src/main/java/roart/iclij/component/SimulateInvestComponent.java | package roart.iclij.component;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Map.Entry;
import java.util.OptionalDouble;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import roart.common.cache.MyCache;
import roart.common.config.CacheConstants;
import roart.common.config.ConfigConstants;
import roart.common.constants.Constants;
import roart.common.constants.EvolveConstants;
import roart.common.constants.ServiceConstants;
import roart.common.model.MetaItem;
import roart.common.pipeline.PipelineConstants;
import roart.common.util.JsonUtil;
import roart.common.util.MapUtil;
import roart.common.util.MathUtil;
import roart.common.util.MetaUtil;
import roart.common.util.TimeUtil;
import roart.common.util.ValidateUtil;
import roart.iclij.component.adviser.Adviser;
import roart.iclij.component.adviser.AdviserFactory;
import roart.component.model.ComponentData;
import roart.component.model.SimulateInvestData;
import roart.constants.IclijConstants;
import roart.constants.SimConstants;
import roart.db.IclijDbDao;
import roart.evolution.chromosome.AbstractChromosome;
import roart.iclij.evolution.chromosome.impl.ConfigMapChromosome2;
import roart.iclij.evolution.chromosome.winner.IclijConfigMapChromosomeWinner;
import roart.evolution.config.EvolutionConfig;
import roart.evolution.fitness.Fitness;
import roart.evolution.iclijconfigmap.genetics.gene.impl.IclijConfigMapChromosome;
import roart.evolution.iclijconfigmap.genetics.gene.impl.IclijConfigMapGene;
import roart.iclij.config.AutoSimulateInvestConfig;
import roart.iclij.config.IclijConfig;
import roart.iclij.config.IclijConfigConstants;
import roart.iclij.config.IclijXMLConfig;
import roart.iclij.config.MLConfigs;
import roart.iclij.config.Market;
import roart.iclij.config.SimulateFilter;
import roart.iclij.config.SimulateInvestConfig;
import roart.iclij.filter.Memories;
import roart.iclij.model.MLMetricsItem;
import roart.iclij.model.IncDecItem;
import roart.iclij.model.MemoryItem;
import roart.iclij.model.Parameters;
import roart.iclij.model.SimDataItem;
import roart.iclij.model.Trend;
import roart.iclij.model.action.MarketActionData;
import roart.iclij.service.IclijServiceResult;
import roart.iclij.verifyprofit.TrendUtil;
import roart.service.model.ProfitData;
import roart.simulate.model.Capital;
import roart.simulate.model.SimulateStock;
import roart.simulate.model.StockHistory;
import roart.simulate.util.SimUtil;
public class SimulateInvestComponent extends ComponentML {
private static final boolean VERIFYCACHE = false;
private static final int MAXARR = 0;
@Override
public void enable(Map<String, Object> valueMap) {
}
@Override
public void disable(Map<String, Object> valueMap) {
}
@Override
public ComponentData handle(MarketActionData action, Market market, ComponentData param, ProfitData profitdata,
Memories positions, boolean evolve, Map<String, Object> aMap, String subcomponent, String mlmarket,
Parameters parameters, boolean hasParent) {
ComponentData componentData = new ComponentData(param);
SimulateInvestData simulateParam;
if (param instanceof SimulateInvestData) {
simulateParam = (SimulateInvestData) param;
} else {
simulateParam = new SimulateInvestData(param);
}
IclijConfig config = param.getInput().getConfig();
// four cases
// autosimconfig set, both evolve and not, and simconfig is null
// autoconfig is not set, and simconfig is set, both evolve and not
// simconfig from siminvest
// localsimconfig from market config file
// simconfig and localsimconfig merges, with simconfig values win
// four cases
// sim: vl
// imp: vl filt
// auto: vl filt
// impauto: vl filt
// extradelay: delay for getting prices
// extradelay: buy and sell is on the same date, just an approx
// delay: days after buy/sell decision.
String conffilters = (String) param.getConfigValueMap().remove(IclijConfigConstants.SIMULATEINVESTFILTERS);
String confautofilters = (String) param.getConfigValueMap().remove(IclijConfigConstants.AUTOSIMULATEINVESTFILTERS);
AutoSimulateInvestConfig autoSimConfig = getAutoSimConfig(config);
SimulateInvestConfig simConfig = getSimConfig(config);
// coming from improvesim
List<SimulateFilter> filter = get(conffilters);
List<SimulateFilter> autofilter = get(confautofilters);
if (simConfig != null) {
filter = simConfig.getFilters();
}
if (autoSimConfig != null) {
autofilter = autoSimConfig.getFilters();
}
//Integer overrideAdviser = null;
boolean evolving = param instanceof SimulateInvestData;
if (!(param instanceof SimulateInvestData)) {
// if not evolving, plain simulating
SimulateInvestConfig localSimConfig = getSimulate(market.getSimulate());
// override with file config
localSimConfig.merge(simConfig);
if (simConfig != null) {
//simConfig.merge(localSimConfig);
}
if (localSimConfig.getExtradelay() != null) {
//extradelay = localSimConfig.getExtradelay();
}
simConfig = localSimConfig;
} else {
// if evolving
/*
if (simulateParam.getConfig() != null) {
overrideAdviser = simulateParam.getConfig().getAdviser();
simConfig.merge(simulateParam.getConfig());
}
*/
/*
if (!simulateParam.getInput().getValuemap().isEmpty()) {
overrideAdviser = simulateParam.getConfig().getAdviser();
simConfig.merge(simulateParam.getConfig());
}
*/
// file configured sim config
SimulateInvestConfig localSimConfig = getSimulate(market.getSimulate());
localSimConfig.merge(simConfig);
if (localSimConfig != null && localSimConfig.getVolumelimits() != null && simConfig.getVolumelimits() == null) {
// override base simconfig with file config volumelimits
//simConfig.setVolumelimits(localSimConfig.getVolumelimits());
}
if (localSimConfig != null && localSimConfig.getExtradelay() != null) {
// use file config extradelay
//simConfig.setExtradelay(localSimConfig.getExtradelay());
//extradelay = localSimConfig.getExtradelay();
}
simConfig = localSimConfig;
}
if (autoSimConfig != null/* && !evolving*/) {
simConfig.setStartdate(autoSimConfig.getStartdate());
simConfig.setEnddate(autoSimConfig.getEnddate());
simConfig.setInterval(autoSimConfig.getInterval());
simConfig.setVolumelimits(autoSimConfig.getVolumelimits());
}
int extradelay = 0;
if (simConfig.getExtradelay() != null) {
extradelay = simConfig.getExtradelay();
}
// coming from improvesim
//List<SimulateFilter> filter = simConfig.getFilters();
//simConfig.setFilters(null);
Data data = new Data();
if (simulateParam.getStockDates() != null) {
data.stockDates = simulateParam.getStockDates();
} else {
data.stockDates = param.getService().getDates(market.getConfig().getMarket());
}
if (!TimeUtil.rangeCheck(data.stockDates, TimeUtil.replace(simConfig.getStartdate()), TimeUtil.replace(simConfig.getEnddate()))) {
Map<String, Object> map = new HashMap<>();
map.put(SimConstants.EMPTY, true);
map.put(EvolveConstants.TITLETEXT, emptyNull(simConfig.getStartdate(), "start") + "-" + emptyNull(simConfig.getEnddate(), "end") + " " + ("any"));
componentData.getUpdateMap().putAll(map);
if (evolving) {
componentData.setResultMap(new HashMap<>());
}
Double score = 0.0;
Map<String, Double> scoreMap = new HashMap<>();
if (score.isNaN()) {
int jj = 0;
}
scoreMap.put("" + score, score);
scoreMap.put(SimConstants.SCORE, score);
componentData.setScoreMap(scoreMap);
handle2(action, market, componentData, profitdata, positions, evolve, aMap, subcomponent, mlmarket, parameters, hasParent);
return componentData;
}
data.categoryValueFillMap = param.getFillCategoryValueMap();
data.categoryValueMap = param.getCategoryValueMap();
data.volumeMap = param.getVolumeMap();
BiMap<String, LocalDate> stockDatesBiMap = getStockDatesBiMap(market.getConfig().getMarket(), data.stockDates);
//ComponentData componentData = component.improve2(action, param, market, profitdata, null, buy, subcomponent, parameters, mlTests);
String mldate = getMlDate(market, simConfig, data, autoSimConfig);
int investStartOffset = data.stockDates.size() - 1 - TimeUtil.getIndexEqualBefore(data.stockDates, mldate);
String adatestring = data.stockDates.get(data.stockDates.size() - 1 - investStartOffset);
LocalDate investStart = stockDatesBiMap.get(adatestring);
/*
try {
investStart = TimeUtil.convertDate(mldate);
} catch (ParseException e1) {
log.error(Constants.EXCEPTION, e1);
}
*/
LocalDate investEnd = param.getFutureDate();
try {
String enddate;
if (autoSimConfig != null) {
enddate = autoSimConfig.getEnddate();
} else {
enddate = simConfig.getEnddate();
}
if (enddate != null) {
enddate = enddate.replace('-', '.');
investEnd = TimeUtil.convertDate(enddate);
}
} catch (ParseException e1) {
log.error(Constants.EXCEPTION, e1);
}
int endIndexOffset = 0;
if (investEnd != null) {
String investEndStr = TimeUtil.convertDate2(investEnd);
endIndexOffset = data.stockDates.size() - 1 - data.stockDates.indexOf(investEndStr);
}
boolean intervalwhole;
if (autoSimConfig != null) {
intervalwhole = config.getAutoSimulateInvestIntervalwhole();
} else {
intervalwhole = config.wantsSimulateInvestIntervalWhole();
}
int end = 1;
if (intervalwhole) {
end = autoSimConfig != null ? autoSimConfig.getInterval() : simConfig.getInterval();
}
List<String> parametersList = new ArrayList<>(); //adviser.getParameters();
if (parametersList.isEmpty()) {
parametersList.add(null);
}
List<Double> scores = new ArrayList<>();
//LocalDate date = TimeUtil.getEqualBefore(data.stockDates, investStart);
//int indexOffset = data.stockDates.size() - 1 - TimeUtil.getIndexEqualAfter(data.stockDates, datestring2);
// TODO investend and other reset of more params
Parameters realParameters = parameters;
if (realParameters == null || realParameters.getThreshold() == 1.0) {
String aParameter = JsonUtil.convert(realParameters);
investEnd = getAdjustedInvestEnd(extradelay, data, investEnd);
LocalDate lastInvestEnd = getAdjustedLastInvestEnd(data, investEnd, simConfig.getDelay());
setDataIdx(data, investStart, lastInvestEnd);
setExclusions(market, data, simConfig);
setDataVolumeAndTrend(market, param, simConfig, data, investStart, investEnd, lastInvestEnd, evolving);
long time0 = System.currentTimeMillis();
Map<String, Object> resultMap = new HashMap<>();
for (int offset = 0; offset < end; offset++) {
Integer origAdviserId = (Integer) param.getInput().getValuemap().get(IclijConfigConstants.SIMULATEINVESTADVISER);
Mydate mydate = new Mydate();
mydate.indexOffset = investStartOffset - offset;
if (mydate.indexOffset < 0) {
continue;
}
String adatestring2 = data.stockDates.get(data.stockDates.size() - 1 - mydate.indexOffset);
mydate.date = stockDatesBiMap.get(adatestring2);
//getAdjustedDate(data, investStart, offset, mydate);
Map<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> simConfigs;
List<SimulateFilter[]> filters = new ArrayList<>();
if (autoSimConfig == null) {
simConfigs = new HashMap<>();
List<SimulateFilter> listoverride = filter; //simConfig.getFilters();
List<SimulateFilter[]> list = getDefaultList();
if (list != null) {
filters.addAll(list);
}
if (listoverride != null) {
mergeFilterList(list, listoverride);
}
//simConfigs = new ArrayList<>();
//simConfigs.add(getSimConfig(config));
} else {
simConfigs = getSimConfigs(market.getConfig().getMarket(), autoSimConfig, autofilter, filters, config);
simConfigs = new HashMap<>(simConfigs);
}
List<SimulateInvestConfig> simsConfigs = new ArrayList<>();
if (autoSimConfig == null) {
simsConfigs.add(simConfig);
} else {
Set<Pair<LocalDate, LocalDate>> keys = new HashSet<>();
if (mydate.date != null) {
simsConfigs = getSimConfigs(simConfigs, mydate, keys, market);
simConfigs.keySet().removeAll(keys);
}
}
List<Triple<SimulateInvestConfig, OneRun, Results>> simTriplets = getTriples(market, param, data,
investStart, investEnd, mydate, simsConfigs);
if (evolving || offset > 0) {
investEnd = lastInvestEnd;
}
SimulateInvestConfig currentSimConfig = null;
if (autoSimConfig == null) {
currentSimConfig = simConfig;
}
OneRun currentOneRun = getOneRun(market, param, simConfig, data, investStart, investEnd, null);
Adviser selladviser = null;
Adviser voteadviser = null;
SimulateInvestConfig sell = null;
SimulateInvestConfig vote = null;
if (autoSimConfig == null) {
int adviserId = simConfig.getAdviser();
currentOneRun.adviser = new AdviserFactory().get(adviserId, market, investStart, investEnd, param, simConfig);
currentOneRun.adviser.getValueMap(data.stockDates, data.firstidx, data.lastidx, data.getCatValMap(simConfig.getInterpolate()));
} else {
selladviser = new AdviserFactory().get(-1, market, investStart, investEnd, param, simConfig);
sell = JsonUtil.copy(simConfig);
sell.setConfidence(true);
sell.setConfidenceValue(2.0);
sell.setConfidenceFindTimes(0);
if (autoSimConfig.getVote() != null && autoSimConfig.getVote()) {
voteadviser = new AdviserFactory().get(-2, market, investStart, investEnd, param, simConfig);
vote = JsonUtil.copy(simConfig);
//vote.setConfidence(true);
//vote.setConfidenceValue(2.0);
//vote.setConfidenceFindTimes(0);
//currentSimConfig = vote;
}
}
Results mainResult = new Results();
/*
if (mydate.date != null) {
mydate.date = TimeUtil.getForwardEqualAfter2(mydate.date, 0 , data.stockDates);
String datestring2 = TimeUtil.convertDate2(mydate.date);
mydate.indexOffset = data.stockDates.size() - 1 - TimeUtil.getIndexEqualAfter(data.stockDates, datestring2);
}
*/
while (mydate.indexOffset >= endIndexOffset) {
boolean lastInvest = offset == 0 && mydate.indexOffset == endIndexOffset;
/*
if (currentSimConfig != null) {
doOneRun(param, currentSimConfig, extradelay, evolving, aParameter, offset, currentOneRun, mainResult,
data, lastInvest, mydate, autoSimConfig != null, stockDatesBiMap);
}
*/
if (autoSimConfig != null) {
if (MAXARR > 0 && !simTriplets.isEmpty() && simTriplets.get(0).getMiddle().autoscore != null && simTriplets.get(0).getMiddle().autoscore != 0) {
Collections.shuffle(simTriplets);
}
for (Triple<SimulateInvestConfig, OneRun, Results> aPair : simTriplets) {
SimulateInvestConfig aSimConfig = aPair.getLeft();
OneRun aOneRun = aPair.getMiddle();
Results aResult = aPair.getRight();
doOneRun(param, aSimConfig, extradelay, evolving, aParameter, offset, aOneRun, aResult,
data, lastInvest, mydate, autoSimConfig != null, stockDatesBiMap, false, endIndexOffset);
}
}
if (currentSimConfig != null) {
if (!simTriplets.isEmpty() && simTriplets.get(0).getMiddle().autoscore != null && simTriplets.get(0).getMiddle().autoscore != 0 && autoSimConfig.getVote() != null && autoSimConfig.getVote()) {
List<String> buys = new ArrayList<>();
//Collections.sort(simTriplets, (o1, o2) -> Double.compare(o2.getMiddle().autoscore, o1.getMiddle().autoscore));
List<Triple<SimulateInvestConfig, OneRun, Results>> new2 = getAdviserTriplets(simTriplets);
List<Triple<SimulateInvestConfig, OneRun, Results>> others = new2;
for (Triple<SimulateInvestConfig, OneRun, Results> triplet : others) {
OneRun aresult = triplet.getMiddle();
buys.addAll(aresult.buys.stream().map(SimulateStock::getId).collect(Collectors.toList()));
}
currentOneRun.adviser.setExtra(buys);
}
doOneRun(param, currentSimConfig, extradelay, evolving, aParameter, offset, currentOneRun, mainResult,
data, lastInvest, mydate, autoSimConfig != null, stockDatesBiMap, true, endIndexOffset);
}
if (autoSimConfig != null) {
for (Triple<SimulateInvestConfig, OneRun, Results> aTriple : simTriplets) {
SimulateInvestConfig aSimConfig = aTriple.getLeft();
OneRun aOneRun = aTriple.getMiddle();
Results aResult = aTriple.getRight();
// best or best last
double score = getScore(autoSimConfig, aOneRun, aResult);
aOneRun.autoscore = score;
if (score < 0) {
int jj = 0;
}
}
// no. hits etc may be reset if changed
// winnerAdviser
Collections.sort(simTriplets, (o1, o2) -> Double.compare(o2.getMiddle().autoscore, o1.getMiddle().autoscore));
if (MAXARR > 0) {
if (MAXARR < 11) {
if (!simTriplets.isEmpty() && simTriplets.get(0).getMiddle().autoscore != 0) {
List<Triple<SimulateInvestConfig, OneRun, Results>> new2 = getAdviserTriplets(
simTriplets);
if (simTriplets.size() != new2.size()) {
for (Triple<SimulateInvestConfig, OneRun, Results> anew : new2) {
SimulateInvestConfig aconf = anew.getLeft();
log.info("" + aconf.asValuedMap());
}
}
simTriplets = new2;
}
} else {
simTriplets = simTriplets.subList(0, Math.min(MAXARR, simTriplets.size()));
}
}
// overwrite/merge currentOnerun etc
// and get new date range
// and remove old or bad
Set<Pair<LocalDate, LocalDate>> keys = new HashSet<>();
simsConfigs = getSimConfigs(simConfigs, mydate, keys, market);
simConfigs.keySet().removeAll(keys);
List<Triple<SimulateInvestConfig, OneRun, Results>> newSimTriplets = getTriples(market, param, data,
investStart, investEnd, mydate, simsConfigs);
if (newSimTriplets.size() > 0) {
if (MAXARR > 0) {
//newSimTriplets = newSimTriplets.subList(0, Math.min(MAXARR, simTriplets.size()));
}
List<Double> alist = simTriplets.stream().map(o -> (o.getMiddle().capital.amount + getSum(o.getMiddle().mystocks).amount)).collect(Collectors.toList());
log.info("alist {}", alist);
double autolimit = autoSimConfig.getDellimit();
simTriplets = simTriplets.stream().filter(o -> (o.getMiddle().capital.amount + getSum(o.getMiddle().mystocks).amount) > autolimit).collect(Collectors.toList());
}
simTriplets.addAll(newSimTriplets);
}
if (autoSimConfig != null && !simTriplets.isEmpty()) {
List<Double> alist = simTriplets.stream().map(o -> (o.getMiddle().autoscore)).collect(Collectors.toList());
log.info("alist {}", alist);
OneRun oneRun = simTriplets.get(0).getMiddle();
if (oneRun.runs > 1 && ((oneRun.autoscore != null && oneRun.autoscore > autoSimConfig.getAutoscorelimit()) || (autoSimConfig.getKeepAdviser() && currentOneRun.autoscore != null && currentOneRun.autoscore > autoSimConfig.getKeepAdviserLimit()))) {
if (autoSimConfig.getVote() != null && autoSimConfig.getVote()) {
currentOneRun.adviser = voteadviser;
//currentOneRun.hits = SerializationUtils.clone(oneRun.hits);
//currentOneRun.trendDec = SerializationUtils.clone(oneRun.trendDec);
//currentOneRun.trendInc = SerializationUtils.clone(oneRun.trendInc);
currentSimConfig = vote;
} else {
// calc autoscore
Double score = getScore(autoSimConfig, currentOneRun, mainResult);
if (!(autoSimConfig.getKeepAdviser() && score != null && score > autoSimConfig.getKeepAdviserLimit())) {
currentOneRun.adviser = oneRun.adviser;
currentOneRun.hits = SerializationUtils.clone(oneRun.hits);
currentOneRun.trendDec = SerializationUtils.clone(oneRun.trendDec);
currentOneRun.trendInc = SerializationUtils.clone(oneRun.trendInc);
//oneRun.
currentSimConfig = simTriplets.get(0).getLeft();
}
}
} else {
currentOneRun.adviser = selladviser;
if (autoSimConfig.getVote() == null || !autoSimConfig.getVote()) {
currentOneRun.hits = SerializationUtils.clone(oneRun.hits);
currentOneRun.trendDec = SerializationUtils.clone(oneRun.trendDec);
currentOneRun.trendInc = SerializationUtils.clone(oneRun.trendInc);
}
currentSimConfig = sell;
}
}
mydate.prevIndexOffset = mydate.indexOffset;
//int interval = autoSimConfig != null ? autoSimConfig.getInterval() : simConfig.getInterval();
if (mydate.indexOffset - simConfig.getInterval() < 0 * endIndexOffset) {
break;
}
mydate.indexOffset -= simConfig.getInterval();
String adatestring3 = data.stockDates.get(data.stockDates.size() - 1 - mydate.indexOffset);
mydate.date = stockDatesBiMap.get(adatestring3);
}
/*
if (offset == 0) {
try {
lastbuysell(stockDates, date, adviser, capital, simConfig, categoryValueMap, mystocks, extradelay, prevIndexOffset, hits, findTimes, aParameter, param.getUpdateMap(), trendInc, trendDec, configExcludeList, param, market, interval, filteredCategoryValueMap, volumeMap, delay);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
*/
List<Triple<SimulateInvestConfig, OneRun, Results>> endSimTriplets = new ArrayList<>();
endSimTriplets.add(new ImmutableTriple(currentSimConfig, currentOneRun, mainResult));
for (Triple<SimulateInvestConfig, OneRun, Results> aPair : endSimTriplets) {
SimulateInvestConfig aSimConfig = aPair.getLeft();
OneRun aOneRun = aPair.getMiddle();
Results aResult = aPair.getRight();
//boolean lastInvest = offset == 0 && mydate.date != null && lastInvestEnd != null && mydate.date.isAfter(lastInvestEnd);
// check
/*
if (aOneRun.saveLastInvest) {
aOneRun.mystocks = aOneRun.savedStocks;
}
*/
// index == prev
update(data.getCatValMap(simConfig.getInterpolate()), aOneRun.mystocks, endIndexOffset + extradelay, new ArrayList<>(), endIndexOffset + extradelay, endIndexOffset);
Capital sum = getSum(aOneRun.mystocks);
sum.amount += aOneRun.capital.amount;
long days = 0;
if (investStart != null && investEnd != null) {
days = ChronoUnit.DAYS.between(investStart, investEnd);
}
double years = (double) days / 365;
Double score = sum.amount / aOneRun.resultavg;
if (score < -0.1) {
log.error("Negative amount");
}
if (score < 0) {
score = 0.0;
}
if (years != 0) {
score = Math.pow(score, 1 / years);
} else {
score = 0.0;
}
if (score < -1) {
int jj = 0;
}
if (score > 10) {
int jj = 0;
}
if (score > 100) {
int jj = 0;
}
if (score.isNaN()) {
int jj = 0;
}
if (offset == 0) {
Map<String, Object> map = new HashMap<>();
if (!evolving) {
for (SimulateStock stock : aOneRun.mystocks) {
// wrong price in dev
stock.setSellprice(stock.getPrice());
stock.setStatus("END");
}
aResult.stockhistory.addAll(aOneRun.mystocks);
map.put(SimConstants.SUMHISTORY, aResult.sumHistory);
map.put(SimConstants.STOCKHISTORY, aResult.stockhistory);
map.put(SimConstants.PLOTDEFAULT, aResult.plotDefault);
map.put(SimConstants.PLOTDATES, aResult.plotDates);
map.put(SimConstants.PLOTCAPITAL, aResult.plotCapital);
map.put(SimConstants.STARTDATE, investStart);
map.put(SimConstants.ENDDATE, investEnd);
map.put(SimConstants.FILTER, JsonUtil.convert(filter));
map.put(SimConstants.LASTSTOCKS, aOneRun.mystocks.stream().map(SimulateStock::getId).toList());
List<Pair<String, Double>> tradeStocks = SimUtil.getTradeStocks(aResult.stockhistory);
map.put(SimConstants.TRADESTOCKS, tradeStocks);
param.getUpdateMap().putAll(map);
param.getUpdateMap().putIfAbsent(SimConstants.LASTBUYSELL, "Not buying or selling today");
componentData.getUpdateMap().putAll(map);
} else {
if (autoSimConfig != null) {
map.put(EvolveConstants.TITLETEXT, emptyNull(autoSimConfig.getStartdate(), "start") + "-" + emptyNull(autoSimConfig.getEnddate(), "end") + " " + (emptyNull(origAdviserId, "all")));
} else {
map.put(EvolveConstants.TITLETEXT, emptyNull(simConfig.getStartdate(), "start") + "-" + emptyNull(simConfig.getEnddate(), "end") + " " + (emptyNull(origAdviserId, "all")));
}
map.put(SimConstants.FILTER, JsonUtil.convert(filter));
componentData.getUpdateMap().putAll(map);
}
}
if (evolving) {
for (SimulateStock stock : aOneRun.mystocks) {
stock.setSellprice(stock.getPrice());
stock.setStatus("END");
}
aResult.stockhistory.addAll(aOneRun.mystocks);
boolean doFilter = (autoSimConfig != null && autoSimConfig.getImproveFilters()) || (autoSimConfig == null && simConfig.getImproveFilters());
if (doFilter) {
SimulateFilter afilter;
if (autoSimConfig != null) {
afilter = filters.get(0)[0];
} else {
afilter = filters.get(0)[currentSimConfig.getAdviser()];
}
if (afilter.getStable() > 0) {
List<StockHistory> history = aResult.history;
if (!history.isEmpty()) {
if (!SimUtil.isStable(afilter, history, null)) {
score = 0.0;
}
}
}
if (afilter.getCorrelation() > 0) {
if (!(aResult.plotCapital.size() < 2) && !SimUtil.isCorrelating(afilter, aResult.plotCapital, null)) {
score = 0.0;
}
}
if (afilter.getLucky() > 0) {
List<StockHistory> history = aResult.history;
if (!history.isEmpty()) {
StockHistory last = history.get(history.size() - 1);
double total = last.getCapital().amount + last.getSum().amount - 1;
if (total > 0.0) {
List<Pair<String, Double>> list = SimUtil.getTradeStocks(aResult.stockhistory);
double max = 0;
if (!list.isEmpty()) {
max = list.get(0).getValue();
}
if (max / total > afilter.getLucky()) {
score = 0.0;
}
}
}
}
if (afilter.getShortrun() > 0) {
List<StockHistory> history = aResult.history;
if (history.size() < afilter.getShortrun()) {
score = 0.0;
}
}
}
Map<String, Object> map = new HashMap<>();
map.put(SimConstants.HISTORY, aResult.history);
map.put(SimConstants.STOCKHISTORY, aResult.stockhistory);
map.put(SimConstants.PLOTCAPITAL, aResult.plotCapital);
map.put(SimConstants.SCORE, score);
map.put(SimConstants.STARTDATE, TimeUtil.convertDate2(investStart));
map.put(SimConstants.ENDDATE, TimeUtil.convertDate2(investEnd));
if (autoSimConfig != null) {
map.put(EvolveConstants.TITLETEXT, emptyNull(autoSimConfig.getStartdate(), "start") + "-" + emptyNull(autoSimConfig.getEnddate(), "end") + " " + (emptyNull(origAdviserId, "all")));
} else {
map.put(EvolveConstants.SIMTEXT, market.getConfig().getMarket() + " " + emptyNull(simConfig.getStartdate(), "start") + "-" + emptyNull(simConfig.getEnddate(), "end") + " " + (emptyNull(origAdviserId, "all")));
}
map.put(SimConstants.FILTER, JsonUtil.convert(filter));
//map.put("market", market.getConfig().getMarket());
resultMap.put("" + offset, map);
}
scores.add(score);
}
}
if (evolving) {
componentData.setResultMap(resultMap);
}
log.debug("time0 {}", System.currentTimeMillis() - time0);
}
Double score = 0.0;
if (!scores.isEmpty()) {
OptionalDouble average = scores
.stream()
.mapToDouble(a -> a)
.average();
score = average.getAsDouble();
}
if (intervalwhole) {
String stats = scores.stream().filter(Objects::nonNull).mapToDouble(e -> (Double) e).summaryStatistics().toString();
Map<String, Object> map = new HashMap<>();
map.put(SimConstants.SCORES, scores);
map.put(SimConstants.STATS, stats);
double min = Collections.min(scores);
double max = Collections.max(scores);
int minDay = scores.indexOf(min);
int maxDay = scores.indexOf(max);
map.put(SimConstants.MINMAX, "min " + min + " at " + minDay + " and max " + max + " at " + maxDay);
param.getUpdateMap().putAll(map);
componentData.getUpdateMap().putAll(map);
}
Map<String, Double> scoreMap = new HashMap<>();
if (score.isNaN()) {
int jj = 0;
}
scoreMap.put("" + score, score);
scoreMap.put(SimConstants.SCORE, score);
componentData.setScoreMap(scoreMap);
//componentData.setFuturedays(0);
handle2(action, market, componentData, profitdata, positions, evolve, aMap, subcomponent, mlmarket, parameters, hasParent);
return componentData;
}
private Double getScore(AutoSimulateInvestConfig autoSimConfig, OneRun aOneRun, Results aResult) {
int numlast = autoSimConfig.getLastcount();
Double score;
if (numlast == 0 || aOneRun.runs == 1) {
Capital sum = getSum(aOneRun.mystocks);
sum.amount += aOneRun.capital.amount;
score = (sum.amount - 1) / aOneRun.runs;
if (aResult.plotCapital.size() > 0) {
if (numlast == 0) {
if (score != ((aResult.plotCapital.get(aResult.plotCapital.size() - 1) - 1)/ aResult.plotCapital.size())) {
System.out.println("sc " + score + " " + aOneRun.runs);
System.out.println("" + aResult.plotCapital.get(aResult.plotCapital.size() - 1));
System.out.println("" + aResult.plotCapital.size());
System.out.println("" + (((aResult.plotCapital.get(aResult.plotCapital.size() - 1) - 1)/ aResult.plotCapital.size())));
System.out.println("ERRERR");
}
}
int firstidx = aResult.plotCapital.size() - 1 - numlast;
if (firstidx < 0 || numlast == 0) {
firstidx = 0;
}
double newscore = aResult.plotCapital.get(aResult.plotCapital.size() - 1) - aResult.plotCapital.get(firstidx);
newscore = newscore / (aResult.plotCapital.size() - firstidx);
if (Math.abs(newscore - score) > 0.00000000001 ) {
System.out.println("ERRERR");
}
}
} else {
int firstidx = aResult.plotCapital.size() - 1 - numlast;
if (firstidx < 0) {
firstidx = 0;
}
score = null;
if (aResult.plotCapital.size() > 0) {
score = aResult.plotCapital.get(aResult.plotCapital.size() - 1) - aResult.plotCapital.get(firstidx);
score = score / (aResult.plotCapital.size() - firstidx);
} else {
int jj = 0;
}
}
return score;
}
private List<Triple<SimulateInvestConfig, OneRun, Results>> getAdviserTriplets(
List<Triple<SimulateInvestConfig, OneRun, Results>> simTriplets) {
Integer[] advs = new Integer[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<Triple<SimulateInvestConfig, OneRun, Results>> new2 = new ArrayList<>();
int i = 0;
for (int j = 0; i < 10 && j < simTriplets.size(); j++) {
int adv = simTriplets.get(j).getLeft().getAdviser();
if (advs[adv] == null) {
continue;
}
advs[adv] = null;
new2.add(simTriplets.get(j));
i++;
}
return new2;
}
private List<Triple<SimulateInvestConfig, OneRun, Results>> getTriples(Market market, ComponentData param,
Data data, LocalDate investStart, LocalDate investEnd, Mydate mydate, List<SimulateInvestConfig> simsConfigs) {
List<Triple<SimulateInvestConfig, OneRun, Results>> simPairs = new ArrayList<>();
for (SimulateInvestConfig aConfig : simsConfigs) {
int adviserId = aConfig.getAdviser();
OneRun onerun = getOneRun(market, param, aConfig, data, investStart, investEnd, adviserId);
Results results = new Results();
Triple<SimulateInvestConfig, OneRun, Results> aTriple = new ImmutableTriple(aConfig, onerun, results);
simPairs.add(aTriple);
}
return simPairs;
}
private OneRun getOneRun(Market market, ComponentData param, SimulateInvestConfig simConfig, Data data,
LocalDate investStart, LocalDate investEnd, Integer adviserId) {
OneRun onerun = new OneRun();
if (adviserId != null) {
onerun.adviser = new AdviserFactory().get(adviserId, market, investStart, investEnd, param, simConfig);
onerun.adviser.getValueMap(data.stockDates, data.firstidx, data.lastidx, data.getCatValMap(simConfig.getInterpolate()));
}
onerun.capital = new Capital();
onerun.capital.amount = 1;
onerun.beatavg = 0;
onerun.runs = 0;
onerun.mystocks = new ArrayList<>();
onerun.resultavg = 1;
onerun.hits = new ImmutablePair[simConfig.getConfidenceFindTimes()];
onerun.trendInc = new Integer[] { 0 };
onerun.trendDec = new Integer[] { 0 };
onerun.saveLastInvest = false;
return onerun;
}
private List<SimulateInvestConfig> getSimConfigs(Map<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> simConfigs, Mydate mydate,
Set<Pair<LocalDate, LocalDate>> keys, Market market) {
List<SimulateInvestConfig> simsConfigs = new ArrayList<>();
for (Entry<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> entry : simConfigs.entrySet()) {
Pair<LocalDate, LocalDate> key = entry.getKey();
List<SimulateInvestConfig> value = entry.getValue();
int months = Period.between(key.getLeft(), key.getRight()).getMonths();
LocalDate checkDate = mydate.date.minusMonths(months);
if (!checkDate.isBefore(key.getLeft()) && checkDate.isBefore(key.getRight())) {
// TODO value.merge...
List<SimulateInvestConfig> configs = value;
for (SimulateInvestConfig config : configs) {
SimulateInvestConfig defaultConfig = getSimulate(market.getSimulate());
defaultConfig.merge(config);
simsConfigs.add(defaultConfig);
}
keys.add(key);
}
}
return simsConfigs;
}
private SimulateInvestConfig getSimulate(SimulateInvestConfig simulate) {
if (simulate == null) {
return new SimulateInvestConfig();
}
SimulateInvestConfig newSimConfig = new SimulateInvestConfig(simulate);
if (!newSimConfig.equals(simulate)) {
log.error("Unequal clone");
}
return newSimConfig;
}
private void setExclusions(Market market, Data data, SimulateInvestConfig simConfig) {
String[] excludes = null;
if (market.getSimulate() != null) {
excludes = market.getSimulate().getExcludes();
}
if (excludes == null) {
excludes = new String[0];
}
data.configExcludeList = Arrays.asList(excludes);
Set<String> configExcludeSet = new HashSet<>(data.configExcludeList);
Set<String> abnormExcludes = getTrendExclude(data, market);
data.filteredCategoryValueMap = new HashMap<>(data.getCatValMap(false));
data.filteredCategoryValueMap.keySet().removeAll(configExcludeSet);
data.filteredCategoryValueMap.keySet().removeAll(abnormExcludes);
data.filteredCategoryValueFillMap = new HashMap<>(data.getCatValMap(true));
data.filteredCategoryValueFillMap.keySet().removeAll(configExcludeSet);
data.filteredCategoryValueFillMap.keySet().removeAll(abnormExcludes);
}
private Set<String> getTrendExclude(Data data, Market market) {
IclijConfig instance = IclijXMLConfig.getConfigInstance();
Double margin = instance.getAbnormalChange();
if (margin == null) {
return new HashSet<>();
}
Set<String> abnormExcludes = null;
String key = CacheConstants.SIMULATEINVESTTRENDEXCLUDE + market.getConfig().getMarket() + "_" + data.firstidx + "_" + data.lastidx + "_" + margin;
abnormExcludes = (Set<String>) MyCache.getInstance().get(key);
Set<String> newAbnormExcludes = null;
if (abnormExcludes == null || VERIFYCACHE) {
long time0 = System.currentTimeMillis();
try {
newAbnormExcludes = new TrendUtil().getTrend(null, data.stockDates, null, null, data.getCatValMap(false), data.firstidx, data.lastidx, margin);
log.info("Abnormal excludes {}", newAbnormExcludes);
} catch (Exception e) {
log.error(Constants.ERROR, e);
}
log.debug("time millis {}", System.currentTimeMillis() - time0);
}
if (VERIFYCACHE && abnormExcludes != null) {
if (newAbnormExcludes != null && !newAbnormExcludes.equals(abnormExcludes)) {
log.error("Difference with cache");
}
}
if (abnormExcludes != null) {
return abnormExcludes;
}
abnormExcludes = newAbnormExcludes;
MyCache.getInstance().put(key, abnormExcludes);
return abnormExcludes;
}
private Map<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> getSimConfigs(String market, AutoSimulateInvestConfig autoSimConf, List<SimulateFilter> filter, List<SimulateFilter[]> filters, IclijConfig config) {
List<SimDataItem> all = new ArrayList<>();
try {
String simkey = CacheConstants.SIMDATA + market + autoSimConf.getStartdate() + autoSimConf.getEnddate();
all = (List<SimDataItem>) MyCache.getInstance().get(simkey);
if (all == null) {
LocalDate startDate = TimeUtil.convertDate(TimeUtil.replace(autoSimConf.getStartdate()));
LocalDate endDate = null;
if (autoSimConf.getEnddate() != null) {
endDate = TimeUtil.convertDate(TimeUtil.replace(autoSimConf.getEnddate()));
}
all = SimDataItem.getAll(market, null, null); // fix later: , startDate, endDate);
MyCache.getInstance().put(simkey, all);
}
/*
if (VERIFYCACHE && trendMap != null) {
for (Entry<Integer, Trend> entry : newTrendMap.entrySet()) {
int key2 = entry.getKey();
Trend v2 = entry.getValue();
Trend v = trendMap.get(key2);
if (v2 != null && !v2.toString().equals(v.toString())) {
log.error("Difference with cache");
}
}
}
*/
} catch (Exception e) {
log.error(Constants.ERROR, e);
}
List<SimulateFilter[]> list = null;
if (autoSimConf != null) {
List<SimulateFilter> listoverride = filter; //autoSimConf.getFilters();
list = getDefaultList();
if (list != null) {
filters.addAll(list);
}
if (listoverride != null) {
mergeFilterList(list, listoverride);
}
}
String listString = JsonUtil.convert(list);
String key = CacheConstants.AUTOSIMCONFIG + market + autoSimConf.getStartdate() + autoSimConf.getEnddate() + "_" + autoSimConf.getInterval() + "_" + autoSimConf.getPeriod() + "_" + autoSimConf.getScorelimit().doubleValue() + " " + listString;
Map<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> retMap = (Map<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>>) MyCache.getInstance().get(key);
Map<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> newRetMap = new HashMap<>();
if (retMap == null || VERIFYCACHE) {
for (SimDataItem data : all) {
if (autoSimConf.getScorelimit().doubleValue() > data.getScore().doubleValue()) {
continue;
}
Integer period = null;
int months = Period.between(data.getStartdate(), data.getEnddate()).getMonths();
switch (months) {
case 1:
period = 0;
break;
case 3:
period = 1;
break;
case 12:
period = 2;
break;
}
if (period == null) {
continue;
}
if (period.intValue() == autoSimConf.getPeriod().intValue()) {
String amarket = data.getMarket();
if (market.equals(amarket)) {
String configStr = data.getConfig();
//SimulateInvestConfig s = JsonUtil.convert(configStr, SimulateInvestConfig.class);
Map defaultMap = config.getDeflt();
Map map = JsonUtil.convert(configStr, Map.class);
Map newMap = new HashMap<>();
newMap.putAll(defaultMap);
newMap.putAll(map);
IclijConfig dummy = new IclijConfig();
dummy.setConfigValueMap(newMap);
SimulateInvestConfig simConf = getSimConfig(dummy);
if (simConf.getInterval().intValue() != autoSimConf.getInterval().intValue()) {
continue;
}
simConf.setVolumelimits(autoSimConf.getVolumelimits());
int adviser = simConf.getAdviser();
String filterStr = data.getFilter();
SimulateFilter myFilter = JsonUtil.convert((String)filterStr, SimulateFilter.class);
SimulateFilter[] autoSimConfFilters = list.get(0);
if (autoSimConfFilters != null) {
SimulateFilter autoSimConfFilter = autoSimConfFilters[adviser];
if (myFilter != null && autoSimConfFilter != null) {
if (myFilter.getCorrelation() != null && autoSimConfFilter.getCorrelation() > 0 && autoSimConfFilter.getCorrelation() > myFilter.getCorrelation()) {
continue;
}
if (autoSimConfFilter.getLucky() > 0 && autoSimConfFilter.getLucky() < myFilter.getLucky()) {
continue;
}
if (autoSimConfFilter.getStable() > 0 && autoSimConfFilter.getStable() < myFilter.getStable()) {
continue;
}
if (autoSimConfFilter.getShortrun() > 0 && autoSimConfFilter.getShortrun() > myFilter.getShortrun()) {
continue;
}
if (autoSimConfFilter.getPopulationabove() > myFilter.getPopulationabove()) {
continue;
}
}
}
Pair<LocalDate, LocalDate> aKey = new ImmutablePair(data.getStartdate(), data.getEnddate());
MapUtil.mapAddMe(newRetMap, aKey, simConf);
}
}
}
}
if (VERIFYCACHE && retMap != null) {
for (Entry<Pair<LocalDate, LocalDate>, List<SimulateInvestConfig>> entry : newRetMap.entrySet()) {
Pair<LocalDate, LocalDate> key2 = entry.getKey();
List<SimulateInvestConfig> v2 = entry.getValue();
List<SimulateInvestConfig> v = retMap.get(key2);
if (v == null || v2 == null || v.size() != v2.size()) {
log.error("Difference with cache");
continue;
}
for (int i = 0; i < v.size(); i++) {
if (!v.get(i).equals(v2.get(i))) {
log.error("Difference with cache");
}
}
}
}
if (retMap != null) {
return retMap;
}
retMap = newRetMap;
MyCache.getInstance().put(key, retMap);
return retMap;
}
private void mergeFilterList(List<SimulateFilter[]> list, List<SimulateFilter> listoverride) {
for (int i = 0; i < listoverride.size(); i++) {
SimulateFilter afilter = list.get(0)[i];
SimulateFilter otherfilter = listoverride.get(i);
afilter.merge(otherfilter);
}
}
private List<SimulateFilter[]> getDefaultList() {
List<SimulateFilter[]> list = null;
IclijConfig instance = IclijXMLConfig.getConfigInstance();
try {
list = IclijXMLConfig.getSimulate(instance);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
return list;
}
private void getAdjustedDate(Data data, LocalDate investStart, int offset, Mydate mydate) {
mydate.date = investStart;
mydate.date = TimeUtil.getEqualBefore(data.stockDates, mydate.date);
if (mydate.date == null) {
try {
mydate.date = TimeUtil.convertDate(data.stockDates.get(0));
} catch (ParseException e) {
log.error(Constants.ERROR, e);
}
}
mydate.date = TimeUtil.getForwardEqualAfter2(mydate.date, offset, data.stockDates);
mydate.prevIndexOffset = 0;
}
private void getAdjustedDate(Data data, LocalDate investStart, int offset, LocalDate date) {
date = investStart;
date = TimeUtil.getEqualBefore(data.stockDates, date);
if (date == null) {
try {
date = TimeUtil.convertDate(data.stockDates.get(0));
} catch (ParseException e) {
log.error(Constants.ERROR, e);
}
}
date = TimeUtil.getForwardEqualAfter2(date, offset, data.stockDates);
//return data.stockDates.size() - 1 - data.stockDates.indexOf(date)
}
private void setDataVolumeAndTrend(Market market, ComponentData param, SimulateInvestConfig simConfig, Data data,
LocalDate investStart, LocalDate investEnd, LocalDate lastInvestEnd, boolean evolving) {
// vol lim w/ adviser?
data.volumeExcludeMap = getVolumeExcludeMap(market, simConfig, data, investStart, investEnd, data.firstidx, data.lastidx, false);
data.volumeExcludeFillMap = getVolumeExcludeMap(market, simConfig, data, investStart, investEnd, data.firstidx, data.lastidx, true);
data.trendMap = getTrendIncDec(market, param, data.stockDates, simConfig.getInterval(), data.firstidx, data.lastidx, simConfig, data, false);
data.trendFillMap = getTrendIncDec(market, param, data.stockDates, simConfig.getInterval(), data.firstidx, data.lastidx, simConfig, data, true);
if (evolving) {
data.trendStrMap = getTrendIncDecStr(market, param, data.stockDates, simConfig.getInterval(), data.firstidx, data.lastidx, simConfig, data, false, data.trendMap);
data.trendStrFillMap = getTrendIncDecStr(market, param, data.stockDates, simConfig.getInterval(), data.firstidx, data.lastidx, simConfig, data, true, data.trendFillMap);
}
Set<Integer> keys = data.trendMap.keySet();
List<Integer> keylist = new ArrayList<>(keys);
Collections.sort(keylist);
log.debug("keylist {}", keylist);
}
private void setDataIdx(Data data, LocalDate investStart, LocalDate lastInvestEnd) {
LocalDate date = investStart;
date = TimeUtil.getEqualBefore(data.stockDates, date);
if (date == null) {
try {
date = TimeUtil.convertDate(data.stockDates.get(0));
} catch (ParseException e) {
log.error(Constants.ERROR, e);
}
}
date = TimeUtil.getForwardEqualAfter2(date, 0 /* findTime */, data.stockDates);
String datestring = TimeUtil.convertDate2(date);
int firstidx = TimeUtil.getIndexEqualAfter(data.stockDates, datestring);
int maxinterval = 20;
firstidx -= maxinterval * 2;
if (firstidx < 0) {
firstidx = 0;
}
String lastInvestEndS = TimeUtil.convertDate2(lastInvestEnd);
int lastidx = data.stockDates.indexOf(lastInvestEndS);
lastidx += maxinterval;
if (lastidx >= data.stockDates.size()) {
lastidx = data.stockDates.size() - 1;
}
firstidx = data.stockDates.size() - 1 - firstidx;
lastidx = data.stockDates.size() - 1 - lastidx;
data.firstidx = firstidx;
data.lastidx = lastidx;
}
private Map<Integer, List<String>> getVolumeExcludeMap(Market market, SimulateInvestConfig simConfig, Data data, LocalDate investStart,
LocalDate investEnd, int firstidx, int lastidx, boolean interpolate) {
String key = CacheConstants.SIMULATEINVESTVOLUMELIMITS + market.getConfig().getMarket() + "_" + simConfig.getInterval() + investStart + investEnd + interpolate + simConfig.getVolumelimits();
Map<Integer, List<String>> verifyVolumeExcludeMap = data.getVolumeExcludeMap(interpolate);
Map<Integer, List<String>> volumeExcludeMap = (Map<Integer, List<String>>) MyCache.getInstance().get(key);
Map<Integer, List<String>> newVolumeExcludeMap = null;
if (volumeExcludeMap == null || VERIFYCACHE) {
long time00 = System.currentTimeMillis();
newVolumeExcludeMap = getVolumeExcludesFull(simConfig, simConfig.getInterval(), data.getCatValMap(interpolate), data.volumeMap, firstidx, lastidx);
log.debug("time0 {}", System.currentTimeMillis() - time00);
}
verifyVolumeExcludeMap(newVolumeExcludeMap, verifyVolumeExcludeMap);
if (volumeExcludeMap == null) {
volumeExcludeMap = newVolumeExcludeMap;
MyCache.getInstance().put(key, volumeExcludeMap);
}
return volumeExcludeMap;
}
private void verifyVolumeExcludeMap(Map<Integer, List<String>> newVolumeExcludeMap,
Map<Integer, List<String>> aVolumeExcludeMap) {
if (VERIFYCACHE && aVolumeExcludeMap != null) {
for (Entry<Integer, List<String>> entry : newVolumeExcludeMap.entrySet()) {
int key2 = entry.getKey();
List<String> v2 = entry.getValue();
List<String> v = aVolumeExcludeMap.get(key2);
if (v2 != null && !v2.equals(v)) {
log.error("Difference with cache");
}
}
}
}
private LocalDate getAdjustedLastInvestEnd(Data data, LocalDate investEnd, int delay) {
LocalDate lastInvestEnd = TimeUtil.getBackEqualBefore2(investEnd, 0 /* findTime */, data.stockDates);
if (lastInvestEnd != null) {
String aDate = TimeUtil.convertDate2(lastInvestEnd);
if (aDate != null) {
int idx = data.stockDates.indexOf(aDate) - delay;
if (idx >=0 ) {
aDate = data.stockDates.get(idx);
try {
lastInvestEnd = TimeUtil.convertDate(aDate);
} catch (ParseException e) {
log.error(Constants.EXCEPTION, e);
}
}
}
}
return lastInvestEnd;
}
private LocalDate getAdjustedInvestEnd(int extradelay, Data data, LocalDate investEnd) {
investEnd = TimeUtil.getBackEqualBefore2(investEnd, 0 /* findTime */, data.stockDates);
if (investEnd != null) {
String aDate = TimeUtil.convertDate2(investEnd);
if (aDate != null) {
int idx = data.stockDates.indexOf(aDate);
if (idx >=0 ) {
aDate = data.stockDates.get(idx);
try {
investEnd = TimeUtil.convertDate(aDate);
} catch (ParseException e) {
log.error(Constants.EXCEPTION, e);
}
}
}
}
return investEnd;
}
private String getMlDate(Market market, SimulateInvestConfig simConfig, Data data, AutoSimulateInvestConfig autoSimConfig) {
String mldate = null;
if (simConfig.getMldate()) {
mldate = market.getConfig().getMldate();
if (mldate != null) {
mldate = mldate.replace('-', '.');
}
//mldate = ((SimulateInvestActionData) action).getMlDate(market, stockDates);
//mldate = ((ImproveSimulateInvestActionData) action).getMlDate(market, stockDates);
} else {
Short populate = market.getConfig().getPopulate();
if (populate == null) {
//mldate = ((SimulateInvestActionData) action).getMlDate(market, stockDates);
mldate = market.getConfig().getMldate();
if (mldate != null) {
mldate = mldate.replace('-', '.');
}
} else {
mldate = data.stockDates.get(populate);
}
}
if (mldate == null) {
mldate = data.stockDates.get(0);
}
if (autoSimConfig != null && autoSimConfig.getStartdate() != null) {
mldate = autoSimConfig.getStartdate();
mldate = mldate.replace('-', '.');
return mldate;
}
if (simConfig.getStartdate() != null) {
mldate = simConfig.getStartdate();
mldate = mldate.replace('-', '.');
}
return mldate;
}
private void doOneRun(ComponentData param, SimulateInvestConfig simConfig, int extradelay, boolean evolving,
String aParameter, int offset, OneRun onerun,
Results results, Data data, boolean lastInvest,
Mydate mydate, boolean auto, BiMap<String, LocalDate> stockDatesBiMap, boolean isMain, int endIndexOffset) {
if (getBSValueIndexOffset(mydate, simConfig) >= endIndexOffset) {
doBuySell(simConfig, onerun, results, data, mydate.indexOffset, stockDatesBiMap);
}
/*
if (lastInvest) {
// not with evolving?
onerun.savedStocks = copy(onerun.mystocks);
onerun.saveLastInvest = true;
}
*/
//Trend trend = getTrendIncDec(market, param, stockDates, interval, filteredCategoryValueMap, trendInc, trendDec, indexOffset);
// no interpolation for trend
Trend trend = getTrendIncDec(data.stockDates, onerun.trendInc, onerun.trendDec, getValueIndexOffset(mydate, simConfig), data.getTrendMap(false /*simConfig.getInterpolate()*/));
// get recommendations
List<String> myExcludes = getExclusions(simConfig, data.stockDates, data.configExcludeList, getValueIndexOffset(mydate, simConfig), data.getVolumeExcludeMap(simConfig.getInterpolate()));
double myavg = increase(onerun.mystocks, getValueIndexOffset(mydate, simConfig), data.getCatValMap(simConfig.getInterpolate()), mydate.prevIndexOffset + extradelay, endIndexOffset);
List<SimulateStock> holdIncrease = new ArrayList<>();
int up = update(data.getCatValMap(simConfig.getInterpolate()), onerun.mystocks, getValueIndexOffset(mydate, simConfig), holdIncrease, mydate.prevIndexOffset + extradelay, endIndexOffset);
List<SimulateStock> sells = new ArrayList<>();
List<SimulateStock> buys = new ArrayList<>();
onerun.buys = buys;
double myreliability = getReliability(onerun.mystocks, onerun.hits, simConfig.getConfidenceFindTimes(), up);
if (simConfig.getStoploss()) {
stoploss(onerun.mystocks, data.stockDates, getValueIndexOffset(mydate, simConfig), data.getCatValMap(simConfig.getInterpolate()), getValueIndexOffset(mydate, simConfig) + 1, sells, simConfig.getStoplossValue(), "STOP", stockDatesBiMap, endIndexOffset);
}
if (simConfig.getIntervalStoploss()) {
stoploss(onerun.mystocks, data.stockDates, getValueIndexOffset(mydate, simConfig), data.getCatValMap(simConfig.getInterpolate()), getValueIndexOffset(mydate, simConfig) + simConfig.getInterval(), sells, simConfig.getIntervalStoplossValue(), "ISTOP", stockDatesBiMap, endIndexOffset);
}
holdIncrease.removeAll(sells);
boolean confidence = !simConfig.getConfidence() || myreliability >= simConfig.getConfidenceValue();
boolean confidence1 = !simConfig.getConfidencetrendincrease() || onerun.trendInc[0] >= simConfig.getConfidencetrendincreaseTimes();
boolean noconfidence2 = simConfig.getNoconfidencetrenddecrease() && onerun.trendDec[0] >= simConfig.getNoconfidencetrenddecreaseTimes();
boolean noconfidence = !confidence || !confidence1 || noconfidence2;
List<SimulateStock> nextstocks = new ArrayList<>();
if (!noconfidence) {
nextstocks = confidenceBuyHoldSell(simConfig, data.stockDates, data.getCatValMap(simConfig.getInterpolate()), onerun.adviser, myExcludes,
aParameter, onerun.mystocks, sells, buys, holdIncrease, mydate);
} else {
nextstocks = noConfidenceHoldSell(onerun.mystocks, holdIncrease, sells, simConfig);
}
sells = addEvent(onerun, sells, "SELL", getBSIndexOffset(mydate, simConfig));
buys = addEvent(onerun, buys, "BUY", getBSIndexOffset(mydate, simConfig));
if (true) {
if (getBSValueIndexOffset(mydate, simConfig) >= endIndexOffset) {
doBuySell(simConfig, onerun, results, data, mydate.indexOffset, stockDatesBiMap);
}
if (true) {
List<String> myids = onerun.mystocks.stream().map(SimulateStock::getId).collect(Collectors.toList());
if (myids.size() != onerun.mystocks.size()) {
log.error("Sizes");
}
// to delay?
update(data.getCatValMap(simConfig.getInterpolate()), onerun.mystocks, getValueIndexOffset(mydate, simConfig), new ArrayList<>(), mydate.prevIndexOffset + extradelay, endIndexOffset);
if (trend != null && trend.incAverage != 0) {
onerun.resultavg *= trend.incAverage;
}
// depends on delay DELAY
Capital sum = getSum(onerun.mystocks);
//boolean noconf = simConfig.getConfidence() && myreliability < simConfig.getConfidenceValue();
String hasNoConf = noconfidence ? "NOCONF" : "";
String historydatestring = TimeUtil.convertDate2(mydate.date); //data.stockDates.get(data.stockDates.size() - 1 - (mydate.indexOffset - extradelay - simConfig.getDelay()));
List<String> ids = onerun.mystocks.stream().map(SimulateStock::getId).collect(Collectors.toList());
if (!evolving) {
if (offset == 0) {
String adv = auto ? " Adv" + simConfig.getAdviser() : "";
results.sumHistory.add(historydatestring + " " + onerun.capital.toString() + " " + sum.toString() + " " + new MathUtil().round(onerun.resultavg, 2) + " " + hasNoConf + " " + ids + " " + trend + adv);
results.plotDates.add(historydatestring);
results.plotDefault.add(onerun.resultavg);
results.plotCapital.add(sum.amount + onerun.capital.amount);
} else {
results.plotDates.add(historydatestring);
}
} else {
results.plotDates.add(historydatestring);
results.plotCapital.add(sum.amount + onerun.capital.amount);
Integer adv = auto ? simConfig.getAdviser() : null;
Capital aCapital = new Capital();
aCapital.amount = onerun.capital.amount;
// no interpolation for trend
String trendStr = getTrendIncDecStr(data.stockDates, onerun.trendInc, onerun.trendDec, getValueIndexOffset(mydate, simConfig), data.getTrendStrMap(false /*simConfig.getInterpolate()*/));
StockHistory aHistory = new StockHistory(historydatestring, aCapital, sum, onerun.resultavg, hasNoConf, ids, trendStr, adv);
results.history.add(aHistory);
}
if (Double.isInfinite(onerun.resultavg)) {
int jj = 0;
}
onerun.runs++;
if (myavg > trend.incAverage) {
onerun.beatavg++;
}
}
}
if (!lastInvest) {
// in last too?
// 1
for (int j = 1; j < simConfig.getInterval(); j++) {
if (mydate.indexOffset - j < endIndexOffset) {
break;
}
if (getBSValueIndexOffset(mydate, simConfig) - j >= endIndexOffset) {
doBuySell(simConfig, onerun, results, data, mydate.indexOffset - j, stockDatesBiMap);
}
sells = new ArrayList<>();
//System.out.println(interval + " " + j);
if (simConfig.getStoploss()) {
// TODO delay DELAY
stoploss(onerun.mystocks, data.stockDates, getValueIndexOffset(mydate, simConfig) - j, data.getCatValMap(simConfig.getInterpolate()), getValueIndexOffset(mydate, simConfig) - j + 1, sells, simConfig.getStoplossValue(), "STOP", stockDatesBiMap, endIndexOffset);
}
sells = addEvent(onerun, sells, "SELL", getBSIndexOffset(mydate, simConfig) - j);
//addEvent(onerun, buys, "BUY", mydate.indexOffset - j - simConfig.getDelay() - extradelay);
if (getBSValueIndexOffset(mydate, simConfig) - j >= endIndexOffset) {
doBuySell(simConfig, onerun, results, data, mydate.indexOffset - j, stockDatesBiMap);
}
//sell(data.stockDates, data.getCatValMap(simConfig.getInterpolate()), onerun.capital, sells, results.stockhistory, mydate.indexOffset - j - extradelay - simConfig.getDelay(), mydate.date, onerun.mystocks, stockDatesBiMap);
if (offset == 0 && !sells.isEmpty()) {
boolean last = mydate.indexOffset - j == endIndexOffset;
boolean aLastInvest = offset == 0 && last /*date.isAfter(lastInvestEnd) && j == simConfig.getInterval() - 1*/;
if (aLastInvest && isMain) {
List<String> ids = onerun.mystocks.stream().map(SimulateStock::getId).collect(Collectors.toList());
List<String> sellids = sells.stream().map(SimulateStock::getId).collect(Collectors.toList());
//ids.removeAll(sellids);
param.getUpdateMap().put(SimConstants.LASTBUYSELL, "Stoploss sell: " + sellids + " Stocks: " + ids);
} else {
int jj = 0;
}
}
}
} else {
if (!evolving && offset == 0) {
List<String> ids = onerun.mystocks.stream().map(SimulateStock::getId).collect(Collectors.toList());
List<String> buyids = buys.stream().map(SimulateStock::getId).collect(Collectors.toList());
List<String> sellids = sells.stream().map(SimulateStock::getId).collect(Collectors.toList());
if (!noconfidence) {
int buyCnt = simConfig.getStocks() - nextstocks.size();
buyCnt = Math.min(buyCnt, buys.size());
//ids.addAll(buyids.subList(0, buyCnt));
buyids = buyids.subList(0, buyCnt);
} else {
buyids.clear();
}
//ids.removeAll(sellids);
if (isMain) {
param.getUpdateMap().put(SimConstants.LASTBUYSELL, "Buy: " + buyids + " Sell: " + sellids + " Stocks: " + ids);
}
}
}
}
private List<SimulateStock> addEvent(OneRun onerun, List<SimulateStock> stocks, String bs, int myIndexoffset) {
if (stocks == null || stocks.isEmpty()) {
return stocks;
}
List<SimulateStock> filterStocks = getFilterStocks(onerun, stocks);
if (filterStocks == null || filterStocks.isEmpty()) {
return filterStocks;
}
Map<String, List<SimulateStock>> aBSMap = new HashMap<>();
aBSMap.put(bs, filterStocks);
Map<String, List<SimulateStock>> bsMap = onerun.eventMap.computeIfAbsent(myIndexoffset, k -> new HashMap<>());
bsMap.putAll(aBSMap);
return filterStocks;
}
private List<SimulateStock> getFilterStocks(OneRun onerun, List<SimulateStock> stocks) {
List<SimulateStock> filterStocks = new ArrayList<>();
for (SimulateStock stock : stocks) {
boolean found = false;
for (Entry<Integer, Map<String, List<SimulateStock>>> entry : onerun.eventMap.entrySet()) {
Map<String, List<SimulateStock>> aMap = entry.getValue();
for (Entry<String, List<SimulateStock>> anEntry : aMap.entrySet()) {
if (anEntry.getValue().contains(stock)) {
found = true;
}
}
}
if (!found) {
filterStocks.add(stock);
}
}
return filterStocks;
}
private void doBuySell(SimulateInvestConfig simConfig, OneRun onerun, Results results, Data data, int indexOffset,
BiMap<String, LocalDate> stockDatesBiMap) {
Map<String, List<SimulateStock>> myMaps = onerun.eventMap.remove(indexOffset);
if (myMaps != null) {
List<SimulateStock> mySells = myMaps.remove("SELL");
if (mySells != null) {
sell(data.stockDates, data.getCatValMap(simConfig.getInterpolate()), onerun.capital, mySells, results.stockhistory, indexOffset, onerun.mystocks, stockDatesBiMap);
}
List<SimulateStock> myBuys = myMaps.remove("BUY");
if (myBuys != null) {
buy(data.stockDates, data.getCatValMap(simConfig.getInterpolate()), onerun.capital, simConfig.getStocks(), onerun.mystocks, myBuys, indexOffset, stockDatesBiMap);
}
}
}
private BiMap<String, LocalDate> getStockDatesBiMap(String market, List<String> stockDates) {
String key = CacheConstants.DATESMAP + market; // + config.getDate();
BiMap<String, LocalDate> list = (BiMap<String, LocalDate>) MyCache.getInstance().get(key);
if (list != null) {
return list;
}
list = createStockDatesBiMap(stockDates);
MyCache.getInstance().put(key, list);
return list;
}
private BiMap<String, LocalDate> createStockDatesBiMap(List<String> stockDates) {
BiMap<String, LocalDate> biMap = HashBiMap.create();
for (String aDate : stockDates) {
try {
LocalDate date = TimeUtil.convertDate(aDate);
biMap.put(aDate, date);
} catch (ParseException e) {
log.error(Constants.EXCEPTION, e);
}
}
return biMap;
}
private List<SimulateStock> copy(List<SimulateStock> mystocks) {
List<SimulateStock> list = new ArrayList<>();
for (SimulateStock stock : mystocks) {
SimulateStock copy = stock.copy();
list.add(copy);
}
return list;
}
private List<String> getExclusions(SimulateInvestConfig simConfig, List<String> stockDates, List<String> configExcludeList,
int indexOffset, Map<Integer, List<String>> newVolumeMap) {
List<String> myExcludes = new ArrayList<>();
List<String> volumeExcludes = new ArrayList<>();
/*
getVolumeExcludes(simConfig, extradelay, stockDates, interval, categoryValueMap, volumeMap, delay,
indexOffset, volumeExcludes);
*/
long time0 = System.currentTimeMillis();
getVolumeExcludes(simConfig, stockDates, indexOffset, volumeExcludes, newVolumeMap);
//log.info("timed0 {}", System.currentTimeMillis() - time0);
myExcludes.addAll(configExcludeList);
myExcludes.addAll(volumeExcludes);
return myExcludes;
}
private Trend getTrendIncDec(List<String> stockDates, Integer[] trendInc, Integer[] trendDec, int indexOffset,
Map<Integer, Trend> trendMap) {
int idx = stockDates.size() - 1 - indexOffset;
Trend trend = trendMap.get(idx);
if (trend == null) {
int jj = 0;
}
if (trend != null && trend.incAverage < 0) {
int jj = 0;
}
log.debug("Trend {}", trend);
if (trend != null) {
if (trend.incAverage > 1) {
trendInc[0]++;
trendDec[0] = 0;
} else {
trendInc[0] = 0;
trendDec[0]++;
}
}
return trend;
}
private String getTrendIncDecStr(List<String> stockDates, Integer[] trendInc, Integer[] trendDec, int indexOffset,
Map<Integer, String> trendMap) {
int idx = stockDates.size() - 1 - indexOffset;
String trend = trendMap.get(idx);
return trend;
}
private Map<Integer, Trend> getTrendIncDec(Market market, ComponentData param, List<String> stockDates, int interval,
int firstidx, int lastidx, SimulateInvestConfig simConfig, Data data, boolean interpolate) {
Map<Integer, Trend> trendMap = null;
String key = CacheConstants.SIMULATEINVESTTREND + market.getConfig().getMarket() + "_" + interval + "_" + simConfig.getStartdate() + simConfig.getEnddate() + interpolate;
trendMap = (Map<Integer, Trend>) MyCache.getInstance().get(key);
Map<Integer, Trend> newTrendMap = null;
if (trendMap == null || VERIFYCACHE) {
long time0 = System.currentTimeMillis();
try {
newTrendMap = new TrendUtil().getTrend(interval, null, stockDates, param, market, data.getFilterCatValMap(interpolate), firstidx, lastidx);
} catch (Exception e) {
log.error(Constants.ERROR, e);
}
log.debug("time millis {}", System.currentTimeMillis() - time0);
}
if (VERIFYCACHE && trendMap != null) {
for (Entry<Integer, Trend> entry : newTrendMap.entrySet()) {
int key2 = entry.getKey();
Trend v2 = entry.getValue();
Trend v = trendMap.get(key2);
if (v2 != null && !v2.toString().equals(v.toString())) {
log.error("Difference with cache");
}
}
}
if (trendMap != null) {
return trendMap;
}
trendMap = newTrendMap;
MyCache.getInstance().put(key, trendMap);
return trendMap;
}
private Map<Integer, String> getTrendIncDecStr(Market market, ComponentData param, List<String> stockDates, int interval,
int firstidx, int lastidx, SimulateInvestConfig simConfig, Data data, boolean interpolate, Map<Integer, Trend> trendMap) {
Map<Integer, String> trendStrMap = null;
String key = CacheConstants.SIMULATEINVESTTREND + market.getConfig().getMarket() + "_" + interval + "_" + simConfig.getStartdate() + simConfig.getEnddate() + interpolate + "str";
trendStrMap = (Map<Integer, String>) MyCache.getInstance().get(key);
if (trendStrMap != null) {
return trendStrMap;
}
trendStrMap = new HashMap<>();
for (Entry<Integer, Trend> entry : trendMap.entrySet()) {
Integer aKey = entry.getKey();
Trend trend = entry.getValue();
trendStrMap.put(aKey, trend.toString());
}
MyCache.getInstance().put(key, trendStrMap);
return trendStrMap;
}
@Deprecated
private void getVolumeExcludes(SimulateInvestConfig simConfig, int extradelay, List<String> stockDates,
int interval, Map<String, List<List<Double>>> categoryValueMap,
Map<String, List<List<Object>>> volumeMap, int delay, int indexOffset, List<String> volumeExcludes) {
if (simConfig.getVolumelimits() != null) {
Map<String, Double> volumeLimits = simConfig.getVolumelimits();
for (Entry<String, List<List<Double>>> entry : categoryValueMap.entrySet()) {
String id = entry.getKey();
int anOffset = indexOffset /* - extradelay - delay */;
int len = interval * 2;
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
int size = mainList.size();
int first = size - anOffset - len;
if (first < 0) {
first = 0;
}
List<List<Object>> list = volumeMap.get(id);
String currency = null;
for (int i = 0; i < list.size(); i++) {
currency = (String) list.get(i).get(1);
if (currency != null) {
break;
}
}
Double limit = volumeLimits.get(currency);
if (limit == null) {
continue;
}
double sum = 0.0;
int count = 0;
for (int i = first; i <= size - 1 - anOffset; i++) {
Integer volume = (Integer) list.get(i).get(0);
if (volume != null) {
Double price = mainList.get(i /* mainList.size() - 1 - indexOffset */);
if (price == null) {
if (volume > 0) {
log.debug("Price null with volume > 0");
}
continue;
}
sum += volume * price;
count++;
}
}
if (count > 0 && sum / count < limit) {
volumeExcludes.add(id);
}
}
}
}
}
@Deprecated
private Map<String, double[]> getVolumeExcludesFull(SimulateInvestConfig simConfig, List<String> stockDates, int interval,
Map<String, List<List<Double>>> categoryValueMap, Map<String, List<List<Object>>> volumeMap) {
Map<String, double[]> newVolumeMap = new HashMap<>();
if (simConfig.getVolumelimits() != null) {
for (Entry<String, List<List<Double>>> entry : categoryValueMap.entrySet()) {
String id = entry.getKey();
int len = interval * 2;
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
List<List<Object>> list = volumeMap.get(id);
if (mainList != null) {
int size = mainList.size();
double[] newList = new double[size];
for (int i = 0; i < size; i++) {
Integer volume = (Integer) list.get(i).get(0);
Double price = mainList.get(i /* mainList.size() - 1 - indexOffset */);
if (volume != null) {
if (price == null) {
if (volume > 0) {
log.debug("Price null with volume > 0");
}
continue;
}
} else {
continue;
}
for (int j = 0; j < len; j++) {
int idx = i + j;
if (idx > size - 1) {
break;
}
newList[idx] += price * volume;
}
}
newVolumeMap.put(id, newList);
}
}
}
return newVolumeMap;
}
@Deprecated
private void getVolumeExcludes(SimulateInvestConfig simConfig, int extradelay, List<String> stockDates,
int interval, Map<String, List<List<Double>>> categoryValueMap,
Map<String, List<List<Object>>> volumeMap, int delay, int indexOffset, List<String> volumeExcludes, Map<String, double[]> newVolumeMap) {
if (simConfig.getVolumelimits() != null) {
Map<String, Double> volumeLimits = simConfig.getVolumelimits();
int len = interval * 2;
for (Entry<String, List<List<Double>>> entry : categoryValueMap.entrySet()) {
String id = entry.getKey();
String currency = getCurrency(volumeMap, id);
Double limit = volumeLimits.get(currency);
if (limit == null) {
continue;
}
int count = len;
double[] sums = newVolumeMap.get(id);
int idx = sums.length - 1 - indexOffset;
if (idx < count) {
count = idx;
}
double sum = sums[idx];
if (count > 0 && sum / count < limit) {
volumeExcludes.add(id);
}
}
}
}
private String getCurrency(Map<String, List<List<Object>>> volumeMap, String id) {
String currency = null;
List<List<Object>> list = volumeMap.get(id);
for (int i = list.size() - 1; i >= 0; i--) {
currency = (String) list.get(i).get(1);
if (currency != null) {
break;
}
}
return currency;
}
private Map<Integer, List<String>> getVolumeExcludesFull(SimulateInvestConfig simConfig, int interval, Map<String, List<List<Double>>> categoryValueMap,
Map<String, List<List<Object>>> volumeMap, int firstidx, int lastidx) {
Map<Integer, List<String>> listlist = new HashMap<>();
if (simConfig.getVolumelimits() != null) {
Map<String, Double> volumeLimits = simConfig.getVolumelimits();
for (Entry<String, List<List<Double>>> entry : categoryValueMap.entrySet()) {
String id = entry.getKey();
String currency = getCurrency(volumeMap, id);
Double limit = volumeLimits.get(currency);
if (limit == null) {
continue;
}
int len = interval * 2;
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
List<List<Object>> list = volumeMap.get(id);
if (mainList != null) {
int size = mainList.size();
MutablePair<Double, Integer>[] newList = new MutablePair[size];
int start = size - 1 - firstidx;
int end = size - 1 - lastidx;
for (int i = start; i <= end; i++) {
Integer volume = (Integer) list.get(i).get(0);
Double price = mainList.get(i /* mainList.size() - 1 - indexOffset */);
if (volume != null) {
if (price == null) {
if (volume > 0) {
log.debug("Price null with volume > 0");
}
continue;
}
} else {
continue;
}
for (int j = 0; j < len; j++) {
int idx = i + j;
if (idx > size - 1) {
break;
}
MutablePair<Double, Integer> pair = newList[idx];
if (pair == null) {
pair = new MutablePair(0.0, 0);
newList[idx] = pair;
}
pair.setLeft(pair.getLeft() + price * volume);
pair.setRight(pair.getRight() + 1);
}
}
// now make the skip lists
int count = len;
Pair<Double, Integer>[] sums = newList;
for (int i = start; i <= end; i++) {
List<String> datedlist = listlist.get(i);
if (datedlist == null) {
datedlist = new ArrayList<>();
listlist.put(i, datedlist);
}
int idx = i;
if (idx < count) {
count = idx;
}
Pair<Double, Integer> pair = sums[idx];
if (pair == null) {
datedlist.add(id);
continue;
}
Double sum = pair.getLeft();
Integer count2 = pair.getRight();
if (count2 != null && count != count2) {
int jj = 0;
}
if (count2 != null && count2 == 0) {
int jj = 0;
}
if (count2 != 0 && sum / count2 < limit) {
datedlist.add(id);
}
}
}
}
}
Set<Integer> keys = listlist.keySet();
List<Integer> keylist = new ArrayList<>(keys);
Collections.sort(keylist);
log.debug("keylist {}", keylist);
for (int key : keylist) {
log.debug("keylist size {} {}", key, listlist.get(key).size());
}
return listlist;
}
private void getVolumeExcludes(SimulateInvestConfig simConfig, List<String> stockDates, int indexOffset,
List<String> volumeExcludes, Map<Integer, List<String>> listlist) {
if (simConfig.getVolumelimits() != null) {
int idx = stockDates.size() - 1 - indexOffset;
if (idx < 0) {
return;
}
List<String> list = listlist.get(idx);
if (list == null) {
return;
}
volumeExcludes.addAll(list);
}
}
private List<SimulateStock> confidenceBuyHoldSell(SimulateInvestConfig simConfig, List<String> stockDates,
Map<String, List<List<Double>>> categoryValueMap, Adviser adviser, List<String> excludeList,
String aParameter, List<SimulateStock> mystocks, List<SimulateStock> sells, List<SimulateStock> buys, List<SimulateStock> holdIncrease,
Mydate mydate) {
List<SimulateStock> hold;
if (simConfig.getConfidenceholdincrease() == null || simConfig.getConfidenceholdincrease()) {
hold = holdIncrease;
} else {
hold = new ArrayList<>();
}
List<String> anExcludeList = new ArrayList<>(excludeList);
List<String> ids1 = sells.stream().map(SimulateStock::getId).collect(Collectors.toList());
List<String> ids2 = hold.stream().map(SimulateStock::getId).collect(Collectors.toList());
anExcludeList.addAll(ids1);
anExcludeList.addAll(ids2);
Set<String> anExcludeSet = new LinkedHashSet<>(anExcludeList);
// full list
List<String> myincl = adviser.getIncs(aParameter, simConfig.getStocks(), getValueIndexOffset(mydate, simConfig), stockDates, anExcludeList);
Set<String> myincs = new LinkedHashSet<>(myincl);
//myincs = new ArrayList<>(myincs);
myincs.removeAll(anExcludeSet);
//List<IncDecItem> myincs = ds.getIncs(valueList);
//List<ValueList> valueList = ds.getValueList(categoryValueMap, indexOffset);
// full list, except if null value
//int delay = simConfig.getDelay();
List<SimulateStock> buysTmp = getBuyList(categoryValueMap, myincs, simConfig.getStocks());
myincs = null;
//buysTmp = filter(buysTmp, sells);
List<SimulateStock> keeps = keep(mystocks, buysTmp);
keeps.addAll(hold);
buysTmp = filter(buysTmp, mystocks);
//buysTmp = buysTmp.subList(0, Math.min(buysTmp.size(), simConfig.getStocks() - mystocks.size()));
buys.clear();
buys.addAll(buysTmp);
List<SimulateStock> newsells = filter(mystocks, keeps);
//mystocks.removeAll(newsells);
myAddAll(sells, newsells);
mystocks = keeps;
return mystocks;
}
private List<SimulateStock> noConfidenceHoldSell(List<SimulateStock> mystocks, List<SimulateStock> holdIncrease, List<SimulateStock> sells, SimulateInvestConfig simConfig) {
List<SimulateStock> keeps;
if (simConfig.getNoconfidenceholdincrease() == null || simConfig.getNoconfidenceholdincrease()) {
keeps = holdIncrease;
} else {
keeps = new ArrayList<>();
}
List<SimulateStock> newsells = filter(mystocks, keeps);
//mystocks.removeAll(newsells);
myAddAll(sells, newsells);
mystocks = keeps;
return mystocks;
}
private SimulateInvestConfig getSimConfig(IclijConfig config) {
if (config.getConfigValueMap().get(IclijConfigConstants.SIMULATEINVESTDELAY) == null || (int) config.getConfigValueMap().get(IclijConfigConstants.SIMULATEINVESTDELAY) == 0) {
return null;
}
SimulateInvestConfig simConfig = new SimulateInvestConfig();
simConfig.setAdviser(config.getSimulateInvestAdviser());
simConfig.setBuyweight(config.wantsSimulateInvestBuyweight());
simConfig.setConfidence(config.wantsSimulateInvestConfidence());
simConfig.setConfidenceValue(config.getSimulateInvestConfidenceValue());
simConfig.setConfidenceFindTimes(config.getSimulateInvestConfidenceFindtimes());
simConfig.setAbovebelow(config.getSimulateInvestAboveBelow());
simConfig.setConfidenceholdincrease(config.wantsSimulateInvestConfidenceHoldIncrease());
simConfig.setNoconfidenceholdincrease(config.wantsSimulateInvestNoConfidenceHoldIncrease());
simConfig.setConfidencetrendincrease(config.wantsSimulateInvestConfidenceTrendIncrease());
simConfig.setConfidencetrendincreaseTimes(config.wantsSimulateInvestConfidenceTrendIncreaseTimes());
simConfig.setNoconfidencetrenddecrease(config.wantsSimulateInvestNoConfidenceTrendDecrease());
simConfig.setNoconfidencetrenddecreaseTimes(config.wantsSimulateInvestNoConfidenceTrendDecreaseTimes());
try {
simConfig.setImproveFilters(config.getSimulateInvestImproveFilters());
} catch (Exception e) {
int jj = 0;
}
simConfig.setInterval(config.getSimulateInvestInterval());
simConfig.setIndicatorPure(config.wantsSimulateInvestIndicatorPure());
simConfig.setIndicatorRebase(config.wantsSimulateInvestIndicatorRebase());
simConfig.setIndicatorReverse(config.wantsSimulateInvestIndicatorReverse());
simConfig.setIndicatorDirection(config.wantsSimulateInvestIndicatorDirection());
simConfig.setIndicatorDirectionUp(config.wantsSimulateInvestIndicatorDirectionUp());
simConfig.setMldate(config.wantsSimulateInvestMLDate());
try {
simConfig.setPeriod(config.getSimulateInvestPeriod());
} catch (Exception e) {
int jj = 0;
}
simConfig.setStoploss(config.wantsSimulateInvestStoploss());
simConfig.setStoplossValue(config.getSimulateInvestStoplossValue());
simConfig.setIntervalStoploss(config.wantsSimulateInvestIntervalStoploss());
simConfig.setIntervalStoplossValue(config.getSimulateInvestIntervalStoplossValue());
simConfig.setStocks(config.getSimulateInvestStocks());
simConfig.setInterpolate(config.wantsSimulateInvestInterpolate());
simConfig.setDay(config.getSimulateInvestDay());
simConfig.setDelay(config.getSimulateInvestDelay());
try {
simConfig.setFuturecount(config.getSimulateInvestFutureCount());
simConfig.setFuturetime(config.getSimulateInvestFutureTime());
} catch (Exception e) {
}
Map<String, Double> map = JsonUtil.convert(config.getSimulateInvestVolumelimits(), Map.class);
simConfig.setVolumelimits(map);
SimulateFilter[] array = JsonUtil.convert(config.getSimulateInvestFilters(), SimulateFilter[].class);
List<SimulateFilter> list = null;
if (array != null) {
list = Arrays.asList(array);
}
simConfig.setFilters(list);
try {
simConfig.setEnddate(config.getSimulateInvestEnddate());
} catch (Exception e) {
}
try {
simConfig.setStartdate(config.getSimulateInvestStartdate());
} catch (Exception e) {
}
return simConfig;
}
private List<SimulateFilter> get(String json) {
SimulateFilter[] array = JsonUtil.convert(json, SimulateFilter[].class);
List<SimulateFilter> list = null;
if (array != null) {
list = Arrays.asList(array);
}
return list;
}
private AutoSimulateInvestConfig getAutoSimConfig(IclijConfig config) {
if (config.getConfigValueMap().get(IclijConfigConstants.AUTOSIMULATEINVESTINTERVAL) == null || (int) config.getConfigValueMap().get(IclijConfigConstants.AUTOSIMULATEINVESTINTERVAL) == 0) {
return null;
}
AutoSimulateInvestConfig simConfig = new AutoSimulateInvestConfig();
simConfig.setInterval(config.getAutoSimulateInvestInterval());
simConfig.setIntervalwhole(config.getAutoSimulateInvestIntervalwhole());
simConfig.setImproveFilters(config.getAutoSimulateInvestImproveFilters());
simConfig.setPeriod(config.getAutoSimulateInvestPeriod());
simConfig.setLastcount(config.getAutoSimulateInvestLastCount());
simConfig.setDellimit(config.getAutoSimulateInvestDelLimit());
simConfig.setScorelimit(config.getAutoSimulateInvestScoreLimit());
simConfig.setAutoscorelimit(config.getAutoSimulateInvestAutoScoreLimit());
simConfig.setKeepAdviser(config.getAutoSimulateInvestKeepAdviser());
simConfig.setKeepAdviserLimit(config.getAutoSimulateInvestKeepAdviserLimit());
simConfig.setVote(config.getAutoSimulateInvestVote());
simConfig.setFuturecount(config.getAutoSimulateInvestFutureCount());
simConfig.setFuturetime(config.getAutoSimulateInvestFutureTime());
Map<String, Double> map = JsonUtil.convert(config.getAutoSimulateInvestVolumelimits(), Map.class);
simConfig.setVolumelimits(map);
SimulateFilter[] array = JsonUtil.convert(config.getAutoSimulateInvestFilters(), SimulateFilter[].class);
List<SimulateFilter> list = null;
if (array != null) {
list = Arrays.asList(array);
}
simConfig.setFilters(list);
try {
simConfig.setEnddate(config.getAutoSimulateInvestEnddate());
} catch (Exception e) {
}
try {
simConfig.setStartdate(config.getAutoSimulateInvestStartdate());
} catch (Exception e) {
}
return simConfig;
}
private String emptyNull(Object object) {
if (object == null) {
return "";
} else {
return "" + object;
}
}
private String emptyNull(Object object, String defaults) {
if (object == null) {
return defaults;
} else {
return "" + object;
}
}
private List<SimulateStock> filter(List<SimulateStock> stocks, List<SimulateStock> others) {
List<String> ids = others.stream().map(SimulateStock::getId).collect(Collectors.toList());
return stocks.stream().filter(e -> !ids.contains(e.getId())).collect(Collectors.toList());
}
private List<SimulateStock> keep(List<SimulateStock> stocks, List<SimulateStock> others) {
List<String> ids = others.stream().map(SimulateStock::getId).collect(Collectors.toList());
return stocks.stream().filter(e -> ids.contains(e.getId())).collect(Collectors.toList());
}
private Capital getSum(List<SimulateStock> mystocks) {
Capital sum = new Capital();
for (SimulateStock astock : mystocks) {
sum.amount += astock.getCount() * astock.getPrice();
}
return sum;
}
@Override
public ComponentData improve(MarketActionData action, ComponentData componentparam, Market market, ProfitData profitdata,
Memories positions, Boolean buy, String subcomponent, Parameters parameters, boolean wantThree,
List<MLMetricsItem> mlTests, Fitness fitness, boolean save) {
return null;
}
@Override
public MLConfigs getOverrideMLConfig(ComponentData componentdata) {
return null;
}
@Override
public void calculateIncDec(ComponentData param, ProfitData profitdata, Memories positions, Boolean above,
List<MLMetricsItem> mlTests, Parameters parameters) {
}
@Override
public List<MemoryItem> calculateMemory(ComponentData param, Parameters parameters) throws Exception {
return null;
}
@Override
public String getPipeline() {
return PipelineConstants.SIMULATEINVEST;
}
@Override
protected List<String> getConfList() {
return null;
}
@Override
public String getThreshold() {
return null;
}
@Override
public String getFuturedays() {
return null;
}
public Object[] calculateAccuracy(ComponentData componentparam) throws Exception {
return new Object[] { componentparam.getScoreMap().get(SimConstants.SCORE) };
}
private double increase(List<SimulateStock> mystocks, int indexOffset, Map<String, List<List<Double>>> categoryValueMap, int prevIndexOffset, int endIndexOffset) {
List<Double> incs = new ArrayList<>();
for (SimulateStock item : mystocks) {
String id = item.getId();
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
if (indexOffset < endIndexOffset) {
continue;
}
Double valNow = mainList.get(mainList.size() - 1 - indexOffset);
if (prevIndexOffset < endIndexOffset) {
continue;
}
Double valWas = mainList.get(mainList.size() - 1 - prevIndexOffset);
if (valWas != null && valNow != null) {
double inc = valNow / valWas;
incs.add(inc);
}
} else {
// put back if unknown
//mystocks.add(item);
}
}
if (incs.isEmpty()) {
return 1.0;
}
OptionalDouble average = incs
.stream()
.mapToDouble(a -> a)
.average();
return average.getAsDouble();
}
private double getReliability(List<SimulateStock> mystocks, Pair<Integer, Integer>[] hits, int findTimes, int up) {
Pair<Integer, Integer> pair = new ImmutablePair(up, mystocks.size());
for (int j = findTimes - 1; j > 0; j--) {
hits[j] = hits[j - 1];
}
hits[0] = pair;
double count = 0;
int total = 0;
for (Pair<Integer, Integer> aPair : hits) {
if (aPair == null) {
continue;
}
count += aPair.getLeft();
total += aPair.getRight();
}
double reliability = 1;
if (total > 0) {
reliability = count / total;
}
return reliability;
}
private void stoploss(List<SimulateStock> mystocks, List<String> stockDates, int indexOffset, Map<String, List<List<Double>>> categoryValueMap, int prevIndexOffset,
List<SimulateStock> sells, double stoploss, String stop, BiMap<String, LocalDate> stockDatesBiMap, int endIndexOffset) {
List<SimulateStock> newSells = new ArrayList<>();
for (SimulateStock item : mystocks) {
String id = item.getId();
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
String dateNowStr = stockDates.get(stockDates.size() - 1 - indexOffset);
LocalDate dateNow = convertDate(stockDatesBiMap, dateNowStr);
if (!dateNow.isAfter(item.getBuydate())) {
continue;
}
Double valNow = mainList.get(mainList.size() - 1 - indexOffset);
if (prevIndexOffset < endIndexOffset) {
int jj = 0;
continue;
}
Double valWas = mainList.get(mainList.size() - 1 - prevIndexOffset);
if (valWas != null && valNow != null && valNow != 0 && valWas != 0 && valNow / valWas < stoploss) {
log.debug("Id etc {} {} {} {} {} {} {}", stop, id, valWas, valNow, dateNowStr, prevIndexOffset, indexOffset);
item.setStatus(stop);
newSells.add(item);
}
}
}
//mystocks.removeAll(newSells);
myAddAll(sells, newSells);
}
private LocalDate convertDate(BiMap<String, LocalDate> stockDatesBiMap, String dateStr) {
LocalDate date = stockDatesBiMap.get(dateStr);
if (date != null) {
return date;
}
try {
date = TimeUtil.convertDate(dateStr);
} catch (ParseException e) {
log.error(Constants.EXCEPTION, e);
}
return date;
}
private void buy(List<String> stockDates, Map<String, List<List<Double>>> categoryValueMap, Capital capital, int buytop, List<SimulateStock> mystocks, List<SimulateStock> newbuys, int indexOffset, BiMap<String, LocalDate> stockDatesBiMap) {
int buys = buytop - mystocks.size();
buys = Math.min(buys, newbuys.size());
double totalamount = 0;
for (int i = 0; i < buys; i++) {
SimulateStock astock = newbuys.get(i);
String id = astock.getId();
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
Double valNow = mainList.get(mainList.size() - 1 - indexOffset);
if (valNow != null) {
double amount = 0;
amount = capital.amount / buys;
astock.setBuyprice(valNow);
astock.setCount(amount / astock.getBuyprice());
String dateNow = stockDates.get(stockDates.size() - 1 - indexOffset);
LocalDate date = convertDate(stockDatesBiMap, dateNow);
astock.setBuydate(date);
mystocks.add(astock);
totalamount += amount;
} else {
log.error("Not found");
}
}
}
capital.amount -= totalamount;
}
private int update(Map<String, List<List<Double>>> categoryValueMap, List<SimulateStock> mystocks, int indexOffset,
List<SimulateStock> noConfKeep, int prevIndexOffset, int endIndexOffset) {
int up = 0;
for (SimulateStock item : mystocks) {
String id = item.getId();
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
if (indexOffset < endIndexOffset) {
int jj = 0;
}
Double valNow = mainList.get(mainList.size() - 1 - indexOffset);
if (valNow != null) {
item.setPrice(valNow);
} else {
if (item.getPrice() == 0.0) {
item.setPrice(item.getBuyprice());
}
}
if (prevIndexOffset < endIndexOffset) {
continue;
}
Double valWas = mainList.get(mainList.size() - 1 - prevIndexOffset);
if (valNow != null && valWas != null) {
if (valNow > valWas) {
up++;
noConfKeep.add(item);
}
}
}
}
return up;
}
private void sell(List<String> stockDates, Map<String, List<List<Double>>> categoryValueMap, Capital capital,
List<SimulateStock> sells, List<SimulateStock> stockhistory, int indexOffset, List<SimulateStock> mystocks, BiMap<String, LocalDate> stockDatesBiMap) {
for (SimulateStock item : sells) {
String id = item.getId();
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
Double valNow = mainList.get(mainList.size() - 1 - indexOffset);
if (valNow != null) {
item.setSellprice(valNow);
String dateNow = stockDates.get(stockDates.size() - 1 - indexOffset);
LocalDate date = convertDate(stockDatesBiMap, dateNow);
item.setSelldate(date);
stockhistory.add(item);
capital.amount += item.getCount() * item.getSellprice();
mystocks.remove(item);
} else {
// put back if unknown
//mystocks.add(item);
}
} else {
// put back if unknown
//mystocks.add(item);
}
}
}
private List<SimulateStock> getSellList(List<SimulateStock> mystocks, List<SimulateStock> newbuys) {
List<String> myincids = newbuys.stream().map(SimulateStock::getId).collect(Collectors.toList());
return mystocks.stream().filter(e -> !myincids.contains(e.getId())).collect(Collectors.toList());
}
private List<SimulateStock> getBuyList(Map<String, List<List<Double>>> categoryValueMap, Set<String> myincs,
Integer count) {
List<SimulateStock> newbuys = new ArrayList<>();
for (String id : myincs) {
List<List<Double>> resultList = categoryValueMap.get(id);
if (resultList == null || resultList.isEmpty()) {
continue;
}
List<Double> mainList = resultList.get(0);
//ValidateUtil.validateSizes(mainList, stockDates);
if (mainList != null) {
SimulateStock astock = new SimulateStock();
astock.setId(id);
//astock.price = -1;
newbuys.add(astock);
count--;
if (count == 0) {
break;
}
}
}
return newbuys;
}
private List<IncDecItem> getAllIncDecs(Market market, LocalDate investStart, LocalDate investEnd) {
try {
return IclijDbDao.getAllIncDecs(market.getConfig().getMarket(), investStart, investEnd, null);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
return new ArrayList<>();
}
private List<MemoryItem> getAllMemories(Market market, LocalDate investStart, LocalDate investEnd) {
try {
return IclijDbDao.getAllMemories(market.getConfig().getMarket(), IclijConstants.IMPROVEABOVEBELOW, PipelineConstants.ABOVEBELOW, null, null, investStart, investEnd);
// also filter on params
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
return new ArrayList<>();
}
private List<MetaItem> getAllMetas(ComponentData param) {
return param.getService().getMetas();
}
private void myAddAll(List<SimulateStock> mainList, List<SimulateStock> list) {
for (SimulateStock stock : list) {
if (!mainList.contains(stock)) {
mainList.add(stock);
}
}
}
private int getValueIndexOffset(Mydate mydate, SimulateInvestConfig simConfig) {
int extradelay = 0;
if (simConfig.getExtradelay() != null) {
extradelay = simConfig.getExtradelay();
}
return mydate.indexOffset + extradelay;
}
private int getBSIndexOffset(Mydate mydate, SimulateInvestConfig simConfig) {
int extradelay = 0;
if (simConfig.getExtradelay() != null) {
extradelay = simConfig.getExtradelay();
}
return mydate.indexOffset - extradelay - simConfig.getDelay();
}
private int getBSValueIndexOffset(Mydate mydate, SimulateInvestConfig simConfig) {
int extradelay = 0;
if (simConfig.getExtradelay() != null) {
extradelay = simConfig.getExtradelay();
}
return mydate.indexOffset - extradelay;
}
class OneRun {
Adviser adviser;
Capital capital;
int beatavg;
int runs;
List<SimulateStock> mystocks;
double resultavg;
List<SimulateStock> savedStocks;
boolean saveLastInvest;
Integer[] trendInc = new Integer[] { 0 };
Integer[] trendDec = new Integer[] { 0 };
Pair<Integer, Integer>[] hits;
Double autoscore;
List<SimulateStock> buys;
Map<Integer, Map<String, List<SimulateStock>>> eventMap = new HashMap<>();
}
class Results {
List<SimulateStock> stockhistory = new ArrayList<>();
List<StockHistory> history = new ArrayList<>();
List<String> sumHistory = new ArrayList<>();
List<String> plotDates = new ArrayList<>();
List<Double> plotCapital = new ArrayList<>();
List<Double> plotDefault = new ArrayList<>();
}
class Data {
int lastidx;
int firstidx;
Map<String, List<List<Double>>> categoryValueMap;
Map<String, List<List<Double>>> categoryValueFillMap;
Map<String, List<List<Double>>> filteredCategoryValueMap;
Map<String, List<List<Double>>> filteredCategoryValueFillMap;
List<String> stockDates;
Map<Integer, List<String>> volumeExcludeMap;
Map<Integer, List<String>> volumeExcludeFillMap;
List<String> configExcludeList;
Map<String, List<List<Object>>> volumeMap;
Map<Integer, Trend> trendMap;
Map<Integer, Trend> trendFillMap;
Map<Integer, String> trendStrMap;
Map<Integer, String> trendStrFillMap;
public Map<String, List<List<Double>>> getCatValMap(boolean interpolate) {
if (interpolate) {
return categoryValueFillMap;
} else {
return categoryValueMap;
}
}
public Map<String, List<List<Double>>> getFilterCatValMap(boolean interpolate) {
if (interpolate) {
return filteredCategoryValueFillMap;
} else {
return filteredCategoryValueMap;
}
}
public Map<Integer, List<String>> getVolumeExcludeMap(boolean interpolate) {
if (interpolate) {
return volumeExcludeFillMap;
} else {
return volumeExcludeMap;
}
}
public Map<Integer, Trend> getTrendMap(boolean interpolate) {
if (interpolate) {
return trendFillMap;
} else {
return trendMap;
}
}
public Map<Integer, String> getTrendStrMap(boolean interpolate) {
if (interpolate) {
return trendStrFillMap;
} else {
return trendStrMap;
}
}
}
class Mydate {
LocalDate date;
int indexOffset;
int prevIndexOffset;
}
// loop
// get u/n/d trend
// get exclusions, defaults + current low volume traded
// deprecated: get stocks increase
// updated stock prices, return eventual hold list
// check interval stoploss, move stocks to sell list
// calculate reliability
// calculate confidence
// if confidence
//// get recommendations
//// remove exclusions
//// eventually do hold
//// all not recommended nor on hold will be sold
// else
//// all not on hold will be sold
// sell
// buy
// update again
// calculate resultavg
// add to history lists
// loop
//// check 1 day stoploss, move stocks to sell list
//// sell
// lastbuy, get a new buy/sell recommendation
/*
*/
// sim will
// lucky shots / short runs
// config commons / invariants
// one company lucky percentage value / rerun without
// some lucky few days
// too few good results
/*
*/
// loop
// update values with indexoffset - extra
// get advise based on indexoffset info (TODO extra)
// get istoploss sells with indexoffset
// get buy list with indexoffset - delay - extra
// stoploss is based on indexoffset - extra
// algo 0
// loop
// get recommend for buy sell on date1
// sell buy on date1
// date1 = date1 + 1w
// calculate capital after 1w, new date1
// endloop
// #calculate capital after 1w
// # remember stoploss
// algo 1
// loop
// get findprofit recommendations from last week on date1
// ignore sell buy if not reliable lately
// sell buy
// date += 1w
// calc new capital
// endloop
// algo 2
// incr date by 1w
// loop
// date1
// stocklist
// check pr date1 top 5 for last 1m 1w etc
// if stocklist in top 5, keep, else sell
// buy stocklist in top 5
// date1 += 1w
// calc new capital
// endloop
// #get stocklist value
// use mach highest mom
// improve with ds
}
| Fix for date limit for simulate invest action (I220).
| iclij/iclij-common/iclij-component/src/main/java/roart/iclij/component/SimulateInvestComponent.java | Fix for date limit for simulate invest action (I220). | <ide><path>clij/iclij-common/iclij-component/src/main/java/roart/iclij/component/SimulateInvestComponent.java
<ide> int endIndexOffset = 0;
<ide> if (investEnd != null) {
<ide> String investEndStr = TimeUtil.convertDate2(investEnd);
<del> endIndexOffset = data.stockDates.size() - 1 - data.stockDates.indexOf(investEndStr);
<add> int investEndIndex = TimeUtil.getIndexEqualBefore(data.stockDates, investEndStr);
<add> endIndexOffset = data.stockDates.size() - 1 - investEndIndex;
<ide> }
<ide>
<ide> boolean intervalwhole;
<ide> mystocks.add(astock);
<ide> totalamount += amount;
<ide> } else {
<del> log.error("Not found");
<add> log.error("Not found {}", id);
<ide> }
<ide> }
<ide> } |
|
JavaScript | mpl-2.0 | 7da0ad6fcb4c90ea256d2683e141fbd6dea0d85f | 0 | mozilla/elmo,mozilla/elmo,mozilla/elmo,mozilla/elmo | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
$.aH = $.aH || {};
$.widget(
'aH.datetime',
{
options: {
date: undefined,
width: 300
},
_create: function() {
var that = this;
this._dateField = $('<input type="date" />')[0];
this._timeField = $('<input type="time" step="1" />')[0];
this.element.append(this._dateField)
.append(this._timeField)
.addClass('ui-widget');
this._dateField.onchange = () => this.date();
this._timeField.onchange = () => this.date();
this.date((this.options.date === undefined) ? new Date() :
new Date(this.options.date));
},
destroy: function() {
$.Widget.prototype.destroy.call(this);
this.element.removeClass('ui-widget');
},
_days: (30.5 * 24 * 60 * 60 * 1000),
date: function(newDate, dontFire) {
if (arguments.length) {
newDate.setMilliseconds(0);
this._date = newDate;
this._dateField.valueAsDate = this._date;
this._timeField.valueAsDate = this._date;
}
else {
this._date = new Date(
this._dateField.valueAsNumber + this._timeField.valueAsNumber
);
}
if (dontFire === undefined) {
this.element.triggerHandler(this.widgetName + "value",
[this._date]);
}
return this._date;
}
}
);
| apps/pushes/static/pushes/js/widgets.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
$.aH = $.aH || {};
$.widget('aH.spinner', $.ui.mouse, {
options: {
alpha: 120,
n: 5,
value: 0,
width: 150,
fly: 1,
// ui.mouse.defaults
distance: 1,
delay: 0,
cancel: null
},
_create: function() {
var that = this;
this._hovering = false;
that.element.append($('<table cellspacing="0" cellpadding="0" class="ui-widget ui-widget-content ui-state-default"><tr class="ui-state-hover ui-helper-hidden"></tr><tr><td><span class="ui-icon ui-icon-triangle-1-w">foo</span></td><td><canvas height="10" width="' +
that.options.width +
'"></canvas></td><td><span class="ui-icon ui-icon-triangle-1-e">foo</span></td></tr></table>'));
that.element.children('table')
.hover(function(){
$(this).addClass("ui-state-hover");
this._hovering = true;
},
function(){
$(this).removeClass("ui-state-hover");
this._hovering = false;
}
)
that._mouseInit();
that.computeSetup();
that.value(that.options.value);
},
destroy: function() {
$.Widget.prototype.destroy.call(this);
this._mouseDestroy();
},
computeSetup: function() {
this.canvas = this.element.find('canvas')[0];
this.ctx = this.canvas.getContext('2d');
this.r = this.canvas.width/2/Math.sin(this.options.alpha/2/180*Math.PI); //radius
this.rx = this.r * this.options.alpha * Math.PI / 360 / this.options.n; //px per tick
},
updateDisplay: function() {
var off = 1 - this._value % 1;
var end = off ? this.options.n - 1 : this.options.n;
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.beginPath();
this.ctx.strokeStyle = $('.ui-state-default').css('color');
for (var i = -this.options.n; i <= end; i += 1) {
var a = (i + off) * this.rx/this.r;
var x = this.r * Math.sin(a) + this.canvas.width/2;
this.ctx.moveTo(x, 0);
this.ctx.lineTo(x, this.canvas.height);
}
this.ctx.stroke();
},
_mouseStart: function(event) {
this.startValue = this.value();
this.element.children('table').removeClass('ui-state-hover')
.addClass('ui-state-active');
return true;
},
_mouseDrag: function(event) {
var dx = event.clientX - this._mouseDownEvent.clientX;
var now = Date.now();
if (this.previousValue) {
this.speed = (event.clientX - this.previousValue) /
(now - this.previousTime);
}
this.previousValue = event.clientX;
this.previousTime = now;
this.value(this.startValue - dx / this.rx);
},
_mouseStop: function(event) {
this.previousValue = null;
this.element.children('table').removeClass('ui-state-active');
if (this._hovering) this.elememnt.children('table').addClass('ui-state-hover');
if (this.speed && Math.abs(this.speed) >= this.options.fly) {
function _doStep(now, fx) {
// this is the element
if (!now) return;
$(this).spinner('value', fx.options.value + now)
}
this.element.animate({spinnerValue: this.speed/2*200 },
{value: this._value,
easing:'quadratic',
duration: 200,
step:_doStep
});
}
},
value: function(newValue, dontFire) {
if (arguments.length) {
this._value = newValue
this.updateDisplay();
if (dontFire === undefined) {
this.element.triggerHandler(this.widgetName + "value", [newValue]);
}
}
return this._value;
}
});
$.easing.quadratic = function( p, n, firstNum, diff ) {
return firstNum + diff * p * (2 - p);
};
$.widget(
'aH.datetime',
{
options: {
date: undefined,
width: 300
},
_create: function() {
var that = this;
this._dateField = $('<span />')
.attr({style: 'font-family: monospace'});
this._monthSpinner = $('<div />').spinner({n:2, width: this.options.width})
.attr({title:'month'})
.bind('spinnervalue',
function(e, v) {
return that._monthBinder(this, e, v);
});
this._daySpinner = $('<div />').spinner({n:3, width: this.options.width})
.attr({title:'day'});
this._hourSpinner = $('<div />').spinner({n:3, width: this.options.width})
.attr({title:'hour'})
.bind('spinnervalue',
function(e, v) {
return that._hourBinder(this, e, v);
});
this.element.append(this._dateField)
.append(this._monthSpinner)
.append(this._daySpinner)
.append(this._hourSpinner)
.addClass('ui-widget');
this._daySpinner.bind('spinnervalue',
function(e, v) {
return that._dayBinder(this, e, v);
}
)
this.date((this.options.date === undefined) ? new Date() :
new Date(this.options.date));
},
destroy: function() {
$.Widget.prototype.destroy.call(this);
this.element.removeClass('ui-widget');
},
_days: (30.5 * 24 * 60 * 60 * 1000),
_monthBinder: function(elem, e, v) {
var d = new Date(v * this._days);
this.date(d);
},
_dayBinder: function(elem, e, v) {
var d = new Date(v * (24 * 60 * 60 * 1000));
this.date(d);
},
_hourBinder: function(elem, e, v) {
var d = new Date(v * (60 * 60 * 1000));
this.date(d);
},
date: function(newDate, dontFire) {
if (arguments.length) {
this._date = newDate;
this._dateField.text(this._date.toUTCString());
var month = Number(this._date) / this._days;
this._monthSpinner.spinner('value', month,
true);
var date = Number(this._date) / (24 * 60 * 60 * 1000);
this._daySpinner.spinner('value', date,
true);
var hour = Number(this._date) / (60 * 60 * 1000);
this._hourSpinner.spinner('value', hour,
true);
if (dontFire === undefined) {
this.element.triggerHandler(this.widgetName + "value",
[newDate]);
}
}
return this._date;
}
}
);
| simplify datetime picker
| apps/pushes/static/pushes/js/widgets.js | simplify datetime picker | <ide><path>pps/pushes/static/pushes/js/widgets.js
<ide> * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<ide>
<ide> $.aH = $.aH || {};
<del>$.widget('aH.spinner', $.ui.mouse, {
<del> options: {
<del> alpha: 120,
<del> n: 5,
<del> value: 0,
<del> width: 150,
<del> fly: 1,
<del> // ui.mouse.defaults
<del> distance: 1,
<del> delay: 0,
<del> cancel: null
<del> },
<del> _create: function() {
<del> var that = this;
<del> this._hovering = false;
<del> that.element.append($('<table cellspacing="0" cellpadding="0" class="ui-widget ui-widget-content ui-state-default"><tr class="ui-state-hover ui-helper-hidden"></tr><tr><td><span class="ui-icon ui-icon-triangle-1-w">foo</span></td><td><canvas height="10" width="' +
<del> that.options.width +
<del> '"></canvas></td><td><span class="ui-icon ui-icon-triangle-1-e">foo</span></td></tr></table>'));
<del> that.element.children('table')
<del> .hover(function(){
<del> $(this).addClass("ui-state-hover");
<del> this._hovering = true;
<del> },
<del> function(){
<del> $(this).removeClass("ui-state-hover");
<del> this._hovering = false;
<del> }
<del> )
<del> that._mouseInit();
<del> that.computeSetup();
<del> that.value(that.options.value);
<del> },
<del> destroy: function() {
<del> $.Widget.prototype.destroy.call(this);
<del> this._mouseDestroy();
<del> },
<del> computeSetup: function() {
<del> this.canvas = this.element.find('canvas')[0];
<del> this.ctx = this.canvas.getContext('2d');
<del> this.r = this.canvas.width/2/Math.sin(this.options.alpha/2/180*Math.PI); //radius
<del> this.rx = this.r * this.options.alpha * Math.PI / 360 / this.options.n; //px per tick
<del> },
<del> updateDisplay: function() {
<del> var off = 1 - this._value % 1;
<del> var end = off ? this.options.n - 1 : this.options.n;
<del> this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
<del> this.ctx.beginPath();
<del> this.ctx.strokeStyle = $('.ui-state-default').css('color');
<del> for (var i = -this.options.n; i <= end; i += 1) {
<del> var a = (i + off) * this.rx/this.r;
<del> var x = this.r * Math.sin(a) + this.canvas.width/2;
<del> this.ctx.moveTo(x, 0);
<del> this.ctx.lineTo(x, this.canvas.height);
<del> }
<del> this.ctx.stroke();
<del> },
<del> _mouseStart: function(event) {
<del> this.startValue = this.value();
<del> this.element.children('table').removeClass('ui-state-hover')
<del> .addClass('ui-state-active');
<del> return true;
<del> },
<del> _mouseDrag: function(event) {
<del> var dx = event.clientX - this._mouseDownEvent.clientX;
<del> var now = Date.now();
<del> if (this.previousValue) {
<del> this.speed = (event.clientX - this.previousValue) /
<del> (now - this.previousTime);
<del> }
<del> this.previousValue = event.clientX;
<del> this.previousTime = now;
<del> this.value(this.startValue - dx / this.rx);
<del> },
<del> _mouseStop: function(event) {
<del> this.previousValue = null;
<del> this.element.children('table').removeClass('ui-state-active');
<del> if (this._hovering) this.elememnt.children('table').addClass('ui-state-hover');
<del> if (this.speed && Math.abs(this.speed) >= this.options.fly) {
<del> function _doStep(now, fx) {
<del> // this is the element
<del> if (!now) return;
<del> $(this).spinner('value', fx.options.value + now)
<del> }
<del> this.element.animate({spinnerValue: this.speed/2*200 },
<del> {value: this._value,
<del> easing:'quadratic',
<del> duration: 200,
<del> step:_doStep
<del> });
<del> }
<del> },
<del> value: function(newValue, dontFire) {
<del> if (arguments.length) {
<del> this._value = newValue
<del> this.updateDisplay();
<del> if (dontFire === undefined) {
<del> this.element.triggerHandler(this.widgetName + "value", [newValue]);
<del> }
<del> }
<del> return this._value;
<del> }
<del>});
<del>$.easing.quadratic = function( p, n, firstNum, diff ) {
<del> return firstNum + diff * p * (2 - p);
<del>};
<ide>
<ide> $.widget(
<ide> 'aH.datetime',
<ide> },
<ide> _create: function() {
<ide> var that = this;
<del> this._dateField = $('<span />')
<del> .attr({style: 'font-family: monospace'});
<del> this._monthSpinner = $('<div />').spinner({n:2, width: this.options.width})
<del> .attr({title:'month'})
<del> .bind('spinnervalue',
<del> function(e, v) {
<del> return that._monthBinder(this, e, v);
<del> });
<del> this._daySpinner = $('<div />').spinner({n:3, width: this.options.width})
<del> .attr({title:'day'});
<del> this._hourSpinner = $('<div />').spinner({n:3, width: this.options.width})
<del> .attr({title:'hour'})
<del> .bind('spinnervalue',
<del> function(e, v) {
<del> return that._hourBinder(this, e, v);
<del> });
<add> this._dateField = $('<input type="date" />')[0];
<add> this._timeField = $('<input type="time" step="1" />')[0];
<ide> this.element.append(this._dateField)
<del> .append(this._monthSpinner)
<del> .append(this._daySpinner)
<del> .append(this._hourSpinner)
<add> .append(this._timeField)
<ide> .addClass('ui-widget');
<del> this._daySpinner.bind('spinnervalue',
<del> function(e, v) {
<del> return that._dayBinder(this, e, v);
<del> }
<del> )
<add> this._dateField.onchange = () => this.date();
<add> this._timeField.onchange = () => this.date();
<ide> this.date((this.options.date === undefined) ? new Date() :
<ide> new Date(this.options.date));
<ide> },
<ide> this.element.removeClass('ui-widget');
<ide> },
<ide> _days: (30.5 * 24 * 60 * 60 * 1000),
<del> _monthBinder: function(elem, e, v) {
<del> var d = new Date(v * this._days);
<del> this.date(d);
<del> },
<del> _dayBinder: function(elem, e, v) {
<del> var d = new Date(v * (24 * 60 * 60 * 1000));
<del> this.date(d);
<del> },
<del> _hourBinder: function(elem, e, v) {
<del> var d = new Date(v * (60 * 60 * 1000));
<del> this.date(d);
<del> },
<ide> date: function(newDate, dontFire) {
<ide> if (arguments.length) {
<add> newDate.setMilliseconds(0);
<ide> this._date = newDate;
<del> this._dateField.text(this._date.toUTCString());
<del> var month = Number(this._date) / this._days;
<del> this._monthSpinner.spinner('value', month,
<del> true);
<del> var date = Number(this._date) / (24 * 60 * 60 * 1000);
<del> this._daySpinner.spinner('value', date,
<del> true);
<del> var hour = Number(this._date) / (60 * 60 * 1000);
<del> this._hourSpinner.spinner('value', hour,
<del> true);
<del> if (dontFire === undefined) {
<del> this.element.triggerHandler(this.widgetName + "value",
<del> [newDate]);
<del> }
<add> this._dateField.valueAsDate = this._date;
<add> this._timeField.valueAsDate = this._date;
<add> }
<add> else {
<add> this._date = new Date(
<add> this._dateField.valueAsNumber + this._timeField.valueAsNumber
<add> );
<add> }
<add> if (dontFire === undefined) {
<add> this.element.triggerHandler(this.widgetName + "value",
<add> [this._date]);
<ide> }
<ide> return this._date;
<ide> } |
|
Java | agpl-3.0 | a93d25fe92dbe2165056a8f9ddc11cb5bdaf4727 | 0 | SilverTeamWork/Silverpeas-Core,NicolasEYSSERIC/Silverpeas-Core,mmoqui/Silverpeas-Core,auroreallibe/Silverpeas-Core,Silverpeas/Silverpeas-Core,Silverpeas/Silverpeas-Core,CecileBONIN/Silverpeas-Core,Silverpeas/Silverpeas-Core,SilverDav/Silverpeas-Core,CecileBONIN/Silverpeas-Core,mmoqui/Silverpeas-Core,CecileBONIN/Silverpeas-Core,auroreallibe/Silverpeas-Core,ebonnet/Silverpeas-Core,ebonnet/Silverpeas-Core,NicolasEYSSERIC/Silverpeas-Core,stephaneperry/Silverpeas-Core,stephaneperry/Silverpeas-Core,stephaneperry/Silverpeas-Core,ebonnet/Silverpeas-Core,ebonnet/Silverpeas-Core,SilverTeamWork/Silverpeas-Core,ebonnet/Silverpeas-Core,NicolasEYSSERIC/Silverpeas-Core,SilverYoCha/Silverpeas-Core,NicolasEYSSERIC/Silverpeas-Core,CecileBONIN/Silverpeas-Core,ebonnet/Silverpeas-Core,mmoqui/Silverpeas-Core,SilverDav/Silverpeas-Core,SilverYoCha/Silverpeas-Core,SilverYoCha/Silverpeas-Core,stephaneperry/Silverpeas-Core,auroreallibe/Silverpeas-Core,SilverTeamWork/Silverpeas-Core,CecileBONIN/Silverpeas-Core,SilverDav/Silverpeas-Core | /**
* Copyright (C) 2000 - 2009 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://repository.silverpeas.com/legal/licensing"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.form.fieldDisplayer;
import java.io.File;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import com.silverpeas.form.Field;
import com.silverpeas.form.FieldDisplayer;
import com.silverpeas.form.FieldTemplate;
import com.silverpeas.form.Form;
import com.silverpeas.form.FormException;
import com.silverpeas.form.PagesContext;
import com.silverpeas.form.Util;
import com.silverpeas.form.fieldType.FileField;
import com.silverpeas.util.EncodeHelper;
import com.silverpeas.util.FileUtil;
import com.silverpeas.util.ForeignPK;
import com.silverpeas.util.StringUtil;
import com.silverpeas.util.web.servlet.FileUploadUtil;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.silverpeas.versioning.ejb.VersioningBm;
import com.stratelia.silverpeas.versioning.ejb.VersioningBmHome;
import com.stratelia.silverpeas.versioning.model.Document;
import com.stratelia.silverpeas.versioning.model.DocumentPK;
import com.stratelia.silverpeas.versioning.model.DocumentVersion;
import com.stratelia.silverpeas.versioning.model.Worker;
import com.stratelia.silverpeas.versioning.util.VersioningUtil;
import com.stratelia.webactiv.beans.admin.ComponentInst;
import com.stratelia.webactiv.beans.admin.OrganizationController;
import com.stratelia.webactiv.beans.admin.ProfileInst;
import com.stratelia.webactiv.util.EJBUtilitaire;
import com.stratelia.webactiv.util.FileRepositoryManager;
import com.stratelia.webactiv.util.FileServerUtils;
import com.stratelia.webactiv.util.JNDINames;
import com.stratelia.webactiv.util.attachment.control.AttachmentController;
import com.stratelia.webactiv.util.attachment.ejb.AttachmentPK;
import com.stratelia.webactiv.util.attachment.model.AttachmentDetail;
import com.stratelia.webactiv.util.fileFolder.FileFolderManager;
/**
* A FileFieldDisplayer is an object which can display a link to a file (attachment) in HTML and can
* retrieve via HTTP any file.
* @see Field
* @see FieldTemplate
* @see Form
* @see FieldDisplayer
*/
public class FileFieldDisplayer extends AbstractFieldDisplayer {
public static final String CONTEXT_FORM_FILE = "Images";
private VersioningBm versioningBm = null;
/**
* Returns the name of the managed types.
*/
public String[] getManagedTypes() {
return new String[] {FileField.TYPE};
}
/**
* Prints the javascripts which will be used to control the new value given to the named field.
* The error messages may be adapted to a local language. The FieldTemplate gives the field type
* and constraints. The FieldTemplate gives the local labeld too. Never throws an Exception but
* log a silvertrace and writes an empty string when :
* <UL>
* <LI>the fieldName is unknown by the template.
* <LI>the field type is not a managed type.
* </UL>
*/
@Override
public void displayScripts(PrintWriter out, FieldTemplate template, PagesContext PagesContext)
throws java.io.IOException {
String language = PagesContext.getLanguage();
String fieldName = template.getFieldName();
if (!FileField.TYPE.equals(template.getTypeName())) {
SilverTrace.info("form", "FileFieldDisplayer.displayScripts", "form.INFO_NOT_CORRECT_TYPE",
FileField.TYPE);
}
if (template.isMandatory() && PagesContext.useMandatory()) {
out.println(" if (isWhitespace(stripInitialWhitespace(field.value))) {");
out.println(" var " + fieldName + "Value = document.getElementById('" + fieldName +
FileField.PARAM_ID_SUFFIX + "').value;");
out.println(" if (" + fieldName + "Value=='' || " + fieldName +
"Value.substring(0,7)==\"remove_\") {");
out.println(" errorMsg+=\" - '" +
EncodeHelper.javaStringToJsString(template.getLabel(language)) + "' " +
Util.getString("GML.MustBeFilled", language) + "\\n \";");
out.println(" errorNb++;");
out.println(" }");
out.println(" }");
}
Util.getJavascriptChecker(template.getFieldName(), PagesContext, out);
}
/**
* Prints the HTML value of the field. The displayed value must be updatable by the end user. The
* value format may be adapted to a local language. The fieldName must be used to name the html
* form input. Never throws an Exception but log a silvertrace and writes an empty string when :
* <UL>
* <LI>the field type is not a managed type.
* </UL>
* @param out
* @param field
* @param pagesContext
* @param template
* @throws FormException
*/
@Override
public void display(PrintWriter out, Field field, FieldTemplate template,
PagesContext pagesContext) throws FormException {
display(out, field, template, pagesContext, FileServerUtils.getApplicationContext());
}
public void display(PrintWriter out, Field field, FieldTemplate template,
PagesContext pagesContext, String webContext) throws FormException {
SilverTrace.info("form", "FileFieldDisplayer.display", "root.MSG_GEN_ENTER_METHOD",
"fieldName = " + template.getFieldName() + ", value = " + field.getValue() +
", fieldType = " + field.getTypeName());
String html = "";
String fieldName = template.getFieldName();
if (! FileField.TYPE.equals(template.getTypeName())) {
SilverTrace.info("form", "FileFieldDisplayer.display", "form.INFO_NOT_CORRECT_TYPE",
FileField.TYPE);
}
String attachmentId = field.getValue();
String componentId = pagesContext.getComponentId();
AttachmentDetail attachment = null;
if (attachmentId != null && attachmentId.length() > 0) {
attachment =
AttachmentController.searchAttachmentByPK(new AttachmentPK(attachmentId, componentId));
} else {
attachmentId = "";
}
if (template.isReadOnly() && !template.isHidden()) {
if (attachment != null) {
html = "<img alt=\"\" src=\"" + attachment.getAttachmentIcon() + "\" width=\"20\"> ";
html +=
"<a href=\"" + webContext + attachment.getAttachmentURL() + "\" target=\"_blank\">" +
attachment.getLogicalName() + "</a>";
}
} else if (!template.isHidden() && !template.isDisabled() && !template.isReadOnly()) {
html +=
"<input type=\"file\" size=\"50\" id=\"" + fieldName + "\" name=\"" + fieldName + "\"/>";
html +=
"<input type=\"hidden\" id=\"" + fieldName + FileField.PARAM_ID_SUFFIX + "\" name=\"" +
fieldName + FileField.PARAM_NAME_SUFFIX + "\" value=\"" + attachmentId + "\"/>";
if (attachment != null) {
String deleteImg = Util.getIcon("delete");
String deleteLab = Util.getString("removeFile", pagesContext.getLanguage());
html += " <span id=\"div" + fieldName + "\">";
html +=
"<img alt=\"\" align=\"top\" src=\"" + attachment.getAttachmentIcon() +
"\" width=\"20\"/> ";
html +=
"<a href=\"" + webContext + attachment.getAttachmentURL() + "\" target=\"_blank\">" +
attachment.getLogicalName() + "</a>";
html +=
" <a href=\"#\" onclick=\"javascript:" + "document.getElementById('div" +
fieldName + "').style.display='none';" + "document." + pagesContext.getFormName() +
"." + fieldName + FileField.PARAM_NAME_SUFFIX + ".value='remove_" + attachmentId +
"';" + "\">";
html +=
"<img src=\"" + deleteImg + "\" width=\"15\" height=\"15\" border=\"0\" alt=\"" +
deleteLab + "\" align=\"top\" title=\"" + deleteLab + "\"/></a>";
html += "</span>";
}
if (template.isMandatory() && pagesContext.useMandatory()) {
html += Util.getMandatorySnippet();
}
}
out.println(html);
}
@Override
public List<String> update(String attachmentId, Field field, FieldTemplate template,
PagesContext pagesContext) throws FormException {
List<String> attachmentIds = new ArrayList<String>();
if (FileField.TYPE.equals(field.getTypeName())) {
if (attachmentId == null || attachmentId.trim().equals("")) {
field.setNull();
} else {
((FileField) field).setAttachmentId(attachmentId);
attachmentIds.add(attachmentId);
}
} else {
throw new FormException("FileFieldDisplayer.update", "form.EX_NOT_CORRECT_VALUE",
FileField.TYPE);
}
return attachmentIds;
}
/**
* Method declaration
* @return
*/
@Override
public boolean isDisplayedMandatory() {
return true;
}
/**
* Method declaration
* @return
*/
@Override
public int getNbHtmlObjectsDisplayed(FieldTemplate template, PagesContext pagesContext) {
return 2;
}
@Override
public List<String> update(List<FileItem> items, Field field, FieldTemplate template,
PagesContext pageContext) throws FormException {
String itemName = template.getFieldName();
try {
String value = processUploadedFile(items, itemName, pageContext);
String param = FileUploadUtil.getParameter(items, itemName + Field.FILE_PARAM_NAME_SUFFIX);
if (param != null) {
if (param.startsWith("remove_")) {
// Il faut supprimer le fichier
String attachmentId = param.substring("remove_".length());
deleteAttachment(attachmentId, pageContext);
} else if (value != null && StringUtil.isInteger(param)) {
// Y'avait-il un déjà un fichier ?
// Il faut remplacer le fichier donc supprimer l'ancien
deleteAttachment(param, pageContext);
} else if (value == null) {
// pas de nouveau fichier, ni de suppression
// le champ ne doit pas être mis à jour
return new ArrayList<String>();
}
}
if (pageContext.getUpdatePolicy() == PagesContext.ON_UPDATE_IGNORE_EMPTY_VALUES &&
!StringUtil.isDefined(value)) {
return new ArrayList<String>();
}
return update(value, field, template, pageContext);
} catch (Exception e) {
SilverTrace.error("form", "ImageFieldDisplayer.update", "form.EXP_UNKNOWN_FIELD", null, e);
}
return new ArrayList<String>();
}
private String processUploadedFile(List<FileItem> items, String parameterName, PagesContext pagesContext)
throws Exception {
String attachmentId = null;
FileItem item = FileUploadUtil.getFile(items, parameterName);
if (!item.isFormField()) {
String componentId = pagesContext.getComponentId();
String userId = pagesContext.getUserId();
String objectId = pagesContext.getObjectId();
String logicalName = item.getName();
String physicalName = null;
String mimeType = null;
File dir = null;
long size = 0;
VersioningUtil versioningUtil = new VersioningUtil();
if (StringUtil.isDefined(logicalName)) {
if (!FileUtil.isWindows()) {
logicalName = logicalName.replace('\\', File.separatorChar);
SilverTrace.info("form", "AbstractForm.processUploadedFile", "root.MSG_GEN_PARAM_VALUE",
"fullFileName on Unix = " + logicalName);
}
logicalName =
logicalName
.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length());
String type = FileRepositoryManager.getFileExtension(logicalName);
mimeType = item.getContentType();
if (mimeType.equals("application/x-zip-compressed")) {
if (type.equalsIgnoreCase("jar") || type.equalsIgnoreCase("ear") ||
type.equalsIgnoreCase("war")) {
mimeType = "application/java-archive";
} else if (type.equalsIgnoreCase("3D")) {
mimeType = "application/xview3d-3d";
}
}
physicalName = new Long(new Date().getTime()).toString() + "." + type;
String path = "";
if (pagesContext.isVersioningUsed()) {
path = versioningUtil.createPath("useless", componentId, "useless");
} else {
path = AttachmentController.createPath(componentId, FileFieldDisplayer.CONTEXT_FORM_FILE);
}
dir = new File(path + physicalName);
size = item.getSize();
item.write(dir);
// l'ajout du fichier joint ne se fait que si la taille du fichier (size) est >0
// sinon cela indique que le fichier n'est pas valide (chemin non valide, fichier non
// accessible)
if (size > 0) {
AttachmentDetail ad =
createAttachmentDetail(objectId, componentId, physicalName, logicalName, mimeType,
size, FileFieldDisplayer.CONTEXT_FORM_FILE, userId);
if (pagesContext.isVersioningUsed()) {
// mode versioning
attachmentId = createDocument(objectId, ad);
} else {
// mode classique
ad = AttachmentController.createAttachment(ad, true);
attachmentId = ad.getPK().getId();
}
} else {
// le fichier à tout de même été créé sur le serveur avec une taille 0!, il faut le
// supprimer
if (dir != null) {
FileFolderManager.deleteFolder(dir.getPath());
}
}
}
}
return attachmentId;
}
private AttachmentDetail createAttachmentDetail(String objectId, String componentId,
String physicalName, String logicalName, String mimeType, long size, String context,
String userId) {
// create AttachmentPK with spaceId and componentId
AttachmentPK atPK = new AttachmentPK(null, "useless", componentId);
// create foreignKey with spaceId, componentId and id
// use AttachmentPK to build the foreign key of customer object.
AttachmentPK foreignKey = new AttachmentPK("-1", "useless", componentId);
if (objectId != null) {
foreignKey.setId(objectId);
}
// create AttachmentDetail Object
AttachmentDetail ad =
new AttachmentDetail(atPK, physicalName, logicalName, null, mimeType, size, context,
new Date(), foreignKey);
ad.setAuthor(userId);
return ad;
}
private void deleteAttachment(String attachmentId, PagesContext pageContext) {
SilverTrace.info("form", "AbstractForm.deleteAttachment", "root.MSG_GEN_ENTER_METHOD",
"attachmentId = " + attachmentId + ", componentId = " + pageContext.getComponentId());
AttachmentPK pk = new AttachmentPK(attachmentId, pageContext.getComponentId());
AttachmentController.deleteAttachment(pk);
}
private String createDocument(String objectId, AttachmentDetail attachment)
throws RemoteException {
String componentId = attachment.getPK().getInstanceId();
int userId = Integer.parseInt(attachment.getAuthor());
ForeignPK pubPK = new ForeignPK("-1", componentId);
if (objectId != null) {
pubPK.setId(objectId);
}
// Création d'un nouveau document
DocumentPK docPK = new DocumentPK(-1, "useless", componentId);
Document document =
new Document(docPK, pubPK, attachment.getLogicalName(), "", -1, userId, new Date(), null,
null, null, null, 0, 0);
document.setWorkList(getWorkers(componentId, userId));
DocumentVersion version = new DocumentVersion(attachment);
version.setAuthorId(userId);
// et on y ajoute la première version
version.setMajorNumber(1);
version.setMinorNumber(0);
version.setType(DocumentVersion.TYPE_PUBLIC_VERSION);
version.setStatus(DocumentVersion.STATUS_VALIDATION_NOT_REQ);
version.setCreationDate(new Date());
docPK = getVersioningBm().createDocument(document, version);
document.setPk(docPK);
return docPK.getId();
}
private ArrayList getWorkers(String componentId, int creatorId) {
ArrayList workers = new ArrayList();
OrganizationController orga = new OrganizationController();
ComponentInst component = orga.getComponentInst(componentId);
List profilesInst = component.getAllProfilesInst();
List profiles = new ArrayList();
ProfileInst profileInst = null;
for (int p = 0; p < profilesInst.size(); p++) {
profileInst = (ProfileInst) profilesInst.get(p);
profiles.add(profileInst.getName());
}
String[] userIds = orga.getUsersIdsByRoleNames(componentId, profiles);
int userId = -1;
Worker worker = null;
boolean find = false;
for (int u = 0; u < userIds.length; u++) {
userId = Integer.parseInt(userIds[u]);
if (!find && (userId == creatorId)) {
find = true;
}
worker = new Worker(userId, 0, 0, true, true, componentId);
workers.add(worker);
}
if (!find) {
worker = new Worker(creatorId, 0, 0, true, true, componentId);
workers.add(worker);
}
Worker lastWorker = (Worker) workers.get(workers.size() - 1);
lastWorker.setApproval(true);
return workers;
}
private VersioningBm getVersioningBm() {
if (versioningBm == null) {
try {
VersioningBmHome vscEjbHome =
(VersioningBmHome) EJBUtilitaire.getEJBObjectRef(JNDINames.VERSIONING_EJBHOME,
VersioningBmHome.class);
versioningBm = vscEjbHome.create();
} catch (Exception e) {
// NEED
// throw new
// ...RuntimeException("VersioningSessionController.initEJB()",SilverpeasRuntimeException.
// ERROR,"root.EX_CANT_GET_REMOTE_OBJECT",e);
}
}
return versioningBm;
}
} | ejb-core/formtemplate/src/main/java/com/silverpeas/form/fieldDisplayer/FileFieldDisplayer.java | /**
* Copyright (C) 2000 - 2009 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://repository.silverpeas.com/legal/licensing"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.form.fieldDisplayer;
import java.io.File;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import com.silverpeas.form.Field;
import com.silverpeas.form.FieldDisplayer;
import com.silverpeas.form.FieldTemplate;
import com.silverpeas.form.Form;
import com.silverpeas.form.FormException;
import com.silverpeas.form.PagesContext;
import com.silverpeas.form.Util;
import com.silverpeas.form.fieldType.FileField;
import com.silverpeas.util.EncodeHelper;
import com.silverpeas.util.FileUtil;
import com.silverpeas.util.ForeignPK;
import com.silverpeas.util.StringUtil;
import com.silverpeas.util.web.servlet.FileUploadUtil;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.silverpeas.versioning.ejb.VersioningBm;
import com.stratelia.silverpeas.versioning.ejb.VersioningBmHome;
import com.stratelia.silverpeas.versioning.model.Document;
import com.stratelia.silverpeas.versioning.model.DocumentPK;
import com.stratelia.silverpeas.versioning.model.DocumentVersion;
import com.stratelia.silverpeas.versioning.model.Worker;
import com.stratelia.silverpeas.versioning.util.VersioningUtil;
import com.stratelia.webactiv.beans.admin.ComponentInst;
import com.stratelia.webactiv.beans.admin.OrganizationController;
import com.stratelia.webactiv.beans.admin.ProfileInst;
import com.stratelia.webactiv.util.EJBUtilitaire;
import com.stratelia.webactiv.util.FileRepositoryManager;
import com.stratelia.webactiv.util.FileServerUtils;
import com.stratelia.webactiv.util.JNDINames;
import com.stratelia.webactiv.util.attachment.control.AttachmentController;
import com.stratelia.webactiv.util.attachment.ejb.AttachmentPK;
import com.stratelia.webactiv.util.attachment.model.AttachmentDetail;
import com.stratelia.webactiv.util.fileFolder.FileFolderManager;
/**
* A FileFieldDisplayer is an object which can display a link to a file (attachment) in HTML and can
* retrieve via HTTP any file.
* @see Field
* @see FieldTemplate
* @see Form
* @see FieldDisplayer
*/
public class FileFieldDisplayer extends AbstractFieldDisplayer {
public static final String CONTEXT_FORM_FILE = "Images";
private VersioningBm versioningBm = null;
/**
* Returns the name of the managed types.
*/
public String[] getManagedTypes() {
return new String[] {FileField.TYPE};
}
/**
* Prints the javascripts which will be used to control the new value given to the named field.
* The error messages may be adapted to a local language. The FieldTemplate gives the field type
* and constraints. The FieldTemplate gives the local labeld too. Never throws an Exception but
* log a silvertrace and writes an empty string when :
* <UL>
* <LI>the fieldName is unknown by the template.
* <LI>the field type is not a managed type.
* </UL>
*/
@Override
public void displayScripts(PrintWriter out, FieldTemplate template, PagesContext PagesContext)
throws java.io.IOException {
String language = PagesContext.getLanguage();
String fieldName = template.getFieldName();
if (!FileField.TYPE.equals(template.getTypeName())) {
SilverTrace.info("form", "FileFieldDisplayer.displayScripts", "form.INFO_NOT_CORRECT_TYPE",
FileField.TYPE);
}
if (template.isMandatory() && PagesContext.useMandatory()) {
out.println(" if (isWhitespace(stripInitialWhitespace(field.value))) {");
out.println(" var " + fieldName + "Value = document.getElementById('" + fieldName +
FileField.PARAM_NAME_SUFFIX + "').value;");
out.println(" if (" + fieldName + "Value=='' || " + fieldName +
"Value.substring(0,7)==\"remove_\") {");
out.println(" errorMsg+=\" - '" +
EncodeHelper.javaStringToJsString(template.getLabel(language)) + "' " +
Util.getString("GML.MustBeFilled", language) + "\\n \";");
out.println(" errorNb++;");
out.println(" }");
out.println(" }");
}
Util.getJavascriptChecker(template.getFieldName(), PagesContext, out);
}
/**
* Prints the HTML value of the field. The displayed value must be updatable by the end user. The
* value format may be adapted to a local language. The fieldName must be used to name the html
* form input. Never throws an Exception but log a silvertrace and writes an empty string when :
* <UL>
* <LI>the field type is not a managed type.
* </UL>
* @param out
* @param field
* @param pagesContext
* @param template
* @throws FormException
*/
@Override
public void display(PrintWriter out, Field field, FieldTemplate template,
PagesContext pagesContext) throws FormException {
display(out, field, template, pagesContext, FileServerUtils.getApplicationContext());
}
public void display(PrintWriter out, Field field, FieldTemplate template,
PagesContext pagesContext, String webContext) throws FormException {
SilverTrace.info("form", "FileFieldDisplayer.display", "root.MSG_GEN_ENTER_METHOD",
"fieldName = " + template.getFieldName() + ", value = " + field.getValue() +
", fieldType = " + field.getTypeName());
String html = "";
String fieldName = template.getFieldName();
if (! FileField.TYPE.equals(template.getTypeName())) {
SilverTrace.info("form", "FileFieldDisplayer.display", "form.INFO_NOT_CORRECT_TYPE",
FileField.TYPE);
}
String attachmentId = field.getValue();
String componentId = pagesContext.getComponentId();
AttachmentDetail attachment = null;
if (attachmentId != null && attachmentId.length() > 0) {
attachment =
AttachmentController.searchAttachmentByPK(new AttachmentPK(attachmentId, componentId));
} else {
attachmentId = "";
}
if (template.isReadOnly() && !template.isHidden()) {
if (attachment != null) {
html = "<img alt=\"\" src=\"" + attachment.getAttachmentIcon() + "\" width=\"20\"> ";
html +=
"<a href=\"" + webContext + attachment.getAttachmentURL() + "\" target=\"_blank\">" +
attachment.getLogicalName() + "</a>";
}
} else if (!template.isHidden() && !template.isDisabled() && !template.isReadOnly()) {
html +=
"<input type=\"file\" size=\"50\" id=\"" + fieldName + "\" name=\"" + fieldName + "\"/>";
html +=
"<input type=\"hidden\" id=\"" + fieldName + FileField.PARAM_ID_SUFFIX + "\" name=\"" +
fieldName + FileField.PARAM_NAME_SUFFIX + "\" value=\"" + attachmentId + "\"/>";
if (attachment != null) {
String deleteImg = Util.getIcon("delete");
String deleteLab = Util.getString("removeFile", pagesContext.getLanguage());
html += " <span id=\"div" + fieldName + "\">";
html +=
"<img alt=\"\" align=\"top\" src=\"" + attachment.getAttachmentIcon() +
"\" width=\"20\"/> ";
html +=
"<a href=\"" + webContext + attachment.getAttachmentURL() + "\" target=\"_blank\">" +
attachment.getLogicalName() + "</a>";
html +=
" <a href=\"#\" onclick=\"javascript:" + "document.getElementById('div" +
fieldName + "').style.display='none';" + "document." + pagesContext.getFormName() +
"." + fieldName + FileField.PARAM_NAME_SUFFIX + ".value='remove_" + attachmentId +
"';" + "\">";
html +=
"<img src=\"" + deleteImg + "\" width=\"15\" height=\"15\" border=\"0\" alt=\"" +
deleteLab + "\" align=\"top\" title=\"" + deleteLab + "\"/></a>";
html += "</span>";
}
if (template.isMandatory() && pagesContext.useMandatory()) {
html += Util.getMandatorySnippet();
}
}
out.println(html);
}
@Override
public List<String> update(String attachmentId, Field field, FieldTemplate template,
PagesContext pagesContext) throws FormException {
List<String> attachmentIds = new ArrayList<String>();
if (FileField.TYPE.equals(field.getTypeName())) {
if (attachmentId == null || attachmentId.trim().equals("")) {
field.setNull();
} else {
((FileField) field).setAttachmentId(attachmentId);
attachmentIds.add(attachmentId);
}
} else {
throw new FormException("FileFieldDisplayer.update", "form.EX_NOT_CORRECT_VALUE",
FileField.TYPE);
}
return attachmentIds;
}
/**
* Method declaration
* @return
*/
@Override
public boolean isDisplayedMandatory() {
return true;
}
/**
* Method declaration
* @return
*/
@Override
public int getNbHtmlObjectsDisplayed(FieldTemplate template, PagesContext pagesContext) {
return 2;
}
@Override
public List<String> update(List<FileItem> items, Field field, FieldTemplate template,
PagesContext pageContext) throws FormException {
String itemName = template.getFieldName();
try {
String value = processUploadedFile(items, itemName, pageContext);
String param = FileUploadUtil.getParameter(items, itemName + Field.FILE_PARAM_NAME_SUFFIX);
if (param != null) {
if (param.startsWith("remove_")) {
// Il faut supprimer le fichier
String attachmentId = param.substring("remove_".length());
deleteAttachment(attachmentId, pageContext);
} else if (value != null && StringUtil.isInteger(param)) {
// Y'avait-il un déjà un fichier ?
// Il faut remplacer le fichier donc supprimer l'ancien
deleteAttachment(param, pageContext);
} else if (value == null) {
// pas de nouveau fichier, ni de suppression
// le champ ne doit pas être mis à jour
return new ArrayList<String>();
}
}
if (pageContext.getUpdatePolicy() == PagesContext.ON_UPDATE_IGNORE_EMPTY_VALUES &&
!StringUtil.isDefined(value)) {
return new ArrayList<String>();
}
return update(value, field, template, pageContext);
} catch (Exception e) {
SilverTrace.error("form", "ImageFieldDisplayer.update", "form.EXP_UNKNOWN_FIELD", null, e);
}
return new ArrayList<String>();
}
private String processUploadedFile(List<FileItem> items, String parameterName, PagesContext pagesContext)
throws Exception {
String attachmentId = null;
FileItem item = FileUploadUtil.getFile(items, parameterName);
if (!item.isFormField()) {
String componentId = pagesContext.getComponentId();
String userId = pagesContext.getUserId();
String objectId = pagesContext.getObjectId();
String logicalName = item.getName();
String physicalName = null;
String mimeType = null;
File dir = null;
long size = 0;
VersioningUtil versioningUtil = new VersioningUtil();
if (StringUtil.isDefined(logicalName)) {
if (!FileUtil.isWindows()) {
logicalName = logicalName.replace('\\', File.separatorChar);
SilverTrace.info("form", "AbstractForm.processUploadedFile", "root.MSG_GEN_PARAM_VALUE",
"fullFileName on Unix = " + logicalName);
}
logicalName =
logicalName
.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length());
String type = FileRepositoryManager.getFileExtension(logicalName);
mimeType = item.getContentType();
if (mimeType.equals("application/x-zip-compressed")) {
if (type.equalsIgnoreCase("jar") || type.equalsIgnoreCase("ear") ||
type.equalsIgnoreCase("war")) {
mimeType = "application/java-archive";
} else if (type.equalsIgnoreCase("3D")) {
mimeType = "application/xview3d-3d";
}
}
physicalName = new Long(new Date().getTime()).toString() + "." + type;
String path = "";
if (pagesContext.isVersioningUsed()) {
path = versioningUtil.createPath("useless", componentId, "useless");
} else {
path = AttachmentController.createPath(componentId, FileFieldDisplayer.CONTEXT_FORM_FILE);
}
dir = new File(path + physicalName);
size = item.getSize();
item.write(dir);
// l'ajout du fichier joint ne se fait que si la taille du fichier (size) est >0
// sinon cela indique que le fichier n'est pas valide (chemin non valide, fichier non
// accessible)
if (size > 0) {
AttachmentDetail ad =
createAttachmentDetail(objectId, componentId, physicalName, logicalName, mimeType,
size, FileFieldDisplayer.CONTEXT_FORM_FILE, userId);
if (pagesContext.isVersioningUsed()) {
// mode versioning
attachmentId = createDocument(objectId, ad);
} else {
// mode classique
ad = AttachmentController.createAttachment(ad, true);
attachmentId = ad.getPK().getId();
}
} else {
// le fichier à tout de même été créé sur le serveur avec une taille 0!, il faut le
// supprimer
if (dir != null) {
FileFolderManager.deleteFolder(dir.getPath());
}
}
}
}
return attachmentId;
}
private AttachmentDetail createAttachmentDetail(String objectId, String componentId,
String physicalName, String logicalName, String mimeType, long size, String context,
String userId) {
// create AttachmentPK with spaceId and componentId
AttachmentPK atPK = new AttachmentPK(null, "useless", componentId);
// create foreignKey with spaceId, componentId and id
// use AttachmentPK to build the foreign key of customer object.
AttachmentPK foreignKey = new AttachmentPK("-1", "useless", componentId);
if (objectId != null) {
foreignKey.setId(objectId);
}
// create AttachmentDetail Object
AttachmentDetail ad =
new AttachmentDetail(atPK, physicalName, logicalName, null, mimeType, size, context,
new Date(), foreignKey);
ad.setAuthor(userId);
return ad;
}
private void deleteAttachment(String attachmentId, PagesContext pageContext) {
SilverTrace.info("form", "AbstractForm.deleteAttachment", "root.MSG_GEN_ENTER_METHOD",
"attachmentId = " + attachmentId + ", componentId = " + pageContext.getComponentId());
AttachmentPK pk = new AttachmentPK(attachmentId, pageContext.getComponentId());
AttachmentController.deleteAttachment(pk);
}
private String createDocument(String objectId, AttachmentDetail attachment)
throws RemoteException {
String componentId = attachment.getPK().getInstanceId();
int userId = Integer.parseInt(attachment.getAuthor());
ForeignPK pubPK = new ForeignPK("-1", componentId);
if (objectId != null) {
pubPK.setId(objectId);
}
// Création d'un nouveau document
DocumentPK docPK = new DocumentPK(-1, "useless", componentId);
Document document =
new Document(docPK, pubPK, attachment.getLogicalName(), "", -1, userId, new Date(), null,
null, null, null, 0, 0);
document.setWorkList(getWorkers(componentId, userId));
DocumentVersion version = new DocumentVersion(attachment);
version.setAuthorId(userId);
// et on y ajoute la première version
version.setMajorNumber(1);
version.setMinorNumber(0);
version.setType(DocumentVersion.TYPE_PUBLIC_VERSION);
version.setStatus(DocumentVersion.STATUS_VALIDATION_NOT_REQ);
version.setCreationDate(new Date());
docPK = getVersioningBm().createDocument(document, version);
document.setPk(docPK);
return docPK.getId();
}
private ArrayList getWorkers(String componentId, int creatorId) {
ArrayList workers = new ArrayList();
OrganizationController orga = new OrganizationController();
ComponentInst component = orga.getComponentInst(componentId);
List profilesInst = component.getAllProfilesInst();
List profiles = new ArrayList();
ProfileInst profileInst = null;
for (int p = 0; p < profilesInst.size(); p++) {
profileInst = (ProfileInst) profilesInst.get(p);
profiles.add(profileInst.getName());
}
String[] userIds = orga.getUsersIdsByRoleNames(componentId, profiles);
int userId = -1;
Worker worker = null;
boolean find = false;
for (int u = 0; u < userIds.length; u++) {
userId = Integer.parseInt(userIds[u]);
if (!find && (userId == creatorId)) {
find = true;
}
worker = new Worker(userId, 0, 0, true, true, componentId);
workers.add(worker);
}
if (!find) {
worker = new Worker(creatorId, 0, 0, true, true, componentId);
workers.add(worker);
}
Worker lastWorker = (Worker) workers.get(workers.size() - 1);
lastWorker.setApproval(true);
return workers;
}
private VersioningBm getVersioningBm() {
if (versioningBm == null) {
try {
VersioningBmHome vscEjbHome =
(VersioningBmHome) EJBUtilitaire.getEJBObjectRef(JNDINames.VERSIONING_EJBHOME,
VersioningBmHome.class);
versioningBm = vscEjbHome.create();
} catch (Exception e) {
// NEED
// throw new
// ...RuntimeException("VersioningSessionController.initEJB()",SilverpeasRuntimeException.
// ERROR,"root.EX_CANT_GET_REMOTE_OBJECT",e);
}
}
return versioningBm;
}
} | fixing bug #1685
In fact, a Javascript error occurred and blocked form submission
| ejb-core/formtemplate/src/main/java/com/silverpeas/form/fieldDisplayer/FileFieldDisplayer.java | fixing bug #1685 In fact, a Javascript error occurred and blocked form submission | <ide><path>jb-core/formtemplate/src/main/java/com/silverpeas/form/fieldDisplayer/FileFieldDisplayer.java
<ide> if (template.isMandatory() && PagesContext.useMandatory()) {
<ide> out.println(" if (isWhitespace(stripInitialWhitespace(field.value))) {");
<ide> out.println(" var " + fieldName + "Value = document.getElementById('" + fieldName +
<del> FileField.PARAM_NAME_SUFFIX + "').value;");
<add> FileField.PARAM_ID_SUFFIX + "').value;");
<ide> out.println(" if (" + fieldName + "Value=='' || " + fieldName +
<ide> "Value.substring(0,7)==\"remove_\") {");
<ide> out.println(" errorMsg+=\" - '" + |
|
Java | apache-2.0 | 73ae76f52005ac3c0fca2a8fd3a91c7793ed34a5 | 0 | webanno/webanno,webanno/webanno,webanno/webanno,webanno/webanno | /*
* Copyright 2012
* Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology
* Technische Universität Darmstadt
*
* 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.
*/
package de.tudarmstadt.ukp.clarin.webanno.project;
import static java.util.Comparator.comparingInt;
import static org.apache.commons.io.IOUtils.closeQuietly;
import static org.apache.commons.io.IOUtils.copyLarge;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import de.tudarmstadt.ukp.clarin.webanno.api.ProjectService;
import de.tudarmstadt.ukp.clarin.webanno.api.ProjectType;
import de.tudarmstadt.ukp.clarin.webanno.api.SecurityUtil;
import de.tudarmstadt.ukp.clarin.webanno.api.event.AfterProjectCreatedEvent;
import de.tudarmstadt.ukp.clarin.webanno.api.event.BeforeProjectRemovedEvent;
import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocumentState;
import de.tudarmstadt.ukp.clarin.webanno.model.Mode;
import de.tudarmstadt.ukp.clarin.webanno.model.PermissionLevel;
import de.tudarmstadt.ukp.clarin.webanno.model.Project;
import de.tudarmstadt.ukp.clarin.webanno.model.ProjectPermission;
import de.tudarmstadt.ukp.clarin.webanno.security.UserDao;
import de.tudarmstadt.ukp.clarin.webanno.security.model.Authority;
import de.tudarmstadt.ukp.clarin.webanno.security.model.User;
import de.tudarmstadt.ukp.clarin.webanno.support.ZipUtils;
import de.tudarmstadt.ukp.clarin.webanno.support.logging.Logging;
@Component(ProjectService.SERVICE_NAME)
public class ProjectServiceImpl
implements ProjectService, SmartLifecycle
{
private final Logger log = LoggerFactory.getLogger(getClass());
@PersistenceContext
private EntityManager entityManager;
@Resource(name = "userRepository")
private UserDao userRepository;
private @Resource ApplicationEventPublisher applicationEventPublisher;
@Value(value = "${repository.path}")
private File dir;
// The annotation preference properties File name
private static final String annotationPreferencePropertiesFileName = "annotation.properties";
private boolean running = false;
private List<ProjectType> projectTypes;
public ProjectServiceImpl()
{
// Nothing to do
}
@Override
@Transactional
public void createProject(Project aProject)
throws IOException
{
entityManager.persist(aProject);
String path = dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId();
FileUtils.forceMkdir(new File(path));
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aProject.getId()))) {
log.info("Created project [{}]({})", aProject.getName(), aProject.getId());
}
applicationEventPublisher.publishEvent(new AfterProjectCreatedEvent(this, aProject));
}
@Override
@Transactional
public void updateProject(Project aProject)
{
entityManager.merge(aProject);
}
@Override
@Transactional
public void createProjectPermission(ProjectPermission aPermission)
{
entityManager.persist(aPermission);
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aPermission.getProject().getId()))) {
log.info("Created permission [{}] for user [{}] on project [{}]({})",
aPermission.getLevel(), aPermission.getUser(),
aPermission.getProject().getName(), aPermission.getProject().getId());
}
}
@Override
@Transactional
public boolean existsProject(String aName)
{
String query =
"FROM Project " +
"WHERE name = :name";
try {
entityManager
.createQuery(query, Project.class)
.setParameter("name", aName)
.getSingleResult();
return true;
}
catch (NoResultException ex) {
return false;
}
}
@Override
public boolean existsProjectPermission(User aUser, Project aProject)
{
String query =
"FROM ProjectPermission " +
"WHERE user = :user AND project = :project";
List<ProjectPermission> projectPermissions = entityManager
.createQuery(query, ProjectPermission.class)
.setParameter("user", aUser.getUsername())
.setParameter("project", aProject)
.getResultList();
// if at least one permission level exist
if (projectPermissions.size() > 0) {
return true;
}
else {
return false;
}
}
@Override
@Transactional
public boolean existsProjectPermissionLevel(User aUser, Project aProject,
PermissionLevel aLevel)
{
String query =
"FROM ProjectPermission " +
"WHERE user = :user AND project = :project AND level = :level";
try {
entityManager
.createQuery(query, ProjectPermission.class)
.setParameter("user", aUser.getUsername())
.setParameter("project", aProject)
.setParameter("level", aLevel)
.getSingleResult();
return true;
}
catch (NoResultException ex) {
return false;
}
}
@Override
@Transactional
public boolean existsProjectTimeStamp(Project aProject, String aUsername)
{
try {
if (getProjectTimeStamp(aProject, aUsername) == null) {
return false;
}
return true;
}
catch (NoResultException ex) {
return false;
}
}
@Override
public boolean existsProjectTimeStamp(Project aProject)
{
try {
if (getProjectTimeStamp(aProject) == null) {
return false;
}
return true;
}
catch (NoResultException ex) {
return false;
}
}
@Override
public File getProjectLogFile(Project aProject)
{
return new File(dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + "project-"
+ aProject.getId() + ".log");
}
@Override
public File getGuidelinesFolder(Project aProject)
{
return new File(dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId() + "/"
+ GUIDELINES_FOLDER + "/");
}
@Override
public File getMetaInfFolder(Project aProject)
{
return new File(dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId() + "/"
+ META_INF_FOLDER + "/");
}
@Override
@Transactional(noRollbackFor = NoResultException.class)
public List<Authority> listAuthorities(User aUser)
{
String query =
"FROM Authority " +
"WHERE username = :username";
return entityManager
.createQuery(query, Authority.class)
.setParameter("username", aUser).getResultList();
}
@Override
public File getGuideline(Project aProject, String aFilename)
{
return new File(dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId() + "/"
+ GUIDELINES_FOLDER + "/" + aFilename);
}
@Override
@Transactional(noRollbackFor = NoResultException.class)
public List<ProjectPermission> listProjectPermissionLevel(User aUser, Project aProject)
{
String query =
"FROM ProjectPermission " +
"WHERE user =:user AND project =:project";
return entityManager
.createQuery(query, ProjectPermission.class)
.setParameter("user", aUser.getUsername())
.setParameter("project", aProject)
.getResultList();
}
@Override
@Transactional(noRollbackFor = NoResultException.class)
public List<PermissionLevel> getProjectPermissionLevels(User aUser, Project aProject)
{
String query =
"SELECT level " +
"FROM ProjectPermission " +
"WHERE user = :user AND " + "project = :project";
try {
return entityManager
.createQuery(query, PermissionLevel.class)
.setParameter("user", aUser.getUsername())
.setParameter("project", aProject)
.getResultList();
}
catch (NoResultException e) {
return Collections.emptyList();
}
}
@Override
@Transactional(noRollbackFor = NoResultException.class)
public void setProjectPermissionLevels(User aUser, Project aProject,
Collection<PermissionLevel> aLevels)
{
Set<PermissionLevel> levelsToBeGranted = new HashSet<>(aLevels);
List<ProjectPermission> permissions = new ArrayList<>();
try {
permissions.addAll(listProjectPermissionLevel(aUser, aProject));
}
catch (NoResultException e) {
// Nothing to do
}
// Remove permissions that no longer exist
for (ProjectPermission permission : permissions) {
if (!aLevels.contains(permission.getLevel())) {
removeProjectPermission(permission);
}
else {
levelsToBeGranted.remove(permission.getLevel());
}
}
// Grant new permissions
for (PermissionLevel level : levelsToBeGranted) {
createProjectPermission(new ProjectPermission(aProject, aUser.getUsername(), level));
}
}
@Override
public List<User> listProjectUsersWithPermissions(Project aProject)
{
String query =
"SELECT DISTINCT perm.user " +
"FROM ProjectPermission AS perm" +
"WHERE perm.project = :project " +
"ORDER BY perm.user ASC";
List<String> usernames = entityManager
.createQuery(query, String.class)
.setParameter("project", aProject)
.getResultList();
List<User> users = new ArrayList<>();
for (String username : usernames) {
if (userRepository.exists(username)) {
users.add(userRepository.get(username));
}
}
return users;
}
@Override
public List<User> listProjectUsersWithPermissions(Project aProject,
PermissionLevel aPermissionLevel)
{
String query =
"SELECT DISTINCT user " +
"FROM ProjectPermission " +
"WHERE project = :project AND level = :level " +
"ORDER BY user ASC";
List<String> usernames = entityManager
.createQuery(query, String.class)
.setParameter("project", aProject)
.setParameter("level", aPermissionLevel)
.getResultList();
List<User> users = new ArrayList<>();
for (String username : usernames) {
if (userRepository.exists(username)) {
users.add(userRepository.get(username));
}
}
return users;
}
@Override
@Transactional
public Project getProject(String aName)
{
String query =
"FROM Project " +
"WHERE name = :name";
return entityManager
.createQuery(query, Project.class)
.setParameter("name", aName)
.getSingleResult();
}
@Override
public Project getProject(long aId)
{
String query =
"FROM Project " +
"WHERE id = :id";
return entityManager
.createQuery(query, Project.class)
.setParameter("id", aId)
.getSingleResult();
}
@Override
public void createGuideline(Project aProject, File aContent, String aFileName)
throws IOException
{
String guidelinePath = dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId()
+ "/" + GUIDELINES_FOLDER + "/";
FileUtils.forceMkdir(new File(guidelinePath));
copyLarge(new FileInputStream(aContent), new FileOutputStream(new File(guidelinePath
+ aFileName)));
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aProject.getId()))) {
log.info("Created guidelines file [{}] in project [{}]({})",
aFileName, aProject.getName(), aProject.getId());
}
}
@Override
@Transactional(noRollbackFor = NoResultException.class)
public List<ProjectPermission> getProjectPermissions(Project aProject)
{
String query =
"FROM ProjectPermission " +
"WHERE project = :project";
return entityManager
.createQuery(query, ProjectPermission.class)
.setParameter("project", aProject)
.getResultList();
}
@Override
@Transactional
public Date getProjectTimeStamp(Project aProject, String aUsername)
{
String query =
"SELECT MAX(ann.timestamp) " +
"FROM AnnotationDocument AS ann " +
"WHERE ann.project = :project AND ann.user = :user";
return entityManager
.createQuery(query, Date.class)
.setParameter("project", aProject).setParameter("user", aUsername)
.getSingleResult();
}
@Override
public Date getProjectTimeStamp(Project aProject)
{
String query =
"SELECT MAX(doc.timestamp) " +
"FROM SourceDocument AS doc " +
"WHERE doc.project = :project";
return entityManager
.createQuery(query, Date.class)
.setParameter("project", aProject)
.getSingleResult();
}
@Override
@Transactional(noRollbackFor = NoResultException.class)
public List<Project> listProjectsWithFinishedAnnos()
{
String query =
"SELECT DISTINCT ann.project " +
"FROM AnnotationDocument AS ann " +
"WHERE ann.state = :state";
return entityManager
.createQuery(query, Project.class)
.setParameter("state", AnnotationDocumentState.FINISHED)
.getResultList();
}
@Override
public List<String> listGuidelines(Project aProject)
{
// list all guideline files
File[] files = getGuidelinesFolder(aProject).listFiles();
// Name of the guideline files
List<String> annotationGuidelineFiles = new ArrayList<>();
if (files != null) {
for (File file : files) {
annotationGuidelineFiles.add(file.getName());
}
}
return annotationGuidelineFiles;
}
@Override
@Transactional
public List<Project> listProjects()
{
String query =
"FROM Project " +
"ORDER BY name ASC";
return entityManager
.createQuery(query, Project.class)
.getResultList();
}
@Override
public Properties loadUserSettings(String aUsername, Project aProject)
throws IOException
{
Properties property = new Properties();
property.load(new FileInputStream(new File(dir.getAbsolutePath() + "/" + PROJECT_FOLDER
+ "/" + aProject.getId() + "/" + SETTINGS_FOLDER + "/" + aUsername + "/"
+ annotationPreferencePropertiesFileName)));
return property;
}
@Override
@Transactional
public void removeProject(Project aProject)
throws IOException
{
// remove metadata from DB
Project project = aProject;
if (!entityManager.contains(project)) {
project = entityManager.merge(project);
}
applicationEventPublisher.publishEvent(new BeforeProjectRemovedEvent(this, aProject));
for (ProjectPermission permissions : getProjectPermissions(aProject)) {
entityManager.remove(permissions);
}
entityManager.remove(project);
// remove the project directory from the file system
String path = dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId();
try {
FileUtils.deleteDirectory(new File(path));
}
catch (FileNotFoundException e) {
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aProject.getId()))) {
log.info("Project directory to be deleted was not found: [{}]. Ignoring.", path);
}
}
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aProject.getId()))) {
log.info("Removed project [{}]({})", aProject.getName(), aProject.getId());
}
}
@Override
public void removeGuideline(Project aProject, String aFileName)
throws IOException
{
FileUtils.forceDelete(new File(dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/"
+ aProject.getId() + "/" + GUIDELINES_FOLDER + "/" + aFileName));
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aProject.getId()))) {
log.info("Removed guidelines file [{}] from project [{}]({})", aFileName,
aProject.getName(), aProject.getId());
}
}
@Override
@Transactional
public void removeProjectPermission(ProjectPermission aPermission)
{
entityManager.remove(aPermission);
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aPermission.getProject().getId()))) {
log.info("Removed permission [{}] for user [{}] on project [{}]({})",
aPermission.getLevel(), aPermission.getUser(),
aPermission.getProject().getName(), aPermission.getProject().getId());
}
}
@Override
public void savePropertiesFile(Project aProject, InputStream aIs, String aFileName)
throws IOException
{
String path = dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId() + "/"
+ FilenameUtils.getFullPath(aFileName);
FileUtils.forceMkdir(new File(path));
File newTcfFile = new File(path, FilenameUtils.getName(aFileName));
OutputStream os = null;
try {
os = new FileOutputStream(newTcfFile);
copyLarge(aIs, os);
}
finally {
closeQuietly(os);
closeQuietly(aIs);
}
}
@Override
public <T> void saveUserSettings(String aUsername, Project aProject, Mode aSubject,
T aConfigurationObject)
throws IOException
{
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(aConfigurationObject);
Properties props = new Properties();
for (PropertyDescriptor value : wrapper.getPropertyDescriptors()) {
if (wrapper.getPropertyValue(value.getName()) == null) {
continue;
}
props.setProperty(aSubject + "." + value.getName(),
wrapper.getPropertyValue(value.getName()).toString());
}
String propertiesPath = dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/"
+ aProject.getId() + "/" + SETTINGS_FOLDER + "/" + aUsername;
// append existing preferences for the other mode
if (new File(propertiesPath, annotationPreferencePropertiesFileName).exists()) {
for (Entry<Object, Object> entry : loadUserSettings(aUsername, aProject).entrySet()) {
String key = entry.getKey().toString();
// Maintain other Modes of annotations confs than this one
if (!key.substring(0, key.indexOf(".")).equals(aSubject.toString())) {
props.put(entry.getKey(), entry.getValue());
}
}
}
// for (String name : props.stringPropertyNames()) {
// log.info("{} = {}", name, props.getProperty(name));
// }
FileUtils.forceMkdir(new File(propertiesPath));
props.store(new FileOutputStream(new File(propertiesPath,
annotationPreferencePropertiesFileName)), null);
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aProject.getId()))) {
log.info("Saved preferences for user [{}] in project [{}]({})", aUsername,
aProject.getName(), aProject.getId());
}
}
@Override
public List<Project> listAccessibleProjects(User user)
{
List<Project> allowedProject = new ArrayList<>();
List<Project> allProjects = listProjects();
// if global admin, show all projects
if (SecurityUtil.isSuperAdmin(this, user)) {
return allProjects;
}
// else only projects she is admin of
for (Project project : allProjects) {
if (SecurityUtil.isProjectAdmin(project, this, user)) {
allowedProject.add(project);
}
}
return allowedProject;
}
@Override
@Transactional
public void onProjectImport(ZipFile aZip,
de.tudarmstadt.ukp.clarin.webanno.export.model.Project aExportedProject,
Project aProject)
throws Exception
{
// create project log
createProjectLog(aZip, aProject);
// create project guideline
createProjectGuideline(aZip, aProject);
// create project META-INF
createProjectMetaInf(aZip, aProject);
// Import project permissions
createProjectPermission(aExportedProject, aProject);
}
/**
* copy project log files from the exported project
* @param zip the ZIP file.
* @param aProject the project.
* @throws IOException if an I/O error occurs.
*/
@SuppressWarnings("rawtypes")
private void createProjectLog(ZipFile zip, Project aProject)
throws IOException
{
for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();
// Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
String entryName = ZipUtils.normalizeEntryName(entry);
if (entryName.startsWith(LOG_FOLDER + "/")) {
FileUtils.copyInputStreamToFile(zip.getInputStream(entry),
getProjectLogFile(aProject));
log.info("Imported log for project [" + aProject.getName() + "] with id ["
+ aProject.getId() + "]");
}
}
}
/**
* copy guidelines from the exported project
* @param zip the ZIP file.
* @param aProject the project.
* @throws IOException if an I/O error occurs.
*/
@SuppressWarnings("rawtypes")
private void createProjectGuideline(ZipFile zip, Project aProject)
throws IOException
{
for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();
// Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
String entryName = ZipUtils.normalizeEntryName(entry);
if (entryName.startsWith(GUIDELINES_FOLDER + "/")) {
String fileName = FilenameUtils.getName(entry.getName());
if (fileName.trim().isEmpty()) {
continue;
}
File guidelineDir = getGuidelinesFolder(aProject);
FileUtils.forceMkdir(guidelineDir);
FileUtils.copyInputStreamToFile(zip.getInputStream(entry), new File(guidelineDir,
fileName));
log.info("Imported guideline [" + fileName + "] for project [" + aProject.getName()
+ "] with id [" + aProject.getId() + "]");
}
}
}
/**
* copy Project META_INF from the exported project
* @param zip the ZIP file.
* @param aProject the project.
* @throws IOException if an I/O error occurs.
*/
@SuppressWarnings("rawtypes")
private void createProjectMetaInf(ZipFile zip, Project aProject)
throws IOException
{
for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();
// Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
String entryName = ZipUtils.normalizeEntryName(entry);
if (entryName.startsWith(META_INF_FOLDER + "/")) {
File metaInfDir = new File(getMetaInfFolder(aProject),
FilenameUtils.getPath(entry.getName().replace(META_INF_FOLDER + "/", "")));
// where the file reside in the META-INF/... directory
FileUtils.forceMkdir(metaInfDir);
FileUtils.copyInputStreamToFile(zip.getInputStream(entry), new File(metaInfDir,
FilenameUtils.getName(entry.getName())));
log.info("Imported META-INF for project [" + aProject.getName() + "] with id ["
+ aProject.getId() + "]");
}
}
}
/**
* Create {@link ProjectPermission} from the exported
* {@link de.tudarmstadt.ukp.clarin.webanno.export.model.ProjectPermission}
*
* @param aImportedProjectSetting
* the imported project.
* @param aImportedProject
* the project.
* @throws IOException
* if an I/O error occurs.
*/
private void createProjectPermission(
de.tudarmstadt.ukp.clarin.webanno.export.model.Project aImportedProjectSetting,
Project aImportedProject)
throws IOException
{
for (de.tudarmstadt.ukp.clarin.webanno.export.model.ProjectPermission importedPermission :
aImportedProjectSetting.getProjectPermissions()) {
ProjectPermission permission = new ProjectPermission();
permission.setLevel(importedPermission.getLevel());
permission.setProject(aImportedProject);
permission.setUser(importedPermission.getUser());
createProjectPermission(permission);
}
}
@Override
public boolean isRunning()
{
return running;
}
@Override
public void start()
{
running = true;
scanProjectTypes();
}
@Override
public void stop()
{
running = false;
}
@Override
public int getPhase()
{
return Integer.MAX_VALUE;
}
@Override
public boolean isAutoStartup()
{
return true;
}
@Override
public void stop(Runnable aCallback)
{
stop();
aCallback.run();
}
private void scanProjectTypes()
{
projectTypes = new ArrayList<>();
// Scan for project type annotations
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(ProjectType.class));
for (BeanDefinition bd : scanner.findCandidateComponents("de.tudarmstadt.ukp")) {
try {
Class<?> clazz = Class.forName(bd.getBeanClassName());
ProjectType pt = clazz.getAnnotation(ProjectType.class);
if (projectTypes.stream().anyMatch(t -> t.id().equals(pt.id()))) {
log.debug("Ignoring duplicate project type: {} ({})", pt.id(), pt.prio());
}
else {
log.debug("Found project type: {} ({})", pt.id(), pt.prio());
projectTypes.add(pt);
}
}
catch (ClassNotFoundException e) {
log.error("Class [{}] not found", bd.getBeanClassName(), e);
}
}
projectTypes.sort(comparingInt(ProjectType::prio));
}
@Override
public List<ProjectType> listProjectTypes()
{
return Collections.unmodifiableList(projectTypes);
}
}
| webanno-project/src/main/java/de/tudarmstadt/ukp/clarin/webanno/project/ProjectServiceImpl.java | /*
* Copyright 2012
* Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology
* Technische Universität Darmstadt
*
* 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.
*/
package de.tudarmstadt.ukp.clarin.webanno.project;
import static java.util.Comparator.comparingInt;
import static org.apache.commons.io.IOUtils.closeQuietly;
import static org.apache.commons.io.IOUtils.copyLarge;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import de.tudarmstadt.ukp.clarin.webanno.api.ProjectService;
import de.tudarmstadt.ukp.clarin.webanno.api.ProjectType;
import de.tudarmstadt.ukp.clarin.webanno.api.SecurityUtil;
import de.tudarmstadt.ukp.clarin.webanno.api.event.AfterProjectCreatedEvent;
import de.tudarmstadt.ukp.clarin.webanno.api.event.BeforeProjectRemovedEvent;
import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocumentState;
import de.tudarmstadt.ukp.clarin.webanno.model.Mode;
import de.tudarmstadt.ukp.clarin.webanno.model.PermissionLevel;
import de.tudarmstadt.ukp.clarin.webanno.model.Project;
import de.tudarmstadt.ukp.clarin.webanno.model.ProjectPermission;
import de.tudarmstadt.ukp.clarin.webanno.security.UserDao;
import de.tudarmstadt.ukp.clarin.webanno.security.model.Authority;
import de.tudarmstadt.ukp.clarin.webanno.security.model.User;
import de.tudarmstadt.ukp.clarin.webanno.support.ZipUtils;
import de.tudarmstadt.ukp.clarin.webanno.support.logging.Logging;
@Component(ProjectService.SERVICE_NAME)
public class ProjectServiceImpl
implements ProjectService, SmartLifecycle
{
private final Logger log = LoggerFactory.getLogger(getClass());
@PersistenceContext
private EntityManager entityManager;
@Resource(name = "userRepository")
private UserDao userRepository;
private @Resource ApplicationEventPublisher applicationEventPublisher;
@Value(value = "${repository.path}")
private File dir;
// The annotation preference properties File name
private static final String annotationPreferencePropertiesFileName = "annotation.properties";
private boolean running = false;
private List<ProjectType> projectTypes;
public ProjectServiceImpl()
{
// Nothing to do
}
@Override
@Transactional
public void createProject(Project aProject)
throws IOException
{
entityManager.persist(aProject);
String path = dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId();
FileUtils.forceMkdir(new File(path));
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aProject.getId()))) {
log.info("Created project [{}]({})", aProject.getName(), aProject.getId());
}
applicationEventPublisher.publishEvent(new AfterProjectCreatedEvent(this, aProject));
}
@Override
@Transactional
public void updateProject(Project aProject)
{
entityManager.merge(aProject);
}
@Override
@Transactional
public void createProjectPermission(ProjectPermission aPermission)
{
entityManager.persist(aPermission);
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aPermission.getProject().getId()))) {
log.info("Created permission [{}] for user [{}] on project [{}]({})",
aPermission.getLevel(), aPermission.getUser(),
aPermission.getProject().getName(), aPermission.getProject().getId());
}
}
@Override
@Transactional
public boolean existsProject(String aName)
{
try {
entityManager.createQuery("FROM Project WHERE name = :name", Project.class)
.setParameter("name", aName).getSingleResult();
return true;
}
catch (NoResultException ex) {
return false;
}
}
@Override
public boolean existsProjectPermission(User aUser, Project aProject)
{
List<ProjectPermission> projectPermissions = entityManager
.createQuery(
"FROM ProjectPermission WHERE user = :user AND " + "project =:project",
ProjectPermission.class).setParameter("user", aUser.getUsername())
.setParameter("project", aProject).getResultList();
// if at least one permission level exist
if (projectPermissions.size() > 0) {
return true;
}
else {
return false;
}
}
@Override
@Transactional
public boolean existsProjectPermissionLevel(User aUser, Project aProject,
PermissionLevel aLevel)
{
try {
entityManager
.createQuery(
"FROM ProjectPermission WHERE user = :user AND "
+ "project =:project AND level =:level",
ProjectPermission.class)
.setParameter("user", aUser.getUsername()).setParameter("project", aProject)
.setParameter("level", aLevel).getSingleResult();
return true;
}
catch (NoResultException ex) {
return false;
}
}
@Override
@Transactional
public boolean existsProjectTimeStamp(Project aProject, String aUsername)
{
try {
if (getProjectTimeStamp(aProject, aUsername) == null) {
return false;
}
return true;
}
catch (NoResultException ex) {
return false;
}
}
@Override
public boolean existsProjectTimeStamp(Project aProject)
{
try {
if (getProjectTimeStamp(aProject) == null) {
return false;
}
return true;
}
catch (NoResultException ex) {
return false;
}
}
@Override
public File getProjectLogFile(Project aProject)
{
return new File(dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + "project-"
+ aProject.getId() + ".log");
}
@Override
public File getGuidelinesFolder(Project aProject)
{
return new File(dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId() + "/"
+ GUIDELINES_FOLDER + "/");
}
@Override
public File getMetaInfFolder(Project aProject)
{
return new File(dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId() + "/"
+ META_INF_FOLDER + "/");
}
@Override
@Transactional(noRollbackFor = NoResultException.class)
public List<Authority> listAuthorities(User aUser)
{
return entityManager
.createQuery("FROM Authority where username =:username", Authority.class)
.setParameter("username", aUser).getResultList();
}
@Override
public File getGuideline(Project aProject, String aFilename)
{
return new File(dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId() + "/"
+ GUIDELINES_FOLDER + "/" + aFilename);
}
@Override
@Transactional(noRollbackFor = NoResultException.class)
public List<ProjectPermission> listProjectPermissionLevel(User aUser, Project aProject)
{
return entityManager
.createQuery("FROM ProjectPermission WHERE user =:user AND " + "project =:project",
ProjectPermission.class).setParameter("user", aUser.getUsername())
.setParameter("project", aProject).getResultList();
}
@Override
@Transactional(noRollbackFor = NoResultException.class)
public List<PermissionLevel> getProjectPermissionLevels(User aUser, Project aProject)
{
try {
String query = "SELECT level FROM ProjectPermission WHERE user =:user AND " + "project =:project";
return entityManager.createQuery(query, PermissionLevel.class)
.setParameter("user", aUser.getUsername())
.setParameter("project", aProject).getResultList();
}
catch (NoResultException e) {
return Collections.emptyList();
}
}
@Override
@Transactional(noRollbackFor = NoResultException.class)
public void setProjectPermissionLevels(User aUser, Project aProject,
Collection<PermissionLevel> aLevels)
{
Set<PermissionLevel> levelsToBeGranted = new HashSet<>(aLevels);
List<ProjectPermission> permissions = new ArrayList<>();
try {
permissions.addAll(listProjectPermissionLevel(aUser, aProject));
}
catch (NoResultException e) {
// Nothing to do
}
// Remove permissions that no longer exist
for (ProjectPermission permission : permissions) {
if (!aLevels.contains(permission.getLevel())) {
removeProjectPermission(permission);
}
else {
levelsToBeGranted.remove(permission.getLevel());
}
}
// Grant new permissions
for (PermissionLevel level : levelsToBeGranted) {
createProjectPermission(new ProjectPermission(aProject, aUser.getUsername(), level));
}
}
@Override
public List<User> listProjectUsersWithPermissions(Project aProject)
{
List<String> usernames = entityManager
.createQuery(
"SELECT DISTINCT user FROM ProjectPermission WHERE "
+ "project =:project ORDER BY user ASC", String.class)
.setParameter("project", aProject).getResultList();
List<User> users = new ArrayList<>();
for (String username : usernames) {
if (userRepository.exists(username)) {
users.add(userRepository.get(username));
}
}
return users;
}
@Override
public List<User> listProjectUsersWithPermissions(Project aProject,
PermissionLevel aPermissionLevel)
{
List<String> usernames = entityManager
.createQuery(
"SELECT DISTINCT user FROM ProjectPermission WHERE "
+ "project =:project AND level =:level ORDER BY user ASC",
String.class).setParameter("project", aProject)
.setParameter("level", aPermissionLevel).getResultList();
List<User> users = new ArrayList<>();
for (String username : usernames) {
if (userRepository.exists(username)) {
users.add(userRepository.get(username));
}
}
return users;
}
@Override
@Transactional
public Project getProject(String aName)
{
return entityManager.createQuery("FROM Project WHERE name = :name", Project.class)
.setParameter("name", aName).getSingleResult();
}
@Override
public Project getProject(long aId)
{
return entityManager.createQuery("FROM Project WHERE id = :id", Project.class)
.setParameter("id", aId).getSingleResult();
}
@Override
public void createGuideline(Project aProject, File aContent, String aFileName)
throws IOException
{
String guidelinePath = dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId()
+ "/" + GUIDELINES_FOLDER + "/";
FileUtils.forceMkdir(new File(guidelinePath));
copyLarge(new FileInputStream(aContent), new FileOutputStream(new File(guidelinePath
+ aFileName)));
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aProject.getId()))) {
log.info("Created guidelines file [{}] in project [{}]({})",
aFileName, aProject.getName(), aProject.getId());
}
}
@Override
@Transactional(noRollbackFor = NoResultException.class)
public List<ProjectPermission> getProjectPermissions(Project aProject)
{
return entityManager
.createQuery("FROM ProjectPermission WHERE project =:project",
ProjectPermission.class).setParameter("project", aProject).getResultList();
}
@Override
@Transactional
public Date getProjectTimeStamp(Project aProject, String aUsername)
{
return entityManager
.createQuery(
"SELECT max(timestamp) FROM AnnotationDocument WHERE project = :project "
+ " AND user = :user", Date.class)
.setParameter("project", aProject).setParameter("user", aUsername)
.getSingleResult();
}
@Override
public Date getProjectTimeStamp(Project aProject)
{
return entityManager
.createQuery("SELECT max(timestamp) FROM SourceDocument WHERE project = :project",
Date.class).setParameter("project", aProject).getSingleResult();
}
@Override
@Transactional(noRollbackFor = NoResultException.class)
public List<Project> listProjectsWithFinishedAnnos()
{
return entityManager
.createQuery("SELECT DISTINCT project FROM AnnotationDocument WHERE state = :state",
Project.class)
.setParameter("state", AnnotationDocumentState.FINISHED.getName()).getResultList();
}
@Override
public List<String> listGuidelines(Project aProject)
{
// list all guideline files
File[] files = getGuidelinesFolder(aProject).listFiles();
// Name of the guideline files
List<String> annotationGuidelineFiles = new ArrayList<>();
if (files != null) {
for (File file : files) {
annotationGuidelineFiles.add(file.getName());
}
}
return annotationGuidelineFiles;
}
@Override
@Transactional
public List<Project> listProjects()
{
return entityManager.createQuery("FROM Project ORDER BY name ASC ", Project.class)
.getResultList();
}
@Override
public Properties loadUserSettings(String aUsername, Project aProject)
throws IOException
{
Properties property = new Properties();
property.load(new FileInputStream(new File(dir.getAbsolutePath() + "/" + PROJECT_FOLDER
+ "/" + aProject.getId() + "/" + SETTINGS_FOLDER + "/" + aUsername + "/"
+ annotationPreferencePropertiesFileName)));
return property;
}
@Override
@Transactional
public void removeProject(Project aProject)
throws IOException
{
// remove metadata from DB
Project project = aProject;
if (!entityManager.contains(project)) {
project = entityManager.merge(project);
}
applicationEventPublisher.publishEvent(new BeforeProjectRemovedEvent(this, aProject));
for (ProjectPermission permissions : getProjectPermissions(aProject)) {
entityManager.remove(permissions);
}
entityManager.remove(project);
// remove the project directory from the file system
String path = dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId();
try {
FileUtils.deleteDirectory(new File(path));
}
catch (FileNotFoundException e) {
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aProject.getId()))) {
log.info("Project directory to be deleted was not found: [{}]. Ignoring.", path);
}
}
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aProject.getId()))) {
log.info("Removed project [{}]({})", aProject.getName(), aProject.getId());
}
}
@Override
public void removeGuideline(Project aProject, String aFileName)
throws IOException
{
FileUtils.forceDelete(new File(dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/"
+ aProject.getId() + "/" + GUIDELINES_FOLDER + "/" + aFileName));
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aProject.getId()))) {
log.info("Removed guidelines file [{}] from project [{}]({})", aFileName,
aProject.getName(), aProject.getId());
}
}
@Override
@Transactional
public void removeProjectPermission(ProjectPermission aPermission)
{
entityManager.remove(aPermission);
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aPermission.getProject().getId()))) {
log.info("Removed permission [{}] for user [{}] on project [{}]({})",
aPermission.getLevel(), aPermission.getUser(),
aPermission.getProject().getName(), aPermission.getProject().getId());
}
}
@Override
public void savePropertiesFile(Project aProject, InputStream aIs, String aFileName)
throws IOException
{
String path = dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId() + "/"
+ FilenameUtils.getFullPath(aFileName);
FileUtils.forceMkdir(new File(path));
File newTcfFile = new File(path, FilenameUtils.getName(aFileName));
OutputStream os = null;
try {
os = new FileOutputStream(newTcfFile);
copyLarge(aIs, os);
}
finally {
closeQuietly(os);
closeQuietly(aIs);
}
}
@Override
public <T> void saveUserSettings(String aUsername, Project aProject, Mode aSubject,
T aConfigurationObject)
throws IOException
{
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(aConfigurationObject);
Properties props = new Properties();
for (PropertyDescriptor value : wrapper.getPropertyDescriptors()) {
if (wrapper.getPropertyValue(value.getName()) == null) {
continue;
}
props.setProperty(aSubject + "." + value.getName(),
wrapper.getPropertyValue(value.getName()).toString());
}
String propertiesPath = dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/"
+ aProject.getId() + "/" + SETTINGS_FOLDER + "/" + aUsername;
// append existing preferences for the other mode
if (new File(propertiesPath, annotationPreferencePropertiesFileName).exists()) {
for (Entry<Object, Object> entry : loadUserSettings(aUsername, aProject).entrySet()) {
String key = entry.getKey().toString();
// Maintain other Modes of annotations confs than this one
if (!key.substring(0, key.indexOf(".")).equals(aSubject.toString())) {
props.put(entry.getKey(), entry.getValue());
}
}
}
// for (String name : props.stringPropertyNames()) {
// log.info("{} = {}", name, props.getProperty(name));
// }
FileUtils.forceMkdir(new File(propertiesPath));
props.store(new FileOutputStream(new File(propertiesPath,
annotationPreferencePropertiesFileName)), null);
try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
String.valueOf(aProject.getId()))) {
log.info("Saved preferences for user [{}] in project [{}]({})", aUsername,
aProject.getName(), aProject.getId());
}
}
@Override
public List<Project> listAccessibleProjects(User user)
{
List<Project> allowedProject = new ArrayList<>();
List<Project> allProjects = listProjects();
// if global admin, show all projects
if (SecurityUtil.isSuperAdmin(this, user)) {
return allProjects;
}
// else only projects she is admin of
for (Project project : allProjects) {
if (SecurityUtil.isProjectAdmin(project, this, user)) {
allowedProject.add(project);
}
}
return allowedProject;
}
@Override
@Transactional
public void onProjectImport(ZipFile aZip,
de.tudarmstadt.ukp.clarin.webanno.export.model.Project aExportedProject,
Project aProject)
throws Exception
{
// create project log
createProjectLog(aZip, aProject);
// create project guideline
createProjectGuideline(aZip, aProject);
// create project META-INF
createProjectMetaInf(aZip, aProject);
// Import project permissions
createProjectPermission(aExportedProject, aProject);
}
/**
* copy project log files from the exported project
* @param zip the ZIP file.
* @param aProject the project.
* @throws IOException if an I/O error occurs.
*/
@SuppressWarnings("rawtypes")
private void createProjectLog(ZipFile zip, Project aProject)
throws IOException
{
for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();
// Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
String entryName = ZipUtils.normalizeEntryName(entry);
if (entryName.startsWith(LOG_FOLDER + "/")) {
FileUtils.copyInputStreamToFile(zip.getInputStream(entry),
getProjectLogFile(aProject));
log.info("Imported log for project [" + aProject.getName() + "] with id ["
+ aProject.getId() + "]");
}
}
}
/**
* copy guidelines from the exported project
* @param zip the ZIP file.
* @param aProject the project.
* @throws IOException if an I/O error occurs.
*/
@SuppressWarnings("rawtypes")
private void createProjectGuideline(ZipFile zip, Project aProject)
throws IOException
{
for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();
// Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
String entryName = ZipUtils.normalizeEntryName(entry);
if (entryName.startsWith(GUIDELINES_FOLDER + "/")) {
String fileName = FilenameUtils.getName(entry.getName());
if (fileName.trim().isEmpty()) {
continue;
}
File guidelineDir = getGuidelinesFolder(aProject);
FileUtils.forceMkdir(guidelineDir);
FileUtils.copyInputStreamToFile(zip.getInputStream(entry), new File(guidelineDir,
fileName));
log.info("Imported guideline [" + fileName + "] for project [" + aProject.getName()
+ "] with id [" + aProject.getId() + "]");
}
}
}
/**
* copy Project META_INF from the exported project
* @param zip the ZIP file.
* @param aProject the project.
* @throws IOException if an I/O error occurs.
*/
@SuppressWarnings("rawtypes")
private void createProjectMetaInf(ZipFile zip, Project aProject)
throws IOException
{
for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();
// Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
String entryName = ZipUtils.normalizeEntryName(entry);
if (entryName.startsWith(META_INF_FOLDER + "/")) {
File metaInfDir = new File(getMetaInfFolder(aProject),
FilenameUtils.getPath(entry.getName().replace(META_INF_FOLDER + "/", "")));
// where the file reside in the META-INF/... directory
FileUtils.forceMkdir(metaInfDir);
FileUtils.copyInputStreamToFile(zip.getInputStream(entry), new File(metaInfDir,
FilenameUtils.getName(entry.getName())));
log.info("Imported META-INF for project [" + aProject.getName() + "] with id ["
+ aProject.getId() + "]");
}
}
}
/**
* Create {@link ProjectPermission} from the exported
* {@link de.tudarmstadt.ukp.clarin.webanno.export.model.ProjectPermission}
*
* @param aImportedProjectSetting
* the imported project.
* @param aImportedProject
* the project.
* @throws IOException
* if an I/O error occurs.
*/
private void createProjectPermission(
de.tudarmstadt.ukp.clarin.webanno.export.model.Project aImportedProjectSetting,
Project aImportedProject)
throws IOException
{
for (de.tudarmstadt.ukp.clarin.webanno.export.model.ProjectPermission importedPermission :
aImportedProjectSetting.getProjectPermissions()) {
ProjectPermission permission = new ProjectPermission();
permission.setLevel(importedPermission.getLevel());
permission.setProject(aImportedProject);
permission.setUser(importedPermission.getUser());
createProjectPermission(permission);
}
}
@Override
public boolean isRunning()
{
return running;
}
@Override
public void start()
{
running = true;
scanProjectTypes();
}
@Override
public void stop()
{
running = false;
}
@Override
public int getPhase()
{
return Integer.MAX_VALUE;
}
@Override
public boolean isAutoStartup()
{
return true;
}
@Override
public void stop(Runnable aCallback)
{
stop();
aCallback.run();
}
private void scanProjectTypes()
{
projectTypes = new ArrayList<>();
// Scan for project type annotations
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(ProjectType.class));
for (BeanDefinition bd : scanner.findCandidateComponents("de.tudarmstadt.ukp")) {
try {
Class<?> clazz = Class.forName(bd.getBeanClassName());
ProjectType pt = clazz.getAnnotation(ProjectType.class);
if (projectTypes.stream().anyMatch(t -> t.id().equals(pt.id()))) {
log.debug("Ignoring duplicate project type: {} ({})", pt.id(), pt.prio());
}
else {
log.debug("Found project type: {} ({})", pt.id(), pt.prio());
projectTypes.add(pt);
}
}
catch (ClassNotFoundException e) {
log.error("Class [{}] not found", bd.getBeanClassName(), e);
}
}
projectTypes.sort(comparingInt(ProjectType::prio));
}
@Override
public List<ProjectType> listProjectTypes()
{
return Collections.unmodifiableList(projectTypes);
}
}
| No issue. Organized and formatted query strings.
| webanno-project/src/main/java/de/tudarmstadt/ukp/clarin/webanno/project/ProjectServiceImpl.java | No issue. Organized and formatted query strings. | <ide><path>ebanno-project/src/main/java/de/tudarmstadt/ukp/clarin/webanno/project/ProjectServiceImpl.java
<ide> @Transactional
<ide> public boolean existsProject(String aName)
<ide> {
<add> String query =
<add> "FROM Project " +
<add> "WHERE name = :name";
<ide> try {
<del> entityManager.createQuery("FROM Project WHERE name = :name", Project.class)
<del> .setParameter("name", aName).getSingleResult();
<add> entityManager
<add> .createQuery(query, Project.class)
<add> .setParameter("name", aName)
<add> .getSingleResult();
<ide> return true;
<ide> }
<ide> catch (NoResultException ex) {
<ide> @Override
<ide> public boolean existsProjectPermission(User aUser, Project aProject)
<ide> {
<del>
<add> String query =
<add> "FROM ProjectPermission " +
<add> "WHERE user = :user AND project = :project";
<ide> List<ProjectPermission> projectPermissions = entityManager
<del> .createQuery(
<del> "FROM ProjectPermission WHERE user = :user AND " + "project =:project",
<del> ProjectPermission.class).setParameter("user", aUser.getUsername())
<del> .setParameter("project", aProject).getResultList();
<add> .createQuery(query, ProjectPermission.class)
<add> .setParameter("user", aUser.getUsername())
<add> .setParameter("project", aProject)
<add> .getResultList();
<add>
<ide> // if at least one permission level exist
<ide> if (projectPermissions.size() > 0) {
<ide> return true;
<ide> else {
<ide> return false;
<ide> }
<del>
<ide> }
<ide>
<ide> @Override
<ide> public boolean existsProjectPermissionLevel(User aUser, Project aProject,
<ide> PermissionLevel aLevel)
<ide> {
<add> String query =
<add> "FROM ProjectPermission " +
<add> "WHERE user = :user AND project = :project AND level = :level";
<ide> try {
<ide> entityManager
<del> .createQuery(
<del> "FROM ProjectPermission WHERE user = :user AND "
<del> + "project =:project AND level =:level",
<del> ProjectPermission.class)
<del> .setParameter("user", aUser.getUsername()).setParameter("project", aProject)
<del> .setParameter("level", aLevel).getSingleResult();
<add> .createQuery(query, ProjectPermission.class)
<add> .setParameter("user", aUser.getUsername())
<add> .setParameter("project", aProject)
<add> .setParameter("level", aLevel)
<add> .getSingleResult();
<ide> return true;
<ide> }
<ide> catch (NoResultException ex) {
<ide> public boolean existsProjectTimeStamp(Project aProject, String aUsername)
<ide> {
<ide> try {
<del>
<ide> if (getProjectTimeStamp(aProject, aUsername) == null) {
<ide> return false;
<ide> }
<ide> public boolean existsProjectTimeStamp(Project aProject)
<ide> {
<ide> try {
<del>
<ide> if (getProjectTimeStamp(aProject) == null) {
<ide> return false;
<ide> }
<ide> @Transactional(noRollbackFor = NoResultException.class)
<ide> public List<Authority> listAuthorities(User aUser)
<ide> {
<add> String query =
<add> "FROM Authority " +
<add> "WHERE username = :username";
<ide> return entityManager
<del> .createQuery("FROM Authority where username =:username", Authority.class)
<add> .createQuery(query, Authority.class)
<ide> .setParameter("username", aUser).getResultList();
<ide> }
<ide>
<ide> @Transactional(noRollbackFor = NoResultException.class)
<ide> public List<ProjectPermission> listProjectPermissionLevel(User aUser, Project aProject)
<ide> {
<add> String query =
<add> "FROM ProjectPermission " +
<add> "WHERE user =:user AND project =:project";
<ide> return entityManager
<del> .createQuery("FROM ProjectPermission WHERE user =:user AND " + "project =:project",
<del> ProjectPermission.class).setParameter("user", aUser.getUsername())
<del> .setParameter("project", aProject).getResultList();
<add> .createQuery(query, ProjectPermission.class)
<add> .setParameter("user", aUser.getUsername())
<add> .setParameter("project", aProject)
<add> .getResultList();
<ide> }
<ide>
<ide> @Override
<ide> @Transactional(noRollbackFor = NoResultException.class)
<ide> public List<PermissionLevel> getProjectPermissionLevels(User aUser, Project aProject)
<ide> {
<add> String query =
<add> "SELECT level " +
<add> "FROM ProjectPermission " +
<add> "WHERE user = :user AND " + "project = :project";
<ide> try {
<del> String query = "SELECT level FROM ProjectPermission WHERE user =:user AND " + "project =:project";
<del> return entityManager.createQuery(query, PermissionLevel.class)
<add> return entityManager
<add> .createQuery(query, PermissionLevel.class)
<ide> .setParameter("user", aUser.getUsername())
<del> .setParameter("project", aProject).getResultList();
<add> .setParameter("project", aProject)
<add> .getResultList();
<ide> }
<ide> catch (NoResultException e) {
<ide> return Collections.emptyList();
<ide> @Override
<ide> public List<User> listProjectUsersWithPermissions(Project aProject)
<ide> {
<del>
<add> String query =
<add> "SELECT DISTINCT perm.user " +
<add> "FROM ProjectPermission AS perm" +
<add> "WHERE perm.project = :project " +
<add> "ORDER BY perm.user ASC";
<ide> List<String> usernames = entityManager
<del> .createQuery(
<del> "SELECT DISTINCT user FROM ProjectPermission WHERE "
<del> + "project =:project ORDER BY user ASC", String.class)
<del> .setParameter("project", aProject).getResultList();
<add> .createQuery(query, String.class)
<add> .setParameter("project", aProject)
<add> .getResultList();
<ide>
<ide> List<User> users = new ArrayList<>();
<ide>
<ide> public List<User> listProjectUsersWithPermissions(Project aProject,
<ide> PermissionLevel aPermissionLevel)
<ide> {
<add> String query =
<add> "SELECT DISTINCT user " +
<add> "FROM ProjectPermission " +
<add> "WHERE project = :project AND level = :level " +
<add> "ORDER BY user ASC";
<ide> List<String> usernames = entityManager
<del> .createQuery(
<del> "SELECT DISTINCT user FROM ProjectPermission WHERE "
<del> + "project =:project AND level =:level ORDER BY user ASC",
<del> String.class).setParameter("project", aProject)
<del> .setParameter("level", aPermissionLevel).getResultList();
<add> .createQuery(query, String.class)
<add> .setParameter("project", aProject)
<add> .setParameter("level", aPermissionLevel)
<add> .getResultList();
<ide> List<User> users = new ArrayList<>();
<ide> for (String username : usernames) {
<ide> if (userRepository.exists(username)) {
<ide> @Transactional
<ide> public Project getProject(String aName)
<ide> {
<del> return entityManager.createQuery("FROM Project WHERE name = :name", Project.class)
<del> .setParameter("name", aName).getSingleResult();
<add> String query =
<add> "FROM Project " +
<add> "WHERE name = :name";
<add> return entityManager
<add> .createQuery(query, Project.class)
<add> .setParameter("name", aName)
<add> .getSingleResult();
<ide> }
<ide>
<ide> @Override
<ide> public Project getProject(long aId)
<ide> {
<del> return entityManager.createQuery("FROM Project WHERE id = :id", Project.class)
<del> .setParameter("id", aId).getSingleResult();
<add> String query =
<add> "FROM Project " +
<add> "WHERE id = :id";
<add> return entityManager
<add> .createQuery(query, Project.class)
<add> .setParameter("id", aId)
<add> .getSingleResult();
<ide> }
<ide>
<ide> @Override
<ide> @Transactional(noRollbackFor = NoResultException.class)
<ide> public List<ProjectPermission> getProjectPermissions(Project aProject)
<ide> {
<add> String query =
<add> "FROM ProjectPermission " +
<add> "WHERE project = :project";
<ide> return entityManager
<del> .createQuery("FROM ProjectPermission WHERE project =:project",
<del> ProjectPermission.class).setParameter("project", aProject).getResultList();
<add> .createQuery(query, ProjectPermission.class)
<add> .setParameter("project", aProject)
<add> .getResultList();
<ide> }
<ide>
<ide> @Override
<ide> @Transactional
<ide> public Date getProjectTimeStamp(Project aProject, String aUsername)
<ide> {
<add> String query =
<add> "SELECT MAX(ann.timestamp) " +
<add> "FROM AnnotationDocument AS ann " +
<add> "WHERE ann.project = :project AND ann.user = :user";
<ide> return entityManager
<del> .createQuery(
<del> "SELECT max(timestamp) FROM AnnotationDocument WHERE project = :project "
<del> + " AND user = :user", Date.class)
<add> .createQuery(query, Date.class)
<ide> .setParameter("project", aProject).setParameter("user", aUsername)
<ide> .getSingleResult();
<ide> }
<ide> @Override
<ide> public Date getProjectTimeStamp(Project aProject)
<ide> {
<add> String query =
<add> "SELECT MAX(doc.timestamp) " +
<add> "FROM SourceDocument AS doc " +
<add> "WHERE doc.project = :project";
<ide> return entityManager
<del> .createQuery("SELECT max(timestamp) FROM SourceDocument WHERE project = :project",
<del> Date.class).setParameter("project", aProject).getSingleResult();
<add> .createQuery(query, Date.class)
<add> .setParameter("project", aProject)
<add> .getSingleResult();
<ide> }
<ide>
<ide> @Override
<ide> @Transactional(noRollbackFor = NoResultException.class)
<ide> public List<Project> listProjectsWithFinishedAnnos()
<ide> {
<del>
<add> String query =
<add> "SELECT DISTINCT ann.project " +
<add> "FROM AnnotationDocument AS ann " +
<add> "WHERE ann.state = :state";
<ide> return entityManager
<del> .createQuery("SELECT DISTINCT project FROM AnnotationDocument WHERE state = :state",
<del> Project.class)
<del> .setParameter("state", AnnotationDocumentState.FINISHED.getName()).getResultList();
<del>
<add> .createQuery(query, Project.class)
<add> .setParameter("state", AnnotationDocumentState.FINISHED)
<add> .getResultList();
<ide> }
<ide>
<ide> @Override
<ide> @Transactional
<ide> public List<Project> listProjects()
<ide> {
<del> return entityManager.createQuery("FROM Project ORDER BY name ASC ", Project.class)
<add> String query =
<add> "FROM Project " +
<add> "ORDER BY name ASC";
<add> return entityManager
<add> .createQuery(query, Project.class)
<ide> .getResultList();
<ide> }
<ide> |
|
Java | apache-2.0 | 1fbe941e07ed524e05a49dcea86917846d10405b | 0 | connectbot/connectbot,lotan/connectbot,alescdb/connectbot,jklein24/connectbot,iiordanov/BSSH,kruton/connectbot,alescdb/connectbot,connectbot/connectbot,alescdb/connectbot,connectbot/connectbot,kruton/connectbot,lotan/connectbot,kruton/connectbot,jklein24/connectbot,iiordanov/BSSH,trygveaa/connectbot,iiordanov/BSSH,trygveaa/connectbot,jklein24/connectbot,lotan/connectbot,trygveaa/connectbot | /*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* 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.
*/
package org.connectbot;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.StyleRes;
import android.support.annotation.VisibleForTesting;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import org.connectbot.bean.HostBean;
import org.connectbot.data.HostStorage;
import org.connectbot.service.OnHostStatusChangedListener;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.transport.TransportFactory;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PreferenceConstants;
import java.util.List;
public class HostListActivity extends AppCompatListActivity implements OnHostStatusChangedListener {
public final static String TAG = "CB.HostListActivity";
public static final String DISCONNECT_ACTION = "org.connectbot.action.DISCONNECT";
public final static int REQUEST_EDIT = 1;
protected TerminalManager bound = null;
private HostStorage hostdb;
private List<HostBean> hosts;
protected LayoutInflater inflater = null;
protected boolean sortedByColor = false;
private MenuItem sortcolor;
private MenuItem sortlast;
private MenuItem disconnectall;
private SharedPreferences prefs = null;
protected boolean makingShortcut = false;
private boolean waitingForDisconnectAll = false;
/**
* Whether to close the activity when disconnectAll is called. True if this activity was
* only brought to the foreground via the notification button to disconnect all hosts.
*/
private boolean closeOnDisconnectAll = true;
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// update our listview binder to find the service
HostListActivity.this.updateList();
bound.registerOnHostStatusChangedListener(HostListActivity.this);
if (waitingForDisconnectAll) {
disconnectAll();
}
}
public void onServiceDisconnected(ComponentName className) {
bound.unregisterOnHostStatusChangedListener(HostListActivity.this);
bound = null;
HostListActivity.this.updateList();
}
};
@Override
public void onStart() {
super.onStart();
// start the terminal manager service
this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
hostdb = HostDatabase.get(this);
}
@Override
public void onStop() {
super.onStop();
this.unbindService(connection);
hostdb = null;
closeOnDisconnectAll = true;
}
@Override
public void onResume() {
super.onResume();
// Must disconnectAll before setting closeOnDisconnectAll to know whether to keep the
// activity open after disconnecting.
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0 &&
DISCONNECT_ACTION.equals(getIntent().getAction())) {
Log.d(TAG, "Got disconnect all request");
disconnectAll();
}
// Still close on disconnect if waiting for a disconnect.
closeOnDisconnectAll = waitingForDisconnectAll && closeOnDisconnectAll;
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_EDIT) {
this.updateList();
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_hostlist);
setTitle(R.string.title_hosts_list);
mListView = (RecyclerView) findViewById(R.id.list);
mListView.setHasFixedSize(true);
mListView.setLayoutManager(new LinearLayoutManager(this));
mListView.addItemDecoration(new ListItemDecoration(this));
mEmptyView = findViewById(R.id.empty);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
// detect HTC Dream and apply special preferences
if (Build.MANUFACTURER.equals("HTC") && Build.DEVICE.equals("dream")) {
SharedPreferences.Editor editor = prefs.edit();
boolean doCommit = false;
if (!prefs.contains(PreferenceConstants.SHIFT_FKEYS) &&
!prefs.contains(PreferenceConstants.CTRL_FKEYS)) {
editor.putBoolean(PreferenceConstants.SHIFT_FKEYS, true);
editor.putBoolean(PreferenceConstants.CTRL_FKEYS, true);
doCommit = true;
}
if (!prefs.contains(PreferenceConstants.STICKY_MODIFIERS)) {
editor.putString(PreferenceConstants.STICKY_MODIFIERS, PreferenceConstants.YES);
doCommit = true;
}
if (!prefs.contains(PreferenceConstants.KEYMODE)) {
editor.putString(PreferenceConstants.KEYMODE, PreferenceConstants.KEYMODE_RIGHT);
doCommit = true;
}
if (doCommit) {
editor.commit();
}
}
this.makingShortcut = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())
|| Intent.ACTION_PICK.equals(getIntent().getAction());
// connect with hosts database and populate list
this.hostdb = HostDatabase.get(this);
this.sortedByColor = prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false);
this.registerForContextMenu(mListView);
FloatingActionButton addHostButton =
(FloatingActionButton) findViewById(R.id.add_host_button);
addHostButton.setVisibility(makingShortcut ? View.GONE : View.VISIBLE);
addHostButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = EditHostActivity.createIntentForNewHost(HostListActivity.this);
startActivityForResult(intent, REQUEST_EDIT);
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
this.inflater = LayoutInflater.from(this);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// don't offer menus when creating shortcut
if (makingShortcut) return true;
sortcolor.setVisible(!sortedByColor);
sortlast.setVisible(sortedByColor);
disconnectall.setEnabled(bound.getBridges().size() > 0);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// don't offer menus when creating shortcut
if (makingShortcut) return true;
// add host, ssh keys, about
sortcolor = menu.add(R.string.list_menu_sortcolor);
sortcolor.setIcon(android.R.drawable.ic_menu_share);
sortcolor.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
sortedByColor = true;
updateList();
return true;
}
});
sortlast = menu.add(R.string.list_menu_sortname);
sortlast.setIcon(android.R.drawable.ic_menu_share);
sortlast.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
sortedByColor = false;
updateList();
return true;
}
});
MenuItem keys = menu.add(R.string.list_menu_pubkeys);
keys.setIcon(android.R.drawable.ic_lock_lock);
keys.setIntent(new Intent(HostListActivity.this, PubkeyListActivity.class));
MenuItem colors = menu.add(R.string.title_colors);
colors.setIcon(android.R.drawable.ic_menu_slideshow);
colors.setIntent(new Intent(HostListActivity.this, ColorsActivity.class));
disconnectall = menu.add(R.string.list_menu_disconnect);
disconnectall.setIcon(android.R.drawable.ic_menu_delete);
disconnectall.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
disconnectAll();
return false;
}
});
MenuItem settings = menu.add(R.string.list_menu_settings);
settings.setIcon(android.R.drawable.ic_menu_preferences);
settings.setIntent(new Intent(HostListActivity.this, SettingsActivity.class));
MenuItem help = menu.add(R.string.title_help);
help.setIcon(android.R.drawable.ic_menu_help);
help.setIntent(new Intent(HostListActivity.this, HelpActivity.class));
return true;
}
/**
* Disconnects all active connections and closes the activity if appropriate.
*/
private void disconnectAll() {
if (bound == null) {
waitingForDisconnectAll = true;
return;
}
new android.support.v7.app.AlertDialog.Builder(
HostListActivity.this, R.style.AlertDialogTheme)
.setMessage(getString(R.string.disconnect_all_message))
.setPositiveButton(R.string.disconnect_all_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
bound.disconnectAll(true, false);
waitingForDisconnectAll = false;
// Clear the intent so that the activity can be relaunched without closing.
// TODO(jlklein): Find a better way to do this.
setIntent(new Intent());
if (closeOnDisconnectAll) {
finish();
}
}
})
.setNegativeButton(R.string.disconnect_all_neg, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
waitingForDisconnectAll = false;
// Clear the intent so that the activity can be relaunched without closing.
// TODO(jlklein): Find a better way to do this.
setIntent(new Intent());
}
}).create().show();
}
/**
* @return
*/
private boolean startConsoleActivity(Uri uri) {
HostBean host = TransportFactory.findHost(hostdb, uri);
if (host == null) {
host = TransportFactory.getTransport(uri.getScheme()).createHost(uri);
host.setColor(HostDatabase.COLOR_GRAY);
host.setPubkeyId(HostDatabase.PUBKEYID_ANY);
hostdb.saveHost(host);
}
Intent intent = new Intent(HostListActivity.this, ConsoleActivity.class);
intent.setData(uri);
startActivity(intent);
return true;
}
protected void updateList() {
if (prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false) != sortedByColor) {
Editor edit = prefs.edit();
edit.putBoolean(PreferenceConstants.SORT_BY_COLOR, sortedByColor);
edit.commit();
}
if (hostdb == null)
hostdb = HostDatabase.get(this);
hosts = hostdb.getHosts(sortedByColor);
// Don't lose hosts that are connected via shortcuts but not in the database.
if (bound != null) {
for (TerminalBridge bridge : bound.getBridges()) {
if (!hosts.contains(bridge.host))
hosts.add(0, bridge.host);
}
}
mAdapter = new HostAdapter(this, hosts, bound);
mListView.setAdapter(mAdapter);
adjustViewVisibility();
}
@Override
public void onHostStatusChanged() {
updateList();
}
@VisibleForTesting
public class HostViewHolder extends ItemViewHolder {
public final ImageView icon;
public final TextView nickname;
public final TextView caption;
public HostBean host;
public HostViewHolder(View v) {
super(v);
icon = (ImageView) v.findViewById(android.R.id.icon);
nickname = (TextView) v.findViewById(android.R.id.text1);
caption = (TextView) v.findViewById(android.R.id.text2);
}
@Override
public void onClick(View v) {
// launch off to console details
Uri uri = host.getUri();
Intent contents = new Intent(Intent.ACTION_VIEW, uri);
contents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (makingShortcut) {
// create shortcut if requested
ShortcutIconResource icon = Intent.ShortcutIconResource.fromContext(
HostListActivity.this, R.drawable.icon);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, contents);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, host.getNickname());
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
setResult(RESULT_OK, intent);
finish();
} else {
// otherwise just launch activity to show this host
contents.setClass(HostListActivity.this, ConsoleActivity.class);
HostListActivity.this.startActivity(contents);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle(host.getNickname());
// edit, disconnect, delete
MenuItem connect = menu.add(R.string.list_host_disconnect);
final TerminalBridge bridge = (bound == null) ? null : bound.getConnectedBridge(host);
connect.setEnabled(bridge != null);
connect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
bridge.dispatchDisconnect(true);
return true;
}
});
MenuItem edit = menu.add(R.string.list_host_edit);
edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent intent = EditHostActivity.createIntentForExistingHost(
HostListActivity.this, host.getId());
HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
MenuItem portForwards = menu.add(R.string.list_host_portforwards);
portForwards.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(HostListActivity.this, PortForwardListActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, host.getId());
HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
if (!TransportFactory.canForwardPorts(host.getProtocol()))
portForwards.setEnabled(false);
MenuItem delete = menu.add(R.string.list_host_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// prompt user to make sure they really want this
new android.support.v7.app.AlertDialog.Builder(
HostListActivity.this, R.style.AlertDialogTheme)
.setMessage(getString(R.string.delete_message, host.getNickname()))
.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// make sure we disconnect
if (bridge != null)
bridge.dispatchDisconnect(true);
hostdb.deleteHost(host);
updateList();
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
}
}
@VisibleForTesting
private class HostAdapter extends ItemAdapter {
private final List<HostBean> hosts;
private final TerminalManager manager;
public final static int STATE_UNKNOWN = 1, STATE_CONNECTED = 2, STATE_DISCONNECTED = 3;
public HostAdapter(Context context, List<HostBean> hosts, TerminalManager manager) {
super(context);
this.hosts = hosts;
this.manager = manager;
}
/**
* Check if we're connected to a terminal with the given host.
*/
private int getConnectedState(HostBean host) {
// always disconnected if we don't have backend service
if (this.manager == null || host == null) {
return STATE_UNKNOWN;
}
if (manager.getConnectedBridge(host) != null) {
return STATE_CONNECTED;
}
if (manager.disconnected.contains(host)) {
return STATE_DISCONNECTED;
}
return STATE_UNKNOWN;
}
@Override
public HostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_host, parent, false);
HostViewHolder vh = new HostViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
HostViewHolder hostHolder = (HostViewHolder) holder;
HostBean host = hosts.get(position);
hostHolder.host = host;
if (host == null) {
// Well, something bad happened. We can't continue.
Log.e("HostAdapter", "Host bean is null!");
hostHolder.nickname.setText("Error during lookup");
} else {
hostHolder.nickname.setText(host.getNickname());
}
switch (this.getConnectedState(host)) {
case STATE_UNKNOWN:
hostHolder.icon.setImageState(new int[] { }, true);
break;
case STATE_CONNECTED:
hostHolder.icon.setImageState(new int[] { android.R.attr.state_checked }, true);
break;
case STATE_DISCONNECTED:
hostHolder.icon.setImageState(new int[] { android.R.attr.state_expanded }, true);
break;
}
@StyleRes final int chosenStyleFirstLine;
@StyleRes final int chosenStyleSecondLine;
if (HostDatabase.COLOR_RED.equals(host.getColor())) {
chosenStyleFirstLine = R.style.ListItemFirstLineText_Red;
chosenStyleSecondLine = R.style.ListItemSecondLineText_Red;
} else if (HostDatabase.COLOR_GREEN.equals(host.getColor())) {
chosenStyleFirstLine = R.style.ListItemFirstLineText_Green;
chosenStyleSecondLine = R.style.ListItemSecondLineText_Green;
} else if (HostDatabase.COLOR_BLUE.equals(host.getColor())) {
chosenStyleFirstLine = R.style.ListItemFirstLineText_Blue;
chosenStyleSecondLine = R.style.ListItemSecondLineText_Blue;
} else {
chosenStyleFirstLine = R.style.ListItemFirstLineText;
chosenStyleSecondLine = R.style.ListItemSecondLineText;
}
hostHolder.nickname.setTextAppearance(context, chosenStyleFirstLine);
hostHolder.caption.setTextAppearance(context, chosenStyleSecondLine);
CharSequence nice = context.getString(R.string.bind_never);
if (host.getLastConnect() > 0) {
nice = DateUtils.getRelativeTimeSpanString(host.getLastConnect() * 1000);
}
hostHolder.caption.setText(nice);
}
@Override
public long getItemId(int position) {
return hosts.get(position).getId();
}
@Override
public int getItemCount() {
return hosts.size();
}
}
}
| app/src/main/java/org/connectbot/HostListActivity.java | /*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* 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.
*/
package org.connectbot;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.StyleRes;
import android.support.annotation.VisibleForTesting;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import org.connectbot.bean.HostBean;
import org.connectbot.data.HostStorage;
import org.connectbot.service.OnHostStatusChangedListener;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.transport.TransportFactory;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PreferenceConstants;
import java.util.List;
public class HostListActivity extends AppCompatListActivity implements OnHostStatusChangedListener {
public final static String TAG = "CB.HostListActivity";
public static final String DISCONNECT_ACTION = "org.connectbot.action.DISCONNECT";
public final static int REQUEST_EDIT = 1;
protected TerminalManager bound = null;
private HostStorage hostdb;
private List<HostBean> hosts;
protected LayoutInflater inflater = null;
protected boolean sortedByColor = false;
private MenuItem sortcolor;
private MenuItem sortlast;
private MenuItem disconnectall;
private SharedPreferences prefs = null;
protected boolean makingShortcut = false;
private boolean waitingForDisconnectAll = false;
/**
* Whether to close the activity when disconnectAll is called. True if this activity was
* only brought to the foreground via the notification button to disconnect all hosts.
*/
private boolean closeOnDisconnectAll = true;
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// update our listview binder to find the service
HostListActivity.this.updateList();
bound.registerOnHostStatusChangedListener(HostListActivity.this);
if (waitingForDisconnectAll) {
disconnectAll();
}
}
public void onServiceDisconnected(ComponentName className) {
bound.unregisterOnHostStatusChangedListener(HostListActivity.this);
bound = null;
HostListActivity.this.updateList();
}
};
@Override
public void onStart() {
super.onStart();
// start the terminal manager service
this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
hostdb = HostDatabase.get(this);
}
@Override
public void onStop() {
super.onStop();
this.unbindService(connection);
hostdb = null;
closeOnDisconnectAll = true;
}
@Override
public void onResume() {
super.onResume();
// Must disconnectAll before setting closeOnDisconnectAll to know whether to keep the
// activity open after disconnecting.
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0 &&
DISCONNECT_ACTION.equals(getIntent().getAction())) {
Log.d(TAG, "Got disconnect all request");
disconnectAll();
}
// Still close on disconnect if waiting for a disconnect.
closeOnDisconnectAll = waitingForDisconnectAll && closeOnDisconnectAll;
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_EDIT) {
this.updateList();
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_hostlist);
setTitle(R.string.title_hosts_list);
mListView = (RecyclerView) findViewById(R.id.list);
mListView.setHasFixedSize(true);
mListView.setLayoutManager(new LinearLayoutManager(this));
mListView.addItemDecoration(new ListItemDecoration(this));
mEmptyView = findViewById(R.id.empty);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
// detect HTC Dream and apply special preferences
if (Build.MANUFACTURER.equals("HTC") && Build.DEVICE.equals("dream")) {
SharedPreferences.Editor editor = prefs.edit();
boolean doCommit = false;
if (!prefs.contains(PreferenceConstants.SHIFT_FKEYS) &&
!prefs.contains(PreferenceConstants.CTRL_FKEYS)) {
editor.putBoolean(PreferenceConstants.SHIFT_FKEYS, true);
editor.putBoolean(PreferenceConstants.CTRL_FKEYS, true);
doCommit = true;
}
if (!prefs.contains(PreferenceConstants.STICKY_MODIFIERS)) {
editor.putString(PreferenceConstants.STICKY_MODIFIERS, PreferenceConstants.YES);
doCommit = true;
}
if (!prefs.contains(PreferenceConstants.KEYMODE)) {
editor.putString(PreferenceConstants.KEYMODE, PreferenceConstants.KEYMODE_RIGHT);
doCommit = true;
}
if (doCommit) {
editor.commit();
}
}
this.makingShortcut = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())
|| Intent.ACTION_PICK.equals(getIntent().getAction());
// connect with hosts database and populate list
this.hostdb = HostDatabase.get(this);
this.sortedByColor = prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false);
this.registerForContextMenu(mListView);
FloatingActionButton addHostButton =
(FloatingActionButton) findViewById(R.id.add_host_button);
addHostButton.setVisibility(makingShortcut ? View.GONE : View.VISIBLE);
addHostButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = EditHostActivity.createIntentForNewHost(HostListActivity.this);
startActivityForResult(intent, REQUEST_EDIT);
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
this.inflater = LayoutInflater.from(this);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// don't offer menus when creating shortcut
if (makingShortcut) return true;
sortcolor.setVisible(!sortedByColor);
sortlast.setVisible(sortedByColor);
disconnectall.setEnabled(bound.getBridges().size() > 0);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// don't offer menus when creating shortcut
if (makingShortcut) return true;
// add host, ssh keys, about
sortcolor = menu.add(R.string.list_menu_sortcolor);
sortcolor.setIcon(android.R.drawable.ic_menu_share);
sortcolor.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
sortedByColor = true;
updateList();
return true;
}
});
sortlast = menu.add(R.string.list_menu_sortname);
sortlast.setIcon(android.R.drawable.ic_menu_share);
sortlast.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
sortedByColor = false;
updateList();
return true;
}
});
MenuItem keys = menu.add(R.string.list_menu_pubkeys);
keys.setIcon(android.R.drawable.ic_lock_lock);
keys.setIntent(new Intent(HostListActivity.this, PubkeyListActivity.class));
MenuItem colors = menu.add(R.string.title_colors);
colors.setIcon(android.R.drawable.ic_menu_slideshow);
colors.setIntent(new Intent(HostListActivity.this, ColorsActivity.class));
disconnectall = menu.add(R.string.list_menu_disconnect);
disconnectall.setIcon(android.R.drawable.ic_menu_delete);
final HostListActivity self = this;
disconnectall.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
self.disconnectAll();
return false;
}
});
MenuItem settings = menu.add(R.string.list_menu_settings);
settings.setIcon(android.R.drawable.ic_menu_preferences);
settings.setIntent(new Intent(HostListActivity.this, SettingsActivity.class));
MenuItem help = menu.add(R.string.title_help);
help.setIcon(android.R.drawable.ic_menu_help);
help.setIntent(new Intent(HostListActivity.this, HelpActivity.class));
return true;
}
/**
* Disconnects all active connections and closes the activity if appropriate.
*/
private void disconnectAll() {
if (bound == null) {
waitingForDisconnectAll = true;
return;
}
new android.support.v7.app.AlertDialog.Builder(
HostListActivity.this, R.style.AlertDialogTheme)
.setMessage(getString(R.string.disconnect_all_message))
.setPositiveButton(R.string.disconnect_all_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
bound.disconnectAll(true, false);
waitingForDisconnectAll = false;
// Clear the intent so that the activity can be relaunched without closing.
// TODO(jlklein): Find a better way to do this.
setIntent(new Intent());
if (closeOnDisconnectAll) {
finish();
}
}
})
.setNegativeButton(R.string.disconnect_all_neg, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
waitingForDisconnectAll = false;
// Clear the intent so that the activity can be relaunched without closing.
// TODO(jlklein): Find a better way to do this.
setIntent(new Intent());
}
}).create().show();
}
/**
* @return
*/
private boolean startConsoleActivity(Uri uri) {
HostBean host = TransportFactory.findHost(hostdb, uri);
if (host == null) {
host = TransportFactory.getTransport(uri.getScheme()).createHost(uri);
host.setColor(HostDatabase.COLOR_GRAY);
host.setPubkeyId(HostDatabase.PUBKEYID_ANY);
hostdb.saveHost(host);
}
Intent intent = new Intent(HostListActivity.this, ConsoleActivity.class);
intent.setData(uri);
startActivity(intent);
return true;
}
protected void updateList() {
if (prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false) != sortedByColor) {
Editor edit = prefs.edit();
edit.putBoolean(PreferenceConstants.SORT_BY_COLOR, sortedByColor);
edit.commit();
}
if (hostdb == null)
hostdb = HostDatabase.get(this);
hosts = hostdb.getHosts(sortedByColor);
// Don't lose hosts that are connected via shortcuts but not in the database.
if (bound != null) {
for (TerminalBridge bridge : bound.getBridges()) {
if (!hosts.contains(bridge.host))
hosts.add(0, bridge.host);
}
}
mAdapter = new HostAdapter(this, hosts, bound);
mListView.setAdapter(mAdapter);
adjustViewVisibility();
}
@Override
public void onHostStatusChanged() {
updateList();
}
@VisibleForTesting
public class HostViewHolder extends ItemViewHolder {
public final ImageView icon;
public final TextView nickname;
public final TextView caption;
public HostBean host;
public HostViewHolder(View v) {
super(v);
icon = (ImageView) v.findViewById(android.R.id.icon);
nickname = (TextView) v.findViewById(android.R.id.text1);
caption = (TextView) v.findViewById(android.R.id.text2);
}
@Override
public void onClick(View v) {
// launch off to console details
Uri uri = host.getUri();
Intent contents = new Intent(Intent.ACTION_VIEW, uri);
contents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (makingShortcut) {
// create shortcut if requested
ShortcutIconResource icon = Intent.ShortcutIconResource.fromContext(
HostListActivity.this, R.drawable.icon);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, contents);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, host.getNickname());
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
setResult(RESULT_OK, intent);
finish();
} else {
// otherwise just launch activity to show this host
contents.setClass(HostListActivity.this, ConsoleActivity.class);
HostListActivity.this.startActivity(contents);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle(host.getNickname());
// edit, disconnect, delete
MenuItem connect = menu.add(R.string.list_host_disconnect);
final TerminalBridge bridge = (bound == null) ? null : bound.getConnectedBridge(host);
connect.setEnabled(bridge != null);
connect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
bridge.dispatchDisconnect(true);
return true;
}
});
MenuItem edit = menu.add(R.string.list_host_edit);
edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent intent = EditHostActivity.createIntentForExistingHost(
HostListActivity.this, host.getId());
HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
MenuItem portForwards = menu.add(R.string.list_host_portforwards);
portForwards.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(HostListActivity.this, PortForwardListActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, host.getId());
HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
if (!TransportFactory.canForwardPorts(host.getProtocol()))
portForwards.setEnabled(false);
MenuItem delete = menu.add(R.string.list_host_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// prompt user to make sure they really want this
new android.support.v7.app.AlertDialog.Builder(
HostListActivity.this, R.style.AlertDialogTheme)
.setMessage(getString(R.string.delete_message, host.getNickname()))
.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// make sure we disconnect
if (bridge != null)
bridge.dispatchDisconnect(true);
hostdb.deleteHost(host);
updateList();
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
}
}
@VisibleForTesting
private class HostAdapter extends ItemAdapter {
private final List<HostBean> hosts;
private final TerminalManager manager;
public final static int STATE_UNKNOWN = 1, STATE_CONNECTED = 2, STATE_DISCONNECTED = 3;
public HostAdapter(Context context, List<HostBean> hosts, TerminalManager manager) {
super(context);
this.hosts = hosts;
this.manager = manager;
}
/**
* Check if we're connected to a terminal with the given host.
*/
private int getConnectedState(HostBean host) {
// always disconnected if we don't have backend service
if (this.manager == null || host == null) {
return STATE_UNKNOWN;
}
if (manager.getConnectedBridge(host) != null) {
return STATE_CONNECTED;
}
if (manager.disconnected.contains(host)) {
return STATE_DISCONNECTED;
}
return STATE_UNKNOWN;
}
@Override
public HostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_host, parent, false);
HostViewHolder vh = new HostViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
HostViewHolder hostHolder = (HostViewHolder) holder;
HostBean host = hosts.get(position);
hostHolder.host = host;
if (host == null) {
// Well, something bad happened. We can't continue.
Log.e("HostAdapter", "Host bean is null!");
hostHolder.nickname.setText("Error during lookup");
} else {
hostHolder.nickname.setText(host.getNickname());
}
switch (this.getConnectedState(host)) {
case STATE_UNKNOWN:
hostHolder.icon.setImageState(new int[] { }, true);
break;
case STATE_CONNECTED:
hostHolder.icon.setImageState(new int[] { android.R.attr.state_checked }, true);
break;
case STATE_DISCONNECTED:
hostHolder.icon.setImageState(new int[] { android.R.attr.state_expanded }, true);
break;
}
@StyleRes final int chosenStyleFirstLine;
@StyleRes final int chosenStyleSecondLine;
if (HostDatabase.COLOR_RED.equals(host.getColor())) {
chosenStyleFirstLine = R.style.ListItemFirstLineText_Red;
chosenStyleSecondLine = R.style.ListItemSecondLineText_Red;
} else if (HostDatabase.COLOR_GREEN.equals(host.getColor())) {
chosenStyleFirstLine = R.style.ListItemFirstLineText_Green;
chosenStyleSecondLine = R.style.ListItemSecondLineText_Green;
} else if (HostDatabase.COLOR_BLUE.equals(host.getColor())) {
chosenStyleFirstLine = R.style.ListItemFirstLineText_Blue;
chosenStyleSecondLine = R.style.ListItemSecondLineText_Blue;
} else {
chosenStyleFirstLine = R.style.ListItemFirstLineText;
chosenStyleSecondLine = R.style.ListItemSecondLineText;
}
hostHolder.nickname.setTextAppearance(context, chosenStyleFirstLine);
hostHolder.caption.setTextAppearance(context, chosenStyleSecondLine);
CharSequence nice = context.getString(R.string.bind_never);
if (host.getLastConnect() > 0) {
nice = DateUtils.getRelativeTimeSpanString(host.getLastConnect() * 1000);
}
hostHolder.caption.setText(nice);
}
@Override
public long getItemId(int position) {
return hosts.get(position).getId();
}
@Override
public int getItemCount() {
return hosts.size();
}
}
}
| Fix review comments
| app/src/main/java/org/connectbot/HostListActivity.java | Fix review comments | <ide><path>pp/src/main/java/org/connectbot/HostListActivity.java
<ide>
<ide> disconnectall = menu.add(R.string.list_menu_disconnect);
<ide> disconnectall.setIcon(android.R.drawable.ic_menu_delete);
<del> final HostListActivity self = this;
<ide> disconnectall.setOnMenuItemClickListener(new OnMenuItemClickListener() {
<ide> @Override
<ide> public boolean onMenuItemClick(MenuItem menuItem) {
<del> self.disconnectAll();
<add> disconnectAll();
<ide> return false;
<ide> }
<ide> }); |
|
Java | unlicense | 7ed86315218edd0a29f28d3ec461f82b24837c39 | 0 | SamouraiDev/bech32 | package com.samourai.wallet.segwit;
import com.google.common.primitives.Bytes;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SegwitAddressUtil {
private static SegwitAddressUtil instance = null;
private SegwitAddressUtil() { ; }
public static SegwitAddressUtil getInstance() {
if(instance == null) {
instance = new SegwitAddressUtil();
}
return instance;
}
public Pair<Byte, byte[]> decode(String hrp, String addr) throws Exception {
Pair<byte[], byte[]> p = Bech32Util.getInstance().bech32Decode(addr);
byte[] hrpgot = p.getLeft();
if (!hrp.equals(new String(hrpgot))) {
throw new Exception("mismatching bech32 human readeable part");
}
byte[] data = p.getRight();
byte[] decoded = convertBits(Bytes.asList(Arrays.copyOfRange(data, 1, data.length)), 5, 8, false);
if(decoded.length < 2 || decoded.length > 40) {
throw new Exception("invalid decoded data length");
}
byte witnessVersion = data[0];
if (witnessVersion > 16) {
throw new Exception("invalid decoded witness version");
}
if (witnessVersion == 0 && decoded.length != 20 && decoded.length != 32) {
throw new Exception("decoded witness version 0 with unknown length");
}
return Pair.of(witnessVersion, decoded);
}
public String encode(byte[] hrp, byte witnessVersion, byte[] witnessProgram) throws Exception {
byte[] prog = convertBits(Bytes.asList(witnessProgram), 8, 5, true);
byte[] data = new byte[1 + prog.length];
System.arraycopy(new byte[] { witnessVersion }, 0, data, 0, 1);
System.arraycopy(prog, 0, data, 1, prog.length);
String ret = Bech32Util.getInstance().bech32Encode(hrp, data);
assert(Arrays.equals(data, decode(new String(hrp), ret).getRight()));
return ret;
}
private byte[] convertBits(List<Byte> data, int fromBits, int toBits, boolean pad) throws Exception {
int acc = 0;
int bits = 0;
int maxv = (1 << toBits) - 1;
List<Byte> ret = new ArrayList<Byte>();
for(Byte value : data) {
short b = (short)(value.byteValue() & 0xff);
if (b < 0) {
throw new Exception();
}
else if ((b >> fromBits) > 0) {
throw new Exception();
}
else {
;
}
acc = (acc << fromBits) | b;
bits += fromBits;
while (bits >= toBits) {
bits -= toBits;
ret.add((byte)((acc >> bits) & maxv));
}
}
if(pad && (bits > 0)) {
ret.add((byte)((acc << (toBits - bits)) & maxv));
}
else if (bits >= fromBits || (byte)(((acc << (toBits - bits)) & maxv)) != 0) {
throw new Exception("panic");
}
else {
;
}
return Bytes.toArray(ret);
}
public byte[] getScriptPubkey(byte witver, byte[] witprog) {
byte v = (witver > 0) ? (byte)(witver + 0x80) : (byte)0;
byte[] ver = new byte[] { v, (byte)witprog.length };
byte[] ret = new byte[witprog.length + ver.length];
System.arraycopy(ver, 0, ret, 0, ver.length);
System.arraycopy(witprog, 0, ret, ver.length, witprog.length);
return ret;
}
}
| src/com/samourai/wallet/segwit/SegwitAddressUtil.java | package com.samourai.wallet.segwit;
import com.google.common.primitives.Bytes;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SegwitAddressUtil {
private static SegwitAddressUtil instance = null;
private SegwitAddressUtil() { ; }
public static SegwitAddressUtil getInstance() {
if(instance == null) {
instance = new SegwitAddressUtil();
}
return instance;
}
public Pair<Byte, byte[]> decode(String hrp, String addr) throws Exception {
Pair<byte[], byte[]> p = Bech32Util.getInstance().bech32Decode(addr);
byte[] hrpgot = p.getLeft();
if (!hrp.equals(new String(hrpgot))) {
throw new Exception("mismatching bech32 human readeable part");
}
byte[] data = p.getRight();
byte[] decoded = convertBits(Bytes.asList(Arrays.copyOfRange(data, 1, data.length)), 5, 8, false);
if(decoded.length < 2 || decoded.length > 40) {
throw new Exception("invalid decoded data length");
}
byte witnessVersion = data[0];
if (witnessVersion > 16) {
throw new Exception("invalid decoded witness version");
}
if (witnessVersion == 0 && decoded.length != 20 && decoded.length != 32) {
throw new Exception("decoded witness version 0 with unknown length");
}
return Pair.of(witnessVersion, decoded);
}
public String encode(byte[] hrp, byte witnessVerion, byte[] witnessProgram) throws Exception {
byte[] prog = convertBits(Bytes.asList(witnessProgram), 8, 5, true);
byte[] data = new byte[1 + prog.length];
System.arraycopy(new byte[] { witnessVerion }, 0, data, 0, 1);
System.arraycopy(prog, 0, data, 1, prog.length);
String ret = Bech32Util.getInstance().bech32Encode(hrp, data);
assert(Arrays.equals(data, decode(new String(hrp), ret).getRight()));
return ret;
}
private byte[] convertBits(List<Byte> data, int fromBits, int toBits, boolean pad) throws Exception {
int acc = 0;
int bits = 0;
int maxv = (1 << toBits) - 1;
List<Byte> ret = new ArrayList<Byte>();
for(Byte value : data) {
short b = (short)(value.byteValue() & 0xff);
if (b < 0) {
throw new Exception();
}
else if ((b >> fromBits) > 0) {
throw new Exception();
}
else {
;
}
acc = (acc << fromBits) | b;
bits += fromBits;
while (bits >= toBits) {
bits -= toBits;
ret.add((byte)((acc >> bits) & maxv));
}
}
if(pad && (bits > 0)) {
ret.add((byte)((acc << (toBits - bits)) & maxv));
}
else if (bits >= fromBits || (byte)(((acc << (toBits - bits)) & maxv)) != 0) {
throw new Exception("panic");
}
else {
;
}
return Bytes.toArray(ret);
}
public byte[] getScriptPubkey(byte witver, byte[] witprog) {
byte v = (witver > 0) ? (byte)(witver + 0x80) : (byte)0;
byte[] ver = new byte[] { v, (byte)witprog.length };
byte[] ret = new byte[witprog.length + ver.length];
System.arraycopy(ver, 0, ret, 0, ver.length);
System.arraycopy(witprog, 0, ret, ver.length, witprog.length);
return ret;
}
}
| Fixed typo
| src/com/samourai/wallet/segwit/SegwitAddressUtil.java | Fixed typo | <ide><path>rc/com/samourai/wallet/segwit/SegwitAddressUtil.java
<ide> return Pair.of(witnessVersion, decoded);
<ide> }
<ide>
<del> public String encode(byte[] hrp, byte witnessVerion, byte[] witnessProgram) throws Exception {
<add> public String encode(byte[] hrp, byte witnessVersion, byte[] witnessProgram) throws Exception {
<ide>
<ide> byte[] prog = convertBits(Bytes.asList(witnessProgram), 8, 5, true);
<ide> byte[] data = new byte[1 + prog.length];
<ide>
<del> System.arraycopy(new byte[] { witnessVerion }, 0, data, 0, 1);
<add> System.arraycopy(new byte[] { witnessVersion }, 0, data, 0, 1);
<ide> System.arraycopy(prog, 0, data, 1, prog.length);
<ide>
<ide> String ret = Bech32Util.getInstance().bech32Encode(hrp, data); |
|
Java | apache-2.0 | 481783fecb44cc9d6d7081fadc89155f19ea9ea7 | 0 | mosoft521/wicket,astrapi69/wicket,aldaris/wicket,AlienQueen/wicket,selckin/wicket,astrapi69/wicket,dashorst/wicket,klopfdreh/wicket,bitstorm/wicket,selckin/wicket,apache/wicket,selckin/wicket,apache/wicket,AlienQueen/wicket,selckin/wicket,dashorst/wicket,bitstorm/wicket,aldaris/wicket,apache/wicket,topicusonderwijs/wicket,klopfdreh/wicket,aldaris/wicket,freiheit-com/wicket,bitstorm/wicket,klopfdreh/wicket,topicusonderwijs/wicket,dashorst/wicket,freiheit-com/wicket,bitstorm/wicket,aldaris/wicket,mafulafunk/wicket,mafulafunk/wicket,mosoft521/wicket,AlienQueen/wicket,dashorst/wicket,klopfdreh/wicket,apache/wicket,AlienQueen/wicket,mosoft521/wicket,martin-g/wicket-osgi,zwsong/wicket,topicusonderwijs/wicket,mafulafunk/wicket,freiheit-com/wicket,dashorst/wicket,martin-g/wicket-osgi,apache/wicket,zwsong/wicket,freiheit-com/wicket,aldaris/wicket,zwsong/wicket,mosoft521/wicket,topicusonderwijs/wicket,mosoft521/wicket,martin-g/wicket-osgi,topicusonderwijs/wicket,klopfdreh/wicket,AlienQueen/wicket,astrapi69/wicket,astrapi69/wicket,selckin/wicket,zwsong/wicket,freiheit-com/wicket,bitstorm/wicket | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.wicket.request.resource;
import java.io.Serializable;
import java.util.Locale;
import org.apache.wicket.Application;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.lang.Objects;
import org.apache.wicket.util.lang.WicketObjects;
import org.apache.wicket.util.time.Time;
/**
* Reference to a resource. Can be used to reference global resources.
* <p>
* Even though resource reference is just a factory for resources, it still needs to be identified
* by a globally unique identifier, combination of <code>scope</code> and <code>name</code>. Those
* are used to generate URLs for resource references. <code>locale</code>, <code>style</code> and
* <code>variation</code> are optional fields to allow having specific references for individual
* locales, styles and variations.
*
* @author Matej Knopp
* @author Juergen Donnerstag
*/
public abstract class ResourceReference implements Serializable
{
private static final long serialVersionUID = 1L;
private final Key data;
/**
* Creates new {@link ResourceReference} instance.
*
* @param key
* The data makeing up the resource reference
*/
public ResourceReference(final Key key)
{
Args.notNull(key, "key");
data = key;
}
/**
* Creates new {@link ResourceReference} instance.
*
* @param scope
* mandatory parameter
* @param name
* mandatory parameter
* @param locale resource locale
* @param style resource style
* @param variation resource variation
*/
public ResourceReference(Class<?> scope, String name, Locale locale, String style,
String variation)
{
Args.notNull(scope, "scope");
Args.notNull(name, "name");
data = new Key(scope.getName(), name, locale, style, variation);
}
/**
* Creates new {@link ResourceReference} instance.
*
* @param scope
* mandatory parameter
* @param name
* mandatory parameter
*/
public ResourceReference(Class<?> scope, String name)
{
this(scope, name, null, null, null);
}
/**
* Construct.
*
* @param name resource name
*/
public ResourceReference(String name)
{
this(Application.class, name, null, null, null);
}
/**
* @return Gets the data making up the resource reference. They'll be use by
* ResourceReferenceRegistry to make up the key under which the resource reference gets
* stored.
*/
Key getKey()
{
return data;
}
/**
* @return name
*/
public String getName()
{
return data.getName();
}
/**
* @return scope
*/
public Class<?> getScope()
{
return WicketObjects.resolveClass(data.getScope());
}
/**
* @return locale
*/
public Locale getLocale()
{
return data.getLocale();
}
/**
* @return style
*/
public String getStyle()
{
return data.getStyle();
}
/**
* @return variation
*/
public String getVariation()
{
return data.getVariation();
}
/**
* Can be used to disable registering certain resource references in
* {@link ResourceReferenceRegistry}.
*
* @return <code>true</code> if this reference can be registered, <code>false</code> otherwise.
*/
public boolean canBeRegistered()
{
return true;
}
/**
* return the last modification date of the referred resource
* <p/>
*
* @return last modification time or <code>null</code> if not supported
*/
public Time getLastModified()
{
return null;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof ResourceReference == false)
{
return false;
}
ResourceReference that = (ResourceReference)obj;
return Objects.equal(data, that.data);
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return data.hashCode();
}
/**
* Returns the resource.
*
* @return resource instance
*/
public abstract IResource getResource();
/**
* Allows to specify which locale, style and variation values will the generated URL for this
* resource reference have.
*
* @return url attributes
*/
public UrlAttributes getUrlAttributes()
{
return new UrlAttributes(getLocale(), getStyle(), getVariation());
}
/**
* @see ResourceReference#getUrlAttributes()
*
* @author Matej Knopp
*/
public static class UrlAttributes
{
private final Locale locale;
private final String style;
private final String variation;
/**
* Construct.
*
* @param locale resource locale
* @param style resource style
* @param variation resource variation
*/
public UrlAttributes(Locale locale, String style, String variation)
{
this.locale = locale;
this.style = style;
this.variation = variation;
}
/**
* @return locale
*/
public Locale getLocale()
{
return locale;
}
/**
* @return style
*/
public String getStyle()
{
return style;
}
/**
* @return variation
*/
public String getVariation()
{
return variation;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof UrlAttributes == false)
{
return false;
}
UrlAttributes that = (UrlAttributes)obj;
return Objects.equal(getLocale(), that.getLocale()) &&
Objects.equal(getStyle(), that.getStyle()) &&
Objects.equal(getVariation(), that.getVariation());
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return Objects.hashCode(getLocale(), getStyle(), getVariation());
}
}
/**
* A (re-usable) data store for all relevant ResourceReference data
*/
public final static class Key implements Serializable
{
private static final long serialVersionUID = 1L;
final String scope;
final String name;
final Locale locale;
final String style;
final String variation;
/**
* Construct.
*
* @param reference resource reference
*/
public Key(final ResourceReference reference)
{
this(reference.getScope().getName(), reference.getName(), reference.getLocale(),
reference.getStyle(), reference.getVariation());
}
/**
* Construct.
*
* @param scope resource scope
* @param name resource name
* @param locale resource locale
* @param style resource style
* @param variation resource variation
*/
public Key(final String scope, final String name, final Locale locale, final String style,
final String variation)
{
Args.notNull(scope, "scope");
Args.notNull(name, "name");
this.scope = scope.intern();
this.name = name.intern();
this.locale = locale;
this.style = style != null ? style.intern() : null;
this.variation = variation != null ? variation.intern() : null;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof Key == false)
{
return false;
}
Key that = (Key)obj;
return Objects.equal(scope, that.scope) && //
Objects.equal(name, that.name) && //
Objects.equal(locale, that.locale) && //
Objects.equal(style, that.style) && //
Objects.equal(variation, that.variation);
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return Objects.hashCode(scope, name, locale, style, variation);
}
/**
* Gets scope.
*
* @return scope
*/
public final String getScope()
{
return scope;
}
/**
* @return Assuming scope ist a fully qualified class name, than get the associated class
*/
public final Class<?> getScopeClass()
{
return WicketObjects.resolveClass(scope);
}
/**
* Gets name.
*
* @return name
*/
public final String getName()
{
return name;
}
/**
* Gets locale.
*
* @return locale
*/
public final Locale getLocale()
{
return locale;
}
/**
* Gets style.
*
* @return style
*/
public final String getStyle()
{
return style;
}
/**
* Gets variation.
*
* @return variation
*/
public final String getVariation()
{
return variation;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return "scope: " + scope + "; name: " + name + "; locale: " + locale + "; style: " +
style + "; variation: " + variation;
}
}
}
| wicket/src/main/java/org/apache/wicket/request/resource/ResourceReference.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.wicket.request.resource;
import java.io.Serializable;
import java.util.Locale;
import org.apache.wicket.Application;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.lang.Objects;
import org.apache.wicket.util.lang.WicketObjects;
import org.apache.wicket.util.time.Time;
/**
* Reference to a resource. Can be used to reference global resources.
* <p>
* Even though resource reference is just a factory for resources, it still needs to be identified
* by a globally unique identifier, combination of <code>scope</code> and <code>name</code>. Those
* are used to generate URLs for resource references. <code>locale</code>, <code>style</code> and
* <code>variation</code> are optional fields to allow having specific references for individual
* locales, styles and variations.
*
* @author Matej Knopp
* @author Juergen Donnerstag
*/
public abstract class ResourceReference implements Serializable
{
private static final long serialVersionUID = 1L;
private final Key data;
/**
* Creates new {@link ResourceReference} instance.
*
* @param key
* The data makeing up the resource reference
*/
public ResourceReference(final Key key)
{
Args.notNull(key, "key");
data = key;
}
/**
* Creates new {@link ResourceReference} instance.
*
* @param scope
* mandatory parameter
* @param name
* mandatory parameter
* @param locale
* @param style
* @param variation
*/
public ResourceReference(Class<?> scope, String name, Locale locale, String style,
String variation)
{
Args.notNull(scope, "scope");
Args.notNull(name, "name");
data = new Key(scope.getName(), name, locale, style, variation);
}
/**
* Creates new {@link ResourceReference} instance.
*
* @param scope
* mandatory parameter
* @param name
* mandatory parameter
* @param locale
* @param style
* @param variation
*/
public ResourceReference(Class<?> scope, String name)
{
this(scope, name, null, null, null);
}
/**
* Construct.
*
* @param name
*/
public ResourceReference(String name)
{
this(Application.class, name, null, null, null);
}
/**
* @return Gets the data making up the resource reference. They'll be use by
* ResourceReferenceRegistry to make up the key under which the resource reference gets
* stored.
*/
Key getKey()
{
return data;
}
/**
* @return name
*/
public String getName()
{
return data.getName();
}
/**
* @return scope
*/
public Class<?> getScope()
{
return WicketObjects.resolveClass(data.getScope());
}
/**
* @return locale
*/
public Locale getLocale()
{
return data.getLocale();
}
/**
* @return style
*/
public String getStyle()
{
return data.getStyle();
}
/**
* @return variation
*/
public String getVariation()
{
return data.getVariation();
}
/**
* Can be used to disable registering certain resource references in
* {@link ResourceReferenceRegistry}.
*
* @return <code>true</code> if this reference can be registered, <code>false</code> otherwise.
*/
public boolean canBeRegistered()
{
return true;
}
/**
* return the last modification date of the referred resource
* <p/>
*
* @return last modification time or <code>null</code> if not supported
*/
public Time getLastModified()
{
return null;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof ResourceReference == false)
{
return false;
}
ResourceReference that = (ResourceReference)obj;
return Objects.equal(data, that.data);
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return data.hashCode();
}
/**
* Returns the resource.
*
* @return resource instance
*/
public abstract IResource getResource();
/**
* Allows to specify which locale, style and variation values will the generated URL for this
* resource reference have.
*
* @return url attributes
*/
public UrlAttributes getUrlAttributes()
{
return new UrlAttributes(getLocale(), getStyle(), getVariation());
}
/**
* @see ResourceReference#getUrlAttributes()
*
* @author Matej Knopp
*/
public static class UrlAttributes
{
private final Locale locale;
private final String style;
private final String variation;
/**
* Construct.
*
* @param locale
* @param style
* @param variation
*/
public UrlAttributes(Locale locale, String style, String variation)
{
this.locale = locale;
this.style = style;
this.variation = variation;
}
/**
* @return locale
*/
public Locale getLocale()
{
return locale;
}
/**
* @return style
*/
public String getStyle()
{
return style;
}
/**
* @return variation
*/
public String getVariation()
{
return variation;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof UrlAttributes == false)
{
return false;
}
UrlAttributes that = (UrlAttributes)obj;
return Objects.equal(getLocale(), that.getLocale()) &&
Objects.equal(getStyle(), that.getStyle()) &&
Objects.equal(getVariation(), that.getVariation());
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return Objects.hashCode(getLocale(), getStyle(), getVariation());
}
}
/**
* A (re-usable) data store for all relevant ResourceReference data
*/
public final static class Key
{
final String scope;
final String name;
final Locale locale;
final String style;
final String variation;
/**
* Construct.
*
* @param reference
*/
public Key(final ResourceReference reference)
{
this(reference.getScope().getName(), reference.getName(), reference.getLocale(),
reference.getStyle(), reference.getVariation());
}
/**
* Construct.
*
* @param scope
* @param name
* @param locale
* @param style
* @param variation
*/
public Key(final String scope, final String name, final Locale locale, final String style,
final String variation)
{
Args.notNull(scope, "scope");
Args.notNull(name, "name");
this.scope = scope.intern();
this.name = name.intern();
this.locale = locale;
this.style = style != null ? style.intern() : null;
this.variation = variation != null ? variation.intern() : null;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof Key == false)
{
return false;
}
Key that = (Key)obj;
return Objects.equal(scope, that.scope) && //
Objects.equal(name, that.name) && //
Objects.equal(locale, that.locale) && //
Objects.equal(style, that.style) && //
Objects.equal(variation, that.variation);
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return Objects.hashCode(scope, name, locale, style, variation);
}
/**
* Gets scope.
*
* @return scope
*/
public final String getScope()
{
return scope;
}
/**
* @return Assuming scope ist a fully qualified class name, than get the associated class
*/
public final Class<?> getScopeClass()
{
return WicketObjects.resolveClass(scope);
}
/**
* Gets name.
*
* @return name
*/
public final String getName()
{
return name;
}
/**
* Gets locale.
*
* @return locale
*/
public final Locale getLocale()
{
return locale;
}
/**
* Gets style.
*
* @return style
*/
public final String getStyle()
{
return style;
}
/**
* Gets variation.
*
* @return variation
*/
public final String getVariation()
{
return variation;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return "scope: " + scope + "; name: " + name + "; locale: " + locale + "; style: " +
style + "; variation: " + variation;
}
}
}
| let ResourceReference.Key implement java.io.Serializable to remove serialization issue + removed javadoc warnings
git-svn-id: 5a74b5304d8e7e474561603514f78b697e5d94c4@991674 13f79535-47bb-0310-9956-ffa450edef68
| wicket/src/main/java/org/apache/wicket/request/resource/ResourceReference.java | let ResourceReference.Key implement java.io.Serializable to remove serialization issue + removed javadoc warnings | <ide><path>icket/src/main/java/org/apache/wicket/request/resource/ResourceReference.java
<ide> * mandatory parameter
<ide> * @param name
<ide> * mandatory parameter
<del> * @param locale
<del> * @param style
<del> * @param variation
<add> * @param locale resource locale
<add> * @param style resource style
<add> * @param variation resource variation
<ide> */
<ide> public ResourceReference(Class<?> scope, String name, Locale locale, String style,
<ide> String variation)
<ide> * mandatory parameter
<ide> * @param name
<ide> * mandatory parameter
<del> * @param locale
<del> * @param style
<del> * @param variation
<ide> */
<ide> public ResourceReference(Class<?> scope, String name)
<ide> {
<ide> /**
<ide> * Construct.
<ide> *
<del> * @param name
<add> * @param name resource name
<ide> */
<ide> public ResourceReference(String name)
<ide> {
<ide> /**
<ide> * Construct.
<ide> *
<del> * @param locale
<del> * @param style
<del> * @param variation
<add> * @param locale resource locale
<add> * @param style resource style
<add> * @param variation resource variation
<ide> */
<ide> public UrlAttributes(Locale locale, String style, String variation)
<ide> {
<ide> /**
<ide> * A (re-usable) data store for all relevant ResourceReference data
<ide> */
<del> public final static class Key
<del> {
<add> public final static class Key implements Serializable
<add> {
<add> private static final long serialVersionUID = 1L;
<add>
<ide> final String scope;
<ide> final String name;
<ide> final Locale locale;
<ide>
<ide> /**
<ide> * Construct.
<del> *
<del> * @param reference
<del> */
<add> *
<add> * @param reference resource reference
<add> */
<ide> public Key(final ResourceReference reference)
<del> {
<add> {
<ide> this(reference.getScope().getName(), reference.getName(), reference.getLocale(),
<del> reference.getStyle(), reference.getVariation());
<add> reference.getStyle(), reference.getVariation());
<ide> }
<ide>
<ide> /**
<ide> * Construct.
<ide> *
<del> * @param scope
<del> * @param name
<del> * @param locale
<del> * @param style
<del> * @param variation
<add> * @param scope resource scope
<add> * @param name resource name
<add> * @param locale resource locale
<add> * @param style resource style
<add> * @param variation resource variation
<ide> */
<ide> public Key(final String scope, final String name, final Locale locale, final String style,
<del> final String variation)
<add> final String variation)
<ide> {
<ide> Args.notNull(scope, "scope");
<ide> Args.notNull(name, "name");
<ide> {
<ide> if (this == obj)
<ide> {
<del> return true;
<del> }
<add> return true;
<add> }
<ide> if (obj instanceof Key == false)
<ide> {
<ide> return false;
<ide> Objects.equal(variation, that.variation);
<ide> }
<ide>
<del> /**
<add> /**
<ide> * @see java.lang.Object#hashCode()
<ide> */
<ide> @Override
<ide>
<ide> /**
<ide> * Gets scope.
<del> *
<add> *
<ide> * @return scope
<del> */
<add> */
<ide> public final String getScope()
<del> {
<add> {
<ide> return scope;
<del> }
<add> }
<ide>
<ide> /**
<ide> * @return Assuming scope ist a fully qualified class name, than get the associated class
<ide> public final Class<?> getScopeClass()
<ide> {
<ide> return WicketObjects.resolveClass(scope);
<del>}
<add> }
<ide>
<ide> /**
<ide> * Gets name. |
|
JavaScript | mit | 3d886cc69ad330ed55488801b8c037567b4ea35c | 0 | Sosowski/Screeps_Custom,Sosowski/Screeps_Custom | var creep_work5 = {
/** @param {Creep} creep **/
run: function(creep) {
//wew lad
/*if (!creep.room.controller.sign) {
if(creep.pos.isNearTo(creep.room.controller)) {
creep.signController(creep.room.controller, 'This is, by far, the most kupo room I\'ve ever seen!');
}
}*/
var ignoreRoadsValue = false;
if (Memory.IgnoreRoadRooms == creep.room.name) {
ignoreRoadsValue = true;
}
if (creep.carry.energy > 0 && creep.memory.priority != 'miner' && creep.memory.priority != 'minerNearDeath') {
//All creeps check for road under them and repair if needed.
var someStructure = creep.pos.lookFor(LOOK_STRUCTURES);
if (someStructure.length && (someStructure[0].hitsMax - someStructure[0].hits >= 600)) {
creep.repair(someStructure[0]);
}
}
if (creep.memory.priority == 'miner' || creep.memory.priority == 'minerNearDeath') {
if (creep.ticksToLive <= 60) {
creep.memory.priority = 'minerNearDeath';
creep.memory.jobSpecific = creep.memory.jobSpecific + 'NearDeath';
}
//Creep will immediately harvest and store mined materials
var storageTarget = Game.getObjectById(creep.memory.linkSource);
var mineTarget = Game.getObjectById(creep.memory.mineSource);
if (mineTarget && storageTarget) {
if (storageTarget.structureType == STRUCTURE_LINK) {
if (storageTarget.energy == storageTarget.energyCapacity) {
return;
}
}
if (creep.transfer(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageTarget, {
reusePath: 5,
ignoreRoads: ignoreRoadsValue
});
} else if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
creep.moveTo(mineTarget, {
reusePath: 5,
ignoreRoads: ignoreRoadsValue
});
}
/*if ((creep.pos.isNearTo(storageTarget) && !creep.pos.isNearTo(mineTarget))) {
var thisDirection = creep.pos.getDirectionTo(mineTarget);
creep.move(thisDirection);
} else if (!creep.pos.isNearTo(storageTarget) && creep.pos.isNearTo(mineTarget)) {
var thisDirection = creep.pos.getDirectionTo(storageTarget);
creep.move(thisDirection);
}*/
}
} else if (creep.memory.priority == 'upgrader' || creep.memory.priority == 'upgraderNearDeath') {
if (creep.ticksToLive <= 60) {
creep.memory.priority = 'upgraderNearDeath';
}
if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
creep.moveTo(creep.room.controller, {
reusePath: 20
});
}
var linkTarget = Game.getObjectById(creep.memory.linkSource);
if (linkTarget) {
if (creep.withdraw(linkTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(linkTarget, {
reusePath: 20
});
}
}
} else if (creep.memory.priority == 'mule' || creep.memory.priority == 'muleNearDeath') {
if (creep.ticksToLive <= 60) {
creep.memory.priority = 'muleNearDeath';
}
if (_.sum(creep.carry) == 0) {
creep.memory.structureTarget = undefined;
var storageTarget = Game.getObjectById(creep.memory.storageSource);
if (storageTarget) {
if (storageTarget.store[RESOURCE_ENERGY] >= 50) {
//Get from container
if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageTarget, {
reusePath: 5
});
}
} else {
if (!creep.pos.isNearTo(storageTarget)) {
creep.moveTo(storageTarget, {
reusePath: 5
});
}
}
}
} else if (_.sum(creep.carry) > 0) {
var savedTarget = Game.getObjectById(creep.memory.structureTarget)
if (savedTarget) {
if (creep.build(savedTarget) == ERR_INVALID_TARGET) {
//Only other blocker is build.
creep.repair(savedTarget);
if (creep.memory.lookForNewRampart) {
creep.memory.structureTarget = undefined;
creep.memory.lookForNewRampart = undefined;
var newRampart = creep.pos.findClosestByRange(FIND_STRUCTURES, {
filter: (structure) => (structure.structureType == STRUCTURE_RAMPART) && (structure.hits == 1)
});
if (newRampart) {
creep.memory.structureTarget = newRampart.id;
if (creep.repair(newRampart) == ERR_NOT_IN_RANGE) {
creep.moveTo(newRampart, {
reusePath: 5
});
}
}
} else if (savedTarget.structureType != STRUCTURE_CONTAINER && savedTarget.structureType != STRUCTURE_STORAGE && savedTarget.structureType != STRUCTURE_CONTROLLER) {
//Storing in spawn/extension/tower
if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(savedTarget, {
reusePath: 5
});
} else {
//assumed OK, drop target
creep.memory.structureTarget = undefined;
}
} else {
//Upgrading controller
if (creep.upgradeController(savedTarget) == ERR_NOT_IN_RANGE) {
creep.moveTo(savedTarget, {
reusePath: 20
});
} else {
//Check for nearby link and fill it if possible.
var links = creep.pos.findInRange(FIND_STRUCTURES, 3, {
filter: {
structureType: STRUCTURE_LINK
}
});
if (links) {
if (links.length > 0) {
if (links[0].energy < 400) {
if (creep.transfer(links[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(links[0]);
}
}
}
}
}
//Do repair for new ramparts
creep.repair(savedTarget);
}
} else {
if (creep.build(savedTarget) == ERR_NOT_IN_RANGE) {
creep.moveTo(savedTarget, {
reusePath: 5
});
} else if (creep.build(savedTarget) != OK) {
creep.memory.structureTarget = undefined;
}
}
} else {
creep.memory.structureTarget = undefined;
}
//Immediately find a new target if previous transfer worked
if (!creep.memory.structureTarget) {
var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType == STRUCTURE_EXTENSION ||
structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
}
});
if (targets) {
creep.memory.structureTarget = targets.id;
if (creep.transfer(targets, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(targets);
} else {
creep.memory.structureTarget = undefined;
}
} else {
targets3 = creep.pos.findClosestByRange(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType == STRUCTURE_TOWER) && (structure.energy < structure.energyCapacity);
}
});
if (targets3) {
creep.memory.structureTarget = targets3.id;
if (creep.transfer(targets3, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(targets3);
} else {
creep.memory.structureTarget = undefined;
}
} else {
//Store in terminal
terminalTarget = Game.getObjectById(creep.memory.terminalID)
if (terminalTarget) {
if (terminalTarget.store[RESOURCE_ENERGY] < 50000) {
creep.memory.structureTarget = terminalTarget.id;
if (creep.transfer(terminalTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(terminalTarget, {
reusePath: 20
});
}
} else {
terminalTarget = undefined;
}
}
if (!terminalTarget) {
//Build
var targets2 = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
if (targets2) {
creep.memory.structureTarget = targets2.id;
if (targets2.structureType == STRUCTURE_RAMPART) {
creep.memory.lookForNewRampart = true;
}
if (creep.build(targets2) == ERR_NOT_IN_RANGE) {
creep.moveTo(targets2, {
reusePath: 20
});
} else if (creep.build(targets2) == ERR_NO_BODYPART) {
creep.suicide();
}
} else {
//Upgrade
creep.memory.structureTarget = creep.room.controller.id;
if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
creep.moveTo(creep.room.controller, {
reusePath: 20
});
} else if (creep.upgradeController(creep.room.controller) == ERR_NO_BODYPART) {
creep.suicide();
}
}
}
}
}
}
}
} else if (creep.memory.priority == 'repair' || creep.memory.priority == 'repairNearDeath') {
if (creep.ticksToLive <= 60) {
creep.memory.priority = 'repairNearDeath';
}
if (_.sum(creep.carry) == 0) {
creep.memory.structureTarget = undefined;
//Get from storage
var storageTarget = Game.getObjectById(creep.memory.storageSource);
if (storageTarget) {
if (storageTarget.store[RESOURCE_ENERGY] >= 120) {
if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageTarget, {
reusePath: 20
});
}
} else {
if (!creep.pos.isNearTo(storageTarget)) {
creep.moveTo(storageTarget, {
reusePath: 20
});
}
}
}
} else if (creep.memory.structureTarget) {
var thisStructure = Game.getObjectById(creep.memory.structureTarget);
if (thisStructure) {
if (thisStructure.hits == thisStructure.hitsMax) {
creep.memory.structureTarget = undefined;
} else {
if (creep.repair(thisStructure) == ERR_NOT_IN_RANGE) {
creep.moveTo(thisStructure, {
reusePath: 20
});
}
}
} else {
creep.memory.structureTarget = undefined;
}
} else {
var closestDamagedStructure = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => (structure.structureType != STRUCTURE_ROAD) && (structure.hitsMax - structure.hits >= 200)
});
if (closestDamagedStructure.length > 0) {
closestDamagedStructure.sort(repairCompare);
creep.memory.structureTarget = closestDamagedStructure[0].id;
if (creep.repair(closestDamagedStructure[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(closestDamagedStructure[0], {
reusePath: 20
});
}
}
}
} else if (creep.memory.priority == 'mineralMiner') {
var thisMineral = Game.getObjectById(creep.memory.mineralID);
if (thisMineral.mineralAmount == 0) {
//Nothing left to do
creep.suicide();
} else {
//Creep will immediately harvest and store mined materials
var storageTarget = Game.getObjectById(creep.memory.terminalID);
var thisExtractor = Game.getObjectById(creep.memory.extractorID);
if (storageTarget && thisExtractor) {
if (thisExtractor.cooldown == 0) {
if (creep.harvest(thisMineral) == ERR_NOT_IN_RANGE) {
creep.moveTo(thisMineral, {
reusePath: 20
});
}
}
if (creep.transfer(storageTarget, thisMineral.mineralType) == ERR_NOT_IN_RANGE) {
//This should never actually fire, if ideal.
creep.moveTo(storageTarget);
}
/*if ((creep.pos.isNearTo(storageTarget) && !creep.pos.isNearTo(thisExtractor))) {
var thisDirection = creep.pos.getDirectionTo(thisExtractor);
creep.move(thisDirection);
} else if (!creep.pos.isNearTo(storageTarget) && creep.pos.isNearTo(thisExtractor)) {
var thisDirection = creep.pos.getDirectionTo(storageTarget);
creep.move(thisDirection);
}*/
}
}
} else if (creep.memory.priority == 'salvager') {
var sources = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES);
if (!sources && _.sum(creep.carry) == 0) {
//There's nothing left to do
creep.suicide();
} else if (sources && _.sum(creep.carry) < creep.carryCapacity) {
if (creep.pickup(sources) == ERR_NOT_IN_RANGE) {
creep.moveTo(sources);
}
}
if (!sources && _.sum(creep.carry) > 0 || _.sum(creep.carry) > 100) {
var storageTarget = Game.getObjectById(creep.memory.storageTarget);
if (Object.keys(creep.carry).length > 1) {
if (creep.transfer(storageTarget, Object.keys(creep.carry)[1]) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageTarget);
}
} else if (creep.transfer(storageTarget, Object.keys(creep.carry)[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageTarget);
}
}
} else if (creep.memory.priority == 'farClaimer') {
var farIndex = Memory.E1N63FarRoles.indexOf(creep.memory.priority);
if (creep.ticksToLive <= 5 && farIndex > -1) {
//Remove yourself from the list of farCreeps
Memory.E1N63FarRoles.splice(farIndex, 1);
} else if (farIndex == -1) {
Memory.E1N63FarRoles.push('farClaimer')
}
if (creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(24, 2, creep.memory.destination));
} else {
if (creep.room.controller.reservation) {
if (creep.room.controller.reservation.ticksToEnd <= 1000) {
Memory.E1N63ClaimerNeeded = true;
} else {
Memory.E1N63ClaimerNeeded = false;
}
} else {
Memory.E1N63ClaimerNeeded = true;
}
if (creep.reserveController(creep.room.controller) == ERR_NOT_IN_RANGE) {
creep.moveTo(creep.room.controller);
}
}
} else if (creep.memory.priority == 'farMiner') {
var farIndex = Memory.E1N63FarRoles.indexOf(creep.memory.priority);
if (creep.ticksToLive <= 5 && farIndex > -1) {
//Remove yourself from the list of farCreeps
Memory.E1N63FarRoles.splice(farIndex, 1);
} else if (farIndex == -1) {
Memory.E1N63FarRoles.push('farMiner');
}
if (creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(24, 2, creep.memory.destination));
} else {
if (creep.room.controller.reservation) {
if (creep.room.controller.reservation.ticksToEnd <= 1000) {
Memory.E1N63ClaimerNeeded = true;
} else {
Memory.E1N63ClaimerNeeded = false;
}
} else {
Memory.E1N63ClaimerNeeded = true;
}
var mineTarget = Game.getObjectById(creep.memory.mineSource);
if (mineTarget) {
if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
creep.moveTo(mineTarget, {
reusePath: 5
});
}
}
if (creep.memory.storageUnit) {
var thisUnit = Game.getObjectById(creep.memory.storageUnit);
if (thisUnit) {
if (thisUnit.hits < thisUnit.hitsMax) {
creep.repair(thisUnit);
} else {
if (creep.transfer(thisUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(thisUnit);
}
}
}
} else {
var containers = creep.pos.findInRange(FIND_STRUCTURES, 50, {
filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
});
if (containers.length) {
if (creep.transfer(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(containers[0]);
}
creep.memory.storageUnit = containers[0].id;
} else {
var sites = creep.pos.findInRange(FIND_CONSTRUCTION_SITES, 50)
if (sites.length) {
if (creep.build(sites[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(sites[0]);
}
} else {
//Create new container
if (creep.pos.isNearTo(mineTarget)) {
creep.room.createConstructionSite(creep.pos, STRUCTURE_CONTAINER)
}
}
}
}
}
} else if (creep.memory.priority == 'farMule') {
var farIndex = Memory.E1N63FarRoles.indexOf(creep.memory.priority);
if (creep.ticksToLive <= 5 && farIndex > -1) {
//Remove yourself from the list of farCreeps
Memory.E1N63FarRoles.splice(farIndex, 1);
} else if (farIndex == -1) {
Memory.E1N63FarRoles.push('farMule')
}
if (creep.room.name != creep.memory.destination && _.sum(creep.carry) <= 150) {
creep.moveTo(new RoomPosition(24, 2, creep.memory.destination));
} else if (creep.room.name != creep.memory.homeRoom && _.sum(creep.carry) > 150) {
creep.moveTo(new RoomPosition(24, 48, creep.memory.homeRoom));
} else {
if (creep.room.controller.reservation) {
if (creep.room.controller.reservation.ticksToEnd <= 1000) {
Memory.E1N63ClaimerNeeded = true;
} else {
Memory.E1N63ClaimerNeeded = false;
}
} else {
Memory.E1N63ClaimerNeeded = true;
}
if (_.sum(creep.carry) <= 150) {
//in farRoom, pick up container contents
if (creep.memory.containerTarget) {
var thisContainer = Game.getObjectById(creep.memory.containerTarget);
if (thisContainer) {
if (creep.withdraw(thisContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(thisContainer, {
reusePath: 20
});
}
}
}
var containers = creep.pos.findInRange(FIND_STRUCTURES, 50, {
filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
});
if (containers.length) {
creep.memory.containerTarget = containers[0].id;
if (creep.withdraw(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(containers[0], {
reusePath: 20
});
}
}
} else {
//in home room, drop off energy
var storageUnit = Game.getObjectById(creep.memory.storageSource)
if (storageUnit) {
if (creep.transfer(storageUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageUnit, {
reusePath: 20
});
}
}
}
}
}
}
};
module.exports = creep_work5;
function repairCompare(a, b) {
if (a.hits < b.hits)
return -1;
if (a.hits > b.hits)
return 1;
return 0;
} | MainCode/creep.work5.js | var creep_work5 = {
/** @param {Creep} creep **/
run: function(creep) {
//wew lad
/*if (!creep.room.controller.sign) {
if(creep.pos.isNearTo(creep.room.controller)) {
creep.signController(creep.room.controller, 'This is, by far, the most kupo room I\'ve ever seen!');
}
}*/
var ignoreRoadsValue = false;
if (Memory.IgnoreRoadRooms == creep.room.name) {
ignoreRoadsValue = true;
}
if (creep.carry.energy > 0 && creep.memory.priority != 'miner' && creep.memory.priority != 'minerNearDeath') {
//All creeps check for road under them and repair if needed.
var someStructure = creep.pos.lookFor(LOOK_STRUCTURES);
if (someStructure.length && (someStructure[0].hitsMax - someStructure[0].hits >= 600)) {
creep.repair(someStructure[0]);
}
}
if (creep.memory.priority == 'miner' || creep.memory.priority == 'minerNearDeath') {
if (creep.ticksToLive <= 60) {
creep.memory.priority = 'minerNearDeath';
creep.memory.jobSpecific = creep.memory.jobSpecific + 'NearDeath';
}
//Creep will immediately harvest and store mined materials
var storageTarget = Game.getObjectById(creep.memory.linkSource);
var mineTarget = Game.getObjectById(creep.memory.mineSource);
if (mineTarget && storageTarget) {
if (storageTarget.structureType == STRUCTURE_LINK) {
if (storageTarget.energy == storageTarget.energyCapacity) {
break;
}
}
if (creep.transfer(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageTarget, {
reusePath: 5,
ignoreRoads: ignoreRoadsValue
});
} else if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
creep.moveTo(mineTarget, {
reusePath: 5,
ignoreRoads: ignoreRoadsValue
});
}
/*if ((creep.pos.isNearTo(storageTarget) && !creep.pos.isNearTo(mineTarget))) {
var thisDirection = creep.pos.getDirectionTo(mineTarget);
creep.move(thisDirection);
} else if (!creep.pos.isNearTo(storageTarget) && creep.pos.isNearTo(mineTarget)) {
var thisDirection = creep.pos.getDirectionTo(storageTarget);
creep.move(thisDirection);
}*/
}
} else if (creep.memory.priority == 'upgrader' || creep.memory.priority == 'upgraderNearDeath') {
if (creep.ticksToLive <= 60) {
creep.memory.priority = 'upgraderNearDeath';
}
if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
creep.moveTo(creep.room.controller, {
reusePath: 20
});
}
var linkTarget = Game.getObjectById(creep.memory.linkSource);
if (linkTarget) {
if (creep.withdraw(linkTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(linkTarget, {
reusePath: 20
});
}
}
} else if (creep.memory.priority == 'mule' || creep.memory.priority == 'muleNearDeath') {
if (creep.ticksToLive <= 60) {
creep.memory.priority = 'muleNearDeath';
}
if (_.sum(creep.carry) == 0) {
creep.memory.structureTarget = undefined;
var storageTarget = Game.getObjectById(creep.memory.storageSource);
if (storageTarget) {
if (storageTarget.store[RESOURCE_ENERGY] >= 50) {
//Get from container
if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageTarget, {
reusePath: 5
});
}
} else {
if (!creep.pos.isNearTo(storageTarget)) {
creep.moveTo(storageTarget, {
reusePath: 5
});
}
}
}
} else if (_.sum(creep.carry) > 0) {
var savedTarget = Game.getObjectById(creep.memory.structureTarget)
if (savedTarget) {
if (creep.build(savedTarget) == ERR_INVALID_TARGET) {
//Only other blocker is build.
creep.repair(savedTarget);
if (creep.memory.lookForNewRampart) {
creep.memory.structureTarget = undefined;
creep.memory.lookForNewRampart = undefined;
var newRampart = creep.pos.findClosestByRange(FIND_STRUCTURES, {
filter: (structure) => (structure.structureType == STRUCTURE_RAMPART) && (structure.hits == 1)
});
if (newRampart) {
creep.memory.structureTarget = newRampart.id;
if (creep.repair(newRampart) == ERR_NOT_IN_RANGE) {
creep.moveTo(newRampart, {
reusePath: 5
});
}
}
} else if (savedTarget.structureType != STRUCTURE_CONTAINER && savedTarget.structureType != STRUCTURE_STORAGE && savedTarget.structureType != STRUCTURE_CONTROLLER) {
//Storing in spawn/extension/tower
if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(savedTarget, {
reusePath: 5
});
} else {
//assumed OK, drop target
creep.memory.structureTarget = undefined;
}
} else {
//Upgrading controller
if (creep.upgradeController(savedTarget) == ERR_NOT_IN_RANGE) {
creep.moveTo(savedTarget, {
reusePath: 20
});
} else {
//Check for nearby link and fill it if possible.
var links = creep.pos.findInRange(FIND_STRUCTURES, 3, {
filter: {
structureType: STRUCTURE_LINK
}
});
if (links) {
if (links.length > 0) {
if (links[0].energy < 400) {
if (creep.transfer(links[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(links[0]);
}
}
}
}
}
//Do repair for new ramparts
creep.repair(savedTarget);
}
} else {
if (creep.build(savedTarget) == ERR_NOT_IN_RANGE) {
creep.moveTo(savedTarget, {
reusePath: 5
});
} else if (creep.build(savedTarget) != OK) {
creep.memory.structureTarget = undefined;
}
}
} else {
creep.memory.structureTarget = undefined;
}
//Immediately find a new target if previous transfer worked
if (!creep.memory.structureTarget) {
var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType == STRUCTURE_EXTENSION ||
structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
}
});
if (targets) {
creep.memory.structureTarget = targets.id;
if (creep.transfer(targets, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(targets);
} else {
creep.memory.structureTarget = undefined;
}
} else {
targets3 = creep.pos.findClosestByRange(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType == STRUCTURE_TOWER) && (structure.energy < structure.energyCapacity);
}
});
if (targets3) {
creep.memory.structureTarget = targets3.id;
if (creep.transfer(targets3, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(targets3);
} else {
creep.memory.structureTarget = undefined;
}
} else {
//Store in terminal
terminalTarget = Game.getObjectById(creep.memory.terminalID)
if (terminalTarget) {
if (terminalTarget.store[RESOURCE_ENERGY] < 50000) {
creep.memory.structureTarget = terminalTarget.id;
if (creep.transfer(terminalTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(terminalTarget, {
reusePath: 20
});
}
} else {
terminalTarget = undefined;
}
}
if (!terminalTarget) {
//Build
var targets2 = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
if (targets2) {
creep.memory.structureTarget = targets2.id;
if (targets2.structureType == STRUCTURE_RAMPART) {
creep.memory.lookForNewRampart = true;
}
if (creep.build(targets2) == ERR_NOT_IN_RANGE) {
creep.moveTo(targets2, {
reusePath: 20
});
} else if (creep.build(targets2) == ERR_NO_BODYPART) {
creep.suicide();
}
} else {
//Upgrade
creep.memory.structureTarget = creep.room.controller.id;
if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
creep.moveTo(creep.room.controller, {
reusePath: 20
});
} else if (creep.upgradeController(creep.room.controller) == ERR_NO_BODYPART) {
creep.suicide();
}
}
}
}
}
}
}
} else if (creep.memory.priority == 'repair' || creep.memory.priority == 'repairNearDeath') {
if (creep.ticksToLive <= 60) {
creep.memory.priority = 'repairNearDeath';
}
if (_.sum(creep.carry) == 0) {
creep.memory.structureTarget = undefined;
//Get from storage
var storageTarget = Game.getObjectById(creep.memory.storageSource);
if (storageTarget) {
if (storageTarget.store[RESOURCE_ENERGY] >= 120) {
if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageTarget, {
reusePath: 20
});
}
} else {
if (!creep.pos.isNearTo(storageTarget)) {
creep.moveTo(storageTarget, {
reusePath: 20
});
}
}
}
} else if (creep.memory.structureTarget) {
var thisStructure = Game.getObjectById(creep.memory.structureTarget);
if (thisStructure) {
if (thisStructure.hits == thisStructure.hitsMax) {
creep.memory.structureTarget = undefined;
} else {
if (creep.repair(thisStructure) == ERR_NOT_IN_RANGE) {
creep.moveTo(thisStructure, {
reusePath: 20
});
}
}
} else {
creep.memory.structureTarget = undefined;
}
} else {
var closestDamagedStructure = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => (structure.structureType != STRUCTURE_ROAD) && (structure.hitsMax - structure.hits >= 200)
});
if (closestDamagedStructure.length > 0) {
closestDamagedStructure.sort(repairCompare);
creep.memory.structureTarget = closestDamagedStructure[0].id;
if (creep.repair(closestDamagedStructure[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(closestDamagedStructure[0], {
reusePath: 20
});
}
}
}
} else if (creep.memory.priority == 'mineralMiner') {
var thisMineral = Game.getObjectById(creep.memory.mineralID);
if (thisMineral.mineralAmount == 0) {
//Nothing left to do
creep.suicide();
} else {
//Creep will immediately harvest and store mined materials
var storageTarget = Game.getObjectById(creep.memory.terminalID);
var thisExtractor = Game.getObjectById(creep.memory.extractorID);
if (storageTarget && thisExtractor) {
if (thisExtractor.cooldown == 0) {
if (creep.harvest(thisMineral) == ERR_NOT_IN_RANGE) {
creep.moveTo(thisMineral, {
reusePath: 20
});
}
}
if (creep.transfer(storageTarget, thisMineral.mineralType) == ERR_NOT_IN_RANGE) {
//This should never actually fire, if ideal.
creep.moveTo(storageTarget);
}
/*if ((creep.pos.isNearTo(storageTarget) && !creep.pos.isNearTo(thisExtractor))) {
var thisDirection = creep.pos.getDirectionTo(thisExtractor);
creep.move(thisDirection);
} else if (!creep.pos.isNearTo(storageTarget) && creep.pos.isNearTo(thisExtractor)) {
var thisDirection = creep.pos.getDirectionTo(storageTarget);
creep.move(thisDirection);
}*/
}
}
} else if (creep.memory.priority == 'salvager') {
var sources = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES);
if (!sources && _.sum(creep.carry) == 0) {
//There's nothing left to do
creep.suicide();
} else if (sources && _.sum(creep.carry) < creep.carryCapacity) {
if (creep.pickup(sources) == ERR_NOT_IN_RANGE) {
creep.moveTo(sources);
}
}
if (!sources && _.sum(creep.carry) > 0 || _.sum(creep.carry) > 100) {
var storageTarget = Game.getObjectById(creep.memory.storageTarget);
if (Object.keys(creep.carry).length > 1) {
if (creep.transfer(storageTarget, Object.keys(creep.carry)[1]) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageTarget);
}
} else if (creep.transfer(storageTarget, Object.keys(creep.carry)[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageTarget);
}
}
} else if (creep.memory.priority == 'farClaimer') {
var farIndex = Memory.E1N63FarRoles.indexOf(creep.memory.priority);
if (creep.ticksToLive <= 5 && farIndex > -1) {
//Remove yourself from the list of farCreeps
Memory.E1N63FarRoles.splice(farIndex, 1);
} else if (farIndex == -1) {
Memory.E1N63FarRoles.push('farClaimer')
}
if (creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(24, 2, creep.memory.destination));
} else {
if (creep.room.controller.reservation) {
if (creep.room.controller.reservation.ticksToEnd <= 1000) {
Memory.E1N63ClaimerNeeded = true;
} else {
Memory.E1N63ClaimerNeeded = false;
}
} else {
Memory.E1N63ClaimerNeeded = true;
}
if (creep.reserveController(creep.room.controller) == ERR_NOT_IN_RANGE) {
creep.moveTo(creep.room.controller);
}
}
} else if (creep.memory.priority == 'farMiner') {
var farIndex = Memory.E1N63FarRoles.indexOf(creep.memory.priority);
if (creep.ticksToLive <= 5 && farIndex > -1) {
//Remove yourself from the list of farCreeps
Memory.E1N63FarRoles.splice(farIndex, 1);
} else if (farIndex == -1) {
Memory.E1N63FarRoles.push('farMiner');
}
if (creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(24, 2, creep.memory.destination));
} else {
if (creep.room.controller.reservation) {
if (creep.room.controller.reservation.ticksToEnd <= 1000) {
Memory.E1N63ClaimerNeeded = true;
} else {
Memory.E1N63ClaimerNeeded = false;
}
} else {
Memory.E1N63ClaimerNeeded = true;
}
var mineTarget = Game.getObjectById(creep.memory.mineSource);
if (mineTarget) {
if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
creep.moveTo(mineTarget, {
reusePath: 5
});
}
}
if (creep.memory.storageUnit) {
var thisUnit = Game.getObjectById(creep.memory.storageUnit);
if (thisUnit) {
if (thisUnit.hits < thisUnit.hitsMax) {
creep.repair(thisUnit);
} else {
if (creep.transfer(thisUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(thisUnit);
}
}
}
} else {
var containers = creep.pos.findInRange(FIND_STRUCTURES, 50, {
filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
});
if (containers.length) {
if (creep.transfer(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(containers[0]);
}
creep.memory.storageUnit = containers[0].id;
} else {
var sites = creep.pos.findInRange(FIND_CONSTRUCTION_SITES, 50)
if (sites.length) {
if (creep.build(sites[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(sites[0]);
}
} else {
//Create new container
if (creep.pos.isNearTo(mineTarget)) {
creep.room.createConstructionSite(creep.pos, STRUCTURE_CONTAINER)
}
}
}
}
}
} else if (creep.memory.priority == 'farMule') {
var farIndex = Memory.E1N63FarRoles.indexOf(creep.memory.priority);
if (creep.ticksToLive <= 5 && farIndex > -1) {
//Remove yourself from the list of farCreeps
Memory.E1N63FarRoles.splice(farIndex, 1);
} else if (farIndex == -1) {
Memory.E1N63FarRoles.push('farMule')
}
if (creep.room.name != creep.memory.destination && _.sum(creep.carry) <= 150) {
creep.moveTo(new RoomPosition(24, 2, creep.memory.destination));
} else if (creep.room.name != creep.memory.homeRoom && _.sum(creep.carry) > 150) {
creep.moveTo(new RoomPosition(24, 48, creep.memory.homeRoom));
} else {
if (creep.room.controller.reservation) {
if (creep.room.controller.reservation.ticksToEnd <= 1000) {
Memory.E1N63ClaimerNeeded = true;
} else {
Memory.E1N63ClaimerNeeded = false;
}
} else {
Memory.E1N63ClaimerNeeded = true;
}
if (_.sum(creep.carry) <= 150) {
//in farRoom, pick up container contents
if (creep.memory.containerTarget) {
var thisContainer = Game.getObjectById(creep.memory.containerTarget);
if (thisContainer) {
if (creep.withdraw(thisContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(thisContainer, {
reusePath: 20
});
}
}
}
var containers = creep.pos.findInRange(FIND_STRUCTURES, 50, {
filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
});
if (containers.length) {
creep.memory.containerTarget = containers[0].id;
if (creep.withdraw(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(containers[0], {
reusePath: 20
});
}
}
} else {
//in home room, drop off energy
var storageUnit = Game.getObjectById(creep.memory.storageSource)
if (storageUnit) {
if (creep.transfer(storageUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageUnit, {
reusePath: 20
});
}
}
}
}
}
}
};
module.exports = creep_work5;
function repairCompare(a, b) {
if (a.hits < b.hits)
return -1;
if (a.hits > b.hits)
return 1;
return 0;
} | Whoops.
| MainCode/creep.work5.js | Whoops. | <ide><path>ainCode/creep.work5.js
<ide> if (mineTarget && storageTarget) {
<ide> if (storageTarget.structureType == STRUCTURE_LINK) {
<ide> if (storageTarget.energy == storageTarget.energyCapacity) {
<del> break;
<add> return;
<ide> }
<ide> }
<ide> if (creep.transfer(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) { |
|
Java | apache-2.0 | 5898a139bb6a56e9c289963e5c4992b781b9c34f | 0 | LevelFourAB/dust | package se.l4.dust.jaxrs.internal.asset;
import java.util.Date;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import se.l4.dust.api.Context;
import se.l4.dust.api.Namespace;
import se.l4.dust.api.Namespaces;
import se.l4.dust.api.asset.Asset;
import se.l4.dust.api.asset.AssetException;
import se.l4.dust.api.asset.Assets;
import se.l4.dust.api.resource.Resource;
/**
* Provider that servers asset files via a special URL beginning with
* {@code /asset}.
*
* @author Andreas Holstenson
*
*/
@Singleton
@Path("asset")
public class AssetProvider
{
private final Assets manager;
private final Namespaces namespaces;
private final Context context;
@Inject
public AssetProvider(
Namespaces namespaces,
Assets manager)
{
this.namespaces = namespaces;
this.manager = manager;
context = new Context()
{
@Override
public void putValue(Object key, Object value)
{
}
@Override
public <T> T getValue(Object key)
{
return null;
}
};
}
@HEAD
@Path("{ns}/{path:.+}")
public Object head(
@PathParam("ns") String prefix,
@PathParam("path") String path)
{
Object result = serve(prefix, path, null);
if(result instanceof Asset)
{
Asset asset = (Asset) result;
Resource resource = asset.getResource();
return Response.ok()
.lastModified(new Date(resource.getLastModified()))
.type(AssetWriter.getMimeType(asset))
.build();
}
return result;
}
@GET
@Path("{ns}/{path:.+}")
@Produces("*/*")
public Object serve(
@PathParam("ns") String prefix,
@PathParam("path") String path,
@HeaderParam("If-Modified-Since") Date ifModifiedSince)
{
Namespace ns = namespaces.getNamespaceByPrefix(prefix);
if(ns == null)
{
return Response.status(404).build();
}
int idx = path.lastIndexOf('.');
String checksum = null;
if(idx >= 0)
{
// Check extension to get if we need checksum
String extension = path.substring(idx + 1);
if(manager.isProtectedExtension(extension))
{
int idx2 = path.lastIndexOf('.', idx-1);
checksum = path.substring(idx2+1, idx);
path = path.substring(0, idx2) + "." + extension;
}
}
try
{
Asset a = manager.locate(context, ns.getUri(), path);
if(a == null)
{
return Response.status(404).build();
}
if(checksum != null && false == checksum.equals(a.getChecksum()))
{
return Response.status(404).build();
}
if(ifModifiedSince != null && ifModifiedSince.getTime() > a.getResource().getLastModified())
{
return Response.status(304).build();
}
return a;
}
catch(AssetException e)
{
return Response.status(404).build();
}
}
}
| dust-jaxrs/src/main/java/se/l4/dust/jaxrs/internal/asset/AssetProvider.java | package se.l4.dust.jaxrs.internal.asset;
import java.util.Date;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import se.l4.dust.api.Context;
import se.l4.dust.api.Namespace;
import se.l4.dust.api.Namespaces;
import se.l4.dust.api.asset.Asset;
import se.l4.dust.api.asset.Assets;
import se.l4.dust.api.resource.Resource;
/**
* Provider that servers asset files via a special URL beginning with
* {@code /asset}.
*
* @author Andreas Holstenson
*
*/
@Singleton
@Path("asset")
public class AssetProvider
{
private final Assets manager;
private final Namespaces namespaces;
private final Context context;
@Inject
public AssetProvider(
Namespaces namespaces,
Assets manager)
{
this.namespaces = namespaces;
this.manager = manager;
context = new Context()
{
@Override
public void putValue(Object key, Object value)
{
}
@Override
public <T> T getValue(Object key)
{
return null;
}
};
}
@HEAD
@Path("{ns}/{path:.+}")
public Object head(
@PathParam("ns") String prefix,
@PathParam("path") String path)
{
Object result = serve(prefix, path, null);
if(result instanceof Asset)
{
Asset asset = (Asset) result;
Resource resource = asset.getResource();
return Response.ok()
.lastModified(new Date(resource.getLastModified()))
.type(AssetWriter.getMimeType(asset))
.build();
}
return result;
}
@GET
@Path("{ns}/{path:.+}")
@Produces("*/*")
public Object serve(
@PathParam("ns") String prefix,
@PathParam("path") String path,
@HeaderParam("If-Modified-Since") Date ifModifiedSince)
{
Namespace ns = namespaces.getNamespaceByPrefix(prefix);
if(ns == null)
{
return Response.status(404).build();
}
int idx = path.lastIndexOf('.');
String checksum = null;
if(idx >= 0)
{
// Check extension to get if we need checksum
String extension = path.substring(idx + 1);
if(manager.isProtectedExtension(extension))
{
int idx2 = path.lastIndexOf('.', idx-1);
checksum = path.substring(idx2+1, idx);
path = path.substring(0, idx2) + "." + extension;
}
}
Asset a = manager.locate(context, ns.getUri(), path);
if(a == null)
{
return Response.status(404).build();
}
if(checksum != null && false == checksum.equals(a.getChecksum()))
{
return Response.status(404).build();
}
if(ifModifiedSince != null && ifModifiedSince.getTime() > a.getResource().getLastModified())
{
return Response.status(304).build();
}
return a;
}
}
| fix(assets): Protect against AssetException
| dust-jaxrs/src/main/java/se/l4/dust/jaxrs/internal/asset/AssetProvider.java | fix(assets): Protect against AssetException | <ide><path>ust-jaxrs/src/main/java/se/l4/dust/jaxrs/internal/asset/AssetProvider.java
<ide> import se.l4.dust.api.Namespace;
<ide> import se.l4.dust.api.Namespaces;
<ide> import se.l4.dust.api.asset.Asset;
<add>import se.l4.dust.api.asset.AssetException;
<ide> import se.l4.dust.api.asset.Assets;
<ide> import se.l4.dust.api.resource.Resource;
<ide>
<ide> }
<ide> }
<ide>
<del> Asset a = manager.locate(context, ns.getUri(), path);
<del> if(a == null)
<add> try
<add> {
<add> Asset a = manager.locate(context, ns.getUri(), path);
<add> if(a == null)
<add> {
<add> return Response.status(404).build();
<add> }
<add>
<add> if(checksum != null && false == checksum.equals(a.getChecksum()))
<add> {
<add> return Response.status(404).build();
<add> }
<add>
<add> if(ifModifiedSince != null && ifModifiedSince.getTime() > a.getResource().getLastModified())
<add> {
<add> return Response.status(304).build();
<add> }
<add>
<add> return a;
<add> }
<add> catch(AssetException e)
<ide> {
<ide> return Response.status(404).build();
<ide> }
<del>
<del> if(checksum != null && false == checksum.equals(a.getChecksum()))
<del> {
<del> return Response.status(404).build();
<del> }
<del>
<del> if(ifModifiedSince != null && ifModifiedSince.getTime() > a.getResource().getLastModified())
<del> {
<del> return Response.status(304).build();
<del> }
<del>
<del> return a;
<ide> }
<ide> } |
|
Java | agpl-3.0 | 1ef5d962ba9473cf631cddbfeed5e578d26515c6 | 0 | hltn/opencps,VietOpenCPS/opencps,VietOpenCPS/opencps,hltn/opencps,VietOpenCPS/opencps,hltn/opencps | /**
* OpenCPS is the open source Core Public Services software
* Copyright (C) 2016-present OpenCPS community
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package org.opencps.taglib.accountmgt;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.opencps.accountmgt.model.Business;
import org.opencps.accountmgt.model.Citizen;
import org.opencps.dossiermgt.bean.AccountBean;
import org.opencps.usermgt.model.Employee;
import org.opencps.util.AccountUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Organization;
import com.liferay.portal.model.Role;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextFactory;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portlet.documentlibrary.model.DLFolder;
import com.liferay.taglib.util.IncludeTag;
/**
* @author trungnt
*/
public class DefineObjectsTag extends IncludeTag {
@Override
public int doStartTag() {
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
ThemeDisplay themeDisplay = (ThemeDisplay) request
.getAttribute(WebKeys.THEME_DISPLAY);
if (themeDisplay == null) {
return SKIP_BODY;
}
HttpSession session = request
.getSession();
Object accountInstance = null;
AccountBean accountBean = (AccountBean) session
.getAttribute(org.opencps.util.WebKeys.ACCOUNT_BEAN);
String accountType = GetterUtil
.getString(session
.getAttribute(org.opencps.util.WebKeys.ACCOUNT_TYPE));
Citizen citizen = (Citizen) session
.getAttribute(org.opencps.util.WebKeys.CITIZEN_ENTRY);
Business business = (Business) session
.getAttribute(org.opencps.util.WebKeys.BUSINESS_ENTRY);
Employee employee = (Employee) session
.getAttribute(org.opencps.util.WebKeys.EMPLOYEE_ENTRY);
DLFolder accountFolder = (DLFolder) session
.getAttribute(org.opencps.util.WebKeys.ACCOUNT_FOLDER);
List<Role> accountRoles = (List<Role>) session
.getAttribute(org.opencps.util.WebKeys.ACCOUNT_ROLES);
List<Organization> accountOrgs = (List<Organization>) session
.getAttribute(org.opencps.util.WebKeys.ACCOUNT_ORGANIZATION);
long ownerUserId = GetterUtil
.getLong(session
.getAttribute(org.opencps.util.WebKeys.ACCOUNT_OWNERUSERID),
0L);
long ownerOrganizationId = GetterUtil
.getLong(session
.getAttribute(
org.opencps.util.WebKeys.ACCOUNT_OWNERORGANIZATIONID),
0L);
if (themeDisplay
.isSignedIn() && Validator
.isNull(accountBean)) {
try {
// Clean account bean
AccountUtil
.destroy(request, false);
ServiceContext serviceContext = ServiceContextFactory
.getInstance(request);
accountBean = AccountUtil
.getAccountBean(themeDisplay
.getUserId(), themeDisplay
.getScopeGroupId(),
serviceContext);
if (accountBean != null) {
accountType = accountBean
.getAccountType();
if (accountBean
.isBusiness()) {
business = (Business) accountBean
.getAccountInstance();
accountInstance = business;
}
else if (accountBean
.isCitizen()) {
citizen = (Citizen) accountBean
.getAccountInstance();
accountInstance = citizen;
}
else if (accountBean
.isEmployee()) {
employee = (Employee) accountBean
.getAccountInstance();
accountInstance = employee;
}
ownerOrganizationId = accountBean
.getOwnerOrganizationId();
ownerUserId = accountBean
.getOwnerUserId();
accountFolder = accountBean
.getAccountFolder();
accountOrgs = accountBean
.getAccountOrgs();
accountRoles = accountBean
.getAccountRoles();
request
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_TYPE,
accountType);
request
.setAttribute(org.opencps.util.WebKeys.CITIZEN_ENTRY,
citizen);
request
.setAttribute(org.opencps.util.WebKeys.BUSINESS_ENTRY,
business);
request
.setAttribute(org.opencps.util.WebKeys.EMPLOYEE_ENTRY,
employee);
request
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_FOLDER,
accountFolder);
request
.setAttribute(
org.opencps.util.WebKeys.ACCOUNT_OWNERORGANIZATIONID,
ownerOrganizationId);
request
.setAttribute(
org.opencps.util.WebKeys.ACCOUNT_OWNERUSERID,
ownerUserId);
request
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_ROLES,
accountRoles);
request
.setAttribute(
org.opencps.util.WebKeys.ACCOUNT_ORGANIZATION,
accountOrgs);
// Store session
session
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_TYPE,
accountType);
session
.setAttribute(org.opencps.util.WebKeys.CITIZEN_ENTRY,
citizen);
session
.setAttribute(org.opencps.util.WebKeys.BUSINESS_ENTRY,
business);
session
.setAttribute(org.opencps.util.WebKeys.EMPLOYEE_ENTRY,
employee);
session
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_FOLDER,
accountFolder);
session
.setAttribute(
org.opencps.util.WebKeys.ACCOUNT_OWNERORGANIZATIONID,
ownerOrganizationId);
session
.setAttribute(
org.opencps.util.WebKeys.ACCOUNT_OWNERUSERID,
ownerUserId);
session
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_ROLES,
accountRoles);
session
.setAttribute(
org.opencps.util.WebKeys.ACCOUNT_ORGANIZATION,
accountOrgs);
}
else {
_log
.info(DefineObjectsTag.class
.getName() +
": ##########################: AccountBean is null");
}
}
catch (Exception e) {
_log
.error(e);
}
finally {
accountBean = new AccountBean(
accountInstance, accountType, accountFolder, accountRoles,
accountOrgs, ownerUserId, ownerOrganizationId);
session
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_BEAN,
accountBean);
}
}
return SKIP_BODY;
}
private Log _log = LogFactoryUtil
.getLog(DefineObjectsTag.class
.getName());
}
| portlets/opencps-portlet/docroot/WEB-INF/util-taglib/org/opencps/taglib/accountmgt/DefineObjectsTag.java | /**
* OpenCPS is the open source Core Public Services software
* Copyright (C) 2016-present OpenCPS community
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package org.opencps.taglib.accountmgt;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.opencps.accountmgt.model.Business;
import org.opencps.accountmgt.model.Citizen;
import org.opencps.dossiermgt.bean.AccountBean;
import org.opencps.usermgt.model.Employee;
import org.opencps.util.AccountUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Organization;
import com.liferay.portal.model.Role;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextFactory;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portlet.documentlibrary.model.DLFolder;
import com.liferay.taglib.util.IncludeTag;
/**
* @author trungnt
*/
public class DefineObjectsTag extends IncludeTag {
@Override
public int doStartTag() {
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
ThemeDisplay themeDisplay = (ThemeDisplay) request
.getAttribute(WebKeys.THEME_DISPLAY);
if (themeDisplay == null) {
return SKIP_BODY;
}
HttpSession session = request
.getSession();
Object accountInstance = null;
AccountBean accountBean = (AccountBean) session
.getAttribute(org.opencps.util.WebKeys.ACCOUNT_BEAN);
String accountType = GetterUtil
.getString(session
.getAttribute(org.opencps.util.WebKeys.ACCOUNT_TYPE));
Citizen citizen = (Citizen) session
.getAttribute(org.opencps.util.WebKeys.CITIZEN_ENTRY);
Business business = (Business) session
.getAttribute(org.opencps.util.WebKeys.BUSINESS_ENTRY);
Employee employee = (Employee) session
.getAttribute(org.opencps.util.WebKeys.EMPLOYEE_ENTRY);
DLFolder accountFolder = (DLFolder) session
.getAttribute(org.opencps.util.WebKeys.ACCOUNT_FOLDER);
List<Role> accountRoles = (List<Role>) session
.getAttribute(org.opencps.util.WebKeys.ACCOUNT_ROLES);
List<Organization> accountOrgs = (List<Organization>) session
.getAttribute(org.opencps.util.WebKeys.ACCOUNT_ORGANIZATION);
long ownerUserId = GetterUtil
.getLong(session
.getAttribute(org.opencps.util.WebKeys.ACCOUNT_OWNERUSERID),
0L);
long ownerOrganizationId = GetterUtil
.getLong(session
.getAttribute(
org.opencps.util.WebKeys.ACCOUNT_OWNERORGANIZATIONID),
0L);
if (themeDisplay
.isSignedIn() && Validator
.isNull(accountBean)) {
try {
// Clean account bean
AccountUtil
.destroy(request, false);
ServiceContext serviceContext = ServiceContextFactory
.getInstance(request);
accountBean = AccountUtil
.getAccountBean(themeDisplay
.getUserId(), themeDisplay
.getScopeGroupId(),
serviceContext);
if (accountBean != null) {
accountType = accountBean
.getAccountType();
if (accountBean
.isBusiness()) {
business = (Business) accountBean
.getAccountInstance();
accountInstance = business;
}
else if (accountBean
.isCitizen()) {
citizen = (Citizen) accountBean
.getAccountInstance();
accountInstance = citizen;
}
else if (accountBean
.isEmployee()) {
employee = (Employee) accountBean
.getAccountInstance();
accountInstance = employee;
}
ownerOrganizationId = accountBean
.getOwnerOrganizationId();
ownerUserId = accountBean
.getOwnerUserId();
accountFolder = accountBean
.getAccountFolder();
accountOrgs = accountBean
.getAccountOrgs();
accountRoles = accountBean
.getAccountRoles();
request
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_TYPE,
accountType);
request
.setAttribute(org.opencps.util.WebKeys.CITIZEN_ENTRY,
citizen);
request
.setAttribute(org.opencps.util.WebKeys.BUSINESS_ENTRY,
business);
request
.setAttribute(org.opencps.util.WebKeys.EMPLOYEE_ENTRY,
employee);
request
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_FOLDER,
accountFolder);
request
.setAttribute(
org.opencps.util.WebKeys.ACCOUNT_OWNERORGANIZATIONID,
ownerOrganizationId);
request
.setAttribute(
org.opencps.util.WebKeys.ACCOUNT_OWNERUSERID,
ownerUserId);
request
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_ROLES,
accountRoles);
request
.setAttribute(
org.opencps.util.WebKeys.ACCOUNT_ORGANIZATION,
accountOrgs);
// Store session
session
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_TYPE,
accountType);
session
.setAttribute(org.opencps.util.WebKeys.CITIZEN_ENTRY,
citizen);
session
.setAttribute(org.opencps.util.WebKeys.BUSINESS_ENTRY,
business);
session
.setAttribute(org.opencps.util.WebKeys.EMPLOYEE_ENTRY,
employee);
session
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_FOLDER,
accountFolder);
session
.setAttribute(
org.opencps.util.WebKeys.ACCOUNT_OWNERORGANIZATIONID,
ownerOrganizationId);
session
.setAttribute(
org.opencps.util.WebKeys.ACCOUNT_OWNERUSERID,
ownerUserId);
session
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_ROLES,
accountRoles);
session
.setAttribute(
org.opencps.util.WebKeys.ACCOUNT_ORGANIZATION,
accountOrgs);
}
else {
_log
.info(DefineObjectsTag.class
.getName() +
": --------------------------------->>>: AccountBean is null");
}
}
catch (Exception e) {
_log
.error(e);
}
finally {
accountBean = new AccountBean(
accountInstance, accountType, accountFolder, accountRoles,
accountOrgs, ownerUserId, ownerOrganizationId);
session
.setAttribute(org.opencps.util.WebKeys.ACCOUNT_BEAN,
accountBean);
}
}
return SKIP_BODY;
}
private Log _log = LogFactoryUtil
.getLog(DefineObjectsTag.class
.getName());
}
| Update account bean taglib | portlets/opencps-portlet/docroot/WEB-INF/util-taglib/org/opencps/taglib/accountmgt/DefineObjectsTag.java | Update account bean taglib | <ide><path>ortlets/opencps-portlet/docroot/WEB-INF/util-taglib/org/opencps/taglib/accountmgt/DefineObjectsTag.java
<ide> _log
<ide> .info(DefineObjectsTag.class
<ide> .getName() +
<del> ": --------------------------------->>>: AccountBean is null");
<add> ": ##########################: AccountBean is null");
<ide> }
<ide>
<ide> }
<ide> accountBean = new AccountBean(
<ide> accountInstance, accountType, accountFolder, accountRoles,
<ide> accountOrgs, ownerUserId, ownerOrganizationId);
<del>
<ide> session
<ide> .setAttribute(org.opencps.util.WebKeys.ACCOUNT_BEAN,
<ide> accountBean); |
|
Java | apache-2.0 | f38ff727ecdd92a7cdcd57bb9b62bb317dc7b3ba | 0 | mingzuozhibi/mzzb-server,mingzuozhibi/mzzb-server | package com.mingzuozhibi.modules.admin;
import com.mingzuozhibi.commons.base.BaseSupport;
import com.mingzuozhibi.commons.mylog.JmsBind;
import com.mingzuozhibi.commons.mylog.JmsEnums.Name;
import com.mingzuozhibi.commons.mylog.JmsEnums.Type;
import com.mingzuozhibi.modules.core.MessageRepository;
import com.mingzuozhibi.modules.disc.Disc;
import com.mingzuozhibi.modules.disc.GroupService;
import com.mingzuozhibi.modules.record.*;
import com.mingzuozhibi.modules.user.RememberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.*;
import java.util.List;
import java.util.Set;
@Service
@JmsBind(Name.SERVER_CORE)
public class AdminService extends BaseSupport {
@Autowired
private GroupService groupService;
@Autowired
private RecordService recordService;
@Autowired
private RecordCompute recordCompute;
@Autowired
private MessageRepository messageRepository;
@Autowired
private RememberRepository rememberRepository;
@Transactional
public void deleteExpiredRemembers() {
long count = rememberRepository.deleteByExpiredBefore(Instant.now());
bind.info("[自动任务][清理自动登入][共%d个]", count);
}
@Transactional
public void moveExpiredHourRecords() {
List<HourRecord> records = recordService.findHourRecords(LocalDate.now());
records.forEach(hourRecord -> {
DateRecord dateRecord = new DateRecord(hourRecord.getDisc(), hourRecord.getDate());
dateRecord.setRank(hourRecord.getAverRank());
dateRecord.setTodayPt(hourRecord.getTodayPt());
dateRecord.setTotalPt(hourRecord.getTotalPt());
dateRecord.setGuessPt(hourRecord.getGuessPt());
recordService.moveRecord(hourRecord, dateRecord);
});
bind.info("[自动任务][转存昨日排名][共%d个]", records.size());
}
@Transactional
public void recordRankAndComputePt() {
// +9 timezone and prev hour, so +1h -1h = +0h
LocalDateTime now = LocalDateTime.now();
LocalDate date = now.toLocalDate();
int hour = now.getHour();
Set<Disc> discs = groupService.findNeedRecordDiscs();
discs.forEach(disc -> recordCompute.computePtNow(disc, date, hour));
bind.info("[自动任务][记录计算排名][共%d个]", discs.size());
}
@Transactional
public void cleanupModulesMessages() {
{
int c1 = messageRepository.cleanup(Name.SPIDER_CONTENT, 150, Type.INFO, Type.WARNING);
int c2 = messageRepository.cleanup(Name.SPIDER_CONTENT, 200);
bind.info("[清理日志][name=%s][size=%d,%d]", Name.SPIDER_CONTENT, c1, c2);
}
{
int c1 = messageRepository.cleanup(Name.SPIDER_HISTORY, 150, Type.INFO);
int c2 = messageRepository.cleanup(Name.SPIDER_HISTORY, 200);
bind.info("[清理日志][name=%s][size=%d,%d]", Name.SPIDER_HISTORY, c1, c2);
}
{
int c1 = messageRepository.cleanup(Name.SERVER_DISC, 150, Type.INFO);
int c2 = messageRepository.cleanup(Name.SERVER_DISC, 200);
bind.info("[清理日志][name=%s][size=%d,%d]", Name.SERVER_DISC, c1, c2);
}
{
int c1 = messageRepository.cleanup(Name.SERVER_CORE, 200);
bind.info("[清理日志][name=%s][size=%d]", Name.SERVER_CORE, c1);
}
{
int c1 = messageRepository.cleanup(Name.DEFAULT, 200);
bind.info("[清理日志][name=%s][size=%d]", Name.DEFAULT, c1);
}
}
}
| src/main/java/com/mingzuozhibi/modules/admin/AdminService.java | package com.mingzuozhibi.modules.admin;
import com.mingzuozhibi.commons.base.BaseSupport;
import com.mingzuozhibi.commons.mylog.JmsBind;
import com.mingzuozhibi.commons.mylog.JmsEnums.Name;
import com.mingzuozhibi.commons.mylog.JmsEnums.Type;
import com.mingzuozhibi.modules.core.MessageRepository;
import com.mingzuozhibi.modules.disc.Disc;
import com.mingzuozhibi.modules.disc.GroupService;
import com.mingzuozhibi.modules.record.*;
import com.mingzuozhibi.modules.user.RememberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.*;
import java.util.List;
import java.util.Set;
@Service
@JmsBind(Name.SERVER_CORE)
public class AdminService extends BaseSupport {
@Autowired
private GroupService groupService;
@Autowired
private RecordService recordService;
@Autowired
private RecordCompute recordCompute;
@Autowired
private MessageRepository messageRepository;
@Autowired
private RememberRepository rememberRepository;
@Transactional
public void deleteExpiredRemembers() {
long count = rememberRepository.deleteByExpiredBefore(Instant.now());
bind.info("[自动任务][清理自动登入][共%d个]", count);
}
@Transactional
public void moveExpiredHourRecords() {
List<HourRecord> records = recordService.findHourRecords(LocalDate.now());
records.forEach(hourRecord -> {
DateRecord dateRecord = new DateRecord(hourRecord.getDisc(), hourRecord.getDate());
dateRecord.setRank(hourRecord.getAverRank());
dateRecord.setTodayPt(hourRecord.getTodayPt());
dateRecord.setTotalPt(hourRecord.getTotalPt());
dateRecord.setGuessPt(hourRecord.getGuessPt());
recordService.moveRecord(hourRecord, dateRecord);
});
bind.info("[自动任务][转存昨日排名][共%d个]", records.size());
}
@Transactional
public void recordRankAndComputePt() {
// +9 timezone and prev hour, so +1h -1h = +0h
LocalDateTime now = LocalDateTime.now();
LocalDate date = now.toLocalDate();
int hour = now.getHour();
Set<Disc> discs = groupService.findNeedRecordDiscs();
discs.forEach(disc -> recordCompute.computePtNow(disc, date, hour));
bind.info("[自动任务][记录计算排名][共%d个]", discs.size());
}
@Transactional
public void cleanupModulesMessages() {
{
int c1 = messageRepository.cleanup(Name.SPIDER_CONTENT, 100, Type.INFO, Type.WARNING);
int c2 = messageRepository.cleanup(Name.SPIDER_CONTENT, 200);
bind.info("[清理日志][name=%s][size=%d,%d]", Name.SPIDER_CONTENT, c1, c2);
}
{
int c1 = messageRepository.cleanup(Name.SPIDER_HISTORY, 200, Type.INFO);
int c2 = messageRepository.cleanup(Name.SPIDER_HISTORY, 200);
bind.info("[清理日志][name=%s][size=%d,%d]", Name.SPIDER_HISTORY, c1, c2);
}
{
int c1 = messageRepository.cleanup(Name.SERVER_DISC, 200, Type.INFO);
int c2 = messageRepository.cleanup(Name.SERVER_DISC, 200);
bind.info("[清理日志][name=%s][size=%d,%d]", Name.SERVER_DISC, c1, c2);
}
{
int c1 = messageRepository.cleanup(Name.SERVER_CORE, 200);
bind.info("[清理日志][name=%s][size=%d]", Name.SERVER_CORE, c1);
}
{
int c1 = messageRepository.cleanup(Name.DEFAULT, 200);
bind.info("[清理日志][name=%s][size=%d]", Name.DEFAULT, c1);
}
}
}
| feat: Keep debug log 150 pages
| src/main/java/com/mingzuozhibi/modules/admin/AdminService.java | feat: Keep debug log 150 pages | <ide><path>rc/main/java/com/mingzuozhibi/modules/admin/AdminService.java
<ide> @Transactional
<ide> public void cleanupModulesMessages() {
<ide> {
<del> int c1 = messageRepository.cleanup(Name.SPIDER_CONTENT, 100, Type.INFO, Type.WARNING);
<add> int c1 = messageRepository.cleanup(Name.SPIDER_CONTENT, 150, Type.INFO, Type.WARNING);
<ide> int c2 = messageRepository.cleanup(Name.SPIDER_CONTENT, 200);
<ide> bind.info("[清理日志][name=%s][size=%d,%d]", Name.SPIDER_CONTENT, c1, c2);
<ide> }
<ide> {
<del> int c1 = messageRepository.cleanup(Name.SPIDER_HISTORY, 200, Type.INFO);
<add> int c1 = messageRepository.cleanup(Name.SPIDER_HISTORY, 150, Type.INFO);
<ide> int c2 = messageRepository.cleanup(Name.SPIDER_HISTORY, 200);
<ide> bind.info("[清理日志][name=%s][size=%d,%d]", Name.SPIDER_HISTORY, c1, c2);
<ide> }
<ide> {
<del> int c1 = messageRepository.cleanup(Name.SERVER_DISC, 200, Type.INFO);
<add> int c1 = messageRepository.cleanup(Name.SERVER_DISC, 150, Type.INFO);
<ide> int c2 = messageRepository.cleanup(Name.SERVER_DISC, 200);
<ide> bind.info("[清理日志][name=%s][size=%d,%d]", Name.SERVER_DISC, c1, c2);
<ide> } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.